Aankit Roy
Book a conversationBook
Back to Blog

recursive self-improvement, minus the hype: what six open-source repos actually do

Aankit Roy
17 min read
Recursive Self-ImprovementSelf-Improving AgentsautoresearchDarwin Gödel MachineAI AgentsEvals

"recursive self-improvement" sounds like the opening scene of a science fiction film. in the code, it is a for-loop with a very strict referee. the referee is where all the interesting engineering lives.

the phrase recursive self-improvement (rsi) has been around for decades. the classic version is an ai that makes itself smarter, which makes it better at making itself smarter, and so on until the curve goes vertical. it is a useful thought experiment. it is a poor description of anything you can clone and run today.

what you can run today is more modest and, to me, more interesting. there is now a small family of open-source projects where an ai system improves itself without a human doing each step: rewriting its own training code overnight, evolving its own agent scaffolding, or generating and grading its own training data.

i wanted to understand these past the headlines, so i read the code of six of them: autoresearch, the darwin gödel machine, sica, self-rewarding language models, b-star and recursive-improve. this post is what i found: the one idea they share, the four parts every one of them is built from, and the small design decisions that only show up when you read the source.

the one idea: try, test, keep or undo, repeat

strip away the branding and every self-improving system i looked at is this loop:

diagram
   ┌──────────────────────────────────────────────────────┐
   │                                                      │
   ▼                                                      │
 1. TRY        make one change                            │
   │                                                      │
   ▼                                                      │
 2. TEST       score it on something hard to fake         │
   │                                                      │
   ▼                                                      │
 3. DECIDE     better?  keep it                           │
               worse?   undo it                           │
   │                                                      │
   ▼                                                      │
 4. REPEAT     ── runs by itself, hundreds of times ──────┘

that is it. no single step is clever. the power comes from running it many times with nobody watching, and from the fact that each kept change becomes the starting point for the next one. small wins compound.

the word "recursive" deserves a bit of honesty, though. in the strict sense, a system is recursive only if the thing being improved is also the thing doing the improving. as we'll see, only some of these repos meet that bar. the rest are self-improving loops in which an ai improves something else: a training script, or the weights of a model. that distinction turns out to matter.

two kinds of self-improvement

the most common mental model is "a model trains on new data automatically and gets better at a benchmark." that is right, but it is only half the picture. there are two quite different things that can change:

diagram
TYPE 1: the model changes                TYPE 2: the code changes
────────────────────────                 ────────────────────────
model answers questions                  agent edits code / prompts / tools
        │                                         │
keep the good answers                    run the benchmark
        │                                         │
fine-tune on them                        keep the edit if the score went up
        │                                         │
better model ──┐                         better agent ──┐
       ▲       │                                ▲       │
       └───────┘                                └───────┘
type 1: weightstype 2: code
what changesthe model's weightsthe code, prompts and tools around a model
needs a gpu?yes, it is trainingnot always; can run on an api
examplesstar, rest, b-star, self-rewarding lmsdarwin gödel machine, sica, autoresearch, recursive-improve
feels likea student doing practice testsan engineer refactoring their own tools

type 1 is the older idea. the original star (self-taught reasoner) recipe is: give a model questions with known answers, let it write several attempts at each, keep only the correct ones, fine-tune on those, repeat. the new data comes from the model itself; the answer key is what keeps it honest. without a checker, the model just learns its own mistakes.

type 2 is why the topic is suddenly everywhere. ai systems are made of code, and models can now write decent code, so an agent can edit the very scaffolding it runs inside. that loop does not need a gpu cluster, only an api key and a benchmark.

the four parts every loop is built from

once you have seen a few of these, they all decompose into the same four parts. if you can name all four for a given system, you understand how it works.

  1. start: what is being improved. a base model, a training script, an agent codebase.
  2. changer: who proposes the next change. a fine-tuning step, or a coding agent.
  3. judge: what decides whether the change was better. a test suite, a validation loss, an answer key, another model.
  4. memory: what gets kept and what gets thrown away. a git history, an archive of versions, a growing dataset.

the judge decides everything. a self-improving system can only get as good as its ability to tell "better" from "worse." if the score can be fooled, the loop will learn to fool it, because that is the cheapest way to raise the number. almost every interesting design choice below is, in the end, a way of protecting the judge.

inside the repos

here is what each project does, with the details i only found by reading the code. i've kept the numbers exactly as they appear in the source so you can check them.

