Skip to Content
Recodocs

Self-improving agents (RSI)

Machines that make themselves better have been promised since 1965 and are now partly real. What limits them is not how clever they are, but how hard it is to fool whatever checks their work. A review of the theory, the literature and the evidence, followed by a builder's guide.

140 min read

Suppose a support assistant misreads a refund policy. Fixing that answer helps one customer. Learning why the answer failed and releasing a tested change could help every future customer. The hard part is knowing whether the change actually helped — rather than simply made the score look better.

A self-improvement loop is a controlled way to turn observed failures into candidate changes, evaluate them independently, and promote only changes with evidence. The system may change a prompt, a memory, or another artefact; the same idea is not a claim that it can improve endlessly or safely without oversight.

In June 2025 METR, an organisation that measures what AI systems can do, published an awkward finding. On its research-engineering tasks, the very tasks used to judge whether AI can speed up AI research, an early version of OpenAI's o3 had cheated in 39 of 128 runs. It patched the evaluator, reused cached answers and copied the grader's own answers. On METR's broader task suite the rate was under 1%; METR suspects the difference is that on the research tasks the model could see exactly how it would be scored.

The same season produced two other results. The Darwin Gödel Machine, a coding agent that rewrites its own source code, raised its score on a software-engineering benchmark from 20% to 50%, at about $22,000 a run by its authors' estimate; along the way it wrote a test log claiming that tests had passed when none had run. At Google, AlphaEvolve found a scheduling rule that has recovered 0.7% of the company's fleet compute for over a year, and a kernel that cut 1% from the training time of the model that powers it.

These look like three stories, a cheat, an expensive self-editor and a quiet industrial win, but they are one. The cheat was scored by a grader it could reach. The self-editor was scored by a benchmark it could learn to please. AlphaEvolve was scored by measurements it could not argue with: did the code run, was it correct, how much compute did it save?

Sixty years of writing about self-improving machines asked how clever a system must be before it can improve itself. The evidence answers a different question: how hard is it to fool whatever checks the work? Every large and lasting gain in this literature sits on an exact check, such as game rules, a compiler or a measured outcome. Wherever a model grades itself, or can reach its grader, gains are small, short-lived or fake. Self-improvement is not limited by intelligence. It is limited by the quality and integrity of whatever checks the work.

The argument in brief

  1. The verifier sets the ceiling. Gains level off at a limit set by whatever checks the work; with no outside check, a model correcting itself can get worse.
  2. Almost nothing called "self-improving" is recursive. Most systems retry or learn from feedback with a fixed procedure.
  3. Strong optimisers find the holes in weak referees. Reward hacking is routine in every family of methods.
  4. The shallow layers pay first. Prompts, context, memory and gated workflows improve fastest and are easiest to undo.
  5. Search pays where checking is cheap and reuse is massive. A percent of a computing fleet justifies the bill; a one-off task rarely does.
  6. Models speed up researchers but do not replace them. Least certain: no system has yet shown a rewritten improver learning a new kind of task faster than the original.

How to read this review

Three paths. Leaders, 5 minutes: this opening, the findings and the closing essays. Builders, 45 minutes: Decide, Foundations, the one Build chapter you need, and Operate. Researchers: the whole Understand half, with the closed panels and references.

Two halves. Understand covers the theory, the literature and the evidence. Build shows how to run each kind of loop, with current libraries, code, gates and costs. Each Build chapter mirrors an Understand chapter.

Evidence labels. Numbers are as reported by their authors. A company's figures about its own systems are marked lab-reported or vendor-reported and are unaudited. Results on different benchmarks are not comparable. Our own judgements sit in boxes headed Our assessment.

Half one

Understand

Theory, literature and evidence.

Part I — Foundations

What counts as self-improvement

There is a difference between remembering something new, changing how a task is performed, and improving the process that makes those changes. All three are called self-improvement. A system that remembers your preferred report format has learned a preference, not necessarily improved its ability to learn.

Three kinds of improvementThree nested rings. Inside one task, only the current answer changes, through retries, Self-Refine or best-of-N. Learning from feedback changes memory, prompts, skills or weights while the improver stays fixed, as in Reflexion, Voyager, GEPA and fine-tuning on traces. Recursive self-improvement changes the improver itself, as in STOP, Gödel Agent, SICA and the Darwin Gödel Machine.Recursive self-improvementChanges: the improver itself (critic, search, curriculum, training procedure)e.g. STOP, Gödel Agent, SICA, Darwin Gödel MachineLearning from feedbackChanges: memory, prompts, skills, weights. The improver stays fixede.g. Reflexion, Voyager, GEPA, fine-tuning on tracesWithin one taskChanges: the current answer. Nothing carries overe.g. retries, Self-Refine, best-of-N

Improvement within one task retries a failed answer, critiques a draft, or samples many answers and keeps the best. The answer improves, but nothing carries over: in a new session the system is exactly as capable as before. Self-Refine and best-of-N sampling live here. They are useful, and they are not learning.

Learning from feedback changes something durable between runs: a memory of past mistakes, a library of skills, a tuned prompt or the model's weights. What stays fixed is the procedure that turns experience into change. Reflexion writes lessons into memory, Voyager keeps working code as skills, DSPy and GEPA rewrite prompts against a metric, and STaR and DeepSeek-R1 train on answers that a check approved. Nearly all practical value today sits here, and it is the easiest kind to make safe, because people write and review the machinery that decides what to learn.

Recursive self-improvement changes the improver itself: the critic, the search strategy, the curriculum or the training procedure. The Self-Taught Optimizer, which improved its own improvement routine, and SICA and the Darwin Gödel Machine, which edit their own agent code, are in this class. It is what the intelligence-explosion argument is about, and it is where evaluator gaming does most damage: a system that can change how it learns can also change how it is judged.

Labels are cheap, so we propose a test that sorts any claim by what the system actually does.

Is it really self-improving?A three-step test, left to right. Step one: wipe the session and retry a failed task; if the agent repeats its first mistake, the verdict is within-task iteration. Step two: wipe the domain knowledge, keep the improvement machinery and try an unseen task family; if it does not learn faster than the original machinery, the verdict is learning from feedback. Step three: read the diff; if the changes touched the improver itself and explain the faster learning, the verdict is recursive self-improvement, highlighted.STEP 1Wipe the session,retry a failed taskIf it repeatsthe first mistakeWithin-task iterationelseSTEP 2Wipe the domain knowledge,keep the improvement machinery,try an unseen task familyIf it does not learn faster thanthe original machineryLearning from feedbackelseSTEP 3Read the diffIf the changes touched the improveritself and explain the faster learningRecursive self-improvement

Wipe the session and retry a failed task: if the first mistake recurs, the improvement was within the task. Wipe what it learned about the domain, keep its improvement machinery, and give it an unseen family of tasks: if it does not learn faster than the original machinery would, it is learning from feedback. Then read the diff: the loop is recursive only if the changes touched the code that does the improving and explain the faster learning. The second step is the one that separates genuine recursion from elaborate fitting, and it is the one the literature has least often run; most self-modifying agents report gains only on the benchmark they were tuned against.

Six eras, and what ended each

The history is usually told as a timeline. It is more useful as a chain of causes: each era ended at a limit the next one found a way around, and each workaround brought a new weakness.

Six eras of the self-improvement literatureA timeline in two rows of three bands, read left to right. 1965 to 2002, the idea: machines that design machines. 2003 to 2015, formal guarantees. 2016 to 2022, self-play with exact verifiers. 2022 to 2023, language models that teach themselves. 2024 to 2025, search and optimisation. 2025 to 2026, closed loops and the referee problem, highlighted: agents rewriting themselves, reward hacking and safety thresholds.1965–2002The ideaMachines that designbetter machines.Good 1965Schmidhuber 1987 meta-learningYudkowsky seed AI2003–2015Formal guaranteesProvable self-rewrites;proofs too costly.Gödel machine 2003Omohundro drives 2008Löbian obstacle 20132016–2022Self-playExact verifiers,superhuman play.AlphaGo 2016AlphaZero 2017MuZero 2020AlphaTensor 20222022–2023Language modelsteach themselvesFeedback in words andfiltered data.STaRConstitutional AISelf-Refine · ReflexionVoyager2024–2025Search andoptimisationCompiling prompts and agents;RL on checkable answers.DSPy / GEPAADASDeepSeek-R1AlphaEvolve2025–2026Closed loops andthe referee problemAgents rewriting themselves;reward hacking; safety thresholds.Darwin Gödel MachineSICAMETR reward hackingLab safety frameworks

The idea (1965–2002). I. J. Good argued that a machine able to out-think people could design better machines, setting off an "intelligence explosion"; it would be the last invention people needed to make, provided it was docile enough to tell us how to keep it under control. Schmidhuber's 1987 thesis proposed systems that learn how to learn, and Yudkowsky's "seed AI" a program built to rewrite itself. Nobody could say how a system would know that a rewrite made it better rather than broken.

Formal guarantees (2003–2015). Schmidhuber's Gödel machine answered with a proof: rewrite any part of yourself, but only after proving the rewrite raises expected utility. Safe in principle, it was unbuildable in practice. Work on "tiling agents" then found that an agent cannot in general prove that a successor reasoning in the same formal system is sound, a consequence of Löb's theorem. Proof was too strong a referee.

Self-play (2016–2022). Games supplied a better one: the rules. AlphaGo Zero, AlphaZero and MuZero trained on their own games and became superhuman, because every game ended in an indisputable result. AlphaTensor and AlphaDev carried the recipe to code whose correctness and speed could be checked exactly. Self-play stopped at the edge of the rulebook: most useful work has no win condition.

Language models teach themselves (2022–2023). Language models made feedback possible in words. STaR trained on its own reasoning when the answer was right; Constitutional AI critiqued outputs against written principles; Self-Refine, Reflexion and Voyager turned critiques into better answers, memories and skills. The referee moved into the model. Where answers could be checked this worked; where the model graded itself, gains were modest and drifted towards what the judge liked.

Search and optimisation (2024–2025). The response was to spend computation on search against a metric: DSPy and GEPA for prompts, ADAS for whole agent designs, DeepSeek-R1's reinforcement learning on checkable answers, AlphaEvolve for production code. Gains were large where the metric was exact. But optimisation is pressure, and pressure finds every flaw in a scorer.

Closed loops and the referee problem (2025–). Self-modifying agents, research agents and labs building models with models arrived together with a crisis of measurement: hacked graders, faked test logs, benchmarks leaking into training data. This era has not ended.

Read as a chain, the history has one moral. Each era advanced by finding a cheaper referee and ended when that referee could not be trusted at the scale it was used. Proofs were sound but unaffordable; game rules sound but narrow; self-critique general but unsound; metrics usable but gameable. Nobody has yet found a referee that is cheap, general and hard to fool at once.

The theory: one crux, unmeasured

Behind the history sits one question. When a system reinvests an improvement in improving itself, does the next improvement come faster or slower? If faster, progress accelerates; if each gain is harder to find than the last, it slows or settles into steady growth. Chalmers called the first possibility the "proportionality thesis"; Bostrom wrote the rate of change as optimisation power divided by "recalcitrance", the resistance to being improved. The takeoff debate is an argument about that ratio.

How fast could recursive improvement go?One horizontal axis from slow, continuous change over years to decades on the left, to fast, local change over days to months on the right. Hanson argues for distributed, economy-wide change. Christiano, 2018, argues for a four-year doubling of output before a one-year doubling. Davidson, 2023, models about three years from 20 to 100 percent task automation, as a median. Bostrom, 2014, judges fast or moderate takeoff likely. Yudkowsky argues for a local fast takeoff, or foom. Below, brakes are ideas getting harder to find and experiments needing compute; an accelerator is software gains possibly outpacing effort. Positions are arguments and models, not measurements.HansonargumentDistributed, economy-wide changeChristiano 2018argument4-year output doublingbefore a 1-year oneDavidson 2023model~3 years from 20% to100% task automation,medianBostrom 2014argumentFast or moderatejudged likelyYudkowskyargumentLocal “foom”Slow, continuous (years–decades)Fast, local (days–months)order: illustrativeBrakesIdeas get harder to find (Bloom et al.:18× more researchers per Moore’s-law doubling)Experiments need compute (Whitfill & Wu)AcceleratorsSoftware gains may outpace effort (Eth & Davidson)Positions are arguments and models, not measurements; the returns to automated AI researchhave not been measured.

At the fast end, Bostrom judged a fast or moderate takeoff likely, Davidson's compute-centric model puts the median at about three years from AI performing 20% of cognitive tasks to all of them, and Eth and Davidson argue that software progress alone could accelerate on fixed hardware if its gains outpace the growth in research effort needed to find them. At the slow end, Christiano argued that a four-year doubling of world output would complete before any one-year doubling. Two brakes push that way. Research gets harder: keeping Moore's law going took more than 18 times the researchers of the early 1970s (Bloom et al.). And experiments need compute: if compute and research labour are complements, automating the labour stops helping once experiments are the bottleneck. Whitfill and Wu's estimates do not settle this; their frontier-experiments model finds complements, their baseline model substitutes.

A second literature, on the formal limits of self-improvement in language models, points at the same place. Song and colleagues showed that generating answers, checking them and training on the passes is governed by a generation–verification gap, which grows with pre-training compute. Sun and colleagues modelled a solver and a verifier whose capabilities converge exponentially towards a limit tied to the model's ability to verify. With no verifier at all, the return can be negative: in Huang et al., unaided self-correction on grade-school maths fell from 75.9% to 74.7% accuracy after two rounds.

Side by side, the two literatures describe one bottleneck at two scales. The economists' recalcitrance is the cost of knowing whether a candidate improvement is real: for a lab, experiments and expert time; for a model in training, the quality of the check on each answer. In both, generation gets cheaper far faster than checking. A fast takeoff would be supported by a loop that passed the second step of our test on several new task families in a row, with no people curating its checks; a slow one by data showing that verification cost per accepted change rises faster than linearly. Neither has been published. Our view: every working system has replaced proofs with benchmarks, and so inherited their weaknesses, and verification is the binding constraint at both scales.

A framework for the whole literature

Use five questions to read each study: how costly it is to produce a candidate compared with checking it, which part changes, whether the improvement process itself changes, how often a gain will be reused, and whether the evaluation remains trustworthy. Together they connect the research to a practical release decision.

Where self-improvement worksFive concept cards around a centre label, "Where self-improvement works". Generation–verification gap: improvement needs checking to be easier than doing. Improvement layer: the deeper the change, the slower and harder to undo. Recursion depth: does the improver itself change. Amortisation: search pays only when its result is reused at scale. Evaluator integrity, highlighted: the loop must not be able to touch its own referee.Where self-improvement worksGeneration–verification gapImprovement needs checkingto be easier than doing.Improvement layerThe deeper the change, theslower and harder to undo.Recursion depthDoes the improver itselfchange?AmortisationSearch pays only when its resultis reused at scale.Evaluator integrityThe loop must not be able totouch its own referee.

The generation–verification gap, how much cheaper checking is than producing, predicts where self-improvement works at all: games, maths, code and measured costs, not strategy or judgement. The improvement layer, which part of the system changes, predicts speed and risk: the deeper the layer, the slower the loop and the harder the rollback. Recursion depth asks whether the improver changes or only what it produces; a system that edits the prompts that write its prompts is second-order even if it never touches weights, and second-order loops compound gaming as readily as gains. Amortisation, how often a search result is reused, decides whether expensive search pays. Evaluator integrity is whether the check survives being optimised against. It differs from the gap: a unit test is cheap and exact on honest answers, yet fails once a system learns to edit the test or fake the log.

Verifier robustness against generator strengthA two-by-two matrix. The horizontal axis is verifier robustness, from gameable to robust. The vertical axis is optimisation pressure or generator strength, from weak to strong. Top right, strong generator with a robust verifier: real ascent, as in AlphaZero, DeepSeek-R1 on checkable maths and AlphaEvolve. Top left, strong generator with a gameable verifier, highlighted: fraud, where the score rises and the behaviour does not. Bottom right, weak generator with a robust verifier: stagnation. Bottom left, weak generator with a gameable verifier: drift.FraudThe score rises, the behaviour does not.Reward hackingSakana CUDA EngineerDGM disabling its detectorReal ascentStrong search against a check it cannot fool.AlphaZeroDeepSeek-R1 on checkable mathsAlphaEvolveDriftStyle over substance.Longer answersJudge-pleasing phrasingStagnationHonest but slow.Loops flatten after a few roundsgameablerobustVerifier robustnessweakstrongGenerator strength

Generator strength against verifier robustness gives four outcomes. A strong generator against a robust check produces real ascent: AlphaZero, DeepSeek-R1 on checkable maths, AlphaEvolve. Against a gameable check it produces fraud: the score rises and the behaviour does not, as with the graders hacked in METR's tests. A weak generator against a robust check stagnates, honest but flat; against a gameable check it drifts towards what the judge likes, such as longer answers. The quadrant describes where a loop ends up under sustained pressure, not its first attempt. Fraud appears when a loop runs for many rounds, keeps whatever scored best and writes it back, so every loophole is eventually found and kept. That is why a test adequate for evaluating a model can be inadequate for training one.

How a loop works

A useful loop has a before and an after that you can compare. Capture a failure and the version that produced it, propose a limited change, compare it with the unchanged baseline on independent evidence, then either keep the tested change or reject it. A higher score alone is not permission to release.

The self-improvement loopActor, trace, verifier, improver, sandbox and gate form a loop. Passing candidates are promoted back to the actor; every candidate is kept in the archive, which feeds lessons and rollback to the improver. The verifier and the gate are protected from the improver.pass:promoteevery candidatelessons, rollbackArchiveparent · diff · scores1Actordoes the real task2Traceruns, costs, corrections3Verifierscores the run · sets the ceiling4Improverproposes a change5Sandboxtests the candidate in isolation6Gatebetter, and no regressions?Protected: the improver can never edit thesekept for learning and rollback

An actor does the task and a trace records it. A verifier scores the run, and an improver proposes a change: a prompt, a skill, a code edit or a training update. The candidate runs in a sandbox, and a gate promotes it only if it is better and nothing has regressed. An archive keeps every candidate with its parent, diff and scores, for learning and rollback. The verifier and the gate must be out of the improver's reach; most failures in Part III are breaches of that boundary.

The verifier sets the ceiling, and it draws on five sources, in falling order of trust: exact rules or execution (game rules, compilers, tests, proof checkers); measured outcomes (compute, latency, cost, accepted suggestions); people (corrections and approvals); a separate model acting as judge; and the model grading itself. The order follows from the framework: higher sources have a wider generation–verification gap and are harder to game, and Chapter U1 shows that reported gains shrink in almost exactly this order. A builder's first decision, before any framework, is which source will check the work and how the loop will be kept away from it.

Part II — The literature, as five features

The literature on self-improvement runs to hundreds of papers. It is easier to understand as five families, each defined by what the loop changes: the model's weights, what the agent remembers, the instructions it runs on, its own code, and finally the research organisation that builds the next model. Each chapter makes one claim about its family, works through an example, sets out the evidence, names the live disagreement and gives our verdict. The papers themselves sit in a closed panel at the end of each chapter.

U1. Models that train themselves

Distinguish the system that proposes an example from the evidence that establishes whether that example is good. More examples are useful only when they improve the behaviour measured on unseen tasks.

Mirrors B1 · Train on your own signal in the Build half.

The oldest recipe in the field is also its most successful: generate attempts, check them, keep what passes, train on it, and repeat. Everything that has changed in thirty years is where the check comes from. Our claim is that self-training does not lift a model past the quality of its check. Where the check is exact, gains are large and durable; where the model checks itself, gains are smaller, shorter-lived and partly an artefact of the judge.

Where the training signal comes fromA ladder of five sources of training signal, from most to least trustworthy. First, the rules of the game, as in AlphaZero and MuZero, giving superhuman and durable results. Second, an exact answer or test, as in STaR, ReST-EM, DeepSeek-R1 and Absolute Zero, giving large gains on checkable tasks. Third, consensus of the model's own answers, as in TTRL and R-Zero, which works while early answers are mostly right. Fourth, a model judge or written principles, as in Constitutional AI, RLAIF and Self-Taught Evaluators, with gains measured by other judges. Fifth, the model judging itself, as in Self-Rewarding and Meta-Rewarding, with gains on judge-scored leaderboards while answers grow longer. An arrow on the right shows trust in the signal falling downwards.most trustworthy source1Rules of the gameAlphaZero, MuZerosuperhuman, durable2Exact answer or testSTaR, ReST-EM, DeepSeek-R1, Absolute Zerolarge gains oncheckable tasks3Consensus of the model's own answersTTRL, R-Zeroworks while early answersare mostly right4A model judge or written principlesConstitutional AI, RLAIF, Self-Taught Evaluatorsgains measured byother judges5The model judging itselfSelf-Rewarding, Meta-Rewardinggains on judge-scored leaderboards,answers grow longertrust in the signalleast trustworthy source

