Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2556fdace9 | |||
| 6817b074bd | |||
| 46436f2ee0 | |||
| e1e99645be | |||
| 45fd66d3ab | |||
| 66b9651d68 |
@@ -144,11 +144,15 @@
|
||||
!skills/larv-review/standards/
|
||||
!skills/larv-review/standards/*.md
|
||||
!workflow-bench/
|
||||
!workflow-bench/advisor-judge-prompt.md
|
||||
!workflow-bench/advisor-run-prompt.md
|
||||
!workflow-bench/advisor_bench.py
|
||||
!workflow-bench/bench.py
|
||||
!workflow-bench/compare-prompt.md
|
||||
!workflow-bench/compare.py
|
||||
!workflow-bench/review_git.py
|
||||
!workflow-bench/run-prompt.md
|
||||
!workflow-bench/setup.cfg
|
||||
!workflow-bench/test_advisor_bench.py
|
||||
!workflow-bench/test_bench.py
|
||||
!workflow-bench/test_review_git.py
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Add `workflow-bench/advisor_bench.py`, a bench of the advisor tool on six archived L 1 and L 2 chunks. Sonnet 5.5 alone passed all six, as Opus 5.5 at medium did, for 41% less, and its advisor ran in one of six runs, so workers stay without it.
|
||||
- loop-claude's judge on an Opus 5.5 project now runs on Opus 5.5 at xhigh in every chunk, never at medium: in replays medium sometimes closed a chunk whose worker had asked a question the README or records answer, where xhigh quoted the answer. The judge never runs on Fable 5.2 either, since each Fable 5.2 rung replayed missed an interrupt. `judge-replay` now also replays each rung above the project's that a review climbs to, and reports what each misses.
|
||||
|
||||
## 0.8.0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Claude Code configuration
|
||||
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
|
||||
|
||||
## Goals
|
||||
|
||||
|
||||
@@ -416,6 +416,20 @@ loop-claude's prompt names the rungs a trigger opens, so the worker computes no
|
||||
|
||||
Valid while the ladder orders its rungs by competence.
|
||||
|
||||
## routing: a worker runs without the advisor tool
|
||||
|
||||
2026-11-12, lilleman, settled by the bench below. Serves goal 1.4: a switch that raises cost without raising quality is no saving. Valid while the ladder's L 1 and L 2 workers run on Sonnet 5.5 and the advisor would be Opus 5.5.
|
||||
|
||||
`claude -p` calls the advisor. A probe with `--advisor claude-opus-5-5` made one call: it read the whole conversation, 20,187 uncached input tokens, and cost $0.093 beside the worker's $0.036. `workflow-bench/advisor_bench.py` ran six archived chunks of this repo (todo items 290, 251 and 218 at L 1, and 289, 229 and 214 at L 2) once on each of three arms: Sonnet 5.5 at high with the advisor, Sonnet 5.5 at high alone, and Opus 5.5 at medium. A judge on Opus 5.5 at medium, blind to the arm, ruled each run's change against the change that shipped, with the tests of the packages either change touches.
|
||||
|
||||
| Arm | Passes | Mean cost | Mean seconds | Runs with an advisor call |
|
||||
|---|---|---|---|---|
|
||||
| Sonnet 5.5 with the advisor | 6 of 6 | $0.37 | 286 | 1 of 6 |
|
||||
| Sonnet 5.5 alone | 6 of 6 | $0.27 | 151 | 0 of 6 |
|
||||
| Opus 5.5 at medium | 6 of 6 | $0.46 | 197 | 0 of 6 |
|
||||
|
||||
Every arm passed every case, so the bench found no quality gap for an advisor to close, and Sonnet alone cost 41% less than Opus at medium. The advisor's one call, in item 214's run, cost $0.72 of that run's $1.24, against $0.41 for Sonnet alone. Anthropic's reported gain (https://claude.com/blog/the-advisor-strategy) came on SWE-bench Multilingual, a harder set than L 1 and L 2 chunks. The bench ran each arm once per case, and its judge is of the worker's own model family, so it shows a direction only. It tested L 1 and L 2 items alone. Workers on items above L 2 run without the advisor too, since nothing shows it pays there, until a bench of such items does.
|
||||
|
||||
## routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, steps one rung up as the judge interrupts or quotes an answer, or next cycle, up to two rungs above the rung its item picks
|
||||
|
||||
2026-10-15, lilleman asked for it. Serves goals 1.1 and 1.4: when the hard part is the rest of the chunk, handing it to subagents piece by piece leaves the worker, which reads and checks each of their diffs, on a rung that proved too low. The worker climbs only once its run records a trigger.
|
||||
|
||||
@@ -1708,3 +1708,20 @@ Read most (opens and searches):
|
||||
- `skills/comprehension-panel/SKILL.md` 3
|
||||
- `agents/stability-reviewer.md` 2
|
||||
- `CHANGELOG.md` 1
|
||||
|
||||
## Reading cost, chunk 8640ba15252f, finished 2026-11-12T02:12:06Z
|
||||
|
||||
82406 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/decisions.md` 7
|
||||
- `bin/loop_claude/routing.py` 4
|
||||
- `CLAUDE.md` 3
|
||||
- `README.md` 3
|
||||
- `bin/loop_claude/test_black_box.py` 3
|
||||
- `CHANGELOG.md` 2
|
||||
- `bin/judge_replay/main.py` 2
|
||||
- `bin/loop_claude/test_loop_claude.py` 2
|
||||
- `bin/model_routing/route.py` 2
|
||||
- `todo.md` 2
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 331 | 0.9.0 | | question | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.9 |
|
||||
| 320 | 0.9.0 | | | **Bench a worker below the project's rung with the advisor tool against the same worker alone and the project's rung, and file the switch if it wins.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3, 1.1 by 2 | 2.0 |
|
||||
| 315 | 0.9.0 | | | **Start each reviewer under `agents/` without `CLAUDE.md`, and hand it the vocabulary, the prose rules and the project's decision titles.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 6 | 2.0 |
|
||||
| 312 | 0.9.0 | | | **Research the tooling agents read, search and run commands with, and file an item for each tool that cuts tokens a replay shows keep quality.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 |
|
||||
| 325 | 0.9.0 | | | **Give this repo's test suite one command that runs it as README → Test says, prints the failing tests and pytest's summary line, and saves the whole log to a file whose path it prints.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3, 1.5 by 2 | 2.0 |
|
||||
@@ -89,10 +88,6 @@ The architect's 🔀 answer on PR #493 (item 292): four decisions expire "when a
|
||||
|
||||
Recommendation: reword all four as above. They are decisions the repo held before item 292, so the rewording is lilleman's call.
|
||||
|
||||
### 320. Bench a worker below the project's rung with the advisor tool against the same worker alone and the project's rung, and file the switch if it wins.
|
||||
|
||||
Anthropic reports Sonnet 4.6 with an Opus 4.6 advisor scored 2.7 points more on SWE-bench Multilingual at 11.9% less cost than Sonnet alone (the vendor's own run; https://claude.com/blog/the-advisor-strategy). The docs say `/advisor` works with `-p`, but not outright that the advisor is called during a `-p` run, so probe that first. Each advisor call hands the advisor the whole conversation, so count its cost. Bench on `workflow-bench` with archived L 1 and L 2 items: Sonnet with the advisor, Sonnet alone, Opus at medium. lilleman approved on 2026-11-11.
|
||||
|
||||
### 315. Start each reviewer under `agents/` without `CLAUDE.md`, and hand it the vocabulary, the prose rules and the project's decision titles.
|
||||
|
||||
`omitClaudeMd: true` in an agent's frontmatter (Claude Code 2.1.271 or later) starts it without the user, project and local instruction files. About 77% of `CLAUDE.md` is the worker's: "Working loop", "Working with the codebase", "Git", "Handoffs", "Compact instructions". Over the archive, each 1,000 prefix tokens cost $31 across the six reviewers, so this saves about 1.9% of spend. A reviewer still needs "Vocabulary", "Prose" and the project's decision titles: put the first two in the agent bodies or a `SubagentStart` hook's `additionalContext`, and have `larv-review reviewer-header` print the titles.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
You judge one worker's change to a todo item. You see the item, the change that shipped for it, the worker's change, and the result of the tests of the packages that either change touches, run on the worker's tree. You don't know which model wrote the worker's change.
|
||||
|
||||
Rule `pass` where the worker's change does what the item asks, comes with a test that fails without the change, and causes no failing test. Rule `partial` where it does most of the item or lacks that test. Rule `fail` where it misses the item, causes a failing test, or changes unrelated code. The shipped change is one correct answer, not the only one.
|
||||
|
||||
{text}
|
||||
|
||||
## The shipped change
|
||||
|
||||
{reference}
|
||||
|
||||
## The worker's change
|
||||
|
||||
{diff}
|
||||
|
||||
## The tests on the worker's tree
|
||||
|
||||
{tests}
|
||||
|
||||
Reply with JSON only: {{"verdict": "pass" | "partial" | "fail", "why": "<one sentence>"}}
|
||||
@@ -0,0 +1,10 @@
|
||||
You are the worker of one chunk of this repository, a throwaway clone at `{base}`. Implement todo item {item} below as `CLAUDE.md` → "Working loop" says, and stop when it is done and its tests pass.
|
||||
|
||||
{text}
|
||||
|
||||
## Bench rules
|
||||
|
||||
- The clone is yours and has no remote: make no worktree and no branch, open no pull request, don't push anything, run no review pass, and don't edit `todo.md`, `CHANGELOG.md` or `docs/`. Leave your change uncommitted.
|
||||
- Write the test first where a test can check the change, and see it fail.
|
||||
- Run the tests as `README.md` → Test says. No human is reachable: where the item leaves a choice open, take your recommendation.
|
||||
- End with a two-line summary of what you changed.
|
||||
@@ -0,0 +1,204 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bench the advisor tool on archived chunks: advisor_bench.py <work dir> run|grade <case>-<arm>-<n> ..., then advisor_bench.py <work dir> summary
|
||||
|
||||
The question: does a worker below the project's rung, Sonnet 5.5 with Opus 5.5 as its advisor, beat the same
|
||||
Sonnet alone, or match Opus 5.5 at medium for less? Each case is an archived L 1 or L 2 chunk of this repo
|
||||
(CASES holds its todo.md item, the commit it started from and the commit it merged at). `run` clones the repo at
|
||||
the start commit and hands the arm's worker the item's text from todo.md, with the bench rules of
|
||||
advisor-run-prompt.md in place of loop-claude's prompt. It saves, beside the clone in <work dir>: the claude
|
||||
stream (.jsonl), the worker's change (.diff) and the result of the tests of the packages that either change touches (.tests).
|
||||
`grade` has a judge on Opus 5.5 at medium, blind to the arm, rule on the .diff against the merged commit's change
|
||||
(.verdict); `summary` prints a table per arm.
|
||||
Run each arm of each case once; the table shows a direction, not a significance.
|
||||
"""
|
||||
import concurrent.futures
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
BENCH = pathlib.Path(__file__).resolve().parent
|
||||
REPO = BENCH.parent
|
||||
RUN_HEAVY = pathlib.Path.home() / ".claude/bin/run-heavy"
|
||||
SUITE = ["uvx", "--python", sys.executable, "--with", "pytest-xdist==3.8.0", "pytest==9.2.0", "-n", "4", "-q"]
|
||||
CASES = {
|
||||
"290": ("cda45a931", "509804da0"),
|
||||
"251": ("b74322892", "d13c4fb0d"),
|
||||
"218": ("62d57344d", "c424fa66a"),
|
||||
"289": ("034356f34", "62d1f5edd"),
|
||||
"229": ("e2aca90c9", "2321f4930"),
|
||||
"214": ("39dd51bb4", "4764d3d52"),
|
||||
}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Arm:
|
||||
model: str
|
||||
effort: str
|
||||
advisor: str | None = None
|
||||
|
||||
def flags(self):
|
||||
return ["--model", self.model, "--effort", self.effort, *(["--advisor", self.advisor] if self.advisor else [])]
|
||||
|
||||
|
||||
ARMS = {
|
||||
"sonnet-advisor": Arm("claude-sonnet-5-5", "high", "claude-opus-5-5"),
|
||||
"sonnet": Arm("claude-sonnet-5-5", "high"),
|
||||
"opus-medium": Arm("claude-opus-5-5", "medium"),
|
||||
}
|
||||
VERDICTS = ("pass", "partial", "fail")
|
||||
JUDGE = Arm("claude-opus-5-5", "medium")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Outcome:
|
||||
cost: float
|
||||
seconds: float
|
||||
advisor_calls: int
|
||||
|
||||
|
||||
def item_text(todo, item):
|
||||
"""The item's heading and detail in todo.md, up to the next item's heading."""
|
||||
found = re.search(rf"^### {item}\. .*?(?=^### \d+\. |\Z)", todo, re.DOTALL | re.MULTILINE)
|
||||
if not found:
|
||||
raise ValueError(f"item {item} has no detail in todo.md")
|
||||
return found.group().strip()
|
||||
|
||||
|
||||
def read_result(lines):
|
||||
"""The cost, seconds and advisor calls of a claude stream's first result line, which is the worker's: a background task's notification makes the later ones. The cost counts the advisor's tokens."""
|
||||
for line in lines:
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if entry.get("type") == "result":
|
||||
if entry.get("is_error"):
|
||||
raise ValueError(f"the run ended in an error: {entry.get('result')}")
|
||||
iterations = entry.get("usage", {}).get("iterations", [])
|
||||
return Outcome(
|
||||
cost=entry["total_cost_usd"], seconds=entry["duration_ms"] / 1000,
|
||||
advisor_calls=sum(1 for each in iterations if each.get("type") == "advisor_message"))
|
||||
raise ValueError("the stream has no result line")
|
||||
|
||||
|
||||
def verdict_of(reply):
|
||||
"""The verdict in the judge's `claude -p --output-format json` reply."""
|
||||
found = re.search(r"\{.*\}", json.loads(reply)["result"], re.DOTALL)
|
||||
if not found:
|
||||
raise ValueError("the judge's reply has no JSON object")
|
||||
verdict = json.loads(found.group())["verdict"]
|
||||
if verdict not in VERDICTS:
|
||||
raise ValueError(f"the judge's verdict {verdict!r} is none of {VERDICTS}")
|
||||
return verdict
|
||||
|
||||
|
||||
def split_name(name):
|
||||
"""The case, arm and run number of a run's name, such as 290-sonnet-advisor-1."""
|
||||
case, rest = name.split("-", 1)
|
||||
arm, number = rest.rsplit("-", 1)
|
||||
return case, arm, number
|
||||
|
||||
|
||||
def suite_targets(changed):
|
||||
"""The tests to run for a change: the package, or the lone module, under bin/ of each changed file, else all of bin/."""
|
||||
found = {"/".join(path.split("/")[:2]) for path in changed if path.startswith("bin/")}
|
||||
return sorted(found) or ["bin"]
|
||||
|
||||
|
||||
def summary(rows):
|
||||
"""A markdown table with one row per arm, in ARMS' order: its runs, passes, partials, mean cost, mean advisor calls and mean seconds."""
|
||||
lines = ["| arm | runs | pass | partial | mean cost $ | mean advisor calls | mean seconds |", "|---|---|---|---|---|---|---|"]
|
||||
for name in ARMS:
|
||||
own = [row for row in rows if row["arm"] == name]
|
||||
if own:
|
||||
passes, partials = (sum(row["verdict"] == kind for row in own) for kind in ("pass", "partial"))
|
||||
cost, advisor_calls, seconds = (sum(row[key] for row in own) / len(own) for key in ("cost", "advisor_calls", "seconds"))
|
||||
lines.append(f"| {name} | {len(own)} | {passes} | {partials} | {cost:.2f} | {advisor_calls:.1f} | {seconds:.0f} |")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def fresh_clone(base, dest):
|
||||
"""A clone of this repo at base, with no remote to push to."""
|
||||
subprocess.run(["git", "clone", "-q", "--no-local", str(REPO), str(dest)], check=True)
|
||||
git(dest, "checkout", "-q", "--detach", base)
|
||||
git(dest, "remote", "remove", "origin")
|
||||
|
||||
|
||||
def run(work, name):
|
||||
"""One worker run of <case>-<arm>-<n>; the files it leaves are in the module docstring."""
|
||||
case, arm, _ = split_name(name)
|
||||
base = CASES[case][0]
|
||||
clone = work / name
|
||||
if clone.exists():
|
||||
raise ValueError(f"{name} already ran: remove {clone}")
|
||||
fresh_clone(base, clone)
|
||||
prompt = (BENCH / "advisor-run-prompt.md").read_text().format(base=base, item=case, text=item_text(git(REPO, "show", f"{base}:todo.md"), case))
|
||||
with (work / f"{name}.jsonl").open("w") as out:
|
||||
subprocess.run(
|
||||
["claude", "-p", prompt, *ARMS[arm].flags(), "--setting-sources", "project", "--permission-mode", "bypassPermissions",
|
||||
"--no-session-persistence", "--output-format", "stream-json", "--verbose"],
|
||||
cwd=clone, stdout=out, stderr=subprocess.STDOUT)
|
||||
read_result((work / f"{name}.jsonl").read_text().splitlines())
|
||||
git(clone, "add", "--all")
|
||||
(work / f"{name}.diff").write_text(git(clone, "diff", "--cached", base))
|
||||
changed = [*git(clone, "diff", "--cached", "--name-only", base).split(), *git(REPO, "diff", "--name-only", base, CASES[case][1]).split()]
|
||||
targets = [target for target in suite_targets(changed) if (clone / target).exists()] or ["bin"]
|
||||
tests = subprocess.run([str(RUN_HEAVY), *SUITE, *targets], cwd=clone, capture_output=True, text=True)
|
||||
(work / f"{name}.tests").write_text(f"exit {tests.returncode}\n{tests.stdout[-1500:]}")
|
||||
return f"{name}: ran"
|
||||
|
||||
|
||||
def grade(work, name):
|
||||
"""Have the judge rule on one run's diff, blind to its arm, and save the verdict beside it."""
|
||||
case = split_name(name)[0]
|
||||
base, merged = CASES[case]
|
||||
prompt = (BENCH / "advisor-judge-prompt.md").read_text().format(
|
||||
text=item_text(git(REPO, "show", f"{base}:todo.md"), case), reference=git(REPO, "diff", base, merged, "--", ".", ":!todo.md", ":!docs", ":!CHANGELOG.md"),
|
||||
diff=(work / f"{name}.diff").read_text(), tests=(work / f"{name}.tests").read_text())
|
||||
reply = subprocess.run(
|
||||
["claude", "-p", prompt, *JUDGE.flags(), "--setting-sources", "", "--no-session-persistence", "--output-format", "json", "--tools", ""],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
verdict = verdict_of(reply)
|
||||
(work / f"{name}.verdict").write_text(json.dumps({"verdict": verdict, "reply": json.loads(reply)["result"]}))
|
||||
return f"{name}: {verdict}"
|
||||
|
||||
|
||||
def attempted(step, work, name):
|
||||
"""step's result line, or a line naming the failure, so one failed run doesn't stop the other runs' results printing."""
|
||||
try:
|
||||
return step(work, name)
|
||||
except (KeyError, ValueError, subprocess.CalledProcessError, OSError) as failure:
|
||||
return f"{name}: FAILED: {type(failure).__name__}: {failure}"
|
||||
|
||||
|
||||
def rows_of(work):
|
||||
rows = []
|
||||
for verdict_file in sorted(work.glob("*.verdict")):
|
||||
name = verdict_file.stem
|
||||
try:
|
||||
outcome = read_result((work / f"{name}.jsonl").read_text().splitlines())
|
||||
except ValueError as failure:
|
||||
raise ValueError(f"{name}: {failure}") from failure
|
||||
rows.append({"arm": split_name(name)[1], "verdict": json.loads(verdict_file.read_text())["verdict"], **dataclasses.asdict(outcome)})
|
||||
return rows
|
||||
|
||||
|
||||
def main(argv):
|
||||
work, step, names = pathlib.Path(argv[0]), argv[1], argv[2:]
|
||||
if step == "summary":
|
||||
print(summary(rows_of(work)))
|
||||
return
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
||||
for result in pool.map(lambda name: attempted({"run": run, "grade": grade}[step], work, name), names):
|
||||
print(result, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,309 @@
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
import advisor_bench
|
||||
|
||||
TODO = """| table |
|
||||
|
||||
## Details
|
||||
|
||||
### 7. Do the seventh thing.
|
||||
|
||||
Its detail.
|
||||
|
||||
### 8. Do the eighth thing.
|
||||
|
||||
Another detail.
|
||||
"""
|
||||
|
||||
|
||||
def result_line(**fields):
|
||||
return json.dumps({"type": "result", "total_cost_usd": 0.5, "num_turns": 9, "duration_ms": 12000, "usage": {"iterations": []}, **fields})
|
||||
|
||||
|
||||
class Arms(unittest.TestCase):
|
||||
def test_the_advisor_arm_names_its_model_effort_and_advisor(self):
|
||||
self.assertEqual(
|
||||
advisor_bench.ARMS["sonnet-advisor"].flags(), ["--model", "claude-sonnet-5-5", "--effort", "high", "--advisor", "claude-opus-5-5"])
|
||||
|
||||
def test_an_arm_without_an_advisor_passes_no_advisor_flag(self):
|
||||
self.assertEqual(advisor_bench.ARMS["opus-medium"].flags(), ["--model", "claude-opus-5-5", "--effort", "medium"])
|
||||
self.assertNotIn("--advisor", advisor_bench.ARMS["sonnet"].flags())
|
||||
|
||||
|
||||
class SplitName(unittest.TestCase):
|
||||
def test_keeps_a_hyphen_in_the_arm(self):
|
||||
self.assertEqual(advisor_bench.split_name("290-sonnet-advisor-2"), ("290", "sonnet-advisor", "2"))
|
||||
|
||||
|
||||
class SuiteTargets(unittest.TestCase):
|
||||
def test_names_the_package_of_each_changed_file_under_bin_once(self):
|
||||
self.assertEqual(
|
||||
advisor_bench.suite_targets(["bin/rule_hook/rules.py", "bin/rule_hook/test_rule_hook.py", "bin/shell_command.py", "README.md"]),
|
||||
["bin/rule_hook", "bin/shell_command.py"])
|
||||
|
||||
def test_falls_back_to_the_whole_of_bin_where_no_changed_file_is_in_it(self):
|
||||
self.assertEqual(advisor_bench.suite_targets(["README.md"]), ["bin"])
|
||||
|
||||
|
||||
class ItemText(unittest.TestCase):
|
||||
def test_reads_the_heading_and_detail_up_to_the_next_item(self):
|
||||
self.assertEqual(advisor_bench.item_text(TODO, 7), "### 7. Do the seventh thing.\n\nIts detail.")
|
||||
|
||||
def test_reads_the_last_item_to_the_end(self):
|
||||
self.assertEqual(advisor_bench.item_text(TODO, 8), "### 8. Do the eighth thing.\n\nAnother detail.")
|
||||
|
||||
def test_refuses_an_item_with_no_detail(self):
|
||||
with self.assertRaisesRegex(ValueError, "item 9"):
|
||||
advisor_bench.item_text(TODO, 9)
|
||||
|
||||
|
||||
class ReadResult(unittest.TestCase):
|
||||
def test_reads_cost_seconds_and_counts_advisor_calls(self):
|
||||
iterations = [{"type": "message"}, {"type": "advisor_message"}, {"type": "message"}, {"type": "message"}, {"type": "advisor_message"}]
|
||||
outcome = advisor_bench.read_result(["not json", result_line(usage={"iterations": iterations})])
|
||||
self.assertEqual(outcome, advisor_bench.Outcome(cost=0.5, seconds=12.0, advisor_calls=2))
|
||||
|
||||
def test_reads_the_first_result_where_a_background_task_makes_later_ones(self):
|
||||
self.assertEqual(advisor_bench.read_result([result_line(total_cost_usd=0.5), result_line(total_cost_usd=2.0)]).cost, 0.5)
|
||||
|
||||
def test_counts_no_advisor_call_where_the_run_has_no_iterations(self):
|
||||
self.assertEqual(advisor_bench.read_result([result_line(usage={})]).advisor_calls, 0)
|
||||
|
||||
def test_counts_no_advisor_call_where_the_run_has_no_usage(self):
|
||||
line = json.dumps({"type": "result", "total_cost_usd": 0.5, "num_turns": 9, "duration_ms": 12000})
|
||||
self.assertEqual(advisor_bench.read_result([line]).advisor_calls, 0)
|
||||
|
||||
def test_refuses_a_run_that_ended_in_an_error(self):
|
||||
with self.assertRaisesRegex(ValueError, "the run ended in an error: API Error"):
|
||||
advisor_bench.read_result([result_line(is_error=True, result="API Error")])
|
||||
|
||||
def test_refuses_a_stream_with_no_result_line(self):
|
||||
with self.assertRaises(ValueError) as refused:
|
||||
advisor_bench.read_result(['{"type": "assistant"}'])
|
||||
self.assertEqual(str(refused.exception), "the stream has no result line")
|
||||
|
||||
|
||||
class Verdict(unittest.TestCase):
|
||||
def test_reads_the_verdict_from_a_json_reply(self):
|
||||
self.assertEqual(advisor_bench.verdict_of(json.dumps({"result": '{"verdict": "partial", "why": "no test"}'})), "partial")
|
||||
|
||||
def test_reads_the_verdict_from_a_reply_in_a_code_fence_or_after_prose(self):
|
||||
for reply in ('```json\n{"verdict": "fail", "why": "x"}\n```', 'Ruling: {"verdict": "fail", "why": "x"} Done.'):
|
||||
self.assertEqual(advisor_bench.verdict_of(json.dumps({"result": reply})), "fail")
|
||||
|
||||
def test_reads_a_verdict_from_a_reply_that_spans_lines(self):
|
||||
self.assertEqual(advisor_bench.verdict_of(json.dumps({"result": '{\n"verdict": "pass",\n"why": "x"\n}'})), "pass")
|
||||
|
||||
def test_refuses_a_reply_with_no_json_object(self):
|
||||
with self.assertRaises(ValueError) as refused:
|
||||
advisor_bench.verdict_of(json.dumps({"result": "I cannot rule."}))
|
||||
self.assertEqual(str(refused.exception), "the judge's reply has no JSON object")
|
||||
|
||||
def test_refuses_a_verdict_outside_pass_partial_fail(self):
|
||||
with self.assertRaisesRegex(ValueError, "verdict"):
|
||||
advisor_bench.verdict_of(json.dumps({"result": '{"verdict": "great", "why": "x"}'}))
|
||||
|
||||
|
||||
class Summary(unittest.TestCase):
|
||||
def test_prints_one_row_per_arm_with_passes_and_mean_cost(self):
|
||||
rows = [
|
||||
{"arm": "sonnet", "verdict": "pass", "cost": 1.0, "advisor_calls": 0, "seconds": 100.0},
|
||||
{"arm": "sonnet", "verdict": "fail", "cost": 3.0, "advisor_calls": 0, "seconds": 300.0},
|
||||
{"arm": "opus-medium", "verdict": "pass", "cost": 4.0, "advisor_calls": 0, "seconds": 200.0},
|
||||
]
|
||||
rows.append({"arm": "sonnet-advisor", "verdict": "partial", "cost": 1.0, "advisor_calls": 2, "seconds": 50.0})
|
||||
self.assertEqual(advisor_bench.summary(rows).splitlines(), [
|
||||
"| arm | runs | pass | partial | mean cost $ | mean advisor calls | mean seconds |",
|
||||
"|---|---|---|---|---|---|---|",
|
||||
"| sonnet-advisor | 1 | 0 | 1 | 1.00 | 2.0 | 50 |",
|
||||
"| sonnet | 2 | 1 | 0 | 2.00 | 0.0 | 200 |",
|
||||
"| opus-medium | 1 | 1 | 0 | 4.00 | 0.0 | 200 |",
|
||||
])
|
||||
|
||||
|
||||
def commit(repo, message):
|
||||
subprocess.run(["git", "-C", str(repo), "-c", "user.name=bench", "-c", "user.email=bench@example.com", "commit", "-q", "-a", "-m", message], check=True)
|
||||
|
||||
|
||||
class Orchestration(unittest.TestCase):
|
||||
"""run, grade, main and rows_of, on a throwaway repo, with claude and run-heavy faked.
|
||||
|
||||
Case 7 starts at a commit holding bin/pkg/mod.py, and merges a change to bin/pkg/mod.py, a new bin/other/mod.py, and
|
||||
todo.md, docs and CHANGELOG.md; a later commit then changes bin/pkg/mod.py again and adds bin/later/mod.py, which the judge must not see."""
|
||||
|
||||
def setUp(self):
|
||||
scratch = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(scratch.cleanup)
|
||||
root = pathlib.Path(scratch.name)
|
||||
self.repo, self.work = root / "repo", root / "work"
|
||||
self.work.mkdir()
|
||||
subprocess.run(["git", "init", "-q", str(self.repo)], check=True)
|
||||
base = self.commit({"todo.md": TODO, "bin/pkg/mod.py": "x = 1\n", "docs/notes.md": "a\n", "CHANGELOG.md": "a\n"})
|
||||
merged = self.commit({"todo.md": TODO + "\nmore\n", "bin/pkg/mod.py": "x = 2\n", "bin/other/mod.py": "z = 1\n", "docs/notes.md": "b\n", "CHANGELOG.md": "b\n"})
|
||||
self.commit({"bin/pkg/mod.py": "x = 5\n", "bin/later/mod.py": "y = 1\n"})
|
||||
self.calls = []
|
||||
real_run = subprocess.run
|
||||
for patch in (
|
||||
unittest.mock.patch.object(advisor_bench, "REPO", self.repo), unittest.mock.patch.object(advisor_bench, "CASES", {"7": (base, merged)}),
|
||||
unittest.mock.patch.object(advisor_bench.subprocess, "run", side_effect=lambda args, **kwargs: self.fake(real_run, args, **kwargs)),
|
||||
):
|
||||
patch.start()
|
||||
self.addCleanup(patch.stop)
|
||||
self.tests_output = "3 passed\n"
|
||||
self.worker_result = {}
|
||||
self.base = base
|
||||
|
||||
def commit(self, files):
|
||||
for path, text in files.items():
|
||||
(self.repo / path).parent.mkdir(parents=True, exist_ok=True)
|
||||
(self.repo / path).write_text(text)
|
||||
subprocess.run(["git", "-C", str(self.repo), "add", "."], check=True)
|
||||
commit(self.repo, "a commit")
|
||||
return advisor_bench.git(self.repo, "rev-parse", "HEAD").strip()
|
||||
|
||||
def fake(self, real_run, args, **kwargs):
|
||||
if args[0] == "claude":
|
||||
self.calls.append((args, kwargs))
|
||||
if "--tools" in args:
|
||||
return subprocess.CompletedProcess(args, 0, stdout=json.dumps({"result": '{"verdict": "pass", "why": "ok"}'}), stderr="")
|
||||
pathlib.Path(kwargs["cwd"], "bin/pkg/mod.py").write_text("x = 3\n")
|
||||
pathlib.Path(kwargs["cwd"], "bin/pkg/new.py").write_text("n = 1\n")
|
||||
pathlib.Path(kwargs["cwd"], "bin/third").mkdir()
|
||||
pathlib.Path(kwargs["cwd"], "bin/third/mod.py").write_text("t = 1\n")
|
||||
subprocess.run(["git", "-C", str(kwargs["cwd"]), "add", "bin/third"], check=True)
|
||||
commit(kwargs["cwd"], "the worker commits")
|
||||
kwargs["stdout"].write(result_line(**self.worker_result) + "\n")
|
||||
return subprocess.CompletedProcess(args, 0)
|
||||
if args[0] == str(advisor_bench.RUN_HEAVY):
|
||||
self.calls.append((args, kwargs))
|
||||
return subprocess.CompletedProcess(args, 4, stdout=self.tests_output, stderr="")
|
||||
return real_run(args, **kwargs)
|
||||
|
||||
def test_run_clones_at_the_start_commit_and_saves_the_stream_the_diff_and_the_tests(self):
|
||||
self.assertEqual(advisor_bench.run(self.work, "7-sonnet-advisor-1"), "7-sonnet-advisor-1: ran")
|
||||
(claude, claude_kwargs), (tests, tests_kwargs) = self.calls
|
||||
clone = self.work / "7-sonnet-advisor-1"
|
||||
self.assertEqual((claude_kwargs["cwd"], tests_kwargs["cwd"]), (clone, clone))
|
||||
self.assertEqual(claude[:2] + claude[3:], [
|
||||
"claude", "-p", *advisor_bench.ARMS["sonnet-advisor"].flags(), "--setting-sources", "project", "--permission-mode", "bypassPermissions",
|
||||
"--no-session-persistence", "--output-format", "stream-json", "--verbose"])
|
||||
self.assertIn("Do the seventh thing.", claude[2])
|
||||
self.assertIn(f"`{self.base}`", claude[2])
|
||||
self.assertIn("todo item 7 ", claude[2])
|
||||
self.assertEqual(tests, [str(advisor_bench.RUN_HEAVY), *advisor_bench.SUITE, "bin/pkg", "bin/third"])
|
||||
self.assertEqual((tests_kwargs["capture_output"], tests_kwargs["text"]), (True, True))
|
||||
self.assertEqual(claude_kwargs["stdout"].name, str(self.work / "7-sonnet-advisor-1.jsonl"))
|
||||
self.assertEqual(claude_kwargs["stderr"], subprocess.STDOUT)
|
||||
self.assertEqual(advisor_bench.git(clone, "remote"), "")
|
||||
self.assertEqual(advisor_bench.git(clone, "rev-parse", "HEAD~").strip(), self.base)
|
||||
self.assertEqual(json.loads((self.work / "7-sonnet-advisor-1.jsonl").read_text())["total_cost_usd"], 0.5)
|
||||
diff = (self.work / "7-sonnet-advisor-1.diff").read_text()
|
||||
self.assertIn("-x = 1\n+x = 3\n", diff)
|
||||
self.assertIn("+++ b/bin/pkg/new.py", diff)
|
||||
self.assertIn("+++ b/bin/third/mod.py", diff)
|
||||
self.assertEqual((self.work / "7-sonnet-advisor-1.tests").read_text(), "exit 4\n3 passed\n")
|
||||
|
||||
def test_run_tests_all_of_bin_where_no_touched_package_is_in_the_clone(self):
|
||||
with unittest.mock.patch.object(advisor_bench, "suite_targets", return_value=["bin/absent"]):
|
||||
advisor_bench.run(self.work, "7-sonnet-1")
|
||||
self.assertEqual(self.calls[1][0][-1:], ["bin"])
|
||||
|
||||
def test_run_refuses_a_run_that_ended_in_an_error_before_it_tests(self):
|
||||
self.worker_result = {"is_error": True, "result": "API Error"}
|
||||
with self.assertRaisesRegex(ValueError, "API Error"):
|
||||
advisor_bench.run(self.work, "7-sonnet-1")
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
self.assertFalse((self.work / "7-sonnet-1.tests").exists())
|
||||
|
||||
def test_run_keeps_the_last_1500_characters_of_the_tests(self):
|
||||
self.tests_output = "a" * 2000 + "b" * 1500
|
||||
advisor_bench.run(self.work, "7-sonnet-1")
|
||||
self.assertEqual((self.work / "7-sonnet-1.tests").read_text(), "exit 4\n" + "b" * 1500)
|
||||
|
||||
def test_run_refuses_a_name_that_already_ran(self):
|
||||
advisor_bench.run(self.work, "7-sonnet-1")
|
||||
with self.assertRaisesRegex(ValueError, "7-sonnet-1 already ran: remove .*7-sonnet-1"):
|
||||
advisor_bench.run(self.work, "7-sonnet-1")
|
||||
|
||||
def test_a_clone_of_a_missing_repo_fails(self):
|
||||
with unittest.mock.patch.object(advisor_bench, "REPO", self.work / "missing"), self.assertRaises(subprocess.CalledProcessError):
|
||||
advisor_bench.fresh_clone(self.base, self.work / "clone")
|
||||
|
||||
def test_git_fails_where_git_does(self):
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
advisor_bench.git(self.repo, "rev-parse", "no-such-revision")
|
||||
|
||||
def test_grade_saves_the_verdict_and_shows_the_judge_both_changes_but_not_the_arm(self):
|
||||
advisor_bench.run(self.work, "7-sonnet-advisor-1")
|
||||
self.calls.clear()
|
||||
self.assertEqual(advisor_bench.grade(self.work, "7-sonnet-advisor-1"), "7-sonnet-advisor-1: pass")
|
||||
((judge, kwargs),) = self.calls
|
||||
self.assertEqual(judge[:2] + judge[3:], [
|
||||
"claude", "-p", *advisor_bench.JUDGE.flags(), "--setting-sources", "", "--no-session-persistence", "--output-format", "json", "--tools", ""])
|
||||
self.assertEqual((kwargs["capture_output"], kwargs["text"], kwargs["check"]), (True, True, True))
|
||||
prompt = judge[2]
|
||||
self.assertIn("Do the seventh thing.", prompt)
|
||||
self.assertIn("-x = 1\n+x = 2\n", prompt)
|
||||
self.assertIn("+++ b/bin/other/mod.py", prompt)
|
||||
for left_out in ("x = 5", "later", "docs/notes.md", "CHANGELOG.md", "todo.md"):
|
||||
self.assertNotIn(left_out, prompt)
|
||||
self.assertIn("+x = 3", prompt)
|
||||
self.assertIn("3 passed", prompt)
|
||||
self.assertNotIn("sonnet", prompt)
|
||||
self.assertEqual(
|
||||
json.loads((self.work / "7-sonnet-advisor-1.verdict").read_text()),
|
||||
{"verdict": "pass", "reply": '{"verdict": "pass", "why": "ok"}'})
|
||||
|
||||
def test_attempted_names_a_failure_in_place_of_raising_it(self):
|
||||
def step(work, name):
|
||||
raise KeyError("9")
|
||||
self.assertEqual(advisor_bench.attempted(step, self.work, "9-sonnet-1"), "9-sonnet-1: FAILED: KeyError: '9'")
|
||||
|
||||
def test_attempted_hands_the_step_the_work_dir_and_the_name(self):
|
||||
self.assertEqual(advisor_bench.attempted(lambda work, name: f"{work.name} {name}", self.work, "9-sonnet-1"), "work 9-sonnet-1")
|
||||
|
||||
def test_rows_of_pairs_each_verdict_with_its_runs_outcome(self):
|
||||
(self.work / "7-sonnet-advisor-1.jsonl").write_text(result_line(total_cost_usd=2.0) + "\n")
|
||||
(self.work / "7-sonnet-advisor-1.verdict").write_text(json.dumps({"verdict": "fail"}))
|
||||
(self.work / "7-sonnet-2.jsonl").write_text(result_line() + "\n")
|
||||
self.assertEqual(advisor_bench.rows_of(self.work), [{"arm": "sonnet-advisor", "verdict": "fail", "cost": 2.0, "seconds": 12.0, "advisor_calls": 0}])
|
||||
|
||||
def test_rows_of_names_a_run_whose_stream_has_no_result(self):
|
||||
(self.work / "7-sonnet-1.jsonl").write_text("")
|
||||
(self.work / "7-sonnet-1.verdict").write_text(json.dumps({"verdict": "pass"}))
|
||||
with self.assertRaisesRegex(ValueError, "^7-sonnet-1: the stream has no result line$"):
|
||||
advisor_bench.rows_of(self.work)
|
||||
|
||||
def run_main(self, *argv):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
advisor_bench.main([str(self.work), *argv])
|
||||
return out.getvalue()
|
||||
|
||||
def test_main_prints_each_runs_line_though_an_earlier_run_failed(self):
|
||||
def step(work, name):
|
||||
if name == "7-a-1":
|
||||
raise ValueError("no")
|
||||
return f"{name}: ran"
|
||||
with unittest.mock.patch.object(advisor_bench, "run", step):
|
||||
self.assertEqual(self.run_main("run", "7-a-1", "7-b-1"), "7-a-1: FAILED: ValueError: no\n7-b-1: ran\n")
|
||||
|
||||
def test_main_grades_on_grade(self):
|
||||
with unittest.mock.patch.object(advisor_bench, "grade", lambda work, name: f"{work.name} {name}: graded"):
|
||||
self.assertEqual(self.run_main("grade", "7-a-1"), "work 7-a-1: graded\n")
|
||||
|
||||
def test_main_prints_the_work_dirs_summary_on_summary(self):
|
||||
(self.work / "7-sonnet-1.jsonl").write_text(result_line() + "\n")
|
||||
(self.work / "7-sonnet-1.verdict").write_text(json.dumps({"verdict": "pass"}))
|
||||
self.assertIn("| sonnet | 1 | 1 | 0 | 0.50 | 0.0 | 12 |", self.run_main("summary"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user