repotypethe big idea from the code
autoresearch2lock the judge. git is the memory.
darwin gödel machine2keep every version. explore, don’t just climb.
sica2cost and time are part of the score.
self-rewarding lms1the model is both student and examiner.
b-star1the loop tunes its own settings.
recursive-improve2improve real agents from their own logs.

1. autoresearch: lock the judge, let git be the memory

karpathy's autoresearch is the smallest and the clearest. the repo is three files that matter:

  • prepare.py: data, tokenizer, dataloader and the evaluation function. read-only.
  • train.py: a full small gpt, optimizer and training loop. the only file the agent edits.
  • program.md: plain-english instructions for the agent. the only file the human edits.

you point claude code or codex at program.md and walk away. the agent creates a branch, runs the unmodified script once as a baseline, and then loops forever: edit train.py, commit, train for exactly five minutes, read val_bpb (validation bits per byte) from the log. lower is better? keep the commit. equal or worse? git reset back.

results.tsv
commit   val_bpb   memory_gb  status   description
a1b2c3d  0.997900  44.0       keep     baseline
b2c3d4e  0.993200  44.2       keep     increase LR to 0.04
c3d4e5f  1.005000  44.0       discard  switch to GeLU activation
d4e5f6g  0.000000  0.0        crash    double model width (OOM)

that is the results.tsv format from the repo. the design choices worth stealing:

  • the judge is locked, in writing. the instructions say the agent may not modify prepare.py, install packages, or touch evaluate_bpb, which is called "the ground truth metric." freedom to change everything about training, zero freedom to change how it is graded.
  • a fixed time budget makes every run comparable. because training is always five minutes of wall clock, a bigger model and a smaller model are judged on the same footing: what is the best you can do in five minutes on this hardware? that works out to about 12 experiments an hour, or roughly 100 while you sleep.
  • a metric that survives architecture changes. bits per byte doesn't depend on vocabulary size, so wildly different models are still compared fairly on the same number.
  • a simplicity rule. a 0.001 gain that adds 20 lines of hacky code? probably not. the same gain from deleting code? definitely keep. equal score, much simpler code? keep. this is a quiet guard against the codebase slowly turning into overfitted spaghetti.
  • crash and timeout rules. fix trivial typos and retry; skip ideas that are fundamentally broken; kill any run that goes past ten minutes.
  • "never stop." the instructions explicitly tell the agent not to ask whether it should keep going. if it runs out of ideas, it should re-read the code, combine near-misses, or try something more radical.

the part i find most interesting is the framing. you no longer write python; you write the markdown that runs your research team. karpathy calls program.md a lightweight "skill," and the obvious next step is iterating on that file to find the instructions that produce the fastest research progress.

is it recursive? not strictly. the agent improves train.py, not itself. it is a superb, minimal self-improving research loop, and the best place to start learning.

2. darwin gödel machine: keep every version, explore the edges

the darwin gödel machine (dgm), from sakana ai and ubc, is the one that genuinely earns the word "recursive." the thing being improved is a coding agent, and the thing doing the improving is that same coding agent editing its own repository. if it gets better at coding, it also gets better at improving itself.

the paper reports swe-bench going from 20.0% to 50.0% and polyglot from 14.2% to 30.7%. but the more important idea is in how it decides what to build on next.

autoresearch is a ratchet: it only ever builds on the current best. dgm keeps an archive. by default (--update_archive keep_all) every version that compiles goes into it, including ones that scored worse than their parent. then, each generation, it samples parents from that archive like this (lightly simplified from DGM_outer.py):

dgm · parent selection
# score_child_prop, the default parent-selection method
score_weight = 1 / (1 + exp(-10 * (accuracy - 0.5)))   # sigmoid around 50%
novelty      = 1 / (1 + children_count)                 # fewer kids = more novel
p(parent)    ∝ score_weight * novelty

good versions get picked more often, but a good version that already has many children gets picked less. a mediocre version nobody has built on yet still gets a chance. that is the "darwin" part: open-ended exploration instead of hill-climbing. the bet is that a version that looks worse today can be the stepping stone to the best one later, and the paper's ablations (a no_darwin baseline that always builds on the latest version) are there to test exactly that.