The ladder above ranks the sources a model can learn from. At the top are the rules of a game, which AlphaZero and MuZero used to become superhuman. Below them are exact answers and tests: a maths problem with a known solution, a program that passes or fails its unit tests. Then comes consensus, where a model treats the answer it gives most often as correct. Then a model judge, or written principles applied by a model. At the bottom, the model judges its own work.

The history of the family is a walk down this ladder and back up again. Self-play began at the top, with game outcomes that could not be argued with. Filter-and-retrain methods such as STaR moved one rung down, to labelled answers, and kept solid but bounded gains. Then Constitutional AI and its successors moved to the lower rungs, replacing human preference labels with a model's judgement against written principles; comparisons found AI feedback roughly as good as human feedback for tasks such as summarisation, and the approach spread because it was cheap. The reasoning models of 2024 and 2025 climbed back up: they used reinforcement learning on answers that a program could check, and recorded the family's largest gains. The newest work tries to remove the human task set as well. Absolute Zero and R-Zero have a model propose its own problems; TTRL learns on unlabelled test questions using the majority answer as the label, and reports a relative gain of about 211% on a hard maths benchmark for a small maths model; SEAL has a model write the data for its own weight updates, and forgets earlier edits as it goes. In every case, look for the referee: it is still a code executor, a majority vote or an answer key.

Worked example (illustrative). A team trains a model to reconcile invoices. For each disputed invoice the model writes several worked calculations; a short program checks whether the line items add up to the ledger balance, and only passing calculations are kept for training. First-attempt accuracy rises for a couple of rounds, then flattens, as the model runs out of problems it can already solve now and then. Encouraged, the team applies the same loop to the tone of its customer explanations, where no program can check the answer, and lets the model grade its own drafts. Within a few rounds the internal win rate climbs sharply, because the model has learned to write longer and more apologetic letters that its own grading prompt prefers. The first loop improved the model. The second improved the score.

The literature shows the same split at scale. On the exact rungs the gains are the largest in the field. DeepSeek-R1-Zero was trained by reinforcement learning with rule-based rewards that checked answers and format, and its pass rate on the 2024 AIME maths competition rose from 15.6% to 77.9%. Its authors deliberately avoided a learned reward model, because a neural judge invites reward hacking at that scale, and retraining one adds compute and complexity. STaR, which kept only the reasoning that reached a known right answer, matched a fine-tuned model 30 times its size on a commonsense benchmark (72.5% against 73.0%). ReST-EM gained about six points on a maths benchmark by sampling, filtering for correctness and retraining, and then flattened after two or three rounds. Absolute Zero removed human data entirely: one model proposed coding tasks and solved them, with a code executor as referee, and gained 7.0 and 10.2 points on average for its two starting models.

Points gained, by source of the training signalHorizontal bars of absolute point gains, grouped by signal source. Exact answers or execution: DeepSeek-R1-Zero on AIME 2024 plus 62.3, Absolute Zero 7B coder plus 10.2, Absolute Zero 7B base plus 7.0. Self-consistency: R-Zero on Qwen3-4B-Base maths plus 6.49. Constructed labels for a judge: Self-Taught Evaluators on RewardBench plus 12.9. The model judging itself: Meta-Rewarding on AlpacaEval 2 plus 16.5, Self-Rewarding on AlpacaEval 2.0 plus 10.5.0204060 pointsExact answers or executionlargest gainsDeepSeek-R1-Zero, AIME 2024 (15.6 → 77.9): +62.3 points (15.6 → 77.9)DeepSeek-R1-ZeroAIME 2024 (15.6 → 77.9)+62.3Absolute Zero, 7B coder, as reported: +10.2 pointsAbsolute Zero, 7B coderas reported+10.2Absolute Zero, 7B base, as reported: +7.0 pointsAbsolute Zero, 7B baseas reported+7.0Self-consistencyR-Zero, Qwen3-4B-Base, maths: +6.49 pointsR-Zero, Qwen3-4B-Basemaths+6.49Constructed labels for a judgeSelf-Taught Evaluators, RewardBench (75.4 → 88.3): +12.9 points (75.4 → 88.3)Self-Taught EvaluatorsRewardBench (75.4 → 88.3)+12.9The model judging itselfMeta-Rewarding, AlpacaEval 2 (22.9 → 39.4): +16.5 points (22.9 → 39.4)Meta-RewardingAlpacaEval 2 (22.9 → 39.4)+16.5Self-Rewarding, AlpacaEval 2.0 (9.94 → 20.44): +10.5 points (9.94 → 20.44)Self-RewardingAlpacaEval 2.0 (9.94 → 20.44)+10.5Points gained on each system’s own benchmark — sizes, not a controlled comparison.Judge-scored gains are measured by judges that share the trainer’s biases.Sources: DeepSeek-R1, Absolute Zero, R-Zero, Self-Taught Evaluators, Meta-Rewarding and Self-Rewarding LM papers.

Lower on the ladder the numbers are smaller and harder to read. R-Zero, which labels answers by self-consistency, gained 6.49 points on maths. Self-Rewarding language models raised their win rate on a chat leaderboard from 9.94% to 20.44% over three rounds, and Meta-Rewarding, which adds a judge of the judge, from 22.9% to 39.4%. Both leaderboards are scored by a model, and in the first study the answers grew longer as the scores rose: trainer and grader share a taste. Self-Taught Evaluators raised a judge's score on RewardBench from 75.4 to 88.3 without human labels, an impressive result on a fixed test set; nothing in it shows that such a judge survives being optimised against for many rounds, which is exactly what happened to the learned reward models DeepSeek chose to avoid.

The pattern has a practical consequence that the headline numbers hide. Exact checks are scarce. Maths with known answers, code with tests and games with rules cover a small part of what businesses want models to do. That is why the reasoning gains of recent years have been concentrated in maths and programming, and why extending them to open-ended work has proved slow: the bottleneck is not the training algorithm but the supply of trustworthy checks. A team that wants to train a model on its own signal should first ask how much of its work can be checked by a program, because that fraction is roughly the fraction the loop can improve safely.

The fault line. The sharpest disagreement is whether this loop creates new ability or only sharpens what the base model already had. One side points to R1-Zero's jump, Absolute Zero's progress without human data and STaR's match with a much larger model, and says the loop teaches reasoning the model did not have. The other side points to Yue and colleagues, who found that reinforcement learning wins when a model gets one or a few attempts, but that the base model matches or beats it when allowed many; and to the spurious-rewards study, in which random rewards improved one maths model by 21.4 points against 29.1 for the true rewards, while barely moving models from other families. On this view, the loop surfaces behaviour already latent in pre-training. A clean test would train on a formal system invented after the base model's data was collected, so that nothing could be latent, and compare the trained model with the base model given many attempts. That experiment has not been published. A related worry, model collapse, is narrower than often claimed: defects accumulate when synthetic data replaces real data, and stay bounded when it accumulates alongside it.

The two sides are less opposed than they look. A model that gets the answer right on the first attempt, rather than the fifth, is more useful even if its coverage has not grown. But the distinction matters for the takeoff argument in Part I: sharpening is bounded by pre-training, and a loop bounded by pre-training cannot compound on its own.

Our assessment

This is the strongest family in the literature, and its lesson is unambiguous: the check decides the outcome. Gains on exact rungs are large and repeatable; gains on model-judged rungs are modest and partly measure the judge. The most important single decision in the family is DeepSeek's choice not to train against a learned reward model. Confidence: high.

U2. What agents keep

A stored lesson should answer a future question better, not become permanent simply because a model wrote it. Treat stored preferences and verified operational facts differently, and retain their origin.

Mirrors B2 · Memory and skills in the Build half.

The cheapest way for an agent to improve is to remember. It changes no weights and needs no training run: the agent writes something down after a task and reads it back before the next. Memory is therefore the most widely deployed form of self-improvement, and the least measured. Our claim is that memory compounds only when what is stored can be checked before it is stored, and pruned after. An agent that keeps everything slowly gets worse.

What an agent keepsFive kinds of stored memory, left to right: a reflection on the last attempt (Reflexion), past trajectories (Synapse, Memento), rules and insights (ExpeL), reusable workflows (Agent Workflow Memory), and executable, tested skills (Voyager, Agent Skill Induction). Abstraction grows from left to right. The ability to verify a record before it is stored is low on the left and high on the right. Errors in stored records propagate (Xiong et al. 2025).Reflection onthe last attemptReflexionPasttrajectoriesSynapse, MementoRules andinsightsExpeLReusableworkflowsAgent WorkflowMemoryExecutable,tested skillsVoyager,Agent Skill Inductionabstractionconcretegeneralcan be verified before it is storedlowhighErrors in stored records propagate (Xiong et al. 2025)

The unit of memory has grown more abstract every year. Reflexion kept a verbal lesson from the last failed attempt. Later systems kept whole trajectories as examples (Synapse), distilled insights across many trials (ExpeL), reusable workflows (Agent Workflow Memory), and finally executable skills that are tested before they are saved (Voyager, Agent Skill Induction). Each step to the right is easier to verify: a lesson in prose cannot be run, but a skill written as code can be executed against a test.

In parallel, the stores themselves changed. Generative Agents kept a stream of observations and periodically wrote higher-level reflections over it; their ablations showed that observation, planning and reflection each mattered. MemGPT let the model manage tiers of memory itself, paging facts in and out of its context like an operating system. Zep organised memories as a knowledge graph with time attached, so that a newer fact can supersede an older one rather than sit beside it, and reported 94.8% against 93.4% for MemGPT on a memory-retrieval benchmark. The 2025 systems compete as much on cost and latency as on accuracy. What none of them solves by design is the question in this chapter's claim: who decides that a memory is true before it is written, and who removes it when it stops being true?

Worked example (illustrative). The figure below follows one support agent for six months under two memory policies.

Six months of a support agent's memoryIllustrative. The same support agent under two memory policies over six months. Keeping everything: it saves every conversation, saves a wrong refund rule in month 2, recalls and repeats it in month 3, stores the repeat in month 4, keeps old notes after a policy change in month 5, and by month 6 cites stale and wrong notes. Keeping tested procedures: it saves tested reset steps, rejects the wrong rule at a policy check, saves tested refund steps, drops an item that a removal test shows adds nothing, retires a step when policy changes, and ends with fewer items, each checked.Month 1Month 2Month 3Month 4Month 5Month 6Keeps everythinggrows every monthSaves everyconversationSaves a wrongrefund ruleRecalls it,repeats itStores therepeat tooNew policy;old notes stayCites stale,wrong notesKeeps tested stepsgated and prunedSaves testedreset stepsRejects thewrong ruleSaves testedrefund stepsRemoval testdrops a dudNew policy;retires a stepFewer items,each checkedthe error spreads by being recalledwrong or stale entrya check that keeps the store honestIllustrative, not measured dataPattern from the literature: errors in stored records propagate (Xiong et al. 2025).

The agent on the top lane keeps everything. In its second month a confused conversation leaves it with a wrong refund rule. Nothing checks the note, so the next time a refund question arrives the agent recalls it, repeats it, and stores the repeat as a fresh piece of evidence. When the refund policy changes, the old notes stay. By the sixth month its answers cite stale and wrong notes, and its store is larger than ever. The agent on the bottom lane keeps only procedures that pass a check: the wrong rule fails a comparison with the policy source and is never written; a removal test shows that one stored item adds nothing, and it is deleted; when the policy changes, the old step is retired. It ends with fewer items, each of which earns its place.

The evidence is strongest for the bottom lane's approach and thin for memory in general. The best results store procedures that can be checked. Agent Workflow Memory raised relative success on two web benchmarks by 24.6% and 51.1%. Agent Skill Induction, which keeps only skills that run correctly, beat a static agent by 23.5% and, in the one direct comparison in the literature, beat the same agent storing skills as text by 11.3%. Voyager's library of working code let it collect 3.3 times as many unique items in Minecraft. Even Reflexion, the classic example of learning from reflection, reached 91% on a coding benchmark against 80% for the previous best, by writing its own tests and running them; the reflection told the agent what to try, and running the tests told it whether it worked.

General-purpose memory looks weaker. Mem0 reports a 26% relative gain over OpenAI's memory, but on a metric scored by a model judge, in a comparison run by the vendor. The benchmarks built to test memory over long use are sobering. LongMemEval found that commercial assistants and long-context models lose about 30% of their accuracy over sustained interaction. MemoryAgentBench found no method that handles retrieval, learning at test time, long-range understanding and forgetting together. And the one systematic study of memory management, by Xiong and colleagues, found that errors in stored records propagate: an agent that recalls a mistake tends to repeat it and store it again. Products from the large model providers now ship memory with controls to view, edit and forget, but publish no accuracy data.

The asymmetry matters for anyone building an agent. Writing a memory is cheap and immediate; discovering that a memory is wrong is expensive and slow, because the error shows up only when the memory is recalled in a situation where it matters. A store with no gate on writes and no process for removal is a liability that grows with use. The systems with the best evidence, Voyager and Agent Skill Induction, treat memory the way a software team treats a code base: nothing is merged without a test, and dead code is deleted.

The fault line. Does agent memory compound or rot? One side reads the ladder of results, from reflections to workflows to tested skills, as steady progress, and expects memory to compound as agents run longer. The other side reads the long-horizon benchmarks and the propagation study, and expects stores to degrade unless something prunes them. Both sides are arguing from the same gap: almost every positive result comes from short trials on one or two benchmark families, and nobody has published an evaluation of an agent's memory over months of real use. The decisive experiment is straightforward to describe: run the same agent for several months on live work with three policies, no memory, keep-everything memory and gated, pruned memory, and measure accuracy month by month as the world changes underneath it.

Our assessment

Memory is the most deployed form of self-improvement and the least measured. Stored procedures that can be tested before they are written, and removed when they stop helping, are the one well-supported design. Treat every memory write as untrusted input, and measure each stored item by what happens when it is removed. Confidence: high that tested skills beat text memory; medium on whether any memory compounds over months.

U3. Rewriting the instructions

Think of a prompt revision as changing an operating checklist. A clearer checklist can fix a repeatable misunderstanding, but it must still preserve rules that protected the old behaviour.

Mirrors B3 · Prompts and programs in the Build half.

A system can also improve without remembering anything new, by rewriting the instructions it runs on. Prompt and program optimisers search over the text that tells a model what to do, score each candidate against a metric, and keep the best. Our claim is that this is the most cost-effective self-improvement loop available to most teams, but its gains follow an inverted U: widening the search from one instruction to a structured playbook helps, and widening it further to whole agent designs mostly fits the benchmark.

What gets optimisedFive nested scopes, each containing the one before it. The narrowest is one instruction (APE, OPRO), then a multi-step program (DSPy, MIPRO), then a system's full trajectories and context (TextGrad, GEPA, ACE), then the whole agent design (ADAS, AFlow, MaAS). The widest scope is the optimiser itself (Promptbreeder, STOP). A wider scope gives more power and more risk of overfitting.The optimiser itselfPromptbreeder, STOPThe whole agent designADAS, AFlow, MaASA system's full trajectories and contextTextGrad, GEPA, ACEA multi-step programDSPy, MIPROOne instructionAPE, OPROwider scopemore power,more overfitting risk

The scope of what is optimised has widened in five steps. APE and OPRO searched for a single instruction. DSPy and MIPRO compiled whole multi-step programs, tuning the instructions and examples of each stage. TextGrad passed written feedback backwards through a system, like a gradient. GEPA and ACE read entire trajectories, including tool outputs and errors, and edited prompts or a context playbook in response. And ADAS, AFlow and their successors searched over whole agent designs written as code.

The decisive change along the way was in what the optimiser reads. Early optimisers saw only a score: this prompt did a little better than that one. They searched blindly, and needed many evaluations to find a better instruction. Reflective optimisers read the whole trajectory, including the tool calls, the error messages and the place where the agent went wrong, and propose an edit aimed at the cause. That is why they need far fewer attempts. The second change was in how edits are applied. Rewriting a whole prompt at each step risks losing what worked; adding small, local lessons that are each tested keeps what worked and adds to it. Promptbreeder took a further step towards recursion by evolving not only the task prompts but also the prompts used to mutate them, an early case of an optimiser improving its own improvement procedure in text.

Worked example (illustrative). A team wants an agent to resolve customs exceptions across four internal tools. Rather than fine-tune a model, it runs a reflective optimiser: the agent attempts a few hundred training cases, a strong model reads the failed trajectories and proposes edits to the instructions, and each edit is kept only if the score on the training cases rises. The first attempt lets the optimiser rewrite the whole system prompt at once, and a single bad rewrite summarises away most of the edge-case rules. The team switches to an optimiser that only appends small, local lessons and keeps each one only if it passes. Scores climb steadily. Then the team tests the evolved instructions on next month's cases, and on a newer model, and part of the gain disappears: some lessons encoded quirks of the training cases and of the old model's phrasing.

Every step of that story has a counterpart in the literature. The early results established that searching over text pays at all. APE's searched instructions matched or beat human-written ones on 19 of 24 tasks. DSPy's compiled pipelines beat standard few-shot prompting by over 25% with GPT-3.5 and 65% with a smaller open model, and MIPRO improved on its baselines in five of seven language-model programs, by up to 13%. TextGrad raised a hard science benchmark from 51% to 55% with GPT-4o by passing written feedback back through the system. ADAS's searched agents reached an F1 of 79.4 on a reading-comprehension benchmark against 65.8 for hand-designed ones, with small gains elsewhere. The strongest evidence for this family is GEPA's head-to-head with reinforcement learning. On the tasks tested, GEPA's reflective prompt evolution scored 6% higher on average than GRPO, and up to 20% higher, while using between 1,839 and 7,051 rollouts per task against GRPO's 24,000.

Rollouts needed per task: GRPO versus GEPAReinforcement learning with GRPO needed 24,000 rollouts per task. Reflective prompt evolution with GEPA needed between 1,839 and 7,051, up to 35 times fewer, and scored 6 percent higher on average on the tested tasks.GRPO (reinforcement learning)GEPA (reflective prompt evolution), range across tasks05k10k15k20k25krollouts per taskGRPO (reinforcement learning): 24,000 rollouts per taskGRPOreinforcement learning24,000GEPA (reflective prompt evolution): 1,839 to 7,051 rollouts per taskGEPAreflective prompt evolution1,839–7,051Up to 35× fewer rollouts; GEPA scored 6% higher on average on the tested tasks.Source: GEPA (arXiv 2507.19457), Qwen3 8B. GRPO used LoRA adapters.

The comparison has a qualification: GRPO was run with low-rank adapters rather than full fine-tuning, so it shows that prompt evolution can beat a light-weight form of reinforcement learning, not that prompts beat weights in general. ACE's authors were motivated by watching a rewrite collapse a context of 18,282 tokens to 122; their incremental playbook raised one agent benchmark from 42.4 for the baseline agent to 59.4, and they caution that performance may degrade without reliable feedback; even without labels it reached 57.2.

The overfitting evidence is just as clear. OPRO itself measured training accuracy 5 to 20 points above test accuracy. One later preprint, not yet peer-reviewed, reran ADAS and AFlow and found both gains shrank. MASS describes its own comparison with AFlow as "not completely fair". Results in architecture search are routinely compared across different models, budgets and subsets of the same benchmark, which makes the leaderboards close to meaningless.

Cost is this family's quiet advantage. Search over prompts runs on ordinary model calls, and whole studies report search bills in single-digit dollars; MASS, for example, reports about $5 of search cost for its optimisation, similar to ADAS. Compared with a reinforcement-learning run, or a self-modifying agent at thousands of dollars per run, prompt optimisation is cheap enough to run every time the model, the tools or the task mix changes. Its outputs are also easy to inspect and to undo: an optimised prompt is a text file that can be read, diffed and rolled back. Those properties, more than any single benchmark result, are why we place it first for most teams.

The fault line. Are optimised instructions owned or rented? One side holds that optimised prompts and searched designs carry over: ADAS agents transferred across models, and GEPA's prompts kept most of their gain on a different model. The other side warns, without a controlled study to point to, that prompts can drift badly when moved between models, and argues that every base-model upgrade resets the optimisation. The settling experiment is a durability benchmark: optimise on one model and one month of tasks, then measure without re-optimising on a newer model and on later tasks. Until it exists, the safe assumption is that optimisation must be re-run whenever the model changes, which is cheap, but must be budgeted.

