Bench the advisor tool on six archived L 1 and L 2 chunks: Sonnet alone passes as often as Opus at medium for less, so workers stay without it
CI / tests (pull_request) Successful in 2m18s

This commit is contained in:
2026-11-12 04:27:48 +01:00
parent 7a7dc4b75d
commit 66b9651d68
9 changed files with 373 additions and 5 deletions
+4
View File
@@ -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
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- A bench of the advisor tool, `workflow-bench/advisor_bench.py`, found Sonnet 5.5 alone passing six archived L 1 and L 2 chunks as Opus 5.5 at medium did, for 41% less, and Sonnet's advisor called once in 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
+15
View File
@@ -28,6 +28,7 @@ Each project principle states one rule that the decisions below apply; their ent
- review: agents of one type launch in one message, not one a message before the others
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
- routing: a worker runs without the advisor tool, since six archived L 1 and L 2 chunks showed Sonnet 5.5 alone passing as often as Opus 5.5 at medium for less, and its advisor was called once in six runs
- 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
- routing: loop-claude reads the items a chunk takes from the worker's latest `Chunk items:` line and scores them by `todo.md` as the default branch held it when the cycle started; the judge reports the escalation and whether a release is ready to cut
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, when it names a chunk item that picks a higher rung, or when it cites an escalation trigger the judge finds
@@ -416,6 +417,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, since six archived L 1 and L 2 chunks showed Sonnet 5.5 alone passing as often as Opus 5.5 at medium for less, and its advisor was called once in six runs
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, which read 20,187 uncached input tokens, the whole conversation, 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 | Advisor calls |
|---|---|---|---|---|
| Sonnet 5.5 with the advisor | 6 of 6 | $0.37 | 286 | 1 run of 6 |
| Sonnet 5.5 alone | 6 of 6 | $0.27 | 151 | 0 |
| Opus 5.5 at medium | 6 of 6 | $0.46 | 197 | 0 |
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. This bench cannot say whether the advisor pays on items above L 2: it ran one run per arm and case, and its judge is of the worker's own model family.
## 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.
+17
View File
@@ -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
-5
View File
@@ -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.
+19
View File
@@ -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 delivers what the item asks, with a test that fails without the change, and those tests pass or fail only on tests the change cannot have touched. Rule `partial` where it delivers most of the item or lacks the test, and `fail` where it misses the item, breaks those tests, 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>"}}
+10
View File
@@ -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, push nothing, 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.
+198
View File
@@ -0,0 +1,198 @@
#!/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
Item 320's 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: its todo.md item, the commit it started from, the commit it merged at). `run` clones the repo at
the start commit, hands the arm's worker that item as loop-claude's worker would see it, and saves, beside the
clone in <work dir>: the claude stream (.jsonl), the worker's change (.diff) and the result of the tests the worker's and the shipped change touch (.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", "/usr/bin/python3", "--with", "pytest-xdist==3.8.0", "pytest==9.2.0", "-n", "4", "-q"]
# Each case is the item's ID, the commit its chunk started from and the commit it merged at.
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
turns: int
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, turns, seconds and advisor calls of a claude stream's first result line, the worker's own: a background task's notification makes later ones. Its cost counts the advisor's tokens."""
for line in lines:
try:
entry = json.loads(line)
except ValueError:
continue
if entry.get("type") == "result":
iterations = entry.get("usage", {}).get("iterations", [])
return Outcome(
cost=entry["total_cost_usd"], turns=entry["num_turns"], 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)
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()]
tests = subprocess.run([str(RUN_HEAVY), *SUITE, *suite_targets(changed)], 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
outcome = read_result((work / f"{name}.jsonl").read_text().splitlines())
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:])
+109
View File
@@ -0,0 +1,109 @@
import json
import unittest
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_turns_seconds_and_counts_advisor_calls(self):
iterations = [{"type": "message"}, {"type": "advisor_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, turns=9, 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(num_turns=9), result_line(num_turns=2)]).turns, 9)
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_refuses_a_stream_with_no_result_line(self):
with self.assertRaisesRegex(ValueError, "no result"):
advisor_bench.read_result(['{"type": "assistant"}'])
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_refuses_a_reply_with_no_json_object(self):
with self.assertRaisesRegex(ValueError, "no JSON"):
advisor_bench.verdict_of(json.dumps({"result": "I cannot rule."}))
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},
]
self.assertEqual(advisor_bench.summary(rows).splitlines()[2:], [
"| sonnet | 2 | 1 | 0 | 2.00 | 0.0 | 200 |",
"| opus-medium | 1 | 1 | 0 | 4.00 | 0.0 | 200 |",
])
if __name__ == "__main__":
unittest.main()