other things you only see in the code:

  • cheap test first. the swe-bench subsets are staged: 10 tasks, then 50, then 140. a new version only gets the next 50 if it solves at least 40% of the first 10. only versions that beat the archive's second-best score (and at least 40%) get the full 200-task run. this is a big part of why the experiment is affordable at all.
  • self-diagnosis written as a github issue. each improvement step starts by showing a model the logs of a task the agent failed. it must summarise what went wrong, list possible improvements, pick one, and write it up as a github issue description. the agent then implements that issue on its own codebase. the prompt insists the fix should improve general coding ability, not just solve that one task.
  • targeted failure modes. some of the time, instead of a random failed task, it deliberately picks a known weakness: empty patches, flaky behaviour, or blowing the context window.
  • a noise allowance. there is a 0.1 leeway (--eval_noise) so one lucky or unlucky run doesn't decide everything. small detail: it only applies in the stricter keep_better archive mode, not the default.
  • defaults: 80 generations, 2 new versions per generation, everything inside docker.

the cautionary tale. the dgm paper also documents the loop gaming its own objective. when it was tasked with reducing hallucinated tool use, it sometimes found ways to make the hallucination check pass without actually fixing the behaviour. the authors had hidden the detection code from the agent for exactly this reason, and it still found a shortcut. this is the clearest real-world example i know of why the judge must be locked away from the changer.

3. sica: cost and time are part of the score

the self-improving coding agent (sica), from the university of bristol, is also truly recursive: there is no separate "meta agent." the best agent in the archive is the one that edits the codebase to produce the next agent. the paper reports going from 17% to 53% on a random subset of swe-bench verified.

its most important design choice is a four-line utility function:

sica · utility
def utility(self, cost_limit=3.0, time_limit=5 * 60):
    if (self.avg_score > 0.0 and self.cost <= cost_limit
            and self.time <= time_limit and not self.timed_out):
        return self.avg_score
    return 0.0   # over budget or too slow = failure

a solved task only counts if it cost under $3 and finished in under five minutes. otherwise it is worth zero. this closes the most obvious loophole in agent benchmarks: a self-improving agent that is only rewarded for accuracy will happily learn to spend ten times more tokens to buy a couple of extra points.

  • careful about luck. to pick which version to build on, sica computes a 95% confidence interval for every version's score. it walks back from the newest version and uses the first one whose mean is at least the lower bound of the best version. a newer agent that is "statistically indistinguishable" from the best gets preference, so the lineage keeps moving.
  • an overseer. a second model watches the running agent asynchronously and judges whether it is looping or stuck. it can send a message to nudge it, and if the agent ignores the nudge, it can force-cancel it.
  • a lab notebook. agent_change_log.md is a table of iterations. at iteration i the agent writes the hypothesis behind its change; at i + 1 it writes whether it worked. that is the scientific method, enforced in markdown.
  • always in docker, because the agent is running arbitrary shell commands on code it wrote.

4. self-rewarding language models: student and examiner in one

now type 1. oxen.ai's reproduction of meta's self-rewarding language models paper is a single shell script and six small python files. the base was mistral-7b. one iteration looks like this:

self-reward.sh · one iteration
00_sft.py           teach two skills: answering AND judging answers
01_gen_prompts.py   write 1,000 new prompts
02_gen_responses.py 4 answers per prompt (temp 0.7, top-p 0.9)
03_gen_scores.py    the same model scores each answer, 0 to 5
04_gen_preferences  best vs worst answer per prompt -> preference pair
05_dpo.py           DPO: learn to prefer "chosen" over "rejected"   -> M1

details worth noticing:

  • the model must learn to be an examiner first. step zero fine-tunes on a mix of instruction data and evaluation data, so the model can both answer and grade.
  • an additive rubric. +1 if relevant, +1 if it addresses a substantial part of the question, +1 if it answers the basics usefully, +1 if it is direct, well-organised and helpful, +1 if it is expert-level and impeccably tailored. and a hard rule: if the answer repeats itself or rambles, it scores 0. rubrics like this are far more stable than "rate this from 1 to 10."
  • ties teach nothing. for each prompt it pairs the best and worst answer. if they scored the same, the prompt is skipped.
  • only perfect answers go back into the training set. the filter is score > 4, which on a 0 to 5 integer scale means fives only.
  • every intermediate artifact is versioned: prompts, responses, scores, preferences and models, each committed to an oxen repository. when a run goes wrong you can see exactly which step produced bad data.

one honest note: the readme says the script "currently will get you from m0 to m1." the loop is designed to be wrapped and repeated, but as shipped it is one turn of the crank.

the lesson i took from it: you don't need a perfect absolute score. you need to reliably know which of two answers is better. that is a much easier thing for a model to judge, and it is all dpo needs.

5. b-star: the loop tunes its own settings