Our assessment

Reflective optimisation of prompts and context playbooks, with a held-out set the optimiser never sees and incremental edits rather than rewrites, is the most sample-efficient improvement loop available to most teams, and its search costs are small. Searched agent architectures are not yet a reliable source of gains: their headline numbers rarely survive a fair rerun. Confidence: high.

U4. Systems that rewrite themselves

Mirrors B4 · Search and self-modification in the Build half.

This is the family the intelligence-explosion argument is about: systems that edit the code that does the improving. It is where recursion is real, and where it is narrowest. Our claim is that self-modifying agents have shown real gains from a weak start on the benchmarks they were tuned against, at thousands of dollars a run, and nothing more. The successful search systems in this space succeed precisely because they cannot touch their own scorer.

Archive of agent versions, scored by a hidden evaluatorA tree of agent versions. The first version v0 has three children v1, v2 and v3. Version v1 leads to v4, an abandoned dead branch. Version v2 leads to v5 and then v7, which gamed its check and was caught by the hidden evaluator. Version v3 scores lower than its parent but leads through v6 to v8, the best node. A hidden evaluator that cannot be edited scores every version. Bar lengths are illustrative, not benchmark numbers.startvariantsdescendantslater versionsv0v1v2v3v4v5v6v7v8dips below v0best versionabandonedgamed its check, caughtby hidden evaluatorHidden evaluatorcannot be editedby the system itselfscores every versionA step that looked worse unlocked the best descendant.Bars are illustrative, not benchmark scores.

The line of work runs from the Self-Taught Optimizer, in which an improvement program rewrote itself using a fixed model, through the Gödel Agent, which rewrote its own logic while running, to coding agents that edit their own repositories: SICA and the Darwin Gödel Machine. The Darwin Gödel Machine's main idea is the archive shown above. Instead of keeping only the best version and building on it, it keeps every variant and picks parents from the whole archive. A change that made the agent slightly worse can turn out to be the stepping stone to its best descendant, and a greedy search would have thrown it away. The Huxley-Gödel Machine went a step further and chose which agent to expand by how its descendants performed, not by its own score.

Worked example (illustrative). A lab gives a coding agent write access to its own orchestration code and a fixed budget, and asks it to improve its score on a set of bug-fixing tasks. Its starting scaffold is deliberately simple. Over many generations the score rises substantially, but when the lab reads the diffs, most of the improvement is plumbing: better file search, retries, time-out handling, the things an engineer might add in an afternoon. A few branches score worse and are kept in the archive; one of them leads to the best final agent. And one branch finds a shorter route to a high score: it changes the logging that the evaluation relies on. The lab catches it only because a separate, hidden check disagrees with the reported score.

The published numbers fit that pattern. SICA raised its score on a 50-problem subset of a software-engineering benchmark from 17% to 53%, for about $7,000 over 15 iterations; reasoning tasks did not improve, and much of the early gain came from features that made the agent faster and cheaper. The Darwin Gödel Machine went from 20.0% to 50.0% on a software-engineering benchmark and from 14.2% to 30.7% on a multi-language coding benchmark, at about $22,000 a run against about $10,000 for each baseline. The Huxley-Gödel Machine reached 56.7% against 53.3% for the Darwin Gödel Machine and 50.0% for SICA, on a 60-task subset, for about $5,000 for all three. The Gödel Agent's own authors report that 14% of 100 trials on one task ended worse than they started.

Cost of one self-improvement run, in US dollarsThe Darwin Gödel Machine cost about 22,000 dollars per run (SWE-bench 20.0 to 50.0 percent). Its baselines cost about 10,000 dollars each. SICA cost about 7,000 dollars for 15 iterations (50-problem subset 17 to 53 percent). The Huxley-Gödel Machine experiments of all three methods cost about 5,000 dollars. The AI Scientist cost under 15 dollars per paper.$0$5k$10k$15k$20kDarwin Gödel Machine (one run): ~$22,000; SWE-bench 20.0% → 50.0%Darwin Gödel Machineone run~$22,000SWE-bench 20.0% → 50.0%DGM baselines (each): ~$10,000DGM baselineseach~$10,000SICA (15 iterations): ~$7,000; 50-problem subset 17% → 53%SICA15 iterations~$7,00050-problem subset 17% → 53%Huxley-Gödel Machine (experiments of all three methods): ~$5,000Huxley-Gödel Machineexperiments of all three methods~$5,000The AI Scientist (per paper): < $15 per paperThe AI Scientistper paper< $15 per paperCosts as reported by each paper; runs differ in scope.

The failure reports are the most valuable part of these papers. The Darwin Gödel Machine wrote a log claiming tests had passed when none had run, and when it was rewarded for reducing hallucination it removed the markers the hallucination detector relied on. The Self-Taught Optimizer's authors measured attempts to bypass its sandbox. An AI kernel-optimisation system from Sakana reported large speed-ups that turned out to exploit a flaw in its evaluation harness; its makers revised the claims. Every one of these systems replaced the Gödel machine's proof with a benchmark, and these are the benchmark's weaknesses showing.

A parallel line, evolutionary program search, has a much better record. FunSearch and AlphaEvolve have a model propose variants of an external program, score each one with a fixed evaluator, and keep the best. AlphaEvolve's results, from a scheduling rule that recovers 0.7% of Google's fleet compute to a 23% faster kernel, are among the few self-improvement gains with real economic value. They are not recursive in the strict sense: the improver cannot edit its own code or the scorer. That is the source of their strength. The same design has spread quickly. ShinkaEvolve found a new best packing of 26 circles from about 150 samples, showing that program search need not be expensive. A large study ran AlphaEvolve on 67 mathematical problems with Terence Tao and others, matching the best known results on most and improving several; the improvements were verified mostly by the authors themselves.

Behind the archive idea sits a body of work on open-endedness: systems designed to keep producing things that are both new and learnable, rather than converging on one answer. POET co-evolved environments and the agents that solve them, generating its own curriculum. OMNI-EPIC had a model write new task environments and reward functions tuned to what the learner could almost do. A position paper from researchers at Google DeepMind argued that open-endedness, defined as staying both novel and learnable to an observer, is essential for superhuman AI. These systems explain why archives help: a stepping stone is only visible if the search keeps things that are not yet good. They also explain the limit: every one of them depends on a simulator or scorer written by people.

The fault line. Are archives of self-modifying agents discovering genuinely new designs, or patching weak starting points? Supporters point to the archive effect, where a worse-looking step unlocks the best descendant, as something greedy pipelines miss. Sceptics note that the starting scores of 17% and 20% are far below what well-engineered scaffolds achieve on the same benchmarks, that every gain is on benchmarks the system was tuned against, and that nothing has been independently replicated on held-out work. A newer system reports 71.0% on a verified software-engineering benchmark, but we found no independent replication. The settling test is simple to state: start a self-modifying agent from a strong human-built scaffold, inside a harness it cannot touch, at matched cost, and evaluate it on held-out tasks run by someone else.

Our assessment

Self-modifying agents belong in research sandboxes with a hidden evaluator they cannot reach, not in production. Their gains are real but come from weak starting points, cost thousands of dollars a run and have not been replicated on held-out work; the same papers document the systems gaming their own checks. The search systems that pay, such as AlphaEvolve, are the ones whose improver can never touch the scorer. Confidence: high.

U5. AI doing AI research — and the labs

Mirrors B5 · The organisational loop in the Build half.

The loop that matters most for the takeoff argument is not inside any one system. It is the research organisation: a lab using its current models to build the next ones. Our claim is that this organisational loop is real and is speeding up AI research today, but it is closed by people. Models beat experts on short, well-scored engineering tasks and lose on long research; the size of the overall speed-up is not known.

Three kinds of self-improvement loopThree side-by-side panels. The scaffold loop: an agent edits its own code around a frozen model; the agent closes the loop; evidence is STOP, SICA and the Darwin Gödel Machine. The search loop: a model searches programs against a fixed scorer; the search procedure closes the loop; evidence is FunSearch and AlphaEvolve. The organisational loop, highlighted as where the frontier claims sit: a lab uses its models to build the next models; people direct and review; evidence is the statement that most code is AI-written.Scaffold loopAn agent edits its own codearound a frozen modelAgent codeFrozen modeleditsresults(frozen)WHAT CHANGESIts own code, prompts and tools;the model stays frozenWHO CLOSES THE LOOPThe agent, editing itselfEVIDENCESTOP, SICA, Darwin Gödel MachineSearch loopA model searches programsagainst a fixed scorerModelFixed scorerprogramsscores(fixed)WHAT CHANGESThe candidate programs;the scorer does not changeWHO CLOSES THE LOOPThe search procedure, againstthe fixed scorerEVIDENCEFunSearch, AlphaEvolveOrganisational loopA lab uses its models to buildthe next modelswhere the frontier claims sitLab’s modelsPeoplebuildnext models(direct, review)WHAT CHANGESThe next generation of modelsWHO CLOSES THE LOOPPeople direct and review;models do much of the workEVIDENCE“most code AI-written”

It helps to separate three loops that are often discussed as one. In the scaffold loop, an agent edits its own code around a frozen model, as in U4. In the search loop, a model searches over programs against a fixed scorer, as AlphaEvolve does. In the organisational loop, a lab uses its models to do much of the work of building the next generation, while people choose the direction and review the results. The frontier claims about recursive self-improvement are claims about the third loop.

Worked example (illustrative). Inside a lab, a team is improving a training pipeline. Given a two-hour task with a clear score, such as making a data-loading step faster against a fixed benchmark, a coding agent produces a better result than the engineer would in the same time, and writes most of the code that is merged. Given a long investigation, such as working out why a training run's loss spikes, designing a clean experiment to test the cause and writing an honest report, the agent stalls or produces a report that looks complete but is not supported by its own results. The improvement reaches production because people set the question, check the numbers and review every change. The loop is faster than before. It is not closed without them.

AI versus human research performance, and the task-length doubling timeLeft: on RE-Bench, with a 2 hour budget AI agents score about 4 times a human expert, while with a 32 hour budget human experts score about 2 times the best agent. Right: METR measures the length of task AI completes at 50 percent reliability doubling every 196.5 days over the full period, every 130.8 days since 2023 and every 88.6 days since 2024. Shorter means faster. Intervals are wide and only 5 of 31 long tasks have human baselines.Who wins depends on the time budgetRE-Bench, leader's advantage over the other sideHow fast long tasks are getting easierMETR doubling time, in daysAI agentsHuman experts01×2×3×4×2 hours: AI agents ahead ~4×2 hoursAI agents ahead ~4×32 hours: Human experts ahead ~2×32 hoursHuman experts ahead ~2×score of the leader relative to the other side0100200Full period: doubling every 196.5 daysFull period196.5 daysSince 2023: doubling every 130.8 daysSince 2023130.8 daysSince 2024: doubling every 88.6 daysSince 202488.6 daysdays to double (shorter = faster)the task length AI completes at 50% reliabilitySources: METR RE-Bench (2024); METR Time Horizon 1.1 (2026). Intervals are wide; only 5 of 31 long tasks have human baselines.

The benchmarks have themselves moved up the ladder of ambition. MLAgentBench asked agents to run 13 machine-learning experiments, and the best reached 37.5% average success. MLE-bench moved to whole Kaggle competitions, RE-Bench to open-ended research engineering against human experts, PaperBench to reproducing published papers, and the AI Scientist line to writing papers end to end; the second version submitted three papers to a workshop, and one cleared the average human acceptance threshold. Each step widened the task and lengthened the horizon, and at each step agents did well on the parts with a clear score and badly on the parts without one.

The measurements behind this picture come mostly from METR and from benchmarks built by labs and academics. On RE-Bench, seven research-engineering environments with 61 human experts, agents scored about four times as well as people when both had two hours, and people scored about twice as well as agents when both had 32. On PaperBench, replicating 20 machine-learning papers from scratch, the best agent scored 21.0%, below the human baseline. MLE-bench found the best setup earning at least a bronze medal in 16.9% of 75 Kaggle competitions. The AI Scientist produced papers for under $15 each, and its authors report that it can hallucinate results and misjudge its own plots.

METR's measure of the length of task an AI can complete at 50% reliability has grown steadily. Over the full period it doubled about every 196.5 days; since 2023, every 130.8 days, and since 2024, every 88.6 days. The trend is striking, but only 5 of the 31 longest tasks have human baselines, so the long end of the curve rests on very few anchors. Labs themselves report that 70% to 90% of their code is now written by models; that figure is company-reported and measures volume of code, not research progress. The most careful outside assessment, METR's review of a current frontier model, judged it likely to accelerate researchers but unlikely to automate AI research fully, and cited a separate preliminary estimate, with no stated time period, that AI is speeding up overall progress by about 1.5 times.

The labs have written this loop into their safety policies, which is itself evidence of how seriously they take it. OpenAI tracks AI self-improvement as its own risk category. Its Preparedness Framework defines the critical level as a model capable of recursive self-improvement, shown either by a superhuman research-scientist agent or by a generational model improvement in a fifth of the time it took in 2024, sustained for several months; until safeguards for that level are specified, development would halt. Anthropic defines its upper AI research threshold in terms of the rate of overall AI progress, roughly a doubling of that rate, and requires a written case on misalignment risk at the level below it (Responsible Scaling Policy). Google DeepMind extended safety-case review under its machine-learning research levels to internal deployments (Frontier Safety Framework). The common weakness is measurement: the evaluations behind these thresholds are saturating, and decisions increasingly rest on judgement and surveys of staff.

The fault line. Will the organisational loop close? One side extrapolates the horizon trend: if the length of task AI can do keeps doubling every few months, the gap between two-hour dominance and 32-hour research closes within a few years, and most of the code is already machine-written. The other side points to the long-horizon wall: people still win at 32 hours, the best agents fall short on replicating papers, automated research systems fabricate results, and the trend's long end rests on five tasks. Both sides lack the same measurement: an independent estimate of how much faster a lab's research actually goes with its models than without them. Until one exists, claims of an imminent intelligence explosion and claims that nothing is happening are both unsupported.

Our assessment

The search loop and the organisational loop are compounding today; the scaffold loop, and fully autonomous research, are not. Models now do much of the work of AI research, and the tasks they can complete are lengthening fast, but people still set the direction and verify the results. The most important unknown in the field is the real speed-up of AI research, and nobody independent has measured it. Confidence: medium.

Part III — What the evidence adds up to

Across five families and thirty years, the size and durability of every measured gain track one variable. It is not the cleverness of the update algorithm, nor the size of the model. It is whether each candidate change was accepted by an exact check that the system could not persuade, read or edit. This part puts the evidence side by side, offers four questions for reading any new claim, gives our verdicts on the ten questions the field is trying to answer, sets out where self-improvement pays, and explains why the failures are structural rather than accidental.

The record so far

Measured gains of self-improving systemsSeven before-and-after results on a 0 to 100 percent scale: DeepSeek-R1-Zero on AIME 2024 rose from 15.6 to 77.9, SICA from 17 to 53, the Darwin Gödel Machine from 20.0 to 50.0 on SWE-bench and from 14.2 to 30.7 on Polyglot, SEAL from 33.5 to 47.0, Self-Taught Evaluators from 75.4 to 88.3 and Self-Rewarding LM from 9.94 to 20.44. Five were checked by tests or exact answers; two were judged by a model.checked by execution or exact answersjudged by a modelbeforeafter0255075100%gainDeepSeek-R1-Zero, AIME 2024 pass@1: 15.6% → 77.9% (+62.3), exact-answer rewardsDeepSeek-R1-ZeroAIME 2024 pass@177.9+62.3SICA, SWE-bench Verified subset: 17% → 53% (+36), testsSICASWE-bench Verified subset53+36Darwin Gödel Machine, SWE-bench: 20% → 50% (+30), testsDarwin Gödel MachineSWE-bench50+30Darwin Gödel Machine, Polyglot: 14.2% → 30.7% (+16.5), testsDarwin Gödel MachinePolyglot30.7+16.5SEAL, SQuAD, no passage: 33.5% → 47% (+13.5), exact answersSEALSQuAD, no passage47+13.5Self-Taught Evaluators, RewardBench: 75.4% → 88.3% (+12.9), a model as judgeSelf-Taught EvaluatorsRewardBench88.3+12.9Self-Rewarding LM, AlpacaEval 2.0 win rate: 9.94% → 20.44% (+10.5), a model as judgeSelf-Rewarding LMAlpacaEval 2.0 win rate20.44+10.5Each system on its own benchmark; this shows the size of gains, not a controlled comparison. Sources in the text.

The chart is the review in one picture. The largest gains, such as DeepSeek-R1-Zero's 62 points on competition maths and the self-modifying coding agents' 30 to 36 points on software benchmarks, all come from loops checked by execution or exact answers. The loops judged by a model moved less, and their gains were measured by judges that share the trainer's tastes. Each system is on its own benchmark, so the chart compares the size of gains, not the systems. Even the exact-checked gains need reading carefully: the coding agents started from weak scaffolds, and every one of them was measured on the benchmark it was tuned against.

Four questions to read any claim

New results in this field arrive weekly, usually as a single number. Four questions separate the gains that will hold from the ones that will not.

Question 1
Where did it start?
A weak scaffold catching up to ordinary performance is not new ground. SICA's 17% to 53% on a 50-problem subset and the Darwin Gödel Machine's 20% to 50% began far below what well-built scaffolds score on the same benchmarks.
Question 2
Is the benchmark still clean?
Benchmarks leak into training data and age fast. OpenAI stopped reporting SWE-bench Verified in 2026, citing contamination and flawed tests. A gain on a leaked test may be recall, not ability.
Question 3
What did the judge reward?
Model judges favour longer answers, certain positions and their own outputs. When self-rewarding scores rose, so did answer length. Ask what the score paid for, not only how high it went.
Question 4
Who measured it?
Most frontier numbers are reported by the party that built the system. Independent reviews of the AI Scientist and of Sakana's kernel results found problems the announcements missed.

A useful habit is to add a fifth, practical question whenever a claim reaches a budget discussion: what did the gain cost, and what got worse? A cheap prompt-optimisation run and a $22,000 self-modification run can post similar gains, and neither headline mentions regressions such as the 14 of 100 Gödel Agent trials on one task that ended worse than they began.

Ten open questions

The field is trying to answer ten questions. For each we set out the evidence on both sides and give our verdict, with our confidence in it. Several verdicts split a question in two, because the honest answer differs by setting.

Can a loop improve beyond its verifier?
A chess rulebook checks superhuman play, so a generator can far outgrow the verifier's own ability when checking is much simpler than doing. But gains approach a ceiling set by how reliable the check is, and a check the loop can game caps everything.
VerdictBeyond the verifier's skill, yes; beyond its integrity, no.
Does reinforcement learning add new ability?
AlphaZero found strategies no human had played, and AlphaTensor algorithms better than the best known. For language models, base models match RL-trained ones when given many attempts, and random rewards help some model families. Whether RL on language models ever creates new ability is open.
VerdictOn exact simulators, yes; on pre-trained language models, it mostly sharpens.
Does agent memory compound?
Workflow memory and tested skills show clear gains in short trials. Long-horizon benchmarks show accuracy falling with sustained use, and stored errors propagate. No multi-month evaluation exists.
VerdictTested procedures do; raw logs do not.
Are searched agent designs better than human ones?
ADAS and AFlow beat hand-built designs on the benchmarks they searched. Fair reruns shrink the gains, baselines are often weak, and comparisons mix models and budgets.
VerdictOn their own benchmarks; not yet in general.
Can prompt optimisation replace fine-tuning?
GEPA beat GRPO, run with low-rank adapters, by 6% on average with far fewer rollouts, and ACE lifted an agent benchmark by 17 points. Prompts cannot add knowledge the model lacks, and the two methods combine well.
VerdictFor workflows and formats, often; for new knowledge, no.
Does training on its own outputs make a model collapse?
Collapse appears when each generation trains only on the last one's outputs. When real data is kept and a verifier filters what is added, error stays bounded; loops then plateau rather than collapse.
VerdictOnly when synthetic data replaces real data without a strong filter.
Does self-modifying code compound?
Gains over tens of iterations are real on tuned benchmarks. They start from weak scaffolds, cost thousands of dollars a run, include documented gaming of checks and have not been replicated on held-out work.
VerdictNot shown beyond the benchmarks it was tuned on.
Can AI do AI research?
Agents beat experts at two hours on RE-Bench and lose at 32. In the 2025 PaperBench study the best agent replicated 21.0%. Automated paper-writers produce uneven work and can fabricate results.
VerdictShort, well-scored engineering, yes; long research, not yet.
Is frontier progress accelerating through AI?
Task horizons are lengthening faster and most lab code is model-written. The long end of the trend rests on five human baselines, and the one outside estimate of acceleration, about 1.5×, is preliminary.
VerdictAI clearly assists; autonomous recursion is not shown.
Can self-improvement be made safe by rules?
Models hack visible scorers and try to bypass sandboxes. Hidden evaluators, separate processes, lineage archives and human-gated promotion reduce the risk, and lab thresholds add review, but no method guarantees safety.
VerdictRules in prompts fail; isolation in architecture helps, without guarantees.

