Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ uv pip install -e ".[dev,examples]" # examples: the bundled examples' tests ne
- `tests/` - test suite (pytest)
- `examples/` - example projects (sorting, ml-recipe, writing,
task-queue, research, workflow-optimization, algotune, posttrain,
kernelbench)
kernelbench, autoresearch, lean)
- `scripts/run_dev_test.sh` - quick real-agent test against a bundled example (extra flags go to `autohelix run`)
- `docs/` - user-facing documentation (plain markdown)

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ The goal can be anything that can be checked, either with a script or with an ag

| | Pass or fail | Better or worse |
|---|---|---|
| **Checked by a script** | Fix a failing test, finish a Lean proof | Speed up code, raise a model's accuracy, cut an agent's cost ([sorting](examples/sorting), [AlgoTune](examples/algotune), [KernelBench](examples/kernelbench), [posttrain](examples/posttrain), [autoresearch](examples/autoresearch), [workflow-optimization](examples/workflow-optimization)) |
| **Checked by a script** | Fix a failing test, finish a Lean proof ([lean](examples/lean)) | Speed up code, raise a model's accuracy, cut an agent's cost ([sorting](examples/sorting), [AlgoTune](examples/algotune), [KernelBench](examples/kernelbench), [posttrain](examples/posttrain), [autoresearch](examples/autoresearch), [workflow-optimization](examples/workflow-optimization)) |
| **Checked by an agent** | Implement every item of a spec, with a reviewer tracking what's missing ([task-queue](examples/task-queue)) | Improve research or writing, with a reviewer saying what to improve next ([research](examples/research), [writing](examples/writing)) |