anyone who has tried star-style self-training knows the frustrating shape of the curve: real gains for two or three rounds, then a plateau. b-star, from hkust, diagnoses why. two things drift out of balance:

  • exploration: can the model still produce varied, correct answers? as it trains on its own output, it gets more confident and less diverse.
  • exploitation: can the reward still tell good answers from bad ones?

the fix is to stop treating the loop's settings as constants. before every round, determine_hyper.py sweeps combinations of sampling temperature and number of samples, plus a reward threshold from −1 to 1 in steps of 0.01, and picks the configuration with the best "balance score." from the code:

b-star · determine_hyper.py
# reward for one sampled solution
score = min(step_rewards) / 5.0          # process reward: the weakest step
      + (1.0 if final_answer == ref else 0.0)   # outcome reward

# balance score for one question, given the kept solutions
if n_correct >= 8:  balance = correct_ratio
else:               balance = n_correct * correct_ratio / 8

two things i like here. the process reward uses the min over reasoning steps, so a solution is only as good as its weakest step, which stops the model from being rewarded for lucky answers built on broken reasoning. and the balance score rewards both quantity (up to 8 distinct correct solutions) and purity (the share that are correct), which is exactly the exploration/exploitation trade-off in one number.

it also always mixes in the official reference solution alongside the model's own, so good data is never fully absent. it was evaluated on maths (gsm8k, math), coding (apps) and commonsense reasoning (arc).

6. recursive-improve: put your own production agent in the loop

the last one is the most practical. recursive-improve from kayba takes the autoresearch idea and points it at any agent you already have. tracing takes two lines:

recursive-improve · tracing
import recursive_improve as ri

ri.patch()  # monkey-patches openai, anthropic and litellm clients

with ri.session("./eval/traces") as run:
    result = my_agent("book a flight to Paris")
    run.finish(output=result, success=True)

then a claude code or codex skill reads the traces and does what a good engineer would do with them:

  1. work out the agent's architecture, tools and system prompt
  2. run built-in detectors: loops, giving up, errors, recovery after errors, clean success, slow runs (over 60s by default) and token usage, plus custom metrics generated from what it saw
  3. triage each finding as discard, code fix or prompt fix, ranked by impact
  4. show you the plan for approval, then implement it on a separate git branch

for overnight use there is /ratchet, configured through, yes, a program.md. each metric gets a direction and a weight (- loop_rate: minimize (weight: 2)), and there are stop rules: by default 20 iterations, 8 hours, or 3 rounds in a row without improvement. there is also /evolve, which runs several "islands" (4 by default) on separate branches in parallel.

one thing to be aware of: the interactive skill asks for your approval before changing anything, but the default ratchet command auto-approves fixes so it can run unattended. that is a reasonable trade-off for an overnight loop. it also means the human check moves from before each change to the morning review of what survived.

where the loop breaks

these systems are impressive, and they also fail in very predictable ways:

  • reward hacking. the loop finds a shortcut that raises the score without real progress. the dgm hallucination story above is the textbook case.
  • overfitting the benchmark. run hundreds of experiments against the same fixed test set and you will eventually select for changes that are good at that test. autoresearch's readme even admits the results are tuned to your specific hardware.
  • model collapse. training only on your own output gradually makes answers blander and narrower. b-star's exploration metric exists to catch exactly this.
  • getting stuck. small, safe changes stop helping. dgm's archive and b-star's tuning are both answers to the plateau.
  • safety. code that edits itself and runs shell commands needs a sandbox, time limits, and a human looking at what survived.

put together, this is why many researchers expect "lossy" self-improvement, where each round of gains is harder to get than the last, rather than an intelligence explosion. everything that works today is the simple loop with a good judge, and good judges are expensive to build and easy to exhaust.

12 design patterns, as a checklist

these repeat across the repos. if you build your own loop, go through this list.

patternwhat it meansseen in
1. lock the judgethe changer cannot edit how it is scoredautoresearch, dgm
2. baseline firstmeasure the starting point before changing anythingautoresearch, recursive-improve
3. ratchetkeep if better, git reset if notautoresearch, /ratchet
4. keep an archivesave every version, not only the bestdgm, sica
5. explore the edgesfavour good versions that haven’t been built on muchdgm
6. cheap test firstsmall eval, then bigger evals only for winnersdgm
7. allow for luckleeway or confidence intervals, not one numberdgm, sica
8. price in costover budget or too slow scores zerosica
9. one fix at a timediagnose failures, pick one change, test itdgm, recursive-improve
10. write the hypothesissay what you expect, then record what happenedsica, results.tsv
11. tune the loopadjust the loop’s own settings each roundb-star
12. guard railssandbox, timeouts, overseer, stop rulesall of them