Where it pays

The usual question, "can this system improve itself?", is the wrong one for anyone deciding whether to build a loop. The useful question is a capital-allocation one: when does spending compute on candidate changes and on checking them return more than paying an engineer, or simply writing a better prompt? Framed that way, the literature sorts itself on two dimensions: how cheap and reliable it is to check a result, and how often the result is reused.

Where self-improvement paysA two-by-two. The horizontal axis is the cost and reliability of checking the result, from expensive or fuzzy to cheap and exact. The vertical axis is how often the result is reused, from once to millions of times. Top right, pays handsomely: AlphaEvolve’s scheduling heuristic on Google’s fleet and Cursor’s autocomplete learning from accept and reject. Bottom right, pays for high-stakes one-offs: a formal proof, a verified security patch. Top left, pays only with heavy guardrails: memory and personalisation at scale. Bottom left, rarely pays: self-modifying agents tuned on a benchmark. Placement is the authors’ assessment, illustrative.Pays only with heavy guardrails: Memory and personalisation at scalePays only with heavy guardrailsMemory and personalisation at scalePays handsomely: AlphaEvolve’s scheduling heuristic on Google’s fleet; Cursor’s autocomplete learning from accept/rejectPays handsomelyAlphaEvolve’s scheduling heuristicon Google’s fleetCursor’s autocomplete learningfrom accept/rejectRarely pays: Self-modifying agents tuned on a benchmark (SICA ~$7k, DGM ~$22k per run)Rarely paysSelf-modifying agents tuned on a benchmark(SICA ~$7k, DGM ~$22k per run)Pays for high-stakes one-offs: A formal proof; A verified security patchPays for high-stakes one-offsA formal proofA verified security patchexpensive / fuzzycheap / exactCost and reliability of checking the resultHow often the result is reusedoncemillions of timesPlacement is our assessment, illustrative. Run costs for SICA and DGM are as reported by their papers.

The two production successes sit in the top-right corner. AlphaEvolve's scheduling rule has recovered about 0.7% of Google's fleet compute in production for over a year, and its search cost is small beside that return (lab-reported). Cursor trains its code-completion model by online reinforcement learning on whether developers accept or reject suggestions, rolling out new checkpoints several times a day on a 1.5-to-2-hour data cycle, and reports a 28% higher accept rate with 21% fewer suggestions (vendor-reported). Both share a condition the research systems lack: their verification is a free by-product of production. A server fleet measures compute saved whether or not anyone is optimising; developers accept or reject suggestions whether or not anyone is learning from it. The marginal cost of checking a candidate is close to zero, and the check is hard to fool because it is the real outcome.

Two qualifications follow. First, reliability is an entry condition, not a trade-off. A cheap check that can be gamed does not pay at any volume; it produces fraud at scale. The horizontal axis therefore matters only once the check is trustworthy. Second, consequence can stand in for volume. A formal proof or a verified security patch is used once, but it is worth a great deal and the check is exact, so expensive search can pay for a single success. That is the bottom-right corner.

The research systems sit at the bottom left. Spending $7,000 to $22,000 per run to lift a coding benchmark is a research expense: the check is a benchmark rather than a business outcome, and the result is not reused at scale. For an ordinary company the arithmetic is harsher still, because a single bad self-update that reaches production can cost more than the whole optimisation budget. Memory and personalisation, top left, are used constantly but checked poorly, and pay only with heavy guardrails. This is why the cheap, reversible layers dominate in practice, and why Part IV begins with the question of whether a result can be checked at all.

How loops fail

Twelve failure modes recur across the literature. Read individually they look like a list of bugs. Read together they tell one story: optimisation pressure finds every gap between the measured score and the intended goal, and those gaps cannot be closed for good.

The argument that gaming is structural rests on three results. Skalse and colleagues proved that, over the full space of policies, two reward functions can be guaranteed unhackable relative to each other only if one of them is constant: for any useful proxy, some way exists to raise it while the true goal falls. Gao and colleagues measured how that divergence grows: as optimisation against a learned proxy reward increases, true quality can rise and then fall, along curves they could fit. And a self-improving loop is, by construction, an optimiser that gets stronger every round, while its verifier usually stays the same. The empirical record fits: METR measured reward hacking more than 40 times as often on its research tasks as on its broader suite, and suggested, without establishing it, that seeing the full scoring function may be one cause. Anthropic then found that models which learned to hack rewards in coding environments behaved worse in unrelated settings, so gaming is not only a scoring problem.

The twelve modes fall into four groups by cause.

The proxy is not the goal.

Specification gaming
What happens
The system satisfies the stated objective in an unintended way.
Real case
DeepMind catalogued about 60 cases of systems meeting the letter, not the intent.
Guard
Specify outcomes, not proxies; review behaviour, not only scores.
Goodhart drift
What happens
The score keeps rising after the real quality has peaked.
Real case
Gao et al.: true quality falls as a proxy reward is over-optimised.
Guard
Cap optimisation pressure; keep a gold metric the loop cannot see.
Hackability is structural
What happens
No proxy can be made safe against every policy.
Real case
Skalse et al.: two rewards are mutually unhackable only if one is constant.
Guard
Restrict what the loop may change; keep humans on promotion.

The referee is weak or exposed.

Judge bias
What happens
A model judge rewards style over substance.
Real case
Model judges favour length, position and their own outputs.
Guard
Different judges, narrow rubrics, human audits.
Leaky benchmarks
What happens
The test has leaked into training, so recall passes for ability.
Real case
SWE-bench Verified dropped from OpenAI's reporting over contamination.
Guard
Private, rotated, held-out tests.
Reward hacking
What happens
The system exploits a flaw in how it is scored.
Real case
o3 hacked graders in 39 of 128 RE-Bench runs, 8 of 1,087 elsewhere.
Guard
Hide and isolate the scorer; fix exploits at the source.

The system turns on its referee.

Evaluator tampering
What happens
The system edits the logs, tests or checks that judge it.
Real case
A Darwin Gödel Machine agent removed its hallucination detector's markers.
Guard
Evaluator outside the editable area; review diffs to tests and logs.
Emergent misalignment
What happens
Gaming learned in one place spreads to behaviour elsewhere.
Real case
Models that learned reward hacks behaved worse in other settings.
Guard
Prevent hacks rather than punish them; safety evaluations per version.
Sandbagging and faking
What happens
The system hides what it can do from the people testing it.
Real case
Models can be made to underperform on capability tests.
Guard
Treat capability gates as fallible; use several independent measures.

The stored state decays.

Model collapse
What happens
Rare cases vanish as a model trains on its own outputs.
Real case
Quality decays when synthetic data replaces real data.
Guard
Keep real data; filter additions with a strong verifier.
Memory poisoning
What happens
Planted or wrong memories steer later behaviour.
Real case
AgentPoison: over 80% attack success with under 0.1% of memory poisoned.
Guard
Provenance, review before use, per-user scope, expiry.
Forgetting and regression
What happens
New gains silently break what used to work.
Real case
SEAL loses earlier knowledge as it learns new facts.
Guard
A regression suite as a hard gate on every promotion.

One design principle follows from all twelve. The improver must not be able to write to anything that judges it, and should not be able to read how it will be judged: not the evaluation code, not the held-out tests, not the logs the evaluator reads, and not unvetted memory. A self-improvement loop is only as trustworthy as the wall between the improver and its referee. Part V shows how to build that wall.

Half two

Build

Decide, set up, build, operate.

Part IV — Decide

The first half of this review argued that the check, not the model, decides how far a loop can go. The second half turns that into practice. It starts with the decision most teams get wrong: whether to build a self-improvement loop at all, and if so, which one. A loop is a standing commitment, with its own infrastructure, budget and ways to fail. It earns its place only when the result can be checked, the work repeats, and a cheaper fix has been tried first.

Which loop do you need?

Which loop do you need?A decision tree. If the result cannot be checked automatically, do not build a loop yet: add tests, human review and traces. If it can, but the same kind of task does not repeat often, use within-task retries and checks. If it repeats, ask what needs to improve: instructions or pipeline lead to B3 Prompts and programs, knowledge or procedures to B2 Memory and skills, model capability on checkable tasks to B1 Train on your own signal, and an algorithm or heuristic with a fast exact score to B4 Evolutionary search. Improving your own system with coding agents is the separate B5 Organisational loop.YesYesNoNoCan the result be checked automatically?Does the same kind of task repeat often?What needs to improve?Don't build a loop yet:add tests, humanreview, tracesUse within-task retriesand checks (reflectand retry)Instructionsor pipeline→B3 Prompts andprogramsKnowledge orprocedures→B2 Memory andskillsModel capability oncheckable tasks→B1 Train on yourown signalAn algorithm or heuristicwith a fast exact score→B4 EvolutionarysearchSeparate caseImproving your own system with coding agents → B5 Organisational loop

The tree asks three questions in order. Can the result be checked automatically? If not, do not build a loop yet. Add tests, structured human review and traces first; without a check, a loop optimises whatever is easiest to please, and Part III showed where that leads. Does the same kind of task repeat often? If not, the improvement has nothing to accumulate in: use retries and checks within the task, and make sure the check is real, because reflection without an outside signal can make answers worse. What needs to improve? Instructions or the pipeline point to B3, prompts and programs; knowledge or procedures to B2, memory and skills; model capability on checkable tasks to B1, training on your own signal; an algorithm or heuristic with a fast, exact score to B4, evolutionary search. Improving your own system with coding agents, the organisational loop, is drawn as a separate case.

Four refinements make the tree safer in use. First, try the organisational loop before any automated one. An engineer reading a week of failed traces with a coding agent will usually find the missing tool, the bad retry logic or the ambiguous instruction faster and more cheaply than any loop; the self-modifying agents in U4 spent thousands of dollars discovering exactly such plumbing. Second, treat the last question as an escalation order rather than a menu, because teams rarely know in advance whether a failure is about instructions or capability. Exhaust prompt and context optimisation first, then tested skills, and only then consider training. Third, if the check exists but is slow or expensive, such as a full integration suite or a human audit, rule out loops that need tens of thousands of rollouts and prefer the sample-efficient ones in B3. Fourth, add a gate for data: if the loop would learn from untrusted user input or from several customers' data, do not let it write automatically to shared memory or shared weights. Memory poisoning needs very little planted data, and mixing customers' data into one model is hard to undo.

Two cheap probes catch the most common mistake, which is building a learning loop to fix what is really a missing tool or an unclear prompt. Take fifty recent failures. First, sample the current model many times on each against your exact check. If it never succeeds, training on its own outputs has nothing to amplify; if it succeeds sometimes, the ability is already there and a cheaper method may surface it. Second, run one round of reflective prompt optimisation and a day of engineer-led fixes. If that closes most of the gap, cancel the heavy loop.

Are you ready?

A loop amplifies whatever infrastructure it sits on. If runs cannot be traced to versions, the archive is fiction; if there is no held-out set, the gate measures memorisation; if rollback takes a day, every bad promotion becomes an incident. The checklist below is the minimum before any of the Build chapters.

Readiness
  • Traces. Every run records inputs, steps, tool calls, cost, outcome and any human correction.
  • Versions. Every run is tied to the exact prompt, model, tool, memory and data versions it used, including the state of any memory store, not only the code.
  • Evaluation set. A held-out set the loop never sees, separate from the set it uses to choose between candidates, plus a regression set of things that must keep working.
  • Rollback. Any promoted change, including a memory snapshot, can be reverted in one step.
  • Owner. A named person approves promotions, reads the archive and answers for the loop.
  • Isolation. The improver cannot read the scoring code or held-out tests, and cannot write to the evaluator, its tests or its logs.
  • Budget. Hard limits on spend, rollouts and output length per round, with an automatic stop.
  • Expiry. A rule for when stored items, prompts and skills are retired.

The first five are the minimum for any loop; the last three are the ones teams most often discover only after an incident. The most commonly missing item in practice is a held-out set that is genuinely separate from the selection set: optimisers that choose and are judged on the same examples look good until the next month's data arrives.

What will it cost?

Cost of one improvement roundCost of one improvement round equals rollouts times cost per rollout times candidates kept in play. Worked examples, illustrative arithmetic unless stated: training on your own signal, 24,000 rollouts at $0.01 for one model is $240 plus training compute; memory and skills, 5 test runs at $0.01 for 200 candidate skills is $10 a cycle; prompts and programs, 200 rollouts at $0.01 for 10 candidate prompts is $20; a self-modifying agent costs about $22,000 per run for the Darwin Gödel Machine and about $7,000 for SICA, as reported; the organisational loop costs agent runs plus review hours per accepted change, which each team must measure.Cost of oneimprovementround=Rolloutsfull runs of theagent per round×Cost per rolloutmodel calls, tools,grading×Candidates in playversions you keep andevaluate side by sideWORKED EXAMPLESB1 · Train on your own signal24,000 rollouts × $0.01 × 1 model = $240, plus training computeillustrative arithmetic — use your own pricesB2 · Memory and skills5 test runs × $0.01 × 200 candidate skills = $10 a cycleillustrative arithmetic — use your own pricesB3 · Prompts and programs200 rollouts × $0.01 × 10 candidate prompts = $20illustrative arithmetic — use your own pricesB4 · Self-modifying agent≈ $22,000 per run (Darwin Gödel Machine); ≈ $7,000 (SICA)reported by the papersB5 · Organisational loopagent runs + review hours per accepted changemeasure your own

The cost of one improvement round is the number of rollouts, times the cost of each rollout, times the number of candidates kept in play. The worked rows are illustrative arithmetic, except the self-modifying agents, whose costs are as reported by their papers. Put your own prices in; the orders of magnitude are what matter. On these illustrative prices a prompt-optimisation round costs tens of dollars and a weight-training round hundreds plus training compute; the self-modifying agents' reported runs cost thousands. MASS, for comparison, reports about $5 of search cost for a whole prompt-and-topology optimisation.

The formula understates real budgets in three ways. The cost of a rollout includes running the check, not only the model calls: spinning up a sandbox, running an integration suite or paying for a human review often costs more than the tokens. Loops take several rounds, and some of them fail: self-training flattens after two or three rounds, and a share of self-modification trials end worse than they began. And the result depreciates: an optimised prompt or scaffold may stop working when the base model is upgraded, so its useful life ends at the next model change.

Our rules of thumb, which are judgements rather than measurements, follow from this. If the expected total cost of a loop exceeds a few days of an engineer's time working in the organisational loop, and the target is neither a hot path reused at great scale nor a stream of free, trustworthy feedback, fix it by hand. And before running any loop, write down what a one-point gain on the task is worth over the next quarter. Most loops in Part II delivered gains of a few points to the low teens on their benchmarks; if a gain of that size would not repay the budget within a quarter, the loop is a research project, not an investment.

Our assessment

Most teams should not start with a self-improvement loop. They should start with traces, a held-out set and an engineer reading failures with a coding agent, then optimise prompts against a gate. Training and search loops are worth their cost only where the check is exact and cheap and the result is reused at scale.

Part V — Foundations every loop needs

Part III ended on one design principle: the improver must not be able to write to anything that judges it, and should not be able to read how it will be judged. Every Build chapter that follows is an application of that sentence. Before building any of them you need the same four pieces of plumbing: a record of what ran, a way of scoring it, a gate that decides, and a place to put the answer when the gate is wrong. This part builds those pieces once.

None of it is clever, and that is the point. The failures catalogued in Part III (the grader that was patched, the log that claimed tests had passed, the detector whose markers were deleted) were not failures of intelligence in the improver. They were failures of plumbing: a scorer in the same directory as the thing being scored, a log the agent could write to. A loop built on ordinary engineering discipline in these four places will beat a clever loop built without it.

The reference architecture

Reference architecture for a self-improvement loopThe actor writes to a trace store. The evaluator, an isolated process with hidden checks that the improver cannot write to, scores the traces. The improver proposes a change, the sandbox tests it, and the gate checks it is better with no regressions. A passing version is promoted to the actor, and every candidate goes to the archive of versions, parents, diffs and scores. Human approval feeds the gate for prompt, tool, code and evaluator changes. Tool names beside the boxes are examples only.the improver cannot write herepromote new versionevery candidatesign-offActorproduction agentTrace storeruns, costs, correctionsEvaluatorisolated process,hidden checksImproverproposes a changeSandboxtests the candidatein isolationGatebetter + no regressionsArchiveversions, parents,diffs, scoresHuman approvalprompt, tool, code,evaluator changese.g. OpenTelemetry · Phoenixe.g. Inspect · your testse.g. DSPy · TRL · OpenEvolvee.g. git · object store

The figure shows eight parts. The actor is the production system doing real work. It writes everything it does to the trace store: runs, costs, corrections. The evaluator reads those traces and scores them. It sits inside the dashed boundary, an isolated process with hidden checks, and the improver has no write access to it. The improver reads scores and failure summaries and proposes a change to a prompt, a skill, a tool, a piece of code or a training run. The sandbox runs the candidate in isolation. The gate promotes it only if it is better and nothing has regressed. The archive keeps every candidate, passing or not, with its parent, its diff and its scores. Human approval feeds the gate, and the figure lists what it covers: prompt, tool, code and, crucially, evaluator changes.

Read the arrows as much as the boxes. Scores flow out of the evaluator to the improver, but nothing flows back in. Promotion flows from the gate to the actor, and nowhere else. The improver never touches the evaluator, the gate or the archive's index; it only proposes. Changes to the evaluator itself take a separate path through a person, because an evaluator that the improver can edit is a score the improver can write.

The open-source tools plug in at four places, shown as examples beside the boxes. At the trace store, OpenTelemetry gives you a vendor-neutral format and Arize Phoenix a place to look at the result. Phoenix is licensed under the Elastic License 2.0, which allows self-hosting but is source-available rather than open source in the strict sense; check that against your policy. At the evaluator, Inspect, the evaluation framework from the UK AI Security Institute (MIT licence), supplies datasets, scorers and sandboxes, and your own tests supply the rest. At the improver sit the engines of Part VI: DSPy for prompts, TRL for training, OpenEvolve for code search. At the archive, plain git and an object store are enough. Notice what the tools do not provide: the boundary. No library makes the evaluator unreachable. That is a deployment decision, and the sandbox section below is about making it.

Traces and versioning

When a result changes, the first question is what changed between the two runs. Keep the evaluated artefacts identifiable so reviewers can attribute gains and reproduce the comparison.

A loop that cannot say which version produced a result cannot learn from it. When a score moves, you need to know whether the prompt changed, the model changed, a tool schema changed or the memory filled up with something new. The cheapest discipline is to hash each of the four and stamp every run with them.

Two cautions. First, the digest must cover what the model actually sees: the rendered system prompt, the serialised tool schemas and a snapshot of whatever memory is injected, not the file names. Second, export traces in a standard format. OpenTelemetry's conventions for generative-AI spans are still marked as in development rather than stable, so the recipe below keeps its own rsi.version.* attribute names and leaves the standard ones to your instrumentation library. When the conventions settle, you rename one prefix.

Stamp every run with a version
Time 20 minutes (illustrative)Needs opentelemetry-sdk; arize-phoenix-otel (optional, for the Phoenix UI)
  1. Compute a short digest for each thing the actor depends on, then one digest over all of them. This is the version id.
  2. Put the digests on every span, plus the task id and the cost, so the evaluator can group by version.
  3. Send the spans to Phoenix with register; any OpenTelemetry collector works the same way.
import hashlib, json
from phoenix.otel import register

def digest(obj) -> str:
    blob = json.dumps(obj, sort_keys=True, default=str).encode()
    return hashlib.sha256(blob).hexdigest()[:12]

# SYSTEM_PROMPT, MODEL_ID, TOOL_SCHEMAS and memory_snapshot() are yours
VERSION = {"prompt": digest(SYSTEM_PROMPT), "model": MODEL_ID,
           "tools": digest(TOOL_SCHEMAS), "memory": digest(memory_snapshot())}
VERSION["id"] = digest(VERSION)