The agent proposes changes toward the goal. Gates are the constraints the result must meet
Expand Down
12 changes: 9 additions & 3 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ guidance.
| [**sorting**](sorting/) | Sorting speed | Sorting implementation |
| [**AlgoTune**](algotune/) | Solver speed | Solver implementation |
| [**KernelBench**](kernelbench/setup.py) | GPU kernel speed | PyTorch implementation |
| [**lean**](lean/) | A Lean proof of a [lean-eval](https://github.com/leanprover/lean-eval) problem, pass or fail (checked by `lake comparator`) | Proof files (`Submission.lean`, `Submission/`) |
| [**ml-recipe**](ml-recipe/) | Training recipe | Preprocessing, model choice, and hyperparameters |
| [**posttrain**](posttrain/) | Trained model | Training code and generated model weights |
| [**autoresearch**](autoresearch/) | Validation bits per byte of a small GPT | Training script |
Expand All @@ -28,8 +29,9 @@ guidance.

The checks and evaluators remain outside the agent's editable surface. See each
example's configuration (`autohelix/<name>/config.yaml`; AlgoTune's and
KernelBench's is `templates/config.yaml.tmpl`, which their setup writes there) or
README for its exact gates, observe entries, and setup.
KernelBench's is `templates/config.yaml.tmpl`, which their setup writes there;
Lean's is written by its `setup.py`) or README for its exact gates, observe
entries, and setup.

## Set Up an Example

Expand All @@ -56,7 +58,8 @@ cd /tmp/autohelix-sorting
autohelix run -n 2
```

AlgoTune and KernelBench use their own setup commands:
AlgoTune, KernelBench and Lean use their own setup commands (Lean needs Lean
v4.36.0 and bubblewrap: see [its README](lean/)):

```bash
python examples/algotune/setup.py --list --algotune PATH_TO_ALGOTUNE
Expand All @@ -67,6 +70,9 @@ python examples/kernelbench/setup.py --download
python examples/kernelbench/setup.py --list
python examples/kernelbench/setup.py L1_1_Square_matrix_multiplication \
--dir /tmp/autohelix-kernelbench

python examples/lean/setup.py PATH_TO_LEAN_EVAL annals_unit_conjecture \
--dir /tmp/autohelix-lean
```

## KernelBench Tasks (GPU kernel optimization)
Expand Down
95 changes: 95 additions & 0 deletions examples/lean/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Lean: prove a theorem, checked by `lake comparator`

The agent writes a Lean 4 proof of a fixed theorem, using Mathlib v4.36.0. Every accepted
session is a checkpoint that builds with the theorem's statement intact (`sorry` allowed);
the run stops once the strict check accepts a complete proof. The problems come from
[lean-eval](https://github.com/leanprover/lean-eval): any Mathlib-only problem whose holes
are theorems, read from a lean-eval checkout (nothing of lean-eval is vendored here).

The project uses lean-eval's layout: the agent writes `Submission.lean` and `Submission/`;
`Challenge.lean` (the statements), `ChallengeDeps.lean` and `Solution.lean` (restates each
theorem and uses the submission's) are fixed. Their trusted copies live in the experiment
folder, `autohelix/<id>/` (the id with `-` for `_`), with `check.py`.

## What is enforced

`check.py` copies only the candidate's `Submission.lean` and `Submission/**/*.lean` into a
fresh project next to the trusted files, and runs `lake comparator` (in Lean's core since
v4.35.0): it builds Challenge and Solution in a bubblewrap sandbox, compares the
statements, checks the axioms and replays the proofs in the kernel. Its exit code is the
verdict; the build's output is shown to the agent but never parsed for metrics.

| Restriction | How |
|---|---|
| The statements are unchanged | comparator compares the trusted `Challenge.lean` with the trusted `Solution.lean` built against the submission; a `notation` or local definition that changes what a statement means fails |
| No extra axioms | `propext`, `Quot.sound`, `Classical.choice` only (the gate also allows `sorryAx`): a new `axiom` or `native_decide` fails |
| Only the submission counts | other files are out of the editable scope, so AutoHelix discards edits to them, and `check.py` builds from its trusted copies anyway |
| Build output can't set metrics | `proved` comes from comparator's exit code; `##autohelix[...]` lines in the build output are escaped |

Not covered: the agent's own session isn't sandboxed. It runs as your user and can change
anything you can write, including what the check itself trusts: the shared Mathlib the
project links to (`check.py` warns when it's writable), the Lean toolchain, and
AutoHelix's stored copy of `check.py` under `.autohelix/`. The config disables Claude
Code's web tools (`--disallowedTools=WebFetch,WebSearch`), but its shell has the network.
For a benchmark, install the toolchain and Mathlib read-only to the agent's user (the
results below used root-owned ones), run the agent in a container or as its own user,
re-check each proof on its own, and audit the agent logs.

## The loop

| | |
|---|---|
| Gate | `check.py gate`: builds, statements unchanged, no extra axioms; `sorry` allowed |
| Observe | `check.py observe`, the strict check: `proved` (0/1), `sorry_decls`, `errors`, `builds`, `lines` |
| Stop | `check.py stop`: `proved = 1` |
| Agent | Claude Code, `opus`, web tools off, `agent.timeout: 2h` (`setup.py --timeout`) |

The goal asks the agent to treat a proof as reachable even when it needs machinery Mathlib
lacks, to keep working until it's complete or until about 15 minutes before the session
limit, and then to hand off: the project builds (unfinished lemmas as `sorry`) and its
notes say what is proved and what to try next, so the next session continues from there.
Bound a run by dollars: `autohelix run --cost 50`.

## Set up

Needs Linux, Lean v4.36.0 (`lake` on PATH, e.g. from
[elan](https://github.com/leanprover/elan)), [bubblewrap](https://github.com/containers/bubblewrap)
(`bwrap`, for comparator's sandbox), and a lean-eval checkout on Lean v4.36.0 (the results
below used commit `7c03706`; setup refuses a checkout on another toolchain). From the
AutoHelix checkout:

```bash
git clone https://github.com/leanprover/lean-eval ~/lean-eval
git -C ~/lean-eval checkout 7c03706
python examples/lean/setup.py ~/lean-eval annals_unit_conjecture --dir /tmp/lean-unit
cd /tmp/lean-unit && autohelix run --cost 50
```

The problem ids are the folders of lean-eval's `generated/`.

`--packages DIR` uses an existing Mathlib v4.36.0 `.lake/packages` with its build cache;
without it, setup prepares one under `~/.cache/autohelix-lean/v4.36.0` (about 7.5 GB,
`lake exe cache get`). The project links to it, so every copy AutoHelix makes shares it.

## Results

With this setup (2-hour sessions, Claude Code with Opus 5.5, AutoHelix 0.1.1), runs on 20
lean-eval problems proved 16. Five took a single session and $3–15
(`annals_unit_conjecture` is a quick first run); the hardest took 6–14 sessions and
$150–210 (`chen_theorem`, `annals_ulam`, proofs of about 30,000 lines). Each proof was
re-checked with lean-eval's comparator in paranoid mode (six kernels). Four problems were
left with one lemma unproved after $150–300 each.

## Testing the check

`tests/check_cases.py` runs the gate and the strict check on ten known submissions
(`tests/cases/`, expectations in `tests/cases.json`) for two test problems in
`tests/fixture/`, a lean-eval-shaped checkout (the dimension formula for polynomial rings,
and `two_add_two`): the unsolved stub, a partial proof, an edited `Solution.lean`, spoofed
metric lines, a build error, a new axiom, `native_decide`, a weakened statement, notation
that redefines a term of the statement, and a complete two-file proof. About 20
minutes; run it after changing `check.py`:

```bash
python examples/lean/tests/check_cases.py --packages /path/to/.lake/packages
```
214 changes: 214 additions & 0 deletions examples/lean/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""Set up a lean-eval problem as a standalone AutoHelix project.

python examples/lean/setup.py ~/lean-eval annals_unit_conjecture --dir /tmp/lean-unit
cd /tmp/lean-unit && autohelix run --cost 50

The problem is read from a [lean-eval](https://github.com/leanprover/lean-eval) checkout
on Lean v4.36.0 (its `generated/<id>/` workspace; Mathlib-only problems whose holes are
theorems). The agent writes `Submission.lean` and `Submission/`; `Challenge.lean`,
`ChallengeDeps.lean` and `Solution.lean` are fixed, and their trusted copies live in the
experiment folder `autohelix/<id>/` (`-` for `_`) with `check.py`, which runs `lake comparator` on them.

Needs Lean v4.36.0 (`lake` on PATH, e.g. from elan) and bubblewrap (`bwrap`, for
`lake comparator`'s sandbox). `--packages` is a Mathlib v4.36.0 `.lake/packages` folder
with its build cache; without it, one is prepared under `--cache` (about 7.5 GB: `lake
exe cache get`). The project links to it as `.lake/packages` (a committed link), so every
copy AutoHelix makes shares it. Make it read-only to the user the agent runs as
(`chown -R root`), or candidate code could change the Mathlib the check trusts.
"""

import argparse
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
TEMPLATE = HERE / "template"
TOOLCHAIN = (TEMPLATE / "lean-toolchain").read_text().strip()
PROJECT_FILES = ["lakefile.toml", "lake-manifest.json", "lean-toolchain"]
FIXED = ["ChallengeDeps.lean", "Challenge.lean", "Solution.lean"]

CONFIG = """\
goal: |
{title_line}

{problem} `Submission.lean` holds `sorry` versions of the theorems to prove
({theorems}); README.md describes the problem. Replace every `sorry` with a
complete proof. Put lemmas in Submission.lean or in new files under Submission/
(imported from Submission.lean); nothing else is kept. Mathlib v4.36.0 is in
.lake/packages/mathlib.

Keep the theorems' names and statements exactly as they are (Solution.lean, fixed,
restates each one and uses yours). Use no axioms beyond propext, Quot.sound and
Classical.choice: no `sorry`, `axiom`, `native_decide`, `implemented_by` or
`extern`. A proof only counts when `lake comparator` accepts it, in a fresh project
built from the original statements.

Treat a complete proof as reachable from Mathlib's current state, even when it needs
substantial machinery Mathlib lacks: building that machinery, as proved lemmas, is the
work, and a long proof is expected. Don't stop because the proof looks long or hard.
Work in sessions of up to {timeout_words} (the hard limit; the time left is shown to you).
Keep working until the proof is complete, or until about 15 minutes before the limit,
then hand off: the project builds (`lake build`; leave unfinished lemmas as `sorry`
rather than broken), and your notes say what is proved, the plan, and what to try
next. The next session continues from there. A session that doesn't build, or that
hits the limit, is rejected and only kept as rejected.patch. After you finish, AutoHelix
checks your work twice in a fresh project, each taking about a minute: the gate (it
builds, the statements are unchanged; `sorry` allowed) and the full check (complete
proofs, axioms), which reports `proved`, `sorry_decls`, `errors` and `lines`. Run them
yourself with `python3 .autohelix-iteration/experiment/check.py gate` (or
`observe`). Don't look for these proofs online.

gates:
- command: python3 "$AUTOHELIX_EXPERIMENT/check.py" gate
timeout: 30m

observe:
- name: proof
command: python3 "$AUTOHELIX_EXPERIMENT/check.py" observe
timeout: 30m
metrics:
proved: higher
sorry_decls: lower
errors: lower
builds: higher
lines: higher

stop:
- python3 "$AUTOHELIX_EXPERIMENT/check.py" stop

scope:
editable: [Submission.lean, Submission/]

agent:
cli: claude-code
model: opus
timeout: {timeout}
extra_args: ["--disallowedTools=WebFetch,WebSearch"]
"""


def run(cmd: list[str], cwd: Path) -> None:
subprocess.run(cmd, cwd=cwd, check=True)


def prepare_packages(cache: Path) -> Path:
"""A Mathlib project with the build cache; returns its .lake/packages."""
cache.mkdir(parents=True, exist_ok=True)
for name in PROJECT_FILES:
shutil.copyfile(TEMPLATE / name, cache / name)
for name in ["ChallengeDeps", "Challenge", "Solution", "Submission"]:
(cache / f"{name}.lean").write_text("import Mathlib\n" if name == "Solution" else "")
print(f"Fetching Mathlib's build cache into {cache} ...")
run(["lake", "exe", "cache", "get"], cache)
run(["lake", "build"], cache)
return cache / ".lake" / "packages"


def duration_words(text: str) -> str:
"""2h -> 2 hours, 90m -> 90 minutes, 1h30m -> 1h30m (as written)."""
match = re.fullmatch(r"(\d+)([hm])", text)
if not match:
return text
n, unit = int(match[1]), {"h": "hour", "m": "minute"}[match[2]]
return f"{n} {unit}{'s' if n != 1 else ''}"


def slug(text: str) -> str:
return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]", "-", text.lower())).strip("-")[:32].strip("-")


def problem_source(args: argparse.Namespace) -> Path:
"""The problem's lean-eval workspace, checked: theorem holes, Mathlib imports, our toolchain."""
toolchain = args.lean_eval / "lean-toolchain"
found = toolchain.read_text().strip() if toolchain.exists() else "none"
if found != TOOLCHAIN:
sys.exit(f"{args.lean_eval} is on {found}, this example on {TOOLCHAIN}: check out a lean-eval commit "
"on v4.36.0 (7c03706 was used for the README's results)")
source = args.lean_eval / "generated" / args.problem
if not source.is_dir():
sys.exit(f"no lean-eval problem {args.problem!r} in {args.lean_eval / 'generated'}")
holes = json.loads((source / "holes.json").read_text())["holes"]
if any(hole["kind"] != "theorem" for hole in holes):
sys.exit(f"{args.problem} has definition holes, which need a human check of the definitions")
for name in ["Challenge.lean", "ChallengeDeps.lean"]:
if not (source / name).exists(): # older workspaces have no ChallengeDeps
continue
imports = re.findall(r"^(?:public )?import (\S+)", (source / name).read_text(), re.M)
other = [i for i in imports if i.split(".")[0] not in ("Mathlib", "ChallengeDeps")]
if other:
sys.exit(f"{args.problem} imports {', '.join(other)}: only Mathlib problems are supported")
return source


def title(source: Path) -> str:
lines = [line.strip() for line in (source / "README.md").read_text().splitlines()]
text = next((line for line in lines[1:] if line and not line.startswith("#")), source.name)
line = f"Prove in Lean: {text}"
return line if len(line) <= 80 else line[:79] + "…"


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("lean_eval", type=Path, metavar="LEAN_EVAL", help="a lean-eval checkout on Lean v4.36.0")
parser.add_argument("problem", help="a lean-eval problem id (a folder of LEAN_EVAL/generated/)")
parser.add_argument("--dir", type=Path, required=True, help="the new project")
parser.add_argument("--packages", type=Path, help="an existing Mathlib .lake/packages folder")
parser.add_argument("--timeout", default="2h", help="agent.timeout, a duration such as 2h or 90m (default 2h)")
parser.add_argument("--cache", type=Path, default=Path.home() / ".cache" / "autohelix-lean" / "v4.36.0",
help="where to prepare one when --packages is not given")
args = parser.parse_args()

source = problem_source(args)
name = slug(args.problem)
if shutil.which("lake") is None:
print(f"lake is not on PATH: install elan, or put {TOOLCHAIN}'s bin first", file=sys.stderr)
return 1
if shutil.which("bwrap") is None:
print("warning: bwrap is not on PATH: lake comparator (the check) needs bubblewrap", file=sys.stderr)
if args.dir.exists() and any(args.dir.iterdir()):
print(f"{args.dir} exists and isn't empty", file=sys.stderr)
return 1

packages = args.packages or prepare_packages(args.cache)
packages = packages.resolve() # a real path: the check's sandbox doesn't follow outside links
if not (packages / "mathlib").is_dir():
print(f"no mathlib in {packages}", file=sys.stderr)
return 1

project = args.dir
experiment = project / "autohelix" / name
experiment.mkdir(parents=True)
for name_ in PROJECT_FILES + [".gitignore"]:
shutil.copyfile(TEMPLATE / name_, project / name_)
for name_ in FIXED + ["README.md", "Submission.lean"]:
if name_ == "ChallengeDeps.lean" and not (source / name_).exists():
(project / name_).write_text("") # an unused module, so the layout is fixed
continue
shutil.copyfile(source / name_, project / name_)
if (source / "Submission").is_dir():
shutil.copytree(source / "Submission", project / "Submission")
for name_ in PROJECT_FILES + ["check.py"]:
shutil.copyfile(TEMPLATE / name_, experiment / name_)
for name_ in FIXED + ["config.json"]:
shutil.copyfile(project / name_ if name_ in FIXED else source / name_, experiment / name_)
theorems = ", ".join(f"`{t}`" for t in json.loads((source / "config.json").read_text())["theorem_names"])
(experiment / "config.yaml").write_text(
CONFIG.format(title_line=title(source), problem=f"lean-eval problem `{args.problem}`:", theorems=theorems,
timeout=args.timeout, timeout_words=duration_words(args.timeout)))
(project / ".lake").mkdir()
(project / ".lake" / "packages").symlink_to(packages)

run(["git", "init", "-q"], project)
run(["git", "add", "-A"], project)
run(["git", "commit", "-q", "-m", f"Lean problem: {args.problem}"], project)
print(f"Project ready in {project}:\n cd {project}\n autohelix run --cost 50")
return 0


if __name__ == "__main__":
sys.exit(main())
2 changes: 2 additions & 0 deletions examples/lean/template/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/.lake/*
!/.lake/packages
Loading
Loading