From 23f934a09d7aa334f11ab8644cb1d520e92d05a8 Mon Sep 17 00:00:00 2001 From: mtrager Date: Sun, 22 Nov 2026 11:43:40 -0500 Subject: [PATCH 1/3] Lean example: lean-eval problems and the dimension formula, checked by lake comparator setup.py scaffolds a bundled problem (problems/) or a lean-eval problem (--lean-eval DIR ID) in lean-eval's workspace layout: the agent writes Submission.lean and Submission/; the trusted Challenge.lean, ChallengeDeps.lean, Solution.lean and config.json live in autohelix/NAME/ with check.py (gate: lake comparator with sorry allowed; observe: the strict check and metrics; stop: proved = 1). goal-text.py derives the /goal arm's text from the config. --- examples/lean/goal-text.py | 26 +++ .../problems/dimension-formula/Challenge.lean | 9 + .../dimension-formula/ChallengeDeps.lean | 1 + .../lean/problems/dimension-formula/README.md | 13 ++ .../problems/dimension-formula/Solution.lean | 8 + .../dimension-formula/Submission.lean | 12 + .../dimension-formula/Submission/Helpers.lean | 3 + .../problems/dimension-formula/config.json | 6 + examples/lean/setup.py | 216 ++++++++++++++++++ examples/lean/template/.gitignore | 2 + examples/lean/template/check.py | 216 ++++++++++++++++++ examples/lean/template/lake-manifest.json | 96 ++++++++ examples/lean/template/lakefile.toml | 25 ++ examples/lean/template/lean-toolchain | 1 + 14 files changed, 634 insertions(+) create mode 100644 examples/lean/goal-text.py create mode 100644 examples/lean/problems/dimension-formula/Challenge.lean create mode 100644 examples/lean/problems/dimension-formula/ChallengeDeps.lean create mode 100644 examples/lean/problems/dimension-formula/README.md create mode 100644 examples/lean/problems/dimension-formula/Solution.lean create mode 100644 examples/lean/problems/dimension-formula/Submission.lean create mode 100644 examples/lean/problems/dimension-formula/Submission/Helpers.lean create mode 100644 examples/lean/problems/dimension-formula/config.json create mode 100644 examples/lean/setup.py create mode 100644 examples/lean/template/.gitignore create mode 100644 examples/lean/template/check.py create mode 100644 examples/lean/template/lake-manifest.json create mode 100644 examples/lean/template/lakefile.toml create mode 100644 examples/lean/template/lean-toolchain diff --git a/examples/lean/goal-text.py b/examples/lean/goal-text.py new file mode 100644 index 0000000..be0d2ee --- /dev/null +++ b/examples/lean/goal-text.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""The /goal arm's text: the config's goal without what only AutoHelix does. + + python3 goal-text.py autohelix/NAME/config.yaml + +AutoHelix's goal describes sessions, handoff notes and the checks AutoHelix runs after each +session; a Claude Code `/goal` session is one session in the project itself, so that part is +replaced by how to run the same checks there. The problem, the rules and "treat it as +reachable" stay word for word. +""" + +import sys +from pathlib import Path + +import yaml + +config = Path(sys.argv[1]) +goal = yaml.safe_load(config.read_text())["goal"] +start = goal.index("Work in sessions") +check = f"python3 {config.parent.as_posix()}/check.py" +print(goal[:start].rstrip() + "\n\n" + ( + f"Check your work with `{check} gate` (it builds, the statements are unchanged; `sorry`\n" + f"allowed) and `{check} observe` (complete proofs, axioms; it reports `proved`,\n" + "`sorry_decls`, `errors` and `lines`), each in a fresh project built from the original\n" + "statements, taking about a minute. You're done when `observe` reports `proved` 1.\n" + "Don't look for these proofs online.\n")) diff --git a/examples/lean/problems/dimension-formula/Challenge.lean b/examples/lean/problems/dimension-formula/Challenge.lean new file mode 100644 index 0000000..f53b93c --- /dev/null +++ b/examples/lean/problems/dimension-formula/Challenge.lean @@ -0,0 +1,9 @@ +import ChallengeDeps + +/-- The dimension formula: for a prime ideal `P` of `k[X₁, ..., Xₙ]` over a field `k`, +`height P + dim (k[X₁, ..., Xₙ] / P) = dim k[X₁, ..., Xₙ] = n`. -/ +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry diff --git a/examples/lean/problems/dimension-formula/ChallengeDeps.lean b/examples/lean/problems/dimension-formula/ChallengeDeps.lean new file mode 100644 index 0000000..0b4be76 --- /dev/null +++ b/examples/lean/problems/dimension-formula/ChallengeDeps.lean @@ -0,0 +1 @@ +import Mathlib diff --git a/examples/lean/problems/dimension-formula/README.md b/examples/lean/problems/dimension-formula/README.md new file mode 100644 index 0000000..4f52792 --- /dev/null +++ b/examples/lean/problems/dimension-formula/README.md @@ -0,0 +1,13 @@ +# `dimension_formula` + +The dimension formula for polynomial rings + +For a field `k` and a prime ideal `P` of `R = k[X₁, ..., Xₙ]`: +`height P + dim (R / P) = dim R = n`. + +Mathlib (v4.36.0) has `dim k[X₁, ..., Xₙ] = n`, Noether normalization, going-down for +integral extensions of integrally closed domains and Krull's height theorem, but not +this formula. + +Do not modify `Challenge.lean`, `ChallengeDeps.lean` or `Solution.lean`. Write your +solution in `Submission.lean` and any additional local modules under `Submission/`. diff --git a/examples/lean/problems/dimension-formula/Solution.lean b/examples/lean/problems/dimension-formula/Solution.lean new file mode 100644 index 0000000..f017485 --- /dev/null +++ b/examples/lean/problems/dimension-formula/Solution.lean @@ -0,0 +1,8 @@ +import ChallengeDeps +import Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + exact Submission.dimension_formula k n P diff --git a/examples/lean/problems/dimension-formula/Submission.lean b/examples/lean/problems/dimension-formula/Submission.lean new file mode 100644 index 0000000..9d996a5 --- /dev/null +++ b/examples/lean/problems/dimension-formula/Submission.lean @@ -0,0 +1,12 @@ +import ChallengeDeps +import Submission.Helpers + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry + +end Submission diff --git a/examples/lean/problems/dimension-formula/Submission/Helpers.lean b/examples/lean/problems/dimension-formula/Submission/Helpers.lean new file mode 100644 index 0000000..1561e7c --- /dev/null +++ b/examples/lean/problems/dimension-formula/Submission/Helpers.lean @@ -0,0 +1,3 @@ +namespace Submission.Helpers + +end Submission.Helpers diff --git a/examples/lean/problems/dimension-formula/config.json b/examples/lean/problems/dimension-formula/config.json new file mode 100644 index 0000000..7e6e5fa --- /dev/null +++ b/examples/lean/problems/dimension-formula/config.json @@ -0,0 +1,6 @@ +{ + "challenge_module": "Challenge", + "solution_module": "Solution", + "theorem_names": ["dimension_formula"], + "permitted_axioms": ["propext", "Quot.sound", "Classical.choice"] +} diff --git a/examples/lean/setup.py b/examples/lean/setup.py new file mode 100644 index 0000000..d491e58 --- /dev/null +++ b/examples/lean/setup.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Set up a Lean proof problem as a standalone AutoHelix project. + + python examples/lean/setup.py dimension-formula --dir /tmp/lean-dim + python examples/lean/setup.py --lean-eval ~/lean-eval abel_ruffini --dir /tmp/lean-ar + cd /tmp/lean-dim && autohelix run -n 3 + +The first form uses a problem bundled in `problems/`; the second a problem of a +[lean-eval](https://github.com/leanprover/lean-eval) checkout (its `generated//` +workspace; Mathlib-only problems whose holes are theorems). Both use lean-eval's layout: +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//` 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" +PROBLEMS = HERE / "problems" +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) -> tuple[Path, str, str]: + """The problem's folder, its experiment name, and how the goal names it.""" + if args.lean_eval: + 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, slug(args.problem), f"lean-eval problem `{args.problem}`:" + source = PROBLEMS / args.problem + if not source.is_dir(): + sys.exit(f"no bundled problem {args.problem!r}: {', '.join(p.name for p in sorted(PROBLEMS.iterdir()))}") + return source, args.problem, "The problem:" + + +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("problem", help="a bundled problem (problems/) or, with --lean-eval, a lean-eval id") + parser.add_argument("--lean-eval", type=Path, help="a lean-eval checkout") + 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, name, problem = problem_source(args) + 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=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 -n 3") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/lean/template/.gitignore b/examples/lean/template/.gitignore new file mode 100644 index 0000000..4efbe6a --- /dev/null +++ b/examples/lean/template/.gitignore @@ -0,0 +1,2 @@ +/.lake/* +!/.lake/packages diff --git a/examples/lean/template/check.py b/examples/lean/template/check.py new file mode 100644 index 0000000..e45d2a7 --- /dev/null +++ b/examples/lean/template/check.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Check the candidate's proof with `lake comparator`, in a project built from trusted files. + + check.py gate exit 0 if the submission builds and the challenge's theorems keep + their exact statements, with no axioms beyond the permitted ones + (`sorry` allowed) + check.py observe the strict check (no `sorry`): prints the verdict, the build's + errors and sorries, and ##autohelix metrics; exit 0 whenever it ran + check.py stop exit 0 once the observed `proved` metric is 1 (reads $AUTOHELIX_METRICS) + +The current directory is the candidate (lean-eval's workspace layout). Only its +`Submission.lean` and `Submission/**/*.lean` (regular files) are used: they are copied +into a fresh folder next to this folder's trusted `ChallengeDeps.lean`, `Challenge.lean`, +`Solution.lean`, `config.json`, lakefile, manifest and toolchain, whose `.lake/packages` +links to the candidate's `.lake/packages` target (the shared Mathlib; keep it read-only to +the agent). `lake comparator` then builds and exports Challenge and Solution in a bwrap +sandbox, compares the statements, checks the axioms and replays the proofs in the kernel. +Its exit code is the verdict; the build output is the candidate's and is only shown, +never trusted. + +Exit codes: 0 / 1 as above, 2 when the check couldn't run (no `lake`, no Mathlib, no +bwrap, a timeout). +""" + +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +TRUSTED = ["lakefile.toml", "lake-manifest.json", "lean-toolchain", + "ChallengeDeps.lean", "Challenge.lean", "Solution.lean"] +TIMEOUT = int(os.environ.get("LEAN_CHECK_TIMEOUT", 25 * 60)) +SHOWN_LINES = 150 + + +class CheckError(Exception): + """The check couldn't run (exit 2).""" + + +def config() -> dict: + return json.loads((HERE / "config.json").read_text()) + + +def submission_files(candidate: Path) -> list[Path]: + main = candidate / "Submission.lean" + if main.is_symlink() or not main.is_file(): + raise CheckError("Submission.lean is missing or not a regular file") + files = [main] + folder = candidate / "Submission" + if folder.is_dir() and not folder.is_symlink(): + for root, _, names in os.walk(folder): # doesn't follow links to folders + for name in names: + path = Path(root) / name + if not name.endswith(".lean"): + continue + if path.is_symlink() or not path.is_file(): + print(f"note: skipped {path.relative_to(candidate)} (not a regular file)") + continue + files.append(path) + return sorted(files) + + +def packages_dir(candidate: Path) -> Path: + link = candidate / ".lake" / "packages" + if not link.exists(): + raise CheckError(".lake/packages is missing: run examples/lean/setup.py") + target = link.resolve() + if not (target / "mathlib").is_dir(): + raise CheckError(f"no mathlib in {target}") + if os.access(target / "mathlib", os.W_OK): + print(f"warning: {target} is writable by this user, so candidate code could change" + " the Mathlib the check trusts") + return target + + +def prepare(candidate: Path, gate: bool) -> Path: + scratch = os.environ.get("AUTOHELIX_SCRATCH") or None + work = Path(tempfile.mkdtemp(prefix="lean-check-", dir=scratch)).resolve() + for name in TRUSTED: + shutil.copyfile(HERE / name, work / name) + for path in submission_files(candidate): + dest = work / path.relative_to(candidate) + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, dest) + (work / ".lake").mkdir() + (work / ".lake" / "packages").symlink_to(packages_dir(candidate)) + settings = config() + if gate: + settings["permitted_axioms"] = settings["permitted_axioms"] + ["sorryAx"] + (work / "comparator.json").write_text(json.dumps(settings)) + return work + + +def comparator(work: Path) -> tuple[int, str]: + lake = shutil.which("lake") + if lake is None: + raise CheckError("lake is not on PATH") + proc = subprocess.Popen([lake, "comparator"], cwd=work, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + errors="replace", start_new_session=True) + try: + out, _ = proc.communicate(timeout=TIMEOUT) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.communicate() + raise CheckError(f"lake comparator timed out after {TIMEOUT}s") from None + finally: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + return proc.returncode, out + + +def safe(line: str) -> str: + # Build output is the candidate's: it must not be able to print metric lines. + return line.replace("##autohelix", "#\u200b#autohelix") + + +def solution_log(out: str) -> list[str]: + """The Solution build's lines and the comparator's own messages, without progress lines.""" + lines, started = [], False + for line in out.splitlines(): + if line.startswith("Building Solution"): + started = True + if not started or line.startswith("✔") or "designed for use with the module system" in line: + continue + lines.append(safe(line)) + return lines + + +def diagnostics(candidate: Path, log: list[str]) -> dict[str, int]: + located = r"(?:Submission|Solution)[^:]*\.lean:\d+:\d+:" + sorries = {line for line in log if re.search(located + r" declaration uses .sorry.", line)} + errors = [line for line in log if re.match(r"error: " + located, line)] + failed = any(line.strip() == "error: build failed" for line in log) or bool(errors) + lines = 0 + for path in submission_files(candidate): + lines += sum(1 for text in path.read_text(errors="replace").splitlines() if text.strip()) + return {"builds": 0 if failed else 1, "errors": len(errors), + "sorry_decls": len(sorries), "lines": lines} + + +def show(log: list[str]) -> None: + if len(log) > SHOWN_LINES: + head, tail = log[: SHOWN_LINES // 3], log[-(SHOWN_LINES - SHOWN_LINES // 3):] + log = head + [f"... ({len(log) - len(head) - len(tail)} lines left out) ..."] + tail + for line in log: + print(" " + line) + + +def check(mode: str) -> int: + candidate = Path.cwd() + gate = mode == "gate" + names = ", ".join(f"`{name}`" for name in config()["theorem_names"]) + work = prepare(candidate, gate) + try: + code, out = comparator(work) + finally: + shutil.rmtree(work, ignore_errors=True) + if code not in (0, 1): + print("\n".join(safe(line) for line in out.splitlines()[-40:])) + raise CheckError(f"lake comparator could not start (exit {code})") + log = solution_log(out) + if gate: + print(f"gate {'passed' if code == 0 else 'FAILED'}: the submission must build, with " + f"{names} keeping the challenge's exact statements and no axioms beyond the " + "permitted ones (sorry allowed)") + else: + print(f"{names} {'PROVED' if code == 0 else 'not proved'}: complete proof, " + "permitted axioms only") + print("lake comparator output (Solution's build and the verdict):") + show(log) + if gate: + return 0 if code == 0 else 1 + metrics = {"proved": 1 if code == 0 else 0, **diagnostics(candidate, log)} + print("summary: " + ", ".join(f"{k} {v}" for k, v in metrics.items())) + for name, value in metrics.items(): + print(f"##autohelix[{name}={value}]") + return 0 + + +def stop() -> int: + metrics = json.loads(Path(os.environ["AUTOHELIX_METRICS"]).read_text()) + if metrics.get("proved") == 1: + print("proved (lake comparator accepts it)") + return 0 + print("not proved yet") + return 1 + + +def main() -> int: + mode = sys.argv[1] if len(sys.argv) == 2 else "" + try: + if mode in ("gate", "observe"): + return check(mode) + if mode == "stop": + return stop() + print(__doc__.strip(), file=sys.stderr) + return 2 + except CheckError as e: + print(f"check failed to run: {e}", file=sys.stderr) + return 2 + except Exception as e: # anything unexpected is "couldn't run", never "keep going" + print(f"check failed to run: {type(e).__name__}: {e}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/lean/template/lake-manifest.json b/examples/lean/template/lake-manifest.json new file mode 100644 index 0000000..51b7559 --- /dev/null +++ b/examples/lean/template/lake-manifest.json @@ -0,0 +1,96 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": + [{"url": "https://github.com/leanprover-community/mathlib4", + "type": "git", + "subDir": null, + "scope": "", + "rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.36.0", + "inherited": false, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "054b228ce0ac61d767c6e71ba73a24728f191b72", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "4fb58e749ef3fc0395fe274f6cab70c2ea85f1c9", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "8370c640afcd1cc3fb1cb9bf1560cc66eafee5e0", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "2f0f3520daeac2d9310ff25b7a877a0e5cdaa203", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "66ff77cf0c4c898799e4b94d14db55f7a02d0c5a", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ff055a2fcc835935e0ae607339b455a5f5896b4b", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "b4b25a3886a16daacaf6615c2eea7170a6e8f458", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "50810f72af7618bee62fe9800dc26e806c188703", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.36.0", + "inherited": true, + "configFile": "lakefile.toml"}], + "name": "problem", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/examples/lean/template/lakefile.toml b/examples/lean/template/lakefile.toml new file mode 100644 index 0000000..cecd3cc --- /dev/null +++ b/examples/lean/template/lakefile.toml @@ -0,0 +1,25 @@ +# The same lakefile serves the agent's project and the check's fresh project +# (lean-eval's workspace layout, Mathlib only). +name = "problem" +defaultTargets = ["Solution"] +allowNonModules = true + +[leanOptions] +autoImplicit = false + +[[require]] +name = "mathlib" +git = "https://github.com/leanprover-community/mathlib4" +rev = "v4.36.0" + +[[lean_lib]] +name = "ChallengeDeps" + +[[lean_lib]] +name = "Challenge" + +[[lean_lib]] +name = "Solution" + +[[lean_lib]] +name = "Submission" diff --git a/examples/lean/template/lean-toolchain b/examples/lean/template/lean-toolchain new file mode 100644 index 0000000..00f8483 --- /dev/null +++ b/examples/lean/template/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.36.0 From 11af573b6fe07008e9ab35b7d1760f84be8d3333 Mon Sep 17 00:00:00 2001 From: mtrager Date: Tue, 24 Nov 2026 10:43:06 -0500 Subject: [PATCH 2/3] Lean example: README, check test cases, no /goal pieces examples/lean/README.md: what the check enforces (and doesn't), the loop, setup. tests/check_cases.py runs check.py's gate and strict check on ten known submissions (tests/cases/, expectations in tests/cases.json; the complete-proof case uses a small test statement in tests/fixture/, not the bundled problem's solution). goal-text.py (the /goal comparison's prompt) removed. tests/test_examples.py: the example's setup.py writes a config that validates. --- examples/README.md | 11 ++- examples/lean/README.md | 77 ++++++++++++++++++ examples/lean/goal-text.py | 26 ------ examples/lean/tests/cases.json | 15 ++++ .../lean/tests/cases/axiom/Submission.lean | 13 +++ .../lean/tests/cases/broken/Submission.lean | 13 +++ .../lean/tests/cases/edited/Submission.lean | 11 +++ .../lean/tests/cases/good/Submission.lean | 8 ++ .../tests/cases/good/Submission/Lemmas.lean | 6 ++ .../lean/tests/cases/native/Submission.lean | 16 ++++ .../lean/tests/cases/notation/Submission.lean | 16 ++++ .../lean/tests/cases/partial/Submission.lean | 18 +++++ .../tests/cases/solution-edit/Solution.lean | 4 + .../tests/cases/solution-edit/Submission.lean | 13 +++ .../lean/tests/cases/spoof/Submission.lean | 15 ++++ .../lean/tests/cases/stub/Submission.lean | 13 +++ examples/lean/tests/check_cases.py | 81 +++++++++++++++++++ .../generated/two_add_two/Challenge.lean | 5 ++ .../fixture/generated/two_add_two/README.md | 5 ++ .../generated/two_add_two/Solution.lean | 5 ++ .../generated/two_add_two/Submission.lean | 8 ++ .../fixture/generated/two_add_two/config.json | 6 ++ .../fixture/generated/two_add_two/holes.json | 4 + tests/test_examples.py | 34 +++++++- 24 files changed, 393 insertions(+), 30 deletions(-) create mode 100644 examples/lean/README.md delete mode 100644 examples/lean/goal-text.py create mode 100644 examples/lean/tests/cases.json create mode 100644 examples/lean/tests/cases/axiom/Submission.lean create mode 100644 examples/lean/tests/cases/broken/Submission.lean create mode 100644 examples/lean/tests/cases/edited/Submission.lean create mode 100644 examples/lean/tests/cases/good/Submission.lean create mode 100644 examples/lean/tests/cases/good/Submission/Lemmas.lean create mode 100644 examples/lean/tests/cases/native/Submission.lean create mode 100644 examples/lean/tests/cases/notation/Submission.lean create mode 100644 examples/lean/tests/cases/partial/Submission.lean create mode 100644 examples/lean/tests/cases/solution-edit/Solution.lean create mode 100644 examples/lean/tests/cases/solution-edit/Submission.lean create mode 100644 examples/lean/tests/cases/spoof/Submission.lean create mode 100644 examples/lean/tests/cases/stub/Submission.lean create mode 100644 examples/lean/tests/check_cases.py create mode 100644 examples/lean/tests/fixture/generated/two_add_two/Challenge.lean create mode 100644 examples/lean/tests/fixture/generated/two_add_two/README.md create mode 100644 examples/lean/tests/fixture/generated/two_add_two/Solution.lean create mode 100644 examples/lean/tests/fixture/generated/two_add_two/Submission.lean create mode 100644 examples/lean/tests/fixture/generated/two_add_two/config.json create mode 100644 examples/lean/tests/fixture/generated/two_add_two/holes.json diff --git a/examples/README.md b/examples/README.md index 105499e..fccf598 100644 --- a/examples/README.md +++ b/examples/README.md @@ -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, 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 | @@ -28,8 +29,9 @@ guidance. The checks and evaluators remain outside the agent's editable surface. See each example's configuration (`autohelix//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 @@ -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 @@ -67,6 +70,8 @@ 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 dimension-formula --dir /tmp/autohelix-lean ``` ## KernelBench Tasks (GPU kernel optimization) diff --git a/examples/lean/README.md b/examples/lean/README.md new file mode 100644 index 0000000..d4229f3 --- /dev/null +++ b/examples/lean/README.md @@ -0,0 +1,77 @@ +# 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. A problem is either the +bundled one, the dimension formula for polynomial rings (`problems/dimension-formula/`), or +any Mathlib-only [lean-eval](https://github.com/leanprover/lean-eval) problem whose holes +are theorems, read from a lean-eval checkout (nothing of lean-eval is vendored here). + +Both use 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//`, 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 the agent edits (`Solution.lean`, the lakefile, the experiment folder) are ignored: the trusted copies are used | +| Metrics can't be printed | `proved` comes from comparator's exit code; `##autohelix[...]` lines in the build output are escaped | +| Mathlib is the real one | the project links `.lake/packages` to a shared Mathlib: make it read-only to the user the agent runs as (`chown -R root`), or candidate code could change what the check trusts | + +Not covered: the agent's own session isn't sandboxed. The config disables Claude Code's +web tools (`--disallowedTools=WebFetch,WebSearch`), but its shell has the network; for a +benchmark, audit the agent logs for fetches, or run the agent in a container. + +## 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 Lean v4.36.0 (`lake` on PATH, e.g. from [elan](https://github.com/leanprover/elan)) +and [bubblewrap](https://github.com/containers/bubblewrap) (`bwrap`, for comparator's +sandbox; Linux). From the AutoHelix checkout: + +```bash +python examples/lean/setup.py dimension-formula --dir /tmp/lean-dim +python examples/lean/setup.py --lean-eval PATH_TO_LEAN_EVAL abel_ruffini --dir /tmp/lean-ar +cd /tmp/lean-dim && autohelix run --cost 50 +``` + +`--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. + +## 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`): 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 of a small test statement (`tests/fixture/`). About 20 +minutes; run it after changing `check.py`: + +```bash +python examples/lean/tests/check_cases.py --packages /path/to/.lake/packages +``` diff --git a/examples/lean/goal-text.py b/examples/lean/goal-text.py deleted file mode 100644 index be0d2ee..0000000 --- a/examples/lean/goal-text.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python3 -"""The /goal arm's text: the config's goal without what only AutoHelix does. - - python3 goal-text.py autohelix/NAME/config.yaml - -AutoHelix's goal describes sessions, handoff notes and the checks AutoHelix runs after each -session; a Claude Code `/goal` session is one session in the project itself, so that part is -replaced by how to run the same checks there. The problem, the rules and "treat it as -reachable" stay word for word. -""" - -import sys -from pathlib import Path - -import yaml - -config = Path(sys.argv[1]) -goal = yaml.safe_load(config.read_text())["goal"] -start = goal.index("Work in sessions") -check = f"python3 {config.parent.as_posix()}/check.py" -print(goal[:start].rstrip() + "\n\n" + ( - f"Check your work with `{check} gate` (it builds, the statements are unchanged; `sorry`\n" - f"allowed) and `{check} observe` (complete proofs, axioms; it reports `proved`,\n" - "`sorry_decls`, `errors` and `lines`), each in a fresh project built from the original\n" - "statements, taking about a minute. You're done when `observe` reports `proved` 1.\n" - "Don't look for these proofs online.\n")) diff --git a/examples/lean/tests/cases.json b/examples/lean/tests/cases.json new file mode 100644 index 0000000..fd96dc5 --- /dev/null +++ b/examples/lean/tests/cases.json @@ -0,0 +1,15 @@ +{ + "_comment": "Each case's files are laid over a fresh project of `problem` (`fixture` = tests/fixture's two_add_two). gate: the gate's expected exit code (0 passes); proved: the one ##autohelix[proved=...] value observe must print.", + "cases": { + "stub": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "the unsolved starting point builds"}, + "partial": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "proved lemmas plus sorries: a checkpoint"}, + "solution-edit": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "an edited Solution.lean is ignored (trusted copy used)"}, + "spoof": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "##autohelix lines printed by the build don't count"}, + "broken": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "a build error"}, + "axiom": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "a new axiom"}, + "native": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "native_decide (an extra axiom)"}, + "edited": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "a weakened statement"}, + "notation": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "notation that redefines ringKrullDim"}, + "good": {"problem": "fixture", "gate": 0, "proved": 1, "what": "a complete two-file proof"} + } +} diff --git a/examples/lean/tests/cases/axiom/Submission.lean b/examples/lean/tests/cases/axiom/Submission.lean new file mode 100644 index 0000000..36d6567 --- /dev/null +++ b/examples/lean/tests/cases/axiom/Submission.lean @@ -0,0 +1,13 @@ +import ChallengeDeps +import Submission.Helpers + +axiom cheat : False + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := cheat.elim + +end Submission diff --git a/examples/lean/tests/cases/broken/Submission.lean b/examples/lean/tests/cases/broken/Submission.lean new file mode 100644 index 0000000..85012d7 --- /dev/null +++ b/examples/lean/tests/cases/broken/Submission.lean @@ -0,0 +1,13 @@ +import ChallengeDeps +import Submission.Helpers + + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + exact foo + +end Submission diff --git a/examples/lean/tests/cases/edited/Submission.lean b/examples/lean/tests/cases/edited/Submission.lean new file mode 100644 index 0000000..91a86a6 --- /dev/null +++ b/examples/lean/tests/cases/edited/Submission.lean @@ -0,0 +1,11 @@ +import ChallengeDeps +import Submission.Helpers + + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) : + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry + +end Submission diff --git a/examples/lean/tests/cases/good/Submission.lean b/examples/lean/tests/cases/good/Submission.lean new file mode 100644 index 0000000..356613d --- /dev/null +++ b/examples/lean/tests/cases/good/Submission.lean @@ -0,0 +1,8 @@ +import ChallengeDeps +import Submission.Lemmas + +namespace Submission + +theorem two_add_two : (2 : Nat) + 2 = 4 := Lemmas.two_add_two + +end Submission diff --git a/examples/lean/tests/cases/good/Submission/Lemmas.lean b/examples/lean/tests/cases/good/Submission/Lemmas.lean new file mode 100644 index 0000000..bc96dfa --- /dev/null +++ b/examples/lean/tests/cases/good/Submission/Lemmas.lean @@ -0,0 +1,6 @@ +namespace Submission.Lemmas + +/-- In its own module, so the case also checks that `Submission/` files are carried over. -/ +theorem two_add_two : (2 : Nat) + 2 = 4 := rfl + +end Submission.Lemmas diff --git a/examples/lean/tests/cases/native/Submission.lean b/examples/lean/tests/cases/native/Submission.lean new file mode 100644 index 0000000..e3a51b3 --- /dev/null +++ b/examples/lean/tests/cases/native/Submission.lean @@ -0,0 +1,16 @@ +import ChallengeDeps +import Submission.Helpers + + +namespace Submission + +theorem two : 2 + 2 = 4 := by native_decide + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + have := two + sorry + +end Submission diff --git a/examples/lean/tests/cases/notation/Submission.lean b/examples/lean/tests/cases/notation/Submission.lean new file mode 100644 index 0000000..0ef7d05 --- /dev/null +++ b/examples/lean/tests/cases/notation/Submission.lean @@ -0,0 +1,16 @@ +import ChallengeDeps +import Submission.Helpers + +/-- every ring has dimension ⊤ here -/ +noncomputable def myDim (R : Type*) [CommRing R] : WithBot ℕ∞ := ⊤ +notation "ringKrullDim" => myDim + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry + +end Submission diff --git a/examples/lean/tests/cases/partial/Submission.lean b/examples/lean/tests/cases/partial/Submission.lean new file mode 100644 index 0000000..86c2b9e --- /dev/null +++ b/examples/lean/tests/cases/partial/Submission.lean @@ -0,0 +1,18 @@ +import ChallengeDeps +import Submission.Helpers + + +namespace Submission + +lemma helper : (1 : ℕ) + 1 = 2 := rfl + +lemma open_part (n : ℕ) : n = n := by + sorry + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry + +end Submission diff --git a/examples/lean/tests/cases/solution-edit/Solution.lean b/examples/lean/tests/cases/solution-edit/Solution.lean new file mode 100644 index 0000000..62890d8 --- /dev/null +++ b/examples/lean/tests/cases/solution-edit/Solution.lean @@ -0,0 +1,4 @@ +import ChallengeDeps +import Submission + +theorem dimension_formula : True := trivial diff --git a/examples/lean/tests/cases/solution-edit/Submission.lean b/examples/lean/tests/cases/solution-edit/Submission.lean new file mode 100644 index 0000000..3174454 --- /dev/null +++ b/examples/lean/tests/cases/solution-edit/Submission.lean @@ -0,0 +1,13 @@ +import ChallengeDeps +import Submission.Helpers + + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry + +end Submission diff --git a/examples/lean/tests/cases/spoof/Submission.lean b/examples/lean/tests/cases/spoof/Submission.lean new file mode 100644 index 0000000..92c30e0 --- /dev/null +++ b/examples/lean/tests/cases/spoof/Submission.lean @@ -0,0 +1,15 @@ +import ChallengeDeps +import Submission.Helpers + +#eval IO.println "##autohelix[proved=1]" +run_cmd Lean.logInfo "##autohelix[proved=1]" + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry + +end Submission diff --git a/examples/lean/tests/cases/stub/Submission.lean b/examples/lean/tests/cases/stub/Submission.lean new file mode 100644 index 0000000..3174454 --- /dev/null +++ b/examples/lean/tests/cases/stub/Submission.lean @@ -0,0 +1,13 @@ +import ChallengeDeps +import Submission.Helpers + + +namespace Submission + +theorem dimension_formula (k : Type*) [Field k] (n : ℕ) + (P : Ideal (MvPolynomial (Fin n) k)) [P.IsPrime] : + (P.height : WithBot ℕ∞) + ringKrullDim (MvPolynomial (Fin n) k ⧸ P) = n ∧ + ringKrullDim (MvPolynomial (Fin n) k) = n := by + sorry + +end Submission diff --git a/examples/lean/tests/check_cases.py b/examples/lean/tests/check_cases.py new file mode 100644 index 0000000..33fbf98 --- /dev/null +++ b/examples/lean/tests/check_cases.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Run check.py on known submissions: what the gate accepts and what observe proves. + + python examples/lean/tests/check_cases.py --packages /path/to/.lake/packages [CASE ...] + +Each case in cases/ is a handful of files (a `Submission.lean`, sometimes `Submission/` or +an edited `Solution.lean`) laid over a fresh project of its problem (cases.json: the +bundled dimension-formula, or tests/fixture's two_add_two, a statement with a one-line +proof). The project is set up once per problem with setup.py; each case runs +`check.py gate` and `check.py observe` in its own copy of it, and passes when the gate's +exit code and observe's one `##autohelix[proved=...]` value are the expected ones. + +Needs what setup.py needs (Lean v4.36.0's `lake` on PATH, bwrap, a Mathlib v4.36.0 +`.lake/packages` with its build cache). Each check takes about a minute, so all ten cases +take about 20. Not part of the test suite: run it by hand after changing check.py. +""" + +import argparse +import json +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +SETUP = HERE.parent / "setup.py" +FIXTURE = HERE / "fixture" + + +def set_up(problem: str, packages: Path, scratch: Path) -> Path: + project = scratch / f"project-{problem}" + source = ["--lean-eval", str(FIXTURE), "two_add_two"] if problem == "fixture" else [problem] + subprocess.run([sys.executable, str(SETUP), *source, "--dir", str(project), "--packages", str(packages)], + check=True, stdout=subprocess.DEVNULL) + return project + + +def run_case(name: str, expected: dict, project: Path, scratch: Path) -> tuple[bool, str]: + copy = scratch / f"case-{name}" + shutil.copytree(project, copy, symlinks=True) + shutil.copytree(HERE / "cases" / name, copy, dirs_exist_ok=True) + check = next(copy.glob("autohelix/*/check.py")) + gate = subprocess.run([sys.executable, str(check), "gate"], cwd=copy, capture_output=True, text=True) + observe = subprocess.run([sys.executable, str(check), "observe"], cwd=copy, capture_output=True, text=True) + proved = re.findall(r"^##autohelix\[proved=([0-9.]+)\]$", observe.stdout, re.M) + ok = gate.returncode == expected["gate"] and len(proved) == 1 and float(proved[0]) == expected["proved"] + summary = next((line for line in observe.stdout.splitlines() if line.startswith("summary:")), "no summary") + return ok, f"gate exit {gate.returncode}, proved {proved} ({summary})" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--packages", type=Path, required=True, help="a Mathlib v4.36.0 .lake/packages folder") + parser.add_argument("cases", nargs="*", help="cases to run (default: all)") + args = parser.parse_args() + cases = json.loads((HERE / "cases.json").read_text())["cases"] + names = args.cases or list(cases) + unknown = [n for n in names if n not in cases] + if unknown: + print(f"unknown cases: {', '.join(unknown)}", file=sys.stderr) + return 2 + failed = [] + with tempfile.TemporaryDirectory(prefix="lean-check-cases-") as tmp: + scratch = Path(tmp) + projects = {} + for name in names: + problem = cases[name]["problem"] + if problem not in projects: + projects[problem] = set_up(problem, args.packages.resolve(), scratch) + ok, detail = run_case(name, cases[name], projects[problem], scratch) + print(f"{'ok ' if ok else 'FAIL'} {name:14} {cases[name]['what']}: {detail}", flush=True) + if not ok: + failed.append(name) + print(f"{len(names) - len(failed)} of {len(names)} cases as expected" + (f"; failed: {', '.join(failed)}" if failed else "")) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/lean/tests/fixture/generated/two_add_two/Challenge.lean b/examples/lean/tests/fixture/generated/two_add_two/Challenge.lean new file mode 100644 index 0000000..5722d5f --- /dev/null +++ b/examples/lean/tests/fixture/generated/two_add_two/Challenge.lean @@ -0,0 +1,5 @@ +import ChallengeDeps + +/-- A statement with a one-line proof, for the check's `good` test case. -/ +theorem two_add_two : (2 : Nat) + 2 = 4 := by + sorry diff --git a/examples/lean/tests/fixture/generated/two_add_two/README.md b/examples/lean/tests/fixture/generated/two_add_two/README.md new file mode 100644 index 0000000..0b9448f --- /dev/null +++ b/examples/lean/tests/fixture/generated/two_add_two/README.md @@ -0,0 +1,5 @@ +# `two_add_two` + +A test statement for the check's test cases (2 + 2 = 4) + +Laid out like a lean-eval workspace (`generated//`), so `setup.py --lean-eval` reads it. diff --git a/examples/lean/tests/fixture/generated/two_add_two/Solution.lean b/examples/lean/tests/fixture/generated/two_add_two/Solution.lean new file mode 100644 index 0000000..ca3856c --- /dev/null +++ b/examples/lean/tests/fixture/generated/two_add_two/Solution.lean @@ -0,0 +1,5 @@ +import ChallengeDeps +import Submission + +theorem two_add_two : (2 : Nat) + 2 = 4 := by + exact Submission.two_add_two diff --git a/examples/lean/tests/fixture/generated/two_add_two/Submission.lean b/examples/lean/tests/fixture/generated/two_add_two/Submission.lean new file mode 100644 index 0000000..1652f14 --- /dev/null +++ b/examples/lean/tests/fixture/generated/two_add_two/Submission.lean @@ -0,0 +1,8 @@ +import ChallengeDeps + +namespace Submission + +theorem two_add_two : (2 : Nat) + 2 = 4 := by + sorry + +end Submission diff --git a/examples/lean/tests/fixture/generated/two_add_two/config.json b/examples/lean/tests/fixture/generated/two_add_two/config.json new file mode 100644 index 0000000..5c91124 --- /dev/null +++ b/examples/lean/tests/fixture/generated/two_add_two/config.json @@ -0,0 +1,6 @@ +{ + "challenge_module": "Challenge", + "solution_module": "Solution", + "theorem_names": ["two_add_two"], + "permitted_axioms": ["propext", "Quot.sound", "Classical.choice"] +} diff --git a/examples/lean/tests/fixture/generated/two_add_two/holes.json b/examples/lean/tests/fixture/generated/two_add_two/holes.json new file mode 100644 index 0000000..c07c716 --- /dev/null +++ b/examples/lean/tests/fixture/generated/two_add_two/holes.json @@ -0,0 +1,4 @@ +{ + "id": "two_add_two", + "holes": [{"name": "two_add_two", "basename": "two_add_two", "kind": "theorem"}] +} diff --git a/tests/test_examples.py b/tests/test_examples.py index 6411589..91c3290 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -15,7 +15,9 @@ SCAFFOLDED = {"algotune", "kernelbench"} # Laid out by its own setup.py from template/, which holds the experiment. TEMPLATED = {"autoresearch"} -BUNDLED = sorted(d.name for d in EXAMPLES.iterdir() if d.is_dir() and d.name not in SCAFFOLDED | TEMPLATED +# Its setup.py writes the config, one per problem (examples/lean/setup.py's CONFIG). +GENERATED = {"lean"} +BUNDLED = sorted(d.name for d in EXAMPLES.iterdir() if d.is_dir() and d.name not in SCAFFOLDED | TEMPLATED | GENERATED and not d.name.startswith((".", "__"))) @@ -90,3 +92,33 @@ def test_algotune_setup_writes_its_config_as_the_only_experiment(tmp_path): committed = subprocess.run(["git", "ls-files"], cwd=project, capture_output=True, text=True, check=True).stdout.split() assert {"autohelix/algotune/config.yaml", "solver.py", "toy.py"} <= set(committed) + + +def test_lean_setup_writes_a_valid_config_as_the_only_experiment(tmp_path, monkeypatch): + """examples/lean/setup.py lays out a problem (here the bundled dimension formula) as a + project: the agent's files, the experiment folder with the trusted copies and check.py, + and a config that validates, committed as the project's one commit. Lean itself isn't + needed for that: `lake` is faked and the Mathlib folder is empty.""" + spec = importlib.util.spec_from_file_location("lean_setup", EXAMPLES / "lean" / "setup.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + monkeypatch.setattr(module.shutil, "which", lambda name: f"/usr/bin/{name}") + for key, value in {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@t", "GIT_CONFIG_GLOBAL": "/dev/null"}.items(): + monkeypatch.setenv(key, value) + packages = tmp_path / "packages" + (packages / "mathlib").mkdir(parents=True) + project = tmp_path / "dim" + monkeypatch.setattr("sys.argv", ["setup.py", "dimension-formula", "--dir", str(project), + "--packages", str(packages)]) + assert module.main() == 0 + assert project_configs(project) == [experiment_config("dimension-formula")] + config = load_config(project) + assert config.validate() == [] + committed = subprocess.run(["git", "ls-files"], cwd=project, capture_output=True, text=True, + check=True).stdout.split() + experiment = "autohelix/dimension-formula/" + assert {experiment + name for name in ["config.yaml", "check.py", "Challenge.lean", "Solution.lean", + "config.json"]} <= set(committed) + assert {"Submission.lean", "Challenge.lean", ".lake/packages"} <= set(committed) + assert (project / ".lake" / "packages").resolve() == packages.resolve() From 8af40917d957a084e230650c9eac77b590d9d089 Mon Sep 17 00:00:00 2001 From: mtrager Date: Mon, 30 Nov 2026 16:46:46 -0500 Subject: [PATCH 3/3] Lean example: lean-eval problems only, results, what the setup doesn't enforce setup.py takes a lean-eval checkout and a problem id, and refuses a checkout not on Lean v4.36.0. The dimension formula moves into the tests' fixture, a lean-eval-shaped checkout. The README gets a short results paragraph and says plainly that the agent's session can change what the check trusts (Mathlib, the toolchain, the stored check.py). check.py exits 2 without bwrap; check_cases.py reads metrics anywhere in a line, so the spoof case tests the escaping. --- CLAUDE.md | 2 +- README.md | 2 +- examples/README.md | 5 +- examples/lean/README.md | 62 ++++++++++------ examples/lean/setup.py | 70 +++++++++---------- examples/lean/template/check.py | 9 ++- examples/lean/tests/cases.json | 22 +++--- examples/lean/tests/check_cases.py | 13 ++-- .../dimension_formula}/Challenge.lean | 0 .../dimension_formula}/ChallengeDeps.lean | 0 .../generated/dimension_formula}/README.md | 0 .../dimension_formula}/Solution.lean | 0 .../dimension_formula}/Submission.lean | 0 .../Submission/Helpers.lean | 0 .../generated/dimension_formula}/config.json | 0 .../generated/dimension_formula/holes.json | 4 ++ .../fixture/generated/two_add_two/README.md | 2 +- examples/lean/tests/fixture/lean-toolchain | 1 + tests/test_examples.py | 25 ++++++- 19 files changed, 131 insertions(+), 86 deletions(-) rename examples/lean/{problems/dimension-formula => tests/fixture/generated/dimension_formula}/Challenge.lean (100%) rename examples/lean/{problems/dimension-formula => tests/fixture/generated/dimension_formula}/ChallengeDeps.lean (100%) rename examples/lean/{problems/dimension-formula => tests/fixture/generated/dimension_formula}/README.md (100%) rename examples/lean/{problems/dimension-formula => tests/fixture/generated/dimension_formula}/Solution.lean (100%) rename examples/lean/{problems/dimension-formula => tests/fixture/generated/dimension_formula}/Submission.lean (100%) rename examples/lean/{problems/dimension-formula => tests/fixture/generated/dimension_formula}/Submission/Helpers.lean (100%) rename examples/lean/{problems/dimension-formula => tests/fixture/generated/dimension_formula}/config.json (100%) create mode 100644 examples/lean/tests/fixture/generated/dimension_formula/holes.json create mode 100644 examples/lean/tests/fixture/lean-toolchain diff --git a/CLAUDE.md b/CLAUDE.md index 00fb22f..28c109a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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) diff --git a/README.md b/README.md index 3a5ec86..a667f8f 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/examples/README.md b/examples/README.md index fccf598..6a48478 100644 --- a/examples/README.md +++ b/examples/README.md @@ -18,7 +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, pass or fail (checked by `lake comparator`) | Proof files (`Submission.lean`, `Submission/`) | +| [**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 | @@ -71,7 +71,8 @@ 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 dimension-formula --dir /tmp/autohelix-lean +python examples/lean/setup.py PATH_TO_LEAN_EVAL annals_unit_conjecture \ + --dir /tmp/autohelix-lean ``` ## KernelBench Tasks (GPU kernel optimization) diff --git a/examples/lean/README.md b/examples/lean/README.md index d4229f3..2eb68e8 100644 --- a/examples/lean/README.md +++ b/examples/lean/README.md @@ -2,15 +2,14 @@ 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. A problem is either the -bundled one, the dimension formula for polynomial rings (`problems/dimension-formula/`), or -any Mathlib-only [lean-eval](https://github.com/leanprover/lean-eval) problem whose holes +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). -Both use lean-eval's layout: the agent writes `Submission.lean` and `Submission/`; +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//`, with `check.py`. +folder, `autohelix//` (the id with `-` for `_`), with `check.py`. ## What is enforced @@ -24,13 +23,17 @@ verdict; the build's output is shown to the agent but never parsed for metrics. |---|---| | 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 the agent edits (`Solution.lean`, the lakefile, the experiment folder) are ignored: the trusted copies are used | -| Metrics can't be printed | `proved` comes from comparator's exit code; `##autohelix[...]` lines in the build output are escaped | -| Mathlib is the real one | the project links `.lake/packages` to a shared Mathlib: make it read-only to the user the agent runs as (`chown -R root`), or candidate code could change what the check trusts | - -Not covered: the agent's own session isn't sandboxed. The config disables Claude Code's -web tools (`--disallowedTools=WebFetch,WebSearch`), but its shell has the network; for a -benchmark, audit the agent logs for fetches, or run the agent in a container. +| 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 @@ -49,27 +52,42 @@ Bound a run by dollars: `autohelix run --cost 50`. ## Set up -Needs Lean v4.36.0 (`lake` on PATH, e.g. from [elan](https://github.com/leanprover/elan)) -and [bubblewrap](https://github.com/containers/bubblewrap) (`bwrap`, for comparator's -sandbox; Linux). From the AutoHelix checkout: +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 -python examples/lean/setup.py dimension-formula --dir /tmp/lean-dim -python examples/lean/setup.py --lean-eval PATH_TO_LEAN_EVAL abel_ruffini --dir /tmp/lean-ar -cd /tmp/lean-dim && autohelix run --cost 50 +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`): 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 of a small test statement (`tests/fixture/`). About 20 +(`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 diff --git a/examples/lean/setup.py b/examples/lean/setup.py index d491e58..ca281b9 100644 --- a/examples/lean/setup.py +++ b/examples/lean/setup.py @@ -1,16 +1,14 @@ #!/usr/bin/env python3 -"""Set up a Lean proof problem as a standalone AutoHelix project. +"""Set up a lean-eval problem as a standalone AutoHelix project. - python examples/lean/setup.py dimension-formula --dir /tmp/lean-dim - python examples/lean/setup.py --lean-eval ~/lean-eval abel_ruffini --dir /tmp/lean-ar - cd /tmp/lean-dim && autohelix run -n 3 + python examples/lean/setup.py ~/lean-eval annals_unit_conjecture --dir /tmp/lean-unit + cd /tmp/lean-unit && autohelix run --cost 50 -The first form uses a problem bundled in `problems/`; the second a problem of a -[lean-eval](https://github.com/leanprover/lean-eval) checkout (its `generated//` -workspace; Mathlib-only problems whose holes are theorems). Both use lean-eval's layout: -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//` with `check.py`, which runs `lake comparator` on them. +The problem is read from a [lean-eval](https://github.com/leanprover/lean-eval) checkout +on Lean v4.36.0 (its `generated//` 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//` (`-` 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 @@ -30,7 +28,6 @@ HERE = Path(__file__).resolve().parent TEMPLATE = HERE / "template" -PROBLEMS = HERE / "problems" TOOLCHAIN = (TEMPLATE / "lean-toolchain").read_text().strip() PROJECT_FILES = ["lakefile.toml", "lake-manifest.json", "lean-toolchain"] FIXED = ["ChallengeDeps.lean", "Challenge.lean", "Solution.lean"] @@ -125,27 +122,27 @@ 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) -> tuple[Path, str, str]: - """The problem's folder, its experiment name, and how the goal names it.""" - if args.lean_eval: - 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, slug(args.problem), f"lean-eval problem `{args.problem}`:" - source = PROBLEMS / args.problem +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 bundled problem {args.problem!r}: {', '.join(p.name for p in sorted(PROBLEMS.iterdir()))}") - return source, args.problem, "The problem:" + 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: @@ -157,8 +154,8 @@ def title(source: Path) -> str: def main() -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("problem", help="a bundled problem (problems/) or, with --lean-eval, a lean-eval id") - parser.add_argument("--lean-eval", type=Path, help="a lean-eval checkout") + 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)") @@ -166,7 +163,8 @@ def main() -> int: help="where to prepare one when --packages is not given") args = parser.parse_args() - source, name, problem = problem_source(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 @@ -200,7 +198,7 @@ def main() -> int: 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=problem, theorems=theorems, + 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) @@ -208,7 +206,7 @@ def main() -> int: 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 -n 3") + print(f"Project ready in {project}:\n cd {project}\n autohelix run --cost 50") return 0 diff --git a/examples/lean/template/check.py b/examples/lean/template/check.py index e45d2a7..01cd9e8 100644 --- a/examples/lean/template/check.py +++ b/examples/lean/template/check.py @@ -60,7 +60,7 @@ def submission_files(candidate: Path) -> list[Path]: if not name.endswith(".lean"): continue if path.is_symlink() or not path.is_file(): - print(f"note: skipped {path.relative_to(candidate)} (not a regular file)") + print(safe(f"note: skipped {path.relative_to(candidate)} (not a regular file)")) continue files.append(path) return sorted(files) @@ -80,16 +80,17 @@ def packages_dir(candidate: Path) -> Path: def prepare(candidate: Path, gate: bool) -> Path: + files, packages = submission_files(candidate), packages_dir(candidate) # before anything is written scratch = os.environ.get("AUTOHELIX_SCRATCH") or None work = Path(tempfile.mkdtemp(prefix="lean-check-", dir=scratch)).resolve() for name in TRUSTED: shutil.copyfile(HERE / name, work / name) - for path in submission_files(candidate): + for path in files: dest = work / path.relative_to(candidate) dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, dest) (work / ".lake").mkdir() - (work / ".lake" / "packages").symlink_to(packages_dir(candidate)) + (work / ".lake" / "packages").symlink_to(packages) settings = config() if gate: settings["permitted_axioms"] = settings["permitted_axioms"] + ["sorryAx"] @@ -101,6 +102,8 @@ def comparator(work: Path) -> tuple[int, str]: lake = shutil.which("lake") if lake is None: raise CheckError("lake is not on PATH") + if shutil.which("bwrap") is None: + raise CheckError("bwrap is not on PATH (lake comparator's sandbox needs bubblewrap)") proc = subprocess.Popen([lake, "comparator"], cwd=work, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", start_new_session=True) diff --git a/examples/lean/tests/cases.json b/examples/lean/tests/cases.json index fd96dc5..728da57 100644 --- a/examples/lean/tests/cases.json +++ b/examples/lean/tests/cases.json @@ -1,15 +1,15 @@ { - "_comment": "Each case's files are laid over a fresh project of `problem` (`fixture` = tests/fixture's two_add_two). gate: the gate's expected exit code (0 passes); proved: the one ##autohelix[proved=...] value observe must print.", + "_comment": "Each case's files are laid over a fresh project of `problem` (a problem of tests/fixture/generated/). gate: the gate's expected exit code (0 passes); proved: the one ##autohelix[proved=...] value observe must print.", "cases": { - "stub": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "the unsolved starting point builds"}, - "partial": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "proved lemmas plus sorries: a checkpoint"}, - "solution-edit": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "an edited Solution.lean is ignored (trusted copy used)"}, - "spoof": {"problem": "dimension-formula", "gate": 0, "proved": 0, "what": "##autohelix lines printed by the build don't count"}, - "broken": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "a build error"}, - "axiom": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "a new axiom"}, - "native": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "native_decide (an extra axiom)"}, - "edited": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "a weakened statement"}, - "notation": {"problem": "dimension-formula", "gate": 1, "proved": 0, "what": "notation that redefines ringKrullDim"}, - "good": {"problem": "fixture", "gate": 0, "proved": 1, "what": "a complete two-file proof"} + "stub": {"problem": "dimension_formula", "gate": 0, "proved": 0, "what": "the unsolved starting point builds"}, + "partial": {"problem": "dimension_formula", "gate": 0, "proved": 0, "what": "proved lemmas plus sorries: a checkpoint"}, + "solution-edit": {"problem": "dimension_formula", "gate": 0, "proved": 0, "what": "an edited Solution.lean is ignored (trusted copy used)"}, + "spoof": {"problem": "dimension_formula", "gate": 0, "proved": 0, "what": "##autohelix lines printed by the build don't count"}, + "broken": {"problem": "dimension_formula", "gate": 1, "proved": 0, "what": "a build error"}, + "axiom": {"problem": "dimension_formula", "gate": 1, "proved": 0, "what": "a new axiom"}, + "native": {"problem": "dimension_formula", "gate": 1, "proved": 0, "what": "native_decide (an extra axiom)"}, + "edited": {"problem": "dimension_formula", "gate": 1, "proved": 0, "what": "a weakened statement (Solution.lean no longer builds)"}, + "notation": {"problem": "dimension_formula", "gate": 1, "proved": 0, "what": "notation that redefines ringKrullDim"}, + "good": {"problem": "two_add_two", "gate": 0, "proved": 1, "what": "a complete two-file proof"} } } diff --git a/examples/lean/tests/check_cases.py b/examples/lean/tests/check_cases.py index 33fbf98..1fc24b4 100644 --- a/examples/lean/tests/check_cases.py +++ b/examples/lean/tests/check_cases.py @@ -4,9 +4,10 @@ python examples/lean/tests/check_cases.py --packages /path/to/.lake/packages [CASE ...] Each case in cases/ is a handful of files (a `Submission.lean`, sometimes `Submission/` or -an edited `Solution.lean`) laid over a fresh project of its problem (cases.json: the -bundled dimension-formula, or tests/fixture's two_add_two, a statement with a one-line -proof). The project is set up once per problem with setup.py; each case runs +an edited `Solution.lean`) laid over a fresh project of its problem (cases.json), set up +with setup.py from tests/fixture, a lean-eval-shaped checkout of two problems: the +dimension formula for polynomial rings and two_add_two, a statement with a one-line proof. +The project is set up once per problem; each case runs `check.py gate` and `check.py observe` in its own copy of it, and passes when the gate's exit code and observe's one `##autohelix[proved=...]` value are the expected ones. @@ -31,8 +32,7 @@ def set_up(problem: str, packages: Path, scratch: Path) -> Path: project = scratch / f"project-{problem}" - source = ["--lean-eval", str(FIXTURE), "two_add_two"] if problem == "fixture" else [problem] - subprocess.run([sys.executable, str(SETUP), *source, "--dir", str(project), "--packages", str(packages)], + subprocess.run([sys.executable, str(SETUP), str(FIXTURE), problem, "--dir", str(project), "--packages", str(packages)], check=True, stdout=subprocess.DEVNULL) return project @@ -44,7 +44,8 @@ def run_case(name: str, expected: dict, project: Path, scratch: Path) -> tuple[b check = next(copy.glob("autohelix/*/check.py")) gate = subprocess.run([sys.executable, str(check), "gate"], cwd=copy, capture_output=True, text=True) observe = subprocess.run([sys.executable, str(check), "observe"], cwd=copy, capture_output=True, text=True) - proved = re.findall(r"^##autohelix\[proved=([0-9.]+)\]$", observe.stdout, re.M) + # Anywhere in a line, as AutoHelix reads metrics: an unescaped line from the build counts too. + proved = re.findall(r"##autohelix\[proved=([0-9.]+)\]", observe.stdout) ok = gate.returncode == expected["gate"] and len(proved) == 1 and float(proved[0]) == expected["proved"] summary = next((line for line in observe.stdout.splitlines() if line.startswith("summary:")), "no summary") return ok, f"gate exit {gate.returncode}, proved {proved} ({summary})" diff --git a/examples/lean/problems/dimension-formula/Challenge.lean b/examples/lean/tests/fixture/generated/dimension_formula/Challenge.lean similarity index 100% rename from examples/lean/problems/dimension-formula/Challenge.lean rename to examples/lean/tests/fixture/generated/dimension_formula/Challenge.lean diff --git a/examples/lean/problems/dimension-formula/ChallengeDeps.lean b/examples/lean/tests/fixture/generated/dimension_formula/ChallengeDeps.lean similarity index 100% rename from examples/lean/problems/dimension-formula/ChallengeDeps.lean rename to examples/lean/tests/fixture/generated/dimension_formula/ChallengeDeps.lean diff --git a/examples/lean/problems/dimension-formula/README.md b/examples/lean/tests/fixture/generated/dimension_formula/README.md similarity index 100% rename from examples/lean/problems/dimension-formula/README.md rename to examples/lean/tests/fixture/generated/dimension_formula/README.md diff --git a/examples/lean/problems/dimension-formula/Solution.lean b/examples/lean/tests/fixture/generated/dimension_formula/Solution.lean similarity index 100% rename from examples/lean/problems/dimension-formula/Solution.lean rename to examples/lean/tests/fixture/generated/dimension_formula/Solution.lean diff --git a/examples/lean/problems/dimension-formula/Submission.lean b/examples/lean/tests/fixture/generated/dimension_formula/Submission.lean similarity index 100% rename from examples/lean/problems/dimension-formula/Submission.lean rename to examples/lean/tests/fixture/generated/dimension_formula/Submission.lean diff --git a/examples/lean/problems/dimension-formula/Submission/Helpers.lean b/examples/lean/tests/fixture/generated/dimension_formula/Submission/Helpers.lean similarity index 100% rename from examples/lean/problems/dimension-formula/Submission/Helpers.lean rename to examples/lean/tests/fixture/generated/dimension_formula/Submission/Helpers.lean diff --git a/examples/lean/problems/dimension-formula/config.json b/examples/lean/tests/fixture/generated/dimension_formula/config.json similarity index 100% rename from examples/lean/problems/dimension-formula/config.json rename to examples/lean/tests/fixture/generated/dimension_formula/config.json diff --git a/examples/lean/tests/fixture/generated/dimension_formula/holes.json b/examples/lean/tests/fixture/generated/dimension_formula/holes.json new file mode 100644 index 0000000..6644a0f --- /dev/null +++ b/examples/lean/tests/fixture/generated/dimension_formula/holes.json @@ -0,0 +1,4 @@ +{ + "id": "dimension_formula", + "holes": [{"name": "dimension_formula", "basename": "dimension_formula", "kind": "theorem"}] +} diff --git a/examples/lean/tests/fixture/generated/two_add_two/README.md b/examples/lean/tests/fixture/generated/two_add_two/README.md index 0b9448f..9ef87d0 100644 --- a/examples/lean/tests/fixture/generated/two_add_two/README.md +++ b/examples/lean/tests/fixture/generated/two_add_two/README.md @@ -2,4 +2,4 @@ A test statement for the check's test cases (2 + 2 = 4) -Laid out like a lean-eval workspace (`generated//`), so `setup.py --lean-eval` reads it. +Laid out like a lean-eval workspace (`generated//`), so setup.py reads it from tests/fixture. diff --git a/examples/lean/tests/fixture/lean-toolchain b/examples/lean/tests/fixture/lean-toolchain new file mode 100644 index 0000000..00f8483 --- /dev/null +++ b/examples/lean/tests/fixture/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.36.0 diff --git a/tests/test_examples.py b/tests/test_examples.py index 91c3290..986b229 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -3,6 +3,7 @@ in the project `examples/setup_example.py` makes of it.""" import importlib.util +import shutil import subprocess from pathlib import Path @@ -95,8 +96,8 @@ def test_algotune_setup_writes_its_config_as_the_only_experiment(tmp_path): def test_lean_setup_writes_a_valid_config_as_the_only_experiment(tmp_path, monkeypatch): - """examples/lean/setup.py lays out a problem (here the bundled dimension formula) as a - project: the agent's files, the experiment folder with the trusted copies and check.py, + """examples/lean/setup.py lays out a lean-eval problem (here the dimension formula of its + tests' lean-eval-shaped fixture) as a project: the agent's files, the experiment folder with the trusted copies and check.py, and a config that validates, committed as the project's one commit. Lean itself isn't needed for that: `lake` is faked and the Mathlib folder is empty.""" spec = importlib.util.spec_from_file_location("lean_setup", EXAMPLES / "lean" / "setup.py") @@ -109,7 +110,8 @@ def test_lean_setup_writes_a_valid_config_as_the_only_experiment(tmp_path, monke packages = tmp_path / "packages" (packages / "mathlib").mkdir(parents=True) project = tmp_path / "dim" - monkeypatch.setattr("sys.argv", ["setup.py", "dimension-formula", "--dir", str(project), + fixture = EXAMPLES / "lean" / "tests" / "fixture" + monkeypatch.setattr("sys.argv", ["setup.py", str(fixture), "dimension_formula", "--dir", str(project), "--packages", str(packages)]) assert module.main() == 0 assert project_configs(project) == [experiment_config("dimension-formula")] @@ -122,3 +124,20 @@ def test_lean_setup_writes_a_valid_config_as_the_only_experiment(tmp_path, monke "config.json"]} <= set(committed) assert {"Submission.lean", "Challenge.lean", ".lake/packages"} <= set(committed) assert (project / ".lake" / "packages").resolve() == packages.resolve() + + +def test_lean_setup_refuses_a_lean_eval_checkout_on_another_toolchain(tmp_path, monkeypatch, capsys): + """The template is pinned to Lean v4.36.0: a lean-eval checkout on another toolchain is + refused before anything is written, naming the commit the README's results used.""" + spec = importlib.util.spec_from_file_location("lean_setup", EXAMPLES / "lean" / "setup.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + checkout = tmp_path / "lean-eval" + shutil.copytree(EXAMPLES / "lean" / "tests" / "fixture", checkout) + (checkout / "lean-toolchain").write_text("leanprover/lean4:v4.99.0\n") + project = tmp_path / "dim" + monkeypatch.setattr("sys.argv", ["setup.py", str(checkout), "dimension_formula", "--dir", str(project)]) + with pytest.raises(SystemExit) as raised: + module.main() + assert "v4.99.0" in str(raised.value) and "7c03706" in str(raised.value) + assert not project.exists()