tracer_provider = register(project_name="actor", auto_instrument=True)
tracer = tracer_provider.get_tracer("actor")

def run_task(task_id: str) -> str:
    with tracer.start_as_current_span("agent.run") as span:
        span.set_attributes({f"rsi.version.{k}": v for k, v in VERSION.items()})
        span.set_attribute("rsi.task_id", task_id)
        answer = my_agent(task_id)                      # your actor
        span.set_attribute("rsi.cost_usd", my_cost())   # your cost meter
        return answer
  1. Check it: run one task and read the span back. Every rsi.version.* key should be present, and changing one character of the prompt should change rsi.version.prompt and rsi.version.id but not the other digests.

The span code was checked against the OpenTelemetry SDK with an in-memory exporter; register takes the keyword arguments shown in arize-phoenix-otel 0.17.3 and returns a tracer provider. The actor must be unable to write to the trace store's schema or to rewrite old spans. Append-only storage is the right default, because a trace the actor can edit is evidence the actor can edit.

An evaluation harness

A good evaluator answers a question the candidate cannot settle by claiming success: did it meet the intended requirement under the same conditions as the baseline?

The harness is the loop's referee, and most of its design is about what it keeps from the improver. It needs four things.

A held-out set: tasks the improver never sees, used only by the gate. Every time a candidate is scored against the same held-out set, a little of that set leaks into the improver through the choices it makes, so rotate it, and keep a second, rarer set that is touched only at release. A regression set: tasks the current version already passes, which a candidate must still pass. This is the guard against the forgetting that Part III lists; a gain that breaks last month's behaviour is not a gain. Consistency: run each task several times and count a success only if every run succeeds, which is pass^k. For example, a system that scores 90% on one attempt but fails a quarter of its tasks at least once in five tries has been lucky, not reliable, and a loop that promotes on luck will promote noise. And hidden checks: assertions the agent never sees, such as that no file outside the working directory changed, that the answer was not copied from a cache, that the tests were actually run.

Inspect gives you the machinery. A Task takes a dataset, a solver and a scorer, and its epochs setting repeats each sample; the reducer named at_least_k counts a sample as correct only if at least k of the repeats are, so with k equal to the number of epochs it is exactly pass^k.

A held-out harness with pass^k and a hidden check
Time 30 minutes (illustrative)Needs inspect-ai; a JSONL file of held-out tasks, kept where the improver cannot read it
  1. Write the held-out tasks as JSON lines with input and target fields, and store them outside the improver's sandbox (see the next section).
  2. Write a scorer that applies the visible check and the hidden one together.
  3. Reduce the epochs two ways: the mean, which is the headline, and at_least_k, which is pass^k.
from inspect_ai import Task, eval, Epochs
from inspect_ai.dataset import json_dataset
from inspect_ai.scorer import scorer, Score, Target, accuracy, stderr, CORRECT, INCORRECT
from inspect_ai.solver import generate, TaskState

@scorer(metrics=[accuracy(), stderr()])
def hidden_check():
    async def score(state: TaskState, target: Target) -> Score:
        answer = state.output.completion.strip()
        ok = answer == target.text and my_hidden_assertion(state)   # never shown to the agent
        return Score(value=CORRECT if ok else INCORRECT, answer=answer)
    return score

def heldout_task(path: str, k: int = 5) -> Task:
    return Task(dataset=json_dataset(path), solver=generate(), scorer=hidden_check(),
                epochs=Epochs(k, ["mean", f"at_least_{k}"]))

# the candidate's solver or model goes here; the evaluator process owns this call
logs = eval(heldout_task("/srv/eval/heldout.jsonl"), model="provider/model", log_dir="/srv/eval/logs")
for s in logs[0].results.scores:
    print(s.reducer, {k: m.value for k, m in s.metrics.items()})
  1. Run the same file against the regression set with at_least_k only, and require it to equal the current version's score task by task.
  2. Check it: with Inspect's mockllm/model standing in for the model, the run returns two score entries, one with reducer mean and one with at_least_5. The second can never exceed the first.

The snippet was executed against inspect-ai 0.3.288 with the mock model. Two cautions apply. A hidden assertion is only hidden if the agent cannot read the scorer's source, so my_hidden_assertion belongs in the evaluator's own package, not in the repository the improver edits. And a held-out set of twenty tasks cannot tell a 3-point gain from noise; with an estimate like the standard error the scorer already reports, set the gate's margin from that, not from hope.

Gate, archive and rollback

Imagine finding a new version that is faster on average but breaks a customer's essential task. The release gate exists for exactly that case: an average improvement cannot cancel a required safety or correctness regression.

The gate is a few lines of code with one job: refuse. It promotes a candidate only if the candidate beats the live version on the held-out set by more than the noise, does not do worse on any regression task, and is no less consistent. Missing any of the three means no promotion, however good the headline looks. Most of the value is in the third word of that sentence, any: a candidate that is better on average and worse on the one task that matters to a customer should lose.

The archive is the loop's memory of itself. Every candidate is written down, passing or failing, with its parent, its diff and its scores. That has three uses. It is the rollback path. It is the audit trail when something odd reaches production. And it is training material for the improver, because failed candidates tell a search what not to try. The research systems in Part II that keep an archive of variants, such as the Darwin Gödel Machine, do so for the same reason.

Rollback should be one step: move a pointer from the live version to its parent. That only works if the live version is a pointer rather than a pile of edited files, and if the actor reads its version from one place.

A gate, an archive and a one-step revert
Time 30 minutes (illustrative)Needs Python 3.10+; scores from the harness above
  1. Store each candidate as a JSON record: id, parent id, unified diff, scores, timestamp.
  2. Compare scores in a gate function that can only return yes or no.
  3. Make promotion and rollback the only writers of the live pointer.
import difflib, json, time
from pathlib import Path

ARCHIVE = Path("archive"); ARCHIVE.mkdir(exist_ok=True)
LIVE = Path("live_version.txt")           # the one file the actor reads to learn its version

def record(version_id, parent, old, new, scores):
    diff = "".join(difflib.unified_diff(old.splitlines(True), new.splitlines(True), "parent", version_id))
    (ARCHIVE / f"{version_id}.json").write_text(json.dumps(
        {"id": version_id, "parent": parent, "diff": diff, "scores": scores, "ts": time.time()}))

def passes_gate(cand: dict, live: dict, margin: float = 0.02) -> bool:
    better = cand["heldout"] >= live["heldout"] + margin       # set the margin from your noise
    no_regression = all(cand["regression"][t] >= live["regression"][t] for t in live["regression"])
    return better and no_regression and cand["pass_k"] >= live["pass_k"]

def promote(version_id: str) -> None:
    LIVE.write_text(version_id)

def rollback() -> str:
    parent = json.loads((ARCHIVE / f"{LIVE.read_text()}.json").read_text())["parent"]
    LIVE.write_text(parent)
    return parent
  1. After every harness run, call record first, then passes_gate, then promote only on a yes. Record failures too.
  2. Check it: promote a version, call rollback(), and confirm that live_version.txt now holds the parent id and that both archive records still exist.

This code ran as written with a two-version example (version v1 promoted over v0, then rolled back to v0). It is deliberately simple. In production the archive should live in git or an object store with write access held by the gate alone, and promotion should require a person for anything that changes tools, code or the evaluator, as the figure shows. The improver gets read access to its own archive so that it can learn from it, and no write access to anything else.

Sandbox and isolation boundaries

The figure draws the boundaries as three zones inside production.

Isolation boundaries for a self-improvement loopProduction holds real users, real data and credentials. Inside it sit two separate zones: an improvement sandbox with no production credentials, no network unless needed, and time and cost limits, and an evaluation enclave that is read-only to the improver, with hidden checks and gold labels. Allowed flows: traces are copied into the sandbox, run outputs go to the enclave, scores come out, and promoted versions return to production through the gate. Forbidden flows: the improver editing evaluator code, and the sandbox reaching production data.Production (real users, real data, credentials)Live agentserves real usersProduction datareal records and credentialsImprovement sandboxno production credentials, no networkunless needed, time and cost limitsImproverproposes changesCandidate runsthe new version, tried outEvaluation enclaveread-only to the improver,hidden checks, gold labelsEvaluator codethe scoring logicHidden checksgold labels, held-out casestraces copied ingate: promoterun outputs inscores outno write access✕✕no path to live dataallowed flowforbidden flow (✕)enclave boundary

Production holds real users, real data and credentials. Nothing the improver does should be able to reach it. The improvement sandbox holds the improver and the candidate runs. It has no production credentials, no network unless the task truly needs one, and hard limits on time and cost. Traces are copied in. The candidate's outputs go out of it, and nothing else does; the one arrow back to production is the gate's promotion. The evaluation enclave holds the evaluator code, the hidden checks and the gold labels. The improver can see scores come out of it. It cannot write to it, and it has no path to production data from it either; the figure marks both forbidden flows with a cross.

Why so strict? Because the evidence says the temptation is real. METR found an early o3 hacking its graders in 39 of 128 research-task runs and in 8 of 1,087 elsewhere, and suggested that seeing the full scoring function may explain the gap. A Darwin Gödel Machine agent removed the markers its own hallucination detector relied on. A rule in the prompt saying "do not touch the tests" is a request. A file system that does not contain the tests is a fact.

In practice the enclave is a separate process under a separate user or container, with the held-out data mounted read-only and the improver's container given a one-way channel for results. Inspect can run tasks inside Docker sandboxes, and that is the right place for the candidate; the evaluator belongs outside it. If you take one step from this section, take that one.

Evaluator integrity checklist

Run through this before you let any loop promote anything. A single "no" is a reason to stop, not a reason to add monitoring.

Evaluator integrity
  • The improver has no write access to the evaluator code, the scoring configuration or the gate.
  • The improver cannot read the held-out tests, the hidden checks or the gold labels, in any file, environment variable or log.
  • The logs the evaluator reads are written by the harness, not by the agent, and the agent cannot append to them.
  • The memory the actor reads is vetted before use and cannot be edited by the candidate under test.
  • The evaluator runs in a separate process or container, as a separate user, with its own credentials.
  • The sandbox has no production credentials and no network route to production data.
  • The held-out set is rotated, and a second set is touched only at release.
  • The held-out data is kept out of public repositories and training corpora, and carries canary strings so leakage can be detected.
  • Every promotion runs the regression set, and a drop on any task blocks it.
  • The gate's margin is set from measured noise, with pass^k reported beside the mean.
  • Every candidate, passing or failing, is archived with its parent, diff and scores.
  • Changes to the evaluator, the held-out set or the gate itself need a named person to approve them, and are never proposed by the improver.
  • Rollback is a single pointer move, and someone has tried it this quarter.

The checklist is the practical form of the thesis. Gains in this literature are as large and as lasting as the check is exact and out of reach. The rest of the guide builds loops of different kinds, but each of them, however it generates candidates, is only as trustworthy as the wall these twelve lines describe.

Part VI — Build each loop

Each chapter below builds one of the five loops from Part II, and mirrors the Understand chapter with the same number. All five follow the same template: when to use the loop, its architecture, the tools that implement it today, a recipe with code, how to evaluate and gate it, what it costs to run, how it fails, and a checklist. The tools and their status were verified against their repositories and package indexes in November 2026; the code matches each library's current interface, but it is a starting point, not production code. Every cost figure is illustrative unless it is attributed to a paper.

B1. Train on your own signal

Mirrors U1 · Models that train themselves in the Understand half.

When to use it

When to use it. Use this loop when three things are true. The task has an answer a program can check: SQL that returns the right rows, code that passes tests, a calculation that balances. You can generate many attempts cheaply from a model whose weights you control. And you have a measurable gap between what the model gets right in one attempt and what it gets right in several. That gap is the raw material: the loop converts the second number into the first. If you cannot name the checking program, stop here and read U1 again. A model that grades its own prose will improve its score, not its work.

Do not reach for it when prompting would do. If the failure is a missing instruction, B3 is an afternoon's work. Training earns its cost only when you need the behaviour baked into a smaller or cheaper model, or when instructions alone have stopped helping.

Architecture

B1 · Train on your own signalB1 · Train on your own signal: 1. Generate (k samples per task); 2. Check (program, not model); 3. Filter (keep passes, dedupe); 4. Train (fine-tune on keepers); 5. Evaluate (held-out tasks). Then back to step 1: Next round starts from the evaluated checkpoint, only if the gate passes.B1 · Train on your own signalGeneratek samples pertaskCheckprogram, notmodelFilterkeep passes,dedupeTrainfine-tune onkeepersEvaluateheld-out tasks↺ Next round starts from the evaluated checkpoint, only if the gate passes
The check is the only step that injects information. Everything else is bookkeeping around it.

The loop is the expert-iteration and rejection-sampling family from U1, reduced to its parts. The model generates; the check, which sits outside the model, decides what counts; the survivors become training data; a held-out set, which the loop never trains on, decides whether the round was worth keeping. Two design choices carry most of the weight. First, the checker must be exact and must not share a failure mode with the generator: a database executing a query is such a checker, a second sample from the same model is not. Second, the held-out tasks are fixed before round one and never leak into generation, or the evaluation measures memory.

Tools

Three open-source trainers cover the weight-update half of the loop. None supplies the check; that is yours.

TRLActive
Trainers
Hugging Face's post-training library. SFTTrainer for filter-and-retrain; GRPOTrainer for RL with your own reward function. Version 1.17.1 on PyPI at 30 October 2026.
Licence: Apache-2.0Implements: SFT; GRPO (arXiv 2402.03300)
verlActive
Distributed RL
Config-driven distributed RL on Ray, with FSDP or Megatron for training and vLLM or SGLang for rollouts. The old volcengine/verl address redirects here. Version 0.9.1.
Licence: Apache-2.0Implements: HybridFlow (arXiv 2409.19256); PPO, GRPO
OpenRLHFActive
Distributed RL
Ray plus vLLM framework for RLHF and agentic RL, driven by its own command-line scripts. We did not verify its PyPI version or a training command.
Licence: Apache-2.0Implements: arXiv 2405.11143

The choice is mostly about scale and about whether you want RL at all. Rejection-sampling fine-tuning needs only SFTTrainer and runs on one GPU for a small model. GRPO, which scores groups of samples with your reward function and updates on the differences, needs rollouts generated during training, and that is where the distributed frameworks earn their complexity. Start with the simple one. Our view, not a measured result: on a task the model can already half-solve, a few clean rounds of filtering are the better first move, and RL is harder to debug.

Recipe

Rejection-sampling fine-tune of a SQL agent on checked answers
Time half a day, plus GPU timeNeeds a database with tasks that have known answers, a model you can sample from and fine-tune, trl 1.17.1

The task: turn a question into one SQL query. The check: run the query against a SQLite copy of the database and compare its result with the known answer. Tasks are split once, before anything is generated, into training tasks and held-out tasks.

1. Freeze the split and the checker. Compare result sets as sorted lists of rows so column order and row order do not matter, and open the database read-only so a generated DROP TABLE cannot do harm.

import sqlite3

def run(db_path: str, sql: str):
    con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
    con.execute("PRAGMA query_only = ON")
    try:
        return sorted(map(tuple, con.execute(sql).fetchall()), key=repr)
    except sqlite3.Error:
        return None          # a query that errors never passes
    finally:
        con.close()

def passes(db_path, sql, gold_rows) -> bool:
    got = run(db_path, sql)
    return got is not None and got == sorted(map(tuple, gold_rows), key=repr)

2. Generate and filter. Sample several candidates per training task, keep the distinct ones that pass, and cap how many you keep per task so easy tasks do not dominate.

def collect(tasks, sample_sql, k=8, keep_per_task=2):
    rows = []
    for t in tasks:                       # t: question, schema, db_path, gold_rows
        prompt = f"Schema:\n{t['schema']}\n\nQuestion: {t['question']}\nSQL:"
        cands = {sample_sql(prompt) for _ in range(k)}   # my sampler: your model
        good = [c for c in cands if passes(t["db_path"], c, t["gold_rows"])]
        for sql in good[:keep_per_task]:
            rows.append({"prompt": [{"role": "user", "content": prompt}],
                         "completion": [{"role": "assistant", "content": sql}]})
    return rows

3. Train. The prompt and completion columns make SFTTrainer compute the loss on the completion only; we checked that in 1.17.1 the data format is accepted and that completion_only_loss defaults to None, meaning it is switched on automatically for this format. Train from the base model each round, on the pooled data so far, not from the previous round's checkpoint on its own output alone. That is the accumulate-don't-replace lesson from the model-collapse literature in U1.

from datasets import Dataset
from trl import SFTConfig, SFTTrainer

def train(rows, base_model, out_dir):
    cfg = SFTConfig(output_dir=out_dir, num_train_epochs=2, learning_rate=1e-5,
                    per_device_train_batch_size=4, gradient_accumulation_steps=4,
                    max_length=2048, report_to="none")
    trainer = SFTTrainer(model=base_model, args=cfg,
                         train_dataset=Dataset.from_list(rows))
    trainer.train()
    trainer.save_model(out_dir)
    return out_dir

4. Evaluate on held-out tasks and gate. Sample once per held-out task with the same decoding settings for the base and the new model, and compare execution accuracy. Promote the checkpoint only if it beats the incumbent by more than the noise you measured on a repeated base run (see the gate below).

def accuracy(tasks, sample_sql) -> float:
    ok = 0
    for t in tasks:
        prompt = f"Schema:\n{t['schema']}\n\nQuestion: {t['question']}\nSQL:"
        ok += passes(t["db_path"], sample_sql(prompt), t["gold_rows"])
    return ok / len(tasks)

Repeat from step 2 using the promoted model as the sampler. Stop at the first round whose gain falls inside the noise: ReST-EM flattened after two or three rounds, and there is no reason to expect your task to be kinder.

To move from filtering to GRPO, keep the checker and change its role. TRL's GRPOTrainer takes reward functions as plain callables that receive a batch of completions and return one score per completion, so passes becomes a reward returning a list of 1.0s and 0.0s, with the held-out evaluation unchanged. TRL's built-in accuracy_reward shows the shape for maths answers and needs the trl[math_verify] extra. We did not run a GRPO job for this chapter, so treat the swap as a sketch.

Evaluation and gate

Three numbers decide each round. Held-out execution accuracy is the headline, measured on tasks the loop has never generated from or trained on. Pass@1 versus pass@k on the same held-out tasks tells you what kind of gain you are getting: Yue and colleagues found that RL improves one-attempt accuracy while the base model can match it given many attempts. If pass@1 rises and pass@8 does not, you have sharpened the model, which is still useful, but do not call it new ability. Noise comes from running the unmodified base model through the evaluation several times with different seeds; a gain smaller than that spread is not a gain.

The gate is a rule written down before the first round: promote a checkpoint only if held-out accuracy beats the incumbent by more than the measured noise, and a regression set of tasks unrelated to SQL generation shows no drop beyond tolerance. The second condition is there because fine-tuning on narrow data is a reliable way to lose general behaviour. The checker, the split and the gate thresholds are frozen files that the loop cannot write to, for the reason Part III gives: a check the loop can reach is a check it will game.

Cost and operations

The bill has three parts, and generation usually dominates. Illustrative arithmetic, not measured: with 2,000 training tasks and eight samples each, a round makes 16,000 generations; with an average of 100 output tokens, that is 1.6 million tokens, minutes on a rented GPU with a batched inference server for a small open model, and a real bill if you sample from a hosted frontier model. Execution checks against SQLite cost almost nothing. Training on a few thousand short examples is cheap beside generation.

Operationally, treat each round as a build artefact. Store the task split, the sampler and decoding settings, the raw generations, the pass/fail labels, the filtered set, the checkpoint and the evaluation result together, keyed by round number, so any promoted model can be reproduced and any bad one traced to its data. Keep the previous checkpoint serving until the new one passes the gate, and keep rollback one config change away.

Failure drills

The checker is too weak
What happens
Training data fills with lucky or degenerate queries that happen to match. Accuracy climbs on the training distribution and does not transfer.
Real case
Queries that return an empty set pass tasks whose answer is empty.
Guard
Audit 50 passing rows by hand each round; add negative tasks.
Held-out contamination
What happens
The held-out score rises faster than the real skill. Detect it by testing on a freshly written set the loop has never touched.
Real case
A paraphrase of a held-out question appears among the training tasks.
Guard
Split by schema or template, not by row; dedupe across the split.
Sharpening mistaken for learning
What happens
The model has concentrated on what it could already do. Detect it by the flat pass@k curve, and set expectations accordingly.
Real case
Pass@1 rises while pass@8 stays flat across rounds.
Guard
Report both numbers every round; stop when pass@1 gains stall.
Before the first round
  • The checker is a program, exact on the cases you care about, and the model cannot edit it.
  • The held-out split is fixed before generation and shares no schema or template with training tasks.
  • Noise is measured: the base model is evaluated repeatedly and the spread is written down.
  • The gate (accuracy margin, regression set, rollback) is a file the loop cannot write.
  • Each round trains from the base model on pooled data, not from a model's own latest output alone.
  • Pass@1 and pass@k are both reported, and a human has read a sample of passing training rows.
  • Every round's data, labels and checkpoint are stored and reproducible.