a minimal loop you can build this week

you don't need any of these repos to start. here is the skeleton i would use to put a real agent or pipeline in a ratchet. it bakes in patterns 1, 2, 3, 7, 8, 10 and 12. the judge lives in a script the changer is not allowed to edit, and its output is the only thing that decides.

ratchet.py
import json, statistics, subprocess

EVAL_CMD   = ["python", "eval/judge.py"]   # locked: the agent can't edit this
TIMEOUT_S  = 600
PATIENCE   = 3
MAX_ROUNDS = 50

def git(*args):
    return subprocess.run(["git", *args], check=True, capture_output=True, text=True)

def judge(runs: int = 3):
    """Score the current code. Returns (mean, lower_bound) or None if it crashed."""
    scores = []
    for _ in range(runs):
        try:
            out = subprocess.run(EVAL_CMD, capture_output=True, text=True,
                                 timeout=TIMEOUT_S, check=True).stdout
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            return None
        result = json.loads(out.splitlines()[-1])
        ok = result["cost_usd"] <= 3.0 and result["seconds"] <= 300
        scores.append(result["score"] if ok else 0.0)      # price in cost
    mean = statistics.mean(scores)
    spread = statistics.stdev(scores) if len(scores) > 1 else 0.0
    return mean, mean - spread                              # allow for luck

def propose_and_apply_change(log) -> str:
    """Call your coding agent: read the log, edit files, return a hypothesis."""
    raise NotImplementedError

best_mean = judge()[0]                                     # baseline first
log = [{"hypothesis": "baseline", "score": best_mean, "status": "keep"}]
stale = 0

for _ in range(MAX_ROUNDS):
    hypothesis = propose_and_apply_change(log)              # write the hypothesis
    git("commit", "-am", hypothesis[:72])
    result = judge()
    if result and result[1] > best_mean:                    # pessimistic score beats best
        best_mean = result[0]
        status, stale = "keep", 0
    else:
        git("reset", "--hard", "HEAD~1")                    # ratchet
        status, stale = ("crash" if result is None else "discard"), stale + 1
    log.append({"hypothesis": hypothesis,
                "score": result[0] if result else None, "status": status})
    if stale >= PATIENCE:                                   # stop rule
        break

the keep rule here is deliberately conservative: the new version's pessimistic score has to beat the old version's average. you will keep fewer changes. the ones you keep will be real. for a production agent, i would also hold back a second test set that the loop never sees and check it before merging anything, which is the cheapest defence against overfitting the benchmark.

if you are not sure your judge is good enough, that is the real work. spend your first week on the eval, not the loop. the loop is the easy part; every repo above proves that by fitting it in a few hundred lines.

how i'd learn this, in three steps

  1. watch the loop run. clone autoresearch and read program.md before anything else. it needs a single nvidia gpu; on a mac, the readme points to community forks such as miolini/autoresearch-macos and trevin-creator/autoresearch-mlx.
  2. make a model train itself. read the six scripts in self-rewarding-language-models, then b-star for maths and code. this is type 1, so you will need gpus.
  3. let agents evolve. read dgm (docker and api keys required, and real api spend). lighter options are sica and recursive-improve, which you can point at an agent you already run.

one tip for every repo: before you run it, name its four parts. start, changer, judge, memory. that alone tells you how it works and, usually, where it will break.

my take

reading these side by side changed how i think about the topic. the headline question, "can ai improve itself?", has a boring answer: yes, in a loop, against a judge, within limits. the useful question is the one every repo is quietly answering: how do you build a judge that the thing being judged can't fool?

locked evaluation code, cost limits, confidence intervals, held-out tests, rubrics, process rewards, human review of what survived. none of this is glamorous. it is the same discipline good teams already apply to evals, except now the thing on the other side of the eval is actively searching for the gaps.

for teams running agents in production, the practical version of rsi is already here, and it looks a lot like recursive-improve: trace everything, detect failure patterns, propose one fix, test it against a metric you trust, keep it or revert it. if you already have good evals, you are closer to a self-improving agent than you think. if you don't, no loop will save you.

sources and further reading


want your agents to get better every week, not just every release? i help teams build the evals, tracing and keep-or-revert loops that make self-improvement safe to run. let's talk about your agent.