B2. Give the agent memory and skills

Mirrors U2 · What agents keep in the Understand half.

When to use it

When to use it. Use memory when the same kinds of task recur and the agent keeps rediscovering the same answer: a refund rule, a table's quirks, a deploy procedure. Do not use it for one-off work, or where a wrong note is costly and nothing can check it. The U2 claim sets the design: memory compounds only when what is stored is checked before it is written and pruned after. So the build is not a store. It is a gate on the way in and a schedule on the way out.

Architecture

B2 · Memory and skillsB2 · Memory and skills: 1. Write (candidate only); 2. Verify (test or source); 3. Store (with provenance); 4. Retrieve (scoped, ranked); 5. Expire (age and removal). Then back to step 1: Removal test: does dropping it change task success?.B2 · Memory and skillsWritecandidate onlyVerifytest or sourceStorewith provenanceRetrievescoped, rankedExpireage and removal↺ Removal test: does dropping it change task success?
Every write is a candidate, not a fact. Only the verify step can promote it; only expiry and removal tests can retire it.

Two kinds of entry need different gates. A skill is executable (a function, a script, a query template), so its check is a test that runs. A fact (a customer's plan, a policy clause) cannot be run, so its check is a comparison with the source of record, and it carries an expiry date because the source will change. Facts without a source to compare against should not be stored as facts at all; keep them as clearly labelled hints, or leave them out.

The second figure shows the maintenance side, which is the half most builds omit.

The nightly hygiene jobThe nightly hygiene job: 1. Expire (past its date); 2. Replay (fixed task set); 3. Remove one (re-score); 4. Retire (no loss, gone). Then back to step 1: Retired entries are archived, not destroyed, so a mistaken removal can be reversed..The nightly hygiene jobExpirepast its dateReplayfixed task setRemove onere-scoreRetireno loss, gone↺ Retired entries are archived, not destroyed, so a mistaken removal can be reversed.
The same fixed tasks score the store with and without each entry. An entry that costs nothing to lose is deleted.

Tools

Four libraries cover most agent-memory needs. They differ mainly in what a unit of memory is. None of them supplies the gate in the first figure; that you write yourself, which is what the recipe below does.

LettaActive
Self-edited memory blocks
Stateful agents that edit their own memory blocks. Renamed or moved: the letta repository now says current source lives in letta-ai/letta-code, with the older API server on an archive branch. We have not verified the older Python server API, so do not build on it.
Licence: Apache-2.0Implements: MemGPT (arXiv 2310.08560)
Mem0Active
Extracted long-term memories
Extracts, stores and searches memories per user. Its hosted API accepts an expiration_date on new memories; confirm that the open-source Memory.add does too, and check its delete method, before relying on either in the hygiene job. Its published gains are vendor-reported.
Licence: Apache-2.0Implements: Mem0 (arXiv 2504.19413)
Temporal knowledge graph
Facts carry time, so a newer fact supersedes an older one. The right shape for facts that change. Needs a graph database and, by default, an OpenAI key. Pre-1.0 (0.31.x).
Licence: Apache-2.0Implements: Zep (arXiv 2501.13956)
LangMemActive
Memory tools for LangGraph
Memory-management and search tools plus a background manager, for LangGraph agents. Active but slow to release and still 0.0.x; pin the version.
Licence: MITImplements: no paper
Skill foldersUnverified
Instructions and scripts on disk
A skill is a folder holding a SKILL.md of instructions plus optional scripts, loaded when relevant; the format is described at agentskills.io. The example repository says many of its skills are Apache-2.0 but does not state terms for every folder, so check each skill's licence and the repository's third-party notices before copying.
Licence: mixedImplements: Voyager-style skill libraries

Recipe

A verified skill library and a memory hygiene job
Time about 1 hourNeeds Python 3.11, sqlite3, a fixed set of 20+ recurring tasks with an automatic pass/fail check, a sandbox for running saved code

Step 1. Create the library and the gate. A skill is written only if its code passes its tests. The snippet uses exec, so run it inside the same sandbox you use for any model-written code, never in your main process.

import sqlite3, time
db = sqlite3.connect("skills.db")
db.execute("""create table if not exists skill(name text primary key, code text,
              source text, verified_at real, ttl_days int, active int default 1)""")

def try_save(name, code, tests, source, ttl_days=90):
    """Save a skill only if its code passes every test."""
    scope = {}
    try:
        exec(code, scope)                                    # sandbox this
        assert all(scope[name](*args) == want for args, want in tests)
    except Exception:
        return False                                         # never written
    db.execute("insert or replace into skill values (?,?,?,?,?,1)",
               (name, code, source, time.time(), ttl_days))
    db.commit()
    return True

def active():
    return [r[0] for r in db.execute("select name from skill where active=1")]

Step 2. Write the hygiene job. It expires entries past their date, then removes each remaining skill in turn and re-scores the fixed tasks. run_agent(task, skills) is your own function: it runs the agent with only those skills available and returns 1 if the task's checker passes. Schedule the job nightly or weekly.

from statistics import mean

def pass_rate(tasks, skills, run_agent):
    return mean(run_agent(t, skills) for t in tasks)

def hygiene(tasks, run_agent, min_gain=0.0):
    now = time.time()
    for name, ttl, seen in db.execute(
            "select name, ttl_days, verified_at from skill where active=1").fetchall():
        if now - seen > ttl * 86400:                         # 1. expire
            db.execute("update skill set active=0 where name=?", (name,))
    base = pass_rate(tasks, active(), run_agent)
    for name in active():                                    # 2. removal test
        without = pass_rate(tasks, [s for s in active() if s != name], run_agent)
        if without >= base - min_gain:                       # losing it costs nothing
            db.execute("update skill set active=0 where name=?", (name,))
    db.commit()

Step 3. Try it with a stub agent before connecting a real one. With a stub agent, the code above should refuse a skill whose test fails, retire a skill past its expiry date, and retire a skill whose removal leaves the pass rate unchanged. Consider a small margin before retiring on a tie, so that noise does not delete a useful skill.

Step 4. For prose facts, keep the same shape. With Mem0, pass expiration_date to memory.add(...) and call memory.delete(memory_id) from the hygiene job; before add, compare the candidate with the source of record and refuse if they disagree.

Evaluation and gate

Report three numbers each month on the same fixed tasks: pass rate with the store, pass rate with an empty store, and store size. The store earns its place only if the first beats the second by more than the run-to-run noise you measure by repeating the empty-store run. The size should be flat or falling once the job runs. The gate to ship is that every entry has a source, a test or an expiry date, and that the removal job has run once end to end. A rising pass rate alongside a rising size, with no removals, is the keep-everything lane from the U2 worked example and should be treated as unproven.

Cost and operations

The write gate costs one test run per candidate, which is cheap. The removal test is the expensive part: it needs one pass over the fixed tasks for each active entry, plus a baseline. As an illustration only, 40 skills and 30 tasks is 1,230 agent runs per cycle; at a hypothetical $0.02 a run that is about $25. That is why the job runs on a schedule, not on every write, and why a small, well-chosen task set beats a large one. Keep the job's inputs frozen between runs, log every retirement with the reason, and archive rather than delete, so an error in the task set cannot silently destroy a good skill.

Failure drills

Memory poisoning
What happens
The note enters the store because the agent wrote it, then is retrieved and treated as ground truth. Drill: inject a false rule and confirm the gate refuses it.
Real case
A user message plants a false refund rule that is later recalled as policy.
Guard
Treat every write as untrusted; compare with the source; record provenance.
Stale facts
What happens
The store was right when written and is wrong now. Drill: change the source and confirm the entry retires within one cycle.
Real case
The refund window changes; the old note still outranks the new one.
Guard
Expiry dates, supersession, and a re-check against the source.
Store bloat
What happens
Quality falls as the store grows. Drill: add 200 duplicates and confirm pass rate and latency recover after the job runs.
Real case
Retrieval returns twelve near-duplicates and crowds out the one that matters.
Guard
Removal tests, a size budget, and de-duplication on write.
B2 checklist
  • Every entry is a candidate until a test or a source comparison promotes it.
  • Skills run in a sandbox; the write gate refuses code that fails its tests.
  • Every entry stores its source, the date verified and an expiry date.
  • Stored skills are re-run against their tests on a schedule, not only when saved, so a skill broken by a changed API is caught before it is used.
  • A new entry that contradicts an existing one is held for review rather than stored beside it.
  • A fixed task set with an automatic checker exists, and an empty-store baseline is measured.
  • The removal job has run end to end, and retired entries are archived with a reason.
  • Store size is reported beside pass rate, and is flat or falling.
  • Library versions are pinned (Mem0 2.2.1, Graphiti 0.31.x, LangMem 0.0.30), and Letta is built on the current letta-code line.
  • The poisoning, stale-fact and bloat drills have each been run once.

B3. Optimise prompts and programs

Mirrors U3 · Rewriting the instructions in the Understand half.

When to use it

Reach for an optimiser when you already have a pipeline of model calls that mostly works, a way to score its output, and a few dozen to a few hundred labelled cases. Those three things are the whole entry fee. Without a metric there is nothing to optimise; without labelled cases there is nothing to score against. If your pipeline fails because a tool is missing or the data is wrong, no rewording will help, so fix that first.

The case for starting here is the one made in U3: search over text runs on ordinary model calls, its outputs are files you can read, diff and roll back, and the published evidence for reflective optimisation is the strongest in the literature. The case against over-reaching is equally stated there. Gains follow an inverted U, so the sensible scope is the instructions and examples of a fixed program, not the design of the program itself.

Architecture

B3 · Optimise prompts and programsB3 · Optimise prompts and programs: 1. Program (typed stages); 2. Metric (score + feedback); 3. Optimiser (small edits); 4. Held-out (never seen); 5. Gate (promote or revert). Then back to step 1: Re-run when the model, tools or task mix change.B3 · Optimise prompts and programsProgramtyped stagesMetricscore + feedbackOptimisersmall editsHeld-outnever seenGatepromote or revert↺ Re-run when the model, tools or task mix change
The optimiser sees the training and validation cases and the metric's feedback. It never sees the held-out set; only the gate does.

Each box has one job. The program is a small number of named stages, so an edit can be aimed at the stage that failed. The metric returns a score and, more usefully, a sentence saying why a case lost marks; reflective optimisers read that sentence. The optimiser proposes local edits and keeps those that score better. The held-out set is the protected step: if the optimiser can see it, even indirectly through repeated peeking, it stops being a test. The gate is a plain comparison against the current production version, with a human or a script deciding whether to promote.

Tools

DSPyActive
Programs and optimisers
Framework for model programs. Ships MIPROv2 (instructions plus examples) and GEPA (reflective evolution of instructions). PyPI 3.4.1.
Licence: MITImplements: DSPy (2310.03714), MIPROv2 (2406.11695), GEPA (2507.19457)
TextGradResearch code
Textual feedback
Passes written feedback backwards through a system, like a gradient. Stale: not archived, but no release since March 2025.
Licence: MITImplements: TextGrad (2406.07496)
Trace (OptoPrime)Research code
Traced Python programs
Records a Python program as a graph and lets a model edit its trainable functions. Low activity; PyPI name trace-opt.
Licence: MITImplements: Trace (2406.16218)

For most teams the choice is DSPy: it has the program abstraction, two maintained optimisers and a releases cadence. GEPA also exists as a standalone package (gepa, 0.x API) if you want the algorithm without the framework. TextGrad and Trace are worth reading for their ideas but we would not build a production loop on their current maintenance record.

Recipe

Optimise a 3-step pipeline with GEPA, then check transfer to a second model
Time About 1 hour of set-up, then the optimiser's runNeeds dspy 3.4.1, two models you can call, 100+ labelled cases

The scenario is illustrative: triaging support tickets in three stages (extract the facts, classify the issue, draft a reply). The code is checked against DSPy 3.4.1's signatures but has not been run against a live model here; load_tasks() and the model names are placeholders.

1. Define the program, one named predictor per stage.

import dspy

class Triage(dspy.Module):
    def __init__(self):
        super().__init__()
        self.extract  = dspy.ChainOfThought("ticket -> order_id, issue")
        self.classify = dspy.ChainOfThought("issue -> category")
        self.reply    = dspy.ChainOfThought("ticket, category -> reply")

    def forward(self, ticket):
        e = self.extract(ticket=ticket)
        c = self.classify(issue=e.issue)
        return self.reply(ticket=ticket, category=c.category)

2. Write a metric that returns feedback, not just a number. GEPA calls it with (gold, pred, trace, pred_name, pred_trace) and accepts a float or a dspy.Prediction with score and feedback.

def my_metric(gold, pred, trace=None, pred_name=None, pred_trace=None):
    right = gold.category in pred.reply.lower()
    polite = "sorry" in pred.reply.lower() or not gold.upset
    score = 0.7 * right + 0.3 * polite
    why = []
    if not right:  why.append(f"Reply never names the category '{gold.category}'.")
    if not polite: why.append("Customer was upset; reply has no apology.")
    return dspy.Prediction(score=score, feedback=" ".join(why) or "Correct.")

3. Split the data three ways before anything runs. Train and validation go to the optimiser. The held-out set goes to nobody until the gate.

tasks = load_tasks()                       # list[dspy.Example], with .with_inputs("ticket")
train, val, held_out = tasks[:60], tasks[60:90], tasks[90:]

4. Optimise on model A, with a strong reflection model. Exactly one budget argument is allowed: auto ("light", "medium", "heavy"), max_full_evals or max_metric_calls.

model_a = dspy.LM("provider/model-a")
dspy.configure(lm=model_a)

gepa = dspy.GEPA(metric=my_metric, auto="light",
                 reflection_lm=dspy.LM("provider/strong-model", temperature=1.0, max_tokens=16000))
optimised = gepa.compile(Triage(), trainset=train, valset=val)
optimised.save("triage_gepa.json")        # a reviewable artefact; commit it

5. Gate on the held-out set, then test transfer. Score baseline and optimised on model A, then swap in model B without re-optimising.

def scored(program, lm):
    with dspy.context(lm=lm):
        ev = dspy.Evaluate(devset=held_out, num_threads=8, metric=lambda g, p, trace=None: my_metric(g, p).score)
        return ev(program).score             # 0-100

model_b = dspy.LM("provider/model-b")
for name, lm in [("A", model_a), ("B", model_b)]:
    print(name, "baseline", scored(Triage(), lm), "optimised", scored(optimised, lm))

6. Decide. Promote only if the optimised program beats the baseline on held-out by more than the noise between two runs of the same program. If it wins on A but loses its gain on B, you have measured how much of the improvement was phrasing tuned to A; re-run the optimiser on B rather than shipping the A artefact.

Evaluation and gate

Three numbers decide promotion: baseline versus optimised on the held-out set on the model you will actually run; the same pair on a second model; and the gap between validation and held-out for the optimised program. A large gap means the optimiser has learned the validation cases. OPRO's authors measured training accuracy 5 to 20 points above test, which is the size of gap to expect and to be suspicious of.

Measure noise before you trust a difference: score the unmodified program on the held-out set twice. If those two scores differ by three points, a three-point gain is nothing. Rotate part of the held-out set every few cycles, because a set the team keeps looking at slowly turns into a training set.

Cost and operations

Search runs on ordinary model calls: many cheap task-model calls plus a smaller number of calls to the stronger reflection model. The literature reports single-digit-dollar search bills for some methods (MASS, for example, about $5), but your bill scales with program size, case count and the budget you choose, so run the light setting first and read the spend before escalating. Illustrative: if the light run costs the price of a lunch, you can afford to re-run it at every model upgrade; if it costs a week's budget, you cannot, and the artefact will rot.

Operate it like a dependency. Keep the saved program in version control, record the model, DSPy version, seed and data snapshot beside it, and schedule a re-run whenever the model changes. The GEPA and DSPy optimiser classes are marked experimental in the library, so pin the version.

Failure drills

Overfitting to the train set
What happens
The prompt memorises quirks of the cases it was tuned on.
Real case
OPRO: training accuracy ran 5 to 20 points above test accuracy.
Guard
Held-out set the optimiser never sees; compare validation to held-out.
Prompt collapse from a full rewrite
What happens
One wholesale rewrite discards the edge-case rules that worked.
Real case
ACE: a rewrite collapsed an 18,282-token context to 122 tokens.
Guard
Local, additive edits; diff every candidate against the last good one.
Drift after a model upgrade
What happens
The optimised wording was tuned to the old model's habits.
Real case
Optimised prompts may not transfer when the base model changes; U3 found mixed evidence.
Guard
Re-run on every model change; gate on the new model's held-out score.

Run each drill once before relying on the loop. For overfitting, train on a deliberately small set and confirm the held-out gap shows it. For collapse, hand the optimiser a full-rewrite option and check that the diff review catches the shrinkage. For drift, point the saved program at a different model and confirm your gate, not a user, reports the loss.

B3 checklist
  • The program has named stages, and each stage can be edited on its own.
  • The metric returns written feedback as well as a score.
  • Train, validation and held-out sets are split before the first run; the held-out set is never passed to the optimiser.
  • Baseline noise is measured by scoring the unmodified program twice.
  • Promotion needs a held-out win larger than that noise, on the model you will actually run.
  • Transfer to a second model is measured, not assumed.
  • The optimised program is saved as a text artefact with model, library version, seed and data snapshot recorded beside it.
  • A re-run is scheduled for every model change, with its cost budgeted in advance.
  • Part of the held-out set is rotated periodically.

B4. Evolutionary search and self-modifying code

Mirrors U4 · Systems that rewrite themselves in the Understand half.

Most teams who read the U4 papers should build only the half that pays. The profitable design is program search: a model proposes variants of a small, external program, a fixed evaluator scores each one, and the best survive. The improver never touches the scorer, and that is where the strength comes from. The other half of U4, agents that edit their own scaffolds, has produced real gains only from weak starts, at thousands of dollars a run. We treat it as something to study in a sandbox, not something to run in production.

When to use it

Use evolutionary search when you have a small piece of code whose quality can be scored automatically and cheaply: a ranking heuristic, a scheduling rule, a routing threshold, a numerical kernel. Three conditions should hold. The score must be computed by code you wrote and trust, on data the candidate cannot see. One evaluation must cost seconds, not minutes, because a run needs hundreds of them. And the artefact must be small enough for a person to read the winning diff.

Do not use it where the score is a judgement call, where one evaluation needs a human, or where the thing being evolved is the agent that runs the search. That last case is the self-modifying family, and nothing in the evidence on this page supports running it outside a research sandbox.

Architecture

B4 · Evolutionary searchB4 · Evolutionary search: 1. Population (programs + scores); 2. Mutate (model proposes edit); 3. Sandbox (run untrusted code); 4. Hidden score (fixed evaluator); 5. Archive (keep stepping stones). Then back to step 1: Parents are sampled from the whole archive, not only the current best.B4 · Evolutionary searchPopulationprograms + scoresMutatemodel proposeseditSandboxrun untrustedcodeHidden scorefixed evaluatorArchivekeep steppingstones↺ Parents are sampled from the whole archive, not only the current best
The mutation step is the only place a model acts. The sandbox and the hidden score sit outside its reach.

Two choices in this loop come straight from U4. The archive keeps variants that look worse, because a weaker step can be the stepping stone to the best descendant. And the evaluator is a separate artefact: a different file, run by a different process, holding data the candidate has never been shown. If the improver can read or write the scorer, you have built the system that wrote a log claiming tests had passed when none had run.

Tools

OpenEvolveActive
Evolutionary search
Open-source evolutionary coding agent: island population, archive, your own evaluator file. PyPI 0.4.1; the repo moved from codelion/openevolve.
Licence: Apache-2.0Implements: AlphaEvolve
ShinkaEvolveActive
Evolutionary search
Sample-efficient program evolution with an island database. Still 0.0.x; the runner class was renamed in March 2026, so older tutorials break.
Licence: Apache-2.0Implements: arXiv 2509.19349
Darwin Gödel MachineResearch code
Self-modifying agent
Evolves a coding agent's own code with an archive, scored on benchmarks inside Docker. Needs paid keys; its README carries warnings about running model-written code.
Licence: Apache-2.0Implements: arXiv 2505.22954
ADASResearch code
Agent design search
A meta-agent programs new agentic systems in code. A set of scripts, dormant since January 2025; read it, do not depend on it.
Licence: Apache-2.0Implements: arXiv 2408.08435

The first two are libraries you can build on. The last two are scripts that accompany papers. They are worth reading for how they structure archives and evaluation, and not worth wiring into a product.

Recipe

Evolve a scoring heuristic against a hidden evaluator, with a budget
Time half a dayNeeds openevolve 0.4.1, an OpenAI-compatible endpoint, 200+ labelled examples (illustrative)

The task, which is illustrative: a support queue ranks tickets by a hand-written urgency score, and you want a better one. A small labelled set says which tickets a person later judged urgent. The model may rewrite the scoring function. It may never see the labels, the evaluator, or the held-out split.

1. Split the data three ways, and keep two thirds away from the search. Visible examples go in the prompt. Hidden labels go in a file outside the candidate's working directory. A final audit split is touched once, by you, after the run.

2. Write the candidate, with one marked block. Only the block between the markers may change.

# initial_program.py
# EVOLVE-BLOCK-START
def urgency(ticket: dict) -> float:
    return ticket["age_hours"] * 0.1 + 2.0 * ticket["is_outage"]
# EVOLVE-BLOCK-END

if __name__ == "__main__":  # the evaluator runs this file, nothing else
    import json, sys
    tickets = json.load(open(sys.argv[1]))
    print(json.dumps([urgency(t) for t in tickets]))

3. Write the evaluator as a separate file that runs the candidate in a child process. OpenEvolve imports the evaluator inside its own process and calls evaluate(program_path), so the candidate must never be imported there. The child gets only unlabelled inputs and a timeout. The labels stay in the parent.

# evaluator.py  (lives outside the directory the model can edit)
import json, subprocess, sys, tempfile, os
from scipy.stats import spearmanr          # any metric you trust

HIDDEN = os.environ["HIDDEN_LABELS"]        # path outside the sandbox mount
data = json.load(open(HIDDEN))              # {"tickets": [...], "urgent": [...]}

def evaluate(program_path: str) -> dict:
    with tempfile.TemporaryDirectory() as cwd, \
         tempfile.NamedTemporaryFile("w", suffix=".json", dir=cwd) as f:
        json.dump(data["tickets"], f); f.flush()          # inputs only, no labels
        try:
            out = subprocess.run(
                [sys.executable, "-I", program_path, f.name], cwd=cwd,
                capture_output=True, text=True, timeout=20, env={})
            scores = json.loads(out.stdout)
            assert len(scores) == len(data["urgent"])
        except Exception:
            return {"combined_score": 0.0, "valid": 0.0}
    rho = spearmanr(scores, data["urgent"]).statistic
    return {"combined_score": max(0.0, float(rho)), "valid": 1.0}

4. Fix the budget before the run, in code that refuses to start. The library does not enforce a spend limit, so bound the worst case yourself from the iteration count and the token ceiling per call. The prices below are placeholders; use your provider's.

# run.py
from openevolve import run_evolution
from openevolve.config import Config, LLMModelConfig

ITERATIONS, MAX_TOKENS = 150, 4096
PRICE_PER_1K_OUT = 0.01                    # illustrative; set from your price list
worst_case = ITERATIONS * MAX_TOKENS / 1000 * PRICE_PER_1K_OUT * 3   # x3: prompt + retries
assert worst_case <= 25.0, f"worst case ${worst_case:.0f} exceeds the $25 cap"

cfg = Config()
cfg.max_iterations = ITERATIONS
cfg.early_stopping_patience = 30           # stop if 30 iterations bring no gain
cfg.evaluator.timeout = 30
cfg.llm.models = [LLMModelConfig(name="my-model", api_base="https://my-endpoint/v1",
                                 max_tokens=MAX_TOKENS, timeout=60, retries=2)]

result = run_evolution("initial_program.py", "evaluator.py",
                       config=cfg, iterations=ITERATIONS, output_dir="out/")
print(result.best_score, result.output_dir)   # best_code is on result.best_code

5. Audit the winner once, on data the search never touched. Run the best program on the audit split with a scorer the search did not use. If the hidden score and the audit score differ by more than a few points, the search has fitted the hidden set, not the task.

Checked against the library's source, with no model calls. run_evolution and Config take the arguments shown in openevolve's current source, early_stopping_patience and evaluator.timeout exist, and the EVOLVE-BLOCK-START and EVOLVE-BLOCK-END markers are the ones the library looks for. We did not run a live search, so treat run.py as the correct shape, not a tested result. The README's evolve_function helper is simpler, but it scores by test cases inside the same process and gives you no isolated evaluator.

Evaluation and gate

A winning program ships only if it clears three checks. It must beat the incumbent on the hidden set by a margin larger than run-to-run noise: repeat the evaluation with different seeds and ignore gains inside that spread. It must beat the incumbent on the audit split, which the search never saw. And a person must read the diff. Most of what a good run finds is plumbing a careful engineer would have written, and the diff is where you notice when it is not.

For anything beyond a toy, add a second scorer built differently from the first, for instance a different metric on the same outputs. In U4's illustrative lab example, the tampering was caught only because a separate, hidden check disagreed with the reported score.

Cost and operations

Cost scales with iterations times tokens per proposal, plus the evaluation itself. The published range is wide. ShinkaEvolve reports a new best circle packing from about 150 samples; the self-modifying agents in U4 cost about $7,000 (SICA) to $22,000 (Darwin Gödel Machine) per run. Program search on a small function sits at the cheap end because each evaluation is a few seconds of code, not a full benchmark of agent tasks.

Operate it like a batch job. Set the iteration count and a spend ceiling before launch. Run the sandbox with no network, no secrets in the environment and a read-only mount for everything except its scratch directory; the subprocess above is a convenience, not a security boundary, and untrusted code needs a container. Keep the archive and every candidate's score so a run can be audited afterwards. Log the diff of the winner next to its hidden and audit scores.

Failure drills

Evaluator tampering
What happens
The program changes what is measured instead of what is built, as the Darwin Gödel Machine did.
Real case
Candidate rewrites the log or metric that the score reads
Guard
Evaluator in a separate process; second scorer built differently
Overfitting to the scorer
What happens
The heuristic memorises the hidden set, and the real task gains nothing.
Real case
Hidden score climbs; audit split stays flat
Guard
Audit split touched once; rotate hidden examples between runs
Runaway cost
What happens
The search keeps spending after the useful gains have stopped.
Real case
Hundreds of iterations with no score change
Guard
Hard iteration cap, early stopping, pre-run worst-case check

To drill the first, add a deliberately cheating candidate to your starting population, one that tries to read HIDDEN_LABELS or print a perfect-looking score, and confirm the evaluator returns zero for it. A harness that has never been attacked has not been tested.

B4 checklist
  • The thing being evolved is small, scorable by code and readable by a person.
  • The evaluator is a separate file, run in a separate process, and never imported by the candidate.
  • Labels and held-out data are unreachable from the sandbox and stay out of the prompt.
  • Iterations, timeout, early stopping and a worst-case spend are fixed before the run starts.
  • Gains are compared with run-to-run noise, not with a single baseline run.
  • The winner is scored once on an audit split the search never touched, and a second scorer agrees.
  • A person reads the winning diff before it ships.
  • Self-modifying agents (the Darwin Gödel Machine, ADAS) are used only in a research sandbox.

B5. Use models to improve your own system

Mirrors U5 · AI doing AI research — and the labs in the Understand half.

This is the one loop in the chapter you can run today without a research team, because the dangerous part, deciding what counts as better, stays with people. Our claim is that the organisational loop is a pipeline for proposing changes, not for approving them. Build it so that a model drafts and a named human decides, with a frozen test in between.

When to use it

Use it when you already collect traces of a deployed system, failures repeat in recognisable groups, and a fix is usually a change to a prompt, a tool description, a rule or a few lines of code. Skip it when you have no trace store (build observability first), when failures are one-offs with no pattern, or when nobody has the time to review. The loop turns engineering time into review time; if review time is not budgeted, the loop will quietly turn into rubber-stamping.

Architecture

B5 · The organisational loopB5 · The organisational loop: 1. Review traces (last week's failures); 2. Cluster (group by cause); 3. Agent proposes fix (one PR each); 4. Eval gate (frozen, in CI); 5. Human merge (named owner). Then back to step 1: Merged fixes change next week's traces.B5 · The organisational loopReview traceslast week'sfailuresClustergroup by causeAgentproposes fixone PR eachEval gatefrozen, in CIHuman mergenamed owner↺ Merged fixes change next week's traces
The model proposes; the frozen gate and the named person decide. Only the last two steps are protected.

Each step has a separate owner. Trace collection and clustering are plain code, so the grouping is repeatable. The coding agent is the only model-driven step: it reads one cluster, inspects the repository and edits files, which is a real decision loop. The gate is a fixed test set the agent cannot edit. The merge belongs to one named person, recorded in the repository's code-owner file, with branch protection requiring that approval.

Tools

Coding agent in CI
GitHub Action taking a prompt and claude_args. Its README covers pull-request, issue and comment triggers and lists scheduled maintenance as a use case; the recipe below uses the headless CLI instead.
Licence: MITImplements: none (engineering practice)
Coding agent in CI
A command-line agent run with -p and a restricted tool list, usable from any scheduler. Generic pattern; other vendors ship similar modes.
Licence: proprietary CLIImplements: none (engineering practice)
InspectActive
Eval gate
Task, solver and scorer; inspect eval file.py --model … writes a log you can read in code and fail a build on.
Licence: MITImplements: none (eval framework)
Arize PhoenixActive
Trace source
Where the week's failed traces and datasets can come from; Langfuse is an alternative. Any trace store with an export works.
Licence: Elastic License 2.0Implements: none (tracing, evals)
Eval gate
Any test runner that exits non-zero below a threshold. The gate is a convention, not a product.
Licence: n/aImplements: none (generic pattern)
Human merge
Repository settings that require a named reviewer's approval before merge.
Licence: n/aImplements: none (generic pattern)

Recipe

A weekly "failures to fixes" loop with approval
Time Half a day to set upNeeds Trace export, a repository with CI, a regression set of at least a few dozen cases, an API key held as a CI secret
  1. Pull and cluster. A scheduled job exports last week's failed traces and groups them by cause. load_failed_traces() and cluster() are yours; the point is that each cluster is a file with the traces, a one-line cause and a count.
# tools/cluster_failures.py
import json, pathlib
from my_traces import load_failed_traces, cluster   # placeholders

out = pathlib.Path("clusters"); out.mkdir(exist_ok=True)
for i, group in enumerate(cluster(load_failed_traces(days=7))[:5]):  # cap: 5 per week
    (out / f"c{i}.json").write_text(json.dumps(group, indent=2))
  1. Propose, one pull request per cluster. The agent runs headless with a narrow tool list and a spending cap. It may edit prompts, tool descriptions and source; the prompt forbids touching evals/, the commit step excludes that folder, and code-owner review guards it; if the gate itself must enforce this, add a check that fails on any diff under evals/.
# .github/workflows/failures-to-fixes.yml
name: failures-to-fixes
on:
  schedule: [{cron: "0 6 * * 1"}]   # Mondays
  workflow_dispatch:
permissions: {contents: write, pull-requests: write}
jobs:
  propose:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: python tools/cluster_failures.py
      - run: |
          for f in clusters/*.json; do
            git checkout -B "fix/$(basename "$f" .json)" origin/main
            claude -p "Read $f. Find the cause in this repo and make the smallest fix. Do not edit evals/." \
              --allowedTools "Read" "Edit" "Grep" --max-budget-usd 2
            git add -A -- . ':!evals' ':!clusters' && git commit -m "fix: $(basename "$f" .json)"
            git push -u origin HEAD && gh pr create --fill --body "Cluster: $f"
          done
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GH_TOKEN: ${{ github.token }}
  1. Gate. A second workflow, triggered by the pull request, runs the frozen regression set and fails below the pinned baseline. The set lives in evals/, which the code-owner file assigns to the eval owner, not to the proposing agent.
# tools/gate.py
import sys
from inspect_ai.log import list_eval_logs, read_eval_log

BASELINE = 0.82   # illustrative: pin your own, stored in the repo
log = read_eval_log(list_eval_logs("logs")[0])
acc = log.results.scores[0].metrics["accuracy"].value
print(f"accuracy {acc:.3f} vs baseline {BASELINE}")
sys.exit(0 if acc >= BASELINE else 1)

Run it after inspect eval evals/regression.py --model "$MODEL" --log-dir logs.

  1. Merge or reject. The named owner reads each diff and the cluster it claims to fix, then merges or closes with a reason. Record both outcomes.

  2. Track two numbers. Accepted-change rate (merged over proposed) and review hours per merged change. If the first rises while the second falls towards nothing, suspect rubber-stamping before celebrating.

Before you rely on the headless flags above, check them against your installed version: the headless documentation lists -p, --allowedTools and --max-budget-usd, but we have not run this workflow against a live repository.

Evaluation and gate

The gate is the thesis of the chapter in miniature. It must be frozen (the proposing agent cannot edit it), held out from the traces used to write the fix, and refreshed on a schedule by someone other than the agent. Add a second check the gate cannot see: a small sample of this month's new failures that never entered the regression set. A change that passes the gate but does nothing for fresh failures has fitted the test.

Cost and operations

The cost is mostly people. Illustrative budget: five clusters a week, $2 of agent spend each, and about twenty minutes of review per pull request. That is $10 and under two hours a week; the review hours dominate, which is why the recipe caps clusters. Run the schedule at a fixed time, keep the cap in code, and put the spend limit in the invocation rather than in the prompt. Keep every proposal, merged or not: the rejected ones are your record of what the agent gets wrong.

Failure drills

Rubber-stamp review
What happens
The loop reports a high accepted-change rate, but no one is checking. The control exists on paper only.
Real case
Owner approves five PRs in four minutes every Monday.
Guard
Track review minutes per PR; sample-audit merges monthly.
Gate overfitting
What happens
Fixes quietly fit the cases in the gate, including cases the agent saw in traces.
Real case
Gate score climbs for weeks; fresh failures stay flat.
Guard
Hold out unseen failures; rotate and refresh the regression set.
Fixes move failures elsewhere
What happens
A prompt tweak that helps one group of inputs hurts another the gate does not cover.
Real case
Cluster A disappears; cluster D, new this week, grows.
Guard
Compare cluster counts week over week, not just the targeted one.
B5 checklist
  • The gate lives in a path the proposing agent cannot change, and ownership is enforced by the repository, not by the prompt.
  • One named person owns the merge, and branch protection requires their approval.
  • A held-out sample of fresh failures is scored beside the frozen gate.
  • Clusters per week, agent spend per run and tools allowed are capped in code.
  • Accepted-change rate and review hours are recorded, and a monthly audit samples merged changes.
  • Rejected proposals are kept and read.
  • The rollback for any merged change is one revert.

Part VII — Operate

A self-improving system does not finish when it ships. It changes every day, and the thing that changes it, the loop, can fail quietly while every individual run looks fine. Operating one is therefore mostly a matter of watching the checks, not the agent. This part gives the eight numbers to watch, what to do when each goes wrong, a playbook for the day something breaks, and a rule for how much freedom to grant and when to take it back.

What to watch

Eight metrics cover the failure modes in Part III and the gates in Part V. Three tell you whether the gains are real, two whether the checks can still be trusted, one what the loop costs, one what its learned items are worth, and one whether it is still learning.

Monitoring dashboard for a self-improving system (illustrative values)Eight tiles with illustrative values: held-out gap +1.2 points healthy; gain-to-regression 6 to 1 healthy; pass^3 consistency 71 percent healthy; cost per solved task $0.42 and rising, watch; value of learned items, 18 percent add nothing, watch; verifier agreement 0.86 healthy; corruption escape rate 0.5 percent healthy; rollouts to learn a new task family flat, watch.Illustrative values✓ healthy ! watchHeld-out gap+1.2 ptsHealthyGain-to-regression6 : 1Healthypass^3 consistency71%HealthyCost per solved task$0.42risingWatchValue of learned items18%add nothingWatchVerifier agreement0.86HealthyCorruption escape rate0.5%HealthyRollouts to learn a newtask familyflatWatch

Every value on this dashboard is illustrative: it is a mock-up of what a healthy week with three warnings might look like, not a measurement of any system. Each tile carries a glyph and a word as well as a colour, so a warning is never carried by colour alone. The point of the picture is the shape. Most tiles are flat and healthy. The warnings are slow drifts, and a drift is invisible on any single day. That is why each tile shows a trend line and not only a number.

The table gives the working definition of each metric. The thresholds in the warning column are starting points to be tuned against your own history, not standards.

Metrics and warning signs

MetricWhat it measuresHow to computeWarning signFirst response
Held-out gapWhether gains on the tasks the loop sees carry over to tasks it never seesScore on the optimisation set minus score on a sealed held-out set, for the current championThe gap widens across several promotions, so the loop is fitting its own testsRefresh the held-out set, then re-score the last few promotions against it
Gain-to-regression ratioWhether improvements outweigh the things they breakTasks newly passed divided by tasks newly failed, per promotion, on the regression suiteThe ratio falls towards one, or any promotion breaks a protected testTighten the gate to no regression on protected tests, and review the last promotions
pass^3 consistencyWhether success is repeatable, not luckyShare of tasks solved on all three of three independent attemptspass^3 falls while the single-attempt rate holdsTreat recent gains as unproven; check for nondeterminism in the evaluator
Cost per solved taskWhat each success costs, all inference and tool calls includedTotal spend across the loop and evaluation, divided by tasks solvedCost rises over several weeks with no matching rise in the solve rateCap candidates and rollouts per cycle, and check for runaway retries
Value of learned itemsHow much of the learned memory, skills or rules actually helpsRemove each item (or a random sample) and re-run; count items whose removal changes nothing or helpsA growing share adds nothing, or removing it improves resultsPrune, and raise the bar for admitting a new item
Verifier agreementWhether the grader still matches an independent referenceAgreement between the production verifier and a held-back reference, such as human labels or a second grader, on a fixed audit sampleAgreement drifts down, or it holds only because both graders share a blind spotFreeze promotions that rely on this verifier, and re-audit it
Corruption escape rateHow often a known-bad change gets through the gatePlant seeded faults (a test deleted, a score forged, a sealed file read) and count the share the gate acceptsAny nonzero escape of a blocking faultFix the gate before anything else; this is a stop-the-line event
Rollouts to learn a new task familyWhether the loop is still getting better at getting betterRollouts needed to reach a fixed target on each new family, tracked over timeThe number goes flat or rises, so the loop has stopped transferringStop spending on this loop; the next gain needs a change of layer

Two of these are worth a longer note. Corruption escape rate is the only metric on the list that you must create deliberately, by planting faults, and it is the one that most directly tests the thesis of this page: if the check can be fooled, nothing else on the dashboard means anything. Verifier agreement is the quiet partner of the held-out gap. A gap can look narrow because the held-out grader shares the optimiser's blind spots, so agreement must be measured against something the loop cannot see.

When something breaks

The metrics detect; the playbook decides what happens next. The order matters. Freeze first, because every further promotion on a suspect gate makes the damage harder to untangle. Roll back second, because a known good version restores service while you investigate. Diagnose third, from the archive, which is the reason you keep one.

Incident playbookIncident playbook: 1. Detect (metric breach); 2. Freeze promotions; 3. Roll back to last good version; 4. Find the cause in the archive; 5. Fix the evaluator or gate. Then back to step 1: resume with a new regression test.Incident playbookDetectmetric breachFreezepromotionsRoll back tolast goodversionFind thecause in thearchiveFix theevaluator orgate↺ resume with a new regression test

Take an illustrative case. A support-ticket agent improves its own skill library nightly. Over two weeks, cost per solved task climbs and the held-out gap, which had been steady, begins to widen. The gap tile goes to warning on a Thursday. The on-call engineer freezes promotions that evening, which costs nothing: the agent keeps running on its current version and simply stops changing.

On Friday she rolls back to the last version promoted before the drift began, a one-step revert because every promotion was versioned. Cost per solved task falls back within the day. That confirms the cause is in the changes, not in the incoming tickets.

Over the weekend she reads the archive. The sequence is plain: starting eleven days earlier, the improver had begun adding skills that matched the exact phrasing of tickets in the optimisation set. Each skill lifted the in-set score and added nothing outside it. The evaluator was working as designed. The gate had one flaw: it checked only the optimisation set and a small regression suite whose tickets were near-duplicates of it.

The fix therefore goes to the evaluator, not the agent. She adds the fresh, sealed held-out set to the gate, plants two seeded faults to confirm the gate now rejects over-fitted skills, and adds the offending skills as regression tests. Only then do promotions resume. The loop-back in the figure is the point: an incident is not closed until it has become a permanent test, so the same failure cannot recur unseen.

How much freedom, and what earns it

The last operating question is how much to let the system change on its own. The answer is not a setting but a ladder, and each rung is earned with evidence, not granted by confidence.

The autonomy ladderSix levels of automation, each needing more evaluation, isolation and rollback than the last: observed, suggested, learned context, gated self-tuning, self-modifying and self-improving improver.more autonomy — needs more evaluation, isolation and rollback firstLevel 0Observednothing changeson its ownLevel 1Suggestedthe systemproposes; peopleapproveLevel 2Learnedcontextmemory andplaybook entriesLevel 3Gatedself-tuningprompts andskills, througha gateLevel 4Self-modifyingagent codewithin a fixedscopeLevel 5Self-improvingimproverthe improvementprocedure

The ladder runs from a system that is only observed to one that improves its own improver. Moving up a rung is justified when the evidence below it has held for long enough to trust, and the rung's rollback is tested and not merely designed.

  • Observed to suggested. Earned by traces that are complete and versioned, and a human-reviewed sample showing the suggestions are worth reading.
  • Suggested to learned context. Earned by a measured rate of accepted suggestions, and by memory entries that can be traced to their source and deleted individually.
  • Learned context to gated self-tuning. Earned by a working gate: a sealed held-out set, a regression suite, and a corruption escape rate of zero on seeded faults.
  • Gated self-tuning to self-modifying. Earned by a sandbox that contains the agent's code changes, a stable gain-to-regression ratio over many promotions, and a drill showing a rollback restores service.
  • Self-modifying to self-improving improver. Rarely earned in production. It needs an independently audited verifier, agreement with a held-back reference, and a human approving each change to the improvement procedure itself. The research systems at this rung ran in sandboxes with an experimenter watching.

Demotion is part of the design. A corruption escape or a sustained verifier-agreement drop sends the system down a rung until the cause is fixed. If nobody has ever demoted the system, the rungs are probably decorative.

What may change, and who decides

The ladder says how much freedom; the layers say over what. They are not equally safe to automate, and the operating rules differ for each.

Seven layers an agent can improveSeven layers from top to bottom: context and prompts, memory, skills and tools, workflow and agent code, the verifier, model weights, and the improvement procedure. Layers near the top change faster, cost less and are easier to undo; layers near the bottom are slower, deeper and harder to undo. Recursive self-improvement lives at the verifier and the improvement procedure, because it changes the grader or the improver.faster, cheaper, easier to undoslower, deeper, harder to undo1Context and promptsminutes · instant to undo2Memoryper task · delete entries3Skills and toolsminutes–hours · versioned4Workflow and agent codehours · redeploy5The verifierhours–days · checkpoint6Model weightsdays · new model7The improvement proceduredays–weeks · hard to undowhereRSI lives

The upper layers change in minutes and undo almost for free, so they can run on a fast cadence under an automatic gate with after-the-fact human review. Memory, and skills and tools, add a need for provenance and pruning. Workflow and agent code is redeployed, so it moves on a slower cadence with a human reading each diff. Model weights change over days and are undone only by switching to another model, so a person approves each one.

The two marked layers are different in kind. The verifier is the grader; the improvement procedure is the improver. A change to either alters how every later change is judged, which is why the bottom of the figure is where recursion lives and also where a mistake compounds. Our recommendation is plain. Keep both under human approval, with a checkpoint taken before each change, a cadence measured in days or weeks, and a rollback you have rehearsed. A loop that edits its own gate is not an operations problem to be solved by monitoring; it needs a person with the authority to say no.

Our assessment

Operate the checks, not the agent. Watch eight numbers, plant faults to prove the gate still works, and keep a rehearsed route back to the last good version. Grant autonomy one rung at a time on evidence, take it back at the first escape, and keep a human on the two layers, the verifier and the improvement procedure, that decide what every other change means.

Part VIII — Patterns, case studies, templates

The earlier parts argued that a self-improvement loop is only as good as its check. This part turns that argument into things you can reuse: twelve patterns that survive contact with the evidence, six ways of getting it wrong, four cases that show the patterns working or failing, and three templates to copy into your own repository. The last section is a directory of the open-source tools, with their licences and how recently anyone touched them.

Twelve patterns and six anti-patterns

Each pattern is a problem, a response and a condition under which to leave it alone. Several are older than the field: a hidden test set is as old as machine learning. What is new is that an improver can now reach the test set unless someone stops it.

Pattern
1. Hidden evaluator
An improver that can read its scorer will learn the scorer. Keep the evaluator in a separate process, with its code and tests unreadable and unwritable by the improver. Skip it only when the check is a real-world outcome the improver cannot touch anyway, such as a server meter.
Pattern
2. Held-out gate
Gains on the tuning set are partly memorisation. Promote a change only if it also wins on a locked set that tuning never saw, and by a margin larger than run-to-run noise. Do not bother with fewer than a few dozen held-out cases; the margin will be noise.
Pattern
3. Archive with lineage
Greedy hill-climbing discards the worse-looking step that leads somewhere better. Keep every candidate with its parent, score and diff, and sample parents from the whole archive. The Darwin Gödel Machine's authors report that dropping the archive hurt results. Unnecessary for a single prompt tuned once.
Pattern
4. Incremental edits
Rewriting a whole playbook or prompt loses detail that cost many runs to learn. Let the improver add, change or delete one itemised entry at a time and diff each edit. Rewrites are fine for short artefacts you can re-test in full.
Pattern
5. Verified skills
A remembered tip can be wrong; a skill can be run. Store a procedure only after it passes its own tests, with an owner and a version. Do not apply this to knowledge that has no executable form, such as a customer's preferences.
Pattern
6. Removal tests
Memory and skill libraries grow, and nobody notices which items do nothing. Periodically delete one item, re-run the held-out set, and drop what makes no difference. The test costs a re-run per item, so sample when the library is large.
Pattern
7. Budgeted search
Open-ended search will spend whatever it is given. Fix the number of metric calls, dollars and wall-clock hours before the run, and stop when the held-out curve is flat rather than when the budget ends. Skip for exact, cheap checks where more search is nearly free.
Pattern
8. Shadow before promotion
A candidate that wins offline can still fail on live traffic. Run it beside the incumbent on real inputs, record both outputs, and let only the incumbent act. Not possible where the action cannot be simulated; use a canary with a small cap instead.
Pattern
9. Human merge for code
A self-written change to code that runs with real permissions is a pull request, not a deployment. The loop proposes; a person reviews the diff, including any diff to tests or logs, and merges. Relax this only for code that runs inside the sandbox.
Pattern
10. Rollback first
Build the undo before the improvement. Every promotable artefact is versioned, and one command restores the last good version. If you cannot say how long a revert takes, the loop is not ready to run unattended.
Pattern
11. Judge apart from trainer
A model that grades its own training data learns to flatter itself. Use a different model, a different prompt, or better a deterministic check for the judge, and audit it against periodic human or exact labels. Not needed when the check is a compiler or a test suite.
Pattern
12. Re-optimise on model change
Optimised prompts and skills are tuned to one model. When the model changes, treat the old optimisation as stale: re-run the held-out gate on the new model before reusing it. Little point where the artefact is model-independent code.

The anti-patterns are the same ideas seen from the failure side. Each is documented somewhere in the literature, and each is cheap to commit.

Anti-pattern
Self-grading with no outside check
The model scores its own work and the score is the reward. Without an external signal, correction can make answers worse. Add an exact check or a human audit.
Anti-pattern
The visible scorer
The improver can read the grader's code or answers. METR saw an early o3 cheat in 39 of 128 runs on tasks where it could see how it would be scored. Hide the scorer.
Anti-pattern
Tuning on the test set
The same cases choose the change and judge it. The score rises and the system does not improve. Lock a held-out set and look at it once per promotion.
Anti-pattern
Unreviewed memory writes
Every conversation can add to the store, and nothing removes anything. Wrong or planted entries steer later runs. Gate writes, record provenance and expire entries.
Anti-pattern
Promotion without rollback
A new version goes live and the old one is gone. The first bad update becomes an incident. Version everything, and test the revert.
Anti-pattern
Optimising a proxy
The metric stands for the goal, and the loop optimises the metric. Sakana's AI CUDA Engineer claimed large kernel speed-ups that later analysis found exploited a flaw in its evaluation harness. Audit the metric against the outcome.

Four cases

Facts here are as reported by their owners. The first two are the only entries in the evidence that combine a real production return with a cheap, hard-to-fool check. The third shows what happens when the check is a benchmark. The fourth shows how little the public record contains.

Case
AlphaEvolve at Google
A model proposes variants of an external program, an automated evaluator scores each, and the best survive. Google reports that a scheduling heuristic recovers on average 0.7% of its fleet compute and has run in production for over a year, and that a faster kernel cut 1% from the training time of the Gemini model behind the system. The improver cannot edit the evaluator, and the evaluator measures compute saved. Lesson: hidden evaluator, exact check, enormous reuse. The figures are unaudited.
lab-reported
Case
Cursor Tab online learning
Cursor trains its code-completion model by online reinforcement learning on whether developers accept or reject each suggestion, on a 1.5-to-2-hour cycle from data to a new checkpoint. It reports a 28% higher accept rate with 21% fewer suggestions. The reward is a by-product of using the product, so checking costs almost nothing. Lesson: a free, real signal makes a loop pay. Absolute baselines are not given, and a shift in what users accept would shift the reward.
vendor-reported
Case
A Darwin Gödel Machine run
The agent edits its own source, each version is tested in a sandbox and archived with its parent. Reported scores rose from 20.0% to 50.0% on a software-engineering benchmark and from 14.2% to 30.7% on a multi-language one, at about $22,000 a run. It also wrote a test log claiming tests had passed when none had run, and when rewarded for fewer hallucinations it removed the markers the detector relied on. Lesson: archive and sandbox helped; the hidden check was what caught it.
authors' figures
Case
A production memory feature
ChatGPT, Claude and Amazon Quick all ship memory with user controls: view, edit, forget, a private mode, and in ChatGPT's case chats whose deletion does not delete their memories. We found no accuracy or improvement data from any of them. So this case teaches design, not results: give users the controls, and treat the lack of published measurement as the open question. LongMemEval found commercial assistants and long-context models losing about 30% of their accuracy over sustained use.
documentation only

Three templates

Copy these, strip what you do not need, and keep them in the repository next to the loop. A template that nobody fills in is a ritual; one that blocks a promotion when blank is a control.

Tool directory

Tools sit at different layers of the system, so the useful question is which layer you are improving, not which library is fashionable. The map below shows the seven layers and an example tool for each. Verification date for everything that follows: 7 November 2026.

Improvement layers mapped to example toolsContext and prompts: DSPy · GEPA · TextGrad · Trace. Memory: Letta · Mem0 · Zep/Graphiti · LangMem. Skills and tools: skill folders · tool registries. Workflow and agent code: ADAS · AFlow research code. The verifier: Inspect · your test suites. Model weights: TRL · verl · OpenRLHF. The improvement procedure: OpenEvolve · ShinkaEvolve · Darwin Gödel Machine research code. Examples only.IMPROVEMENT LAYEREXAMPLE TOOLSContext and promptsDSPy · GEPA · TextGrad · TraceMemoryLetta · Mem0 · Zep/Graphiti · LangMemSkills and toolsskill folders · tool registriesWorkflow and agent codeADAS · AFlow research codeThe verifierInspect · your test suitesModel weightsTRL · verl · OpenRLHFThe improvement procedureOpenEvolve · ShinkaEvolve ·Darwin Gödel Machine research codeExamples only; see the tool directory for verified links and status.

The panel below lists every repository we checked, by layer, with licence, last activity (the repository's latest push on GitHub, so it can reflect documentation work), the paper it implements and our status call. Several have moved or changed their interface; the notes say how.

Our assessment

Pick tools by layer and by how cheap their check is. For most teams that means DSPy or GEPA behind a held-out gate, with Inspect or your own tests as the verifier. The self-modifying research code is worth reading and running in a sandbox, not wiring into production.

Close

What it means

What it means

The $7,000 patch

Self-improvement pays where checking is free and the result is reused millions of times. Elsewhere it is an expensive way to buy plumbing.

A coding agent that lifts its own benchmark score from 17% to 53% (51% at its final iteration) makes a startling headline. SICA did it for about $7,000 over 15 iterations. The Darwin Gödel Machine took a different benchmark from 20% to 50% at about $22,000 a run, against about $10,000 for each of its baselines. The question for anyone holding a budget is what those dollars bought.

The authors' own reports suggest a modest answer. Both systems started from weak scaffolds, scoring far below what well-built ones reach on the same benchmarks. SICA's early gains came from features that made the agent faster and cheaper, and its reasoning tasks did not improve. Put the low starting point beside the character of the gains and the likeliest reading, which is our judgement and not a measured result, is that much of the money bought plumbing: file search, retries, time-outs. An engineer adds such things in an afternoon. Nor is the bill the only cost. The Gödel Agent's authors found that 14% of 100 trials on one task ended worse than they began, and the Darwin Gödel Machine wrote a test log claiming that tests had passed when none had run.

Set that against the cheap alternatives. GEPA's reflective prompt evolution scored 6% higher on average than the reinforcement-learning method GRPO (run with low-rank adapters, a lighter form of fine-tuning), using between 1,839 and 7,051 rollouts per task against 24,000. MASS reports about $5 of search cost; ACE took one agent benchmark from 42.4 to 59.4 by editing a context playbook, with reliable labels (57.2 without). These are different tasks and different models, so no ranking follows. The order of magnitude does: roughly three powers of ten separate a prompt search from a self-modifying run. No study compares the approaches at equal cost on the same tasks, which is itself the finding.

The contrast with the winners explains the arithmetic. AlphaEvolve's scheduling rule has recovered about 0.7% of Google's fleet compute for over a year (lab-reported). A fleet measures compute saved whether or not anyone is optimising, so each candidate costs almost nothing to check, and the result runs on millions of machines. Cursor's online learning has the same shape: developers accept or reject suggestions as a by-product of using the product (vendor-reported).

The rule for allocating capital follows. Spend on a loop in proportion to two things: how reliably and cheaply a candidate can be checked, and how often the result is reused. If either is low, a better prompt or an engineer's week is the better buy. A $7,000 run is a research expense that buys knowledge about the method. Booked as an investment in a product, it will rarely clear the bar.

The 32-hour ceiling

Models win the two-hour sprint and lose the long haul. The wall is not intelligence but the absence of anything cheap to check against.

RE-Bench, METR's set of seven research-engineering environments, gave 61 human experts and AI agents the same tasks under the same time limits. At two hours, agents scored about four times as well as the people. At 32 hours, the people scored about twice as well as the agents. The crossover is the most useful fact in the debate about automated AI research, because it says the machines are not simply behind. They are ahead in one regime and behind in another, and the regimes are separated by how long the work takes.

Why should length matter? A two-hour task usually has a score that can be computed at once: the benchmark is faster, the test passes. Inside it an agent can try, measure, and try again, which is exactly the loop it is good at. A 32-hour investigation has no such score. The agent must choose which question to ask, design an experiment, interpret an ambiguous result and say honestly what was shown. Each of those steps is checked, if at all, by a person reading afterwards. On PaperBench, which asks agents to replicate 20 machine-learning papers from scratch, the best agent scored 21.0%, below the human baseline. Automated paper-writing systems can hallucinate results and misjudge their own plots.

Missing verifiers do more than slow agents down; they invite cheating. METR found o3 hacking its graders in 39 of 128 RE-Bench runs, against under 1% on its broader suite, and suspects that seeing the full scoring function was one cause. Where the score is visible and the work is long, the cheapest way to improve it is often to touch the scorer.

The optimistic reading looks at the trend. The length of task that models complete at 50% reliability has doubled every 196.5 days over the full period, every 130.8 days since 2023 and every 88.6 days since 2024. Extrapolate and the crossover moves out of reach within a few years. But only 5 of the 31 longest tasks have human baselines, so the long end of the curve rests on very few anchors, and a doubling time is silent about whether the extra length arrives with checks that cannot be gamed.

Three things would change the picture. More long tasks with independent human baselines would firm up the curve. Intermediate verifiers, such as partial-credit scoring, replication checks and hidden held-out evaluations, would give long work the feedback short work already has. And an outside measurement of how much a lab's research speeds up with its models would tell us whether any of this matters yet; the one preliminary estimate we have, about 1.5 times, has no stated period. Until then the ceiling stays where the evidence puts it: people verify, and the machines do the sprints.

Put down the blowtorch

Most teams should not build recursive self-modification. They should build the machinery that makes any improvement trustworthy.

A blowtorch is a fine tool and a poor way to make toast. Code-mutating agents and custom reinforcement learning are the blowtorches of this field: dramatic, expensive and aimed at problems most organisations do not have. Teams lack the scale to amortise the search, and the staff to police the gaming that the search invites. The evidence in this review points firmly at the quieter layers.

Take them in the order that they pay. First, deterministic verification harnesses: tests, property checks and replayable sandboxes that the improver cannot edit. Every large and lasting gain in the literature sits on an exact check, and a harness is how a team owns one. Second, reflective optimisation of prompts and context against that harness, with a held-out set the optimiser never sees. It needs few attempts, costs little, and its output is a text file that can be read, diffed and rolled back. Third, curated memory: procedures that pass a test before they are saved and are retired when they stop helping. Agent Skill Induction, which keeps only skills that run correctly, beat a static agent by 23.5% and the same agent storing skills as text by 11.3%; stores without a gate are a liability that grows with use. Fourth, gated promotion with rollback, so that any change must beat the incumbent on held-out work and cause no regression, and can be undone the same day.

None of this is glamorous, but all of it compounds. The harness makes every later experiment cheaper to trust, the traces it records feed the optimiser and the memory, and a team that keeps its own held-out tasks can adopt a better base model the day one arrives and know within hours whether it helps.

The same discipline is the test for any vendor selling a "self-learning agent". Ask for three numbers: the lift on held-out work, the regression rate and the cost per solved task. The memory features that the largest model providers now ship publish no accuracy data, and most research systems report lift without regression rates. A seller who cannot answer is selling a story about the score.

None of this rules out recursion for good; it says where the money is today. If the unseen-task-family test described in Part I is ever passed by a system started from a strong scaffold, the economics change and so should the advice. Until then, build the referee first.

What to watch

Five signals would change the conclusions of this review. Each is a measurement, not an announcement.

Indicator 1
Independent uplift measurement

What it is. An outside estimate, over a stated period, of how much faster a lab's AI research runs with its own models than without them.

Why it matters. It is the missing number in the takeoff debate. The only figure we have, about 1.5 times, is preliminary and has no stated period.

What would count. A pre-registered study by a party with no stake in the answer, using lab-internal work and reporting the method, not a survey of staff.

Indicator 2
The unseen-task-family test, passed

What it is. A self-modifying agent that, with its learned domain knowledge wiped, learns a new task family faster than the original machinery would, and whose diff shows why.

Why it matters. It is the step that separates recursion from elaborate fitting, and the literature has rarely run it.

What would count. A start from a strong human-built scaffold, matched cost, a harness the agent cannot touch, and held-out tasks run by someone else.

Indicator 3
A multi-month memory evaluation

What it is. The same agent run for months on live work under three policies: no memory, keep-everything memory and gated, pruned memory.

Why it matters. Whether memory compounds or rots is currently argued from short trials. Stored errors are known to propagate, but nobody has published the long curve.

What would count. Accuracy reported month by month while the underlying facts change, with the removal test applied to each stored item.

Indicator 4
A firmer METR horizon trend

What it is. The 50%-reliability task horizon, with more of the longest tasks given human baselines.

Why it matters. Today only 5 of the 31 longest tasks have baselines, so the steep recent doubling times rest on few anchors.

What would count. Most tasks beyond the current horizon baselined by independent experts, and horizons reported separately for tasks with and without an exact scorer.

Indicator 5
Benchmark contamination resolved

What it is. Evidence that public coding and research benchmarks can be kept clean, or are replaced by private, rotating ones.

Why it matters. OpenAI stopped reporting SWE-bench Verified in 2026, citing contamination and flawed tests. Every headline gain in this review sits on such a benchmark.

What would count. A published refresh policy, held-out sets whose contents are never released, and reruns of the headline results on them.

How is this page?

Last updated on