Bench questions a script answers from the code against the panel's hardest places

This commit is contained in:
2026-10-09 00:16:45 +02:00
parent 08c5625ac7
commit 083cc782d0
11 changed files with 507 additions and 7 deletions
+3
View File
@@ -27,6 +27,9 @@
!bin/metric-bench
!bin/metric_bench/
!bin/metric_bench/*.py
!bin/question-bench
!bin/question_bench/
!bin/question_bench/*.py
!bin/rank_todo.py
!bin/reading-cost
!bin/reading_cost/
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- The new `bin/question-bench` asks a headless claude, given only Read, Grep and Glob, which units call a unit, which unit names it calls and which test files refer to it, about each unit a project's comprehension history names as hardest and as many others. A script answers each question from the code's syntax tree and scores claude's answer. The bench prints the answer score, claude's tokens and cost, and how well its misses rank the named units, beside metric-bench's metrics on the same units. It spends tokens on each run; no question enters review yet.
- The new `bin/metric-bench` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest: cognitive complexity, length, shared state and change spread, each scored by how well it ranks the named functions above the rest. No metric enters review yet.
- larv-review blocks a merge when simulated readers rule that the PR makes the project read worse than the last measured commit: the default branch's newest merged change that added a scoring run to `docs/comprehension-history.md`, or whose last ruling there is better. A ruling of same leaves that commit in place, so a worse ruling may name places earlier chunks wrote. In each architecture pass Mid A and the inherited architect vote better, same or worse; when they disagree, the maintainability senior and Junior A vote too. A ruling needs a lead of two or more votes, else it is same, and a vote that names no place counts as same. A worse ruling never ships: after three rounds larv-review asks you for another round, a no leaves the PR unmerged, and so does an unattended run. The four-seat scoring run checks the comprehension floor only when a chunk ships or removes a release's last plan item, or ships an item naming the floor; between those runs the floor blocks nothing. A score under the floor blocks the merge until fixed or until you decide to ship; a decision in `docs/decisions.md` that lets every chunk ship under the floor counts as yours.
- larv-review reruns fewer passes after a fix. A fix reruns the pass whose 🔴 or 🟡 it answers, plus stability when the fix changes behaviour, security when it opens an untrusted-input boundary or touches authn/authz, secrets or crypto, and architecture when it carries an architectural decision. A rerun reviews only what changed since that pass last reviewed. A fix for a 🟢, a ❓ or any prose finding reruns no pass, and prose takes one round.
+1
View File
@@ -69,6 +69,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `question-bench [--model <model>] [history]` asks a headless claude questions a script answers from the code, about the units a project's comprehension history names as hardest and as many others, and benches its misses against those places beside metric-bench's metrics; it spends tokens, and `question-bench --help` states the questions and the scores.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
+4 -4
View File
@@ -1,4 +1,4 @@
from typing import Callable
from typing import Callable, Sequence
import collections
import dataclasses
import statistics
@@ -62,16 +62,16 @@ def bench(units: list[Unit], places: list[Place], unresolved: int, spread: dict[
return RunScores(len(units), len(named), unmeasured, scores)
def auc(named: list[int], rest: list[int]) -> float:
def auc(named: Sequence[float], rest: Sequence[float]) -> float:
"""The chance a named unit outranks one not named, a tie counting half: 0.5 is a coin toss, 1.0 a perfect ranking."""
wins = sum((a > b) + 0.5 * (a == b) for a in named for b in rest)
return wins / (len(named) * len(rest))
def top_k(named: list[int], rest: list[int]) -> float:
def top_k(named: Sequence[float], rest: Sequence[float]) -> float:
"""The share of the metric's k highest units the seats named, k being how many they named. Units tied at the cut share its remaining slots evenly, as a random order of them would."""
k = len(named)
cut = sorted(named + rest, reverse=True)[k - 1]
cut = sorted([*named, *rest], reverse=True)[k - 1]
above = sum(value > cut for value in named)
slots = k - above - sum(value > cut for value in rest)
tied_named = sum(value == cut for value in named)
+14 -2
View File
@@ -22,17 +22,29 @@ class ScoringRun:
heading: str
commit: str
places: list[Place]
overall: float | None
def scoring_runs(history: str) -> list[ScoringRun]:
"""Each scoring run in a comprehension history, with the places its seats named, as they wrote them; paired rulings name what changed, not what is hard, and are left out."""
"""Each scoring run in a comprehension history, with the places its seats named, as they wrote them, and the seats' mean overall score; paired rulings name what changed, not what is hard, and are left out."""
runs = []
for heading, bodies in sections(history).items():
if (named := RUN.match(heading)) and ", against " not in heading:
runs.append(ScoringRun(heading, named.group(3), [place for body in bodies for place in seat_places(body)]))
runs.append(ScoringRun(heading, named.group(3), [place for body in bodies for place in seat_places(body)], mean_overall("\n".join(bodies))))
return runs
def mean_overall(body: str) -> float | None:
"""The last cell of the table's `Mean` row."""
for line in body.splitlines():
if line.startswith("| Mean |"):
try:
return float(line.strip().strip("|").split("|")[-1])
except ValueError:
return None
return None
def seat_places(body: str) -> list[Place]:
places = []
listing = False
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from question_bench import main
sys.exit(main.main(sys.argv[1:]))
View File
+191
View File
@@ -0,0 +1,191 @@
"""Bench questions a script asks about a project's Python against the places its comprehension panel named as hardest.
usage: question-bench [--model <model>] [history]
history defaults to docs/comprehension-history.md in the checkout it runs in, and the bench reads
the checkout that holds the history. For each scoring run in it, at the commit the panel read, it
asks a headless claude, given only Read, Grep and Glob, three questions about each unit the panel
named and about as many units picked by a hash of the commit: which units call it, which unit names
it calls, and which test files refer to it. The answers come from the code's syntax tree, so a
script checks them. Units are as in metric-bench, and a unit whose name another unit shares is not
asked about. --model picks claude's model; claude's default answers otherwise.
Each answer scores the Jaccard index of what claude named and the truth. A unit misses by 1 less
its answers' mean score. The bench prints, for each run: the units asked about, how many the panel
named, the panel's mean overall score, claude's mean answer score, the new input tokens claude
took in (uncached and cache-written, as reading-cost counts them) and its cost in USD, then how
well the misses rank the named units above the rest, beside each metric-bench metric on the same
units: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share of the k highest
units the panel named, k being how many it named). A last row gives the medians.
Below the table it names each run skipped because its commit is not in the checkout, each run not
asked because no unit it names can be asked about or no other unit can, each file left out because
it does not parse, and each run claude did not answer, with why.
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history
cannot be read, or no run could be scored.
"""
import dataclasses
import json
import pathlib
import statistics
import subprocess
import sys
import tempfile
from question_bench.questions import answer_schema, askable, calls, Code, misses, prompt, Question, questions, referred, sample_units, sampled
from metric_bench.bench import auc, bench, co_changed, METRICS, Score, top_k
from metric_bench.main import cell, failed, git, noted, read_history
from failure import Failure
from metric_bench.python_units import measured, python_units, Unit
from metric_bench.places import resolved, scoring_runs, ScoringRun
USAGE = "usage: question-bench [--model <model>] [history]"
@dataclasses.dataclass(frozen=True)
class Answered:
units: int
named: int
overall: float | None
answer_score: float
tokens: int
cost: float
scores: dict[str, Score]
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
model = None
if argv[:1] == ["--model"] and len(argv) > 1:
model, argv = argv[1], argv[2:]
if len(argv) > 1 or argv[:1] and argv[0].startswith("-"):
print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr)
return 1
read = read_history(pathlib.Path(argv[0]).resolve() if argv else None)
if isinstance(read, Failure):
return failed(read)
top, history, text = read
rows = []
notes = []
for run in scoring_runs(text):
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
continue
answered = answer_run(run, top, model, notes)
if isinstance(answered, Failure):
notes.append(f"Not answered: {run.heading}: {answered.reason}")
elif answered:
rows.append((run.heading, answered))
if not rows:
return failed(Failure(f"no scoring run in {history} could be scored{noted(notes)}"))
print(table(rows) + noted(notes))
return 0
def answer_run(run: ScoringRun, top: str, model: str | None, notes: list[str]) -> Answered | None | Failure:
"""The run's answers scored and benched; None, with a note, when it has nothing to ask."""
listed = git(["ls-tree", "-r", "-z", "--name-only", run.commit], top)
if isinstance(listed, Failure):
return listed
tracked = list(filter(None, listed.split("\0")))
read = read_code(run, top, tracked, notes)
if isinstance(read, Failure):
return read
units, code = read
places, _ = resolved(run.places, tracked)
named = {(place.path, place.name) for place in places if place.name}
asked_units = sampled(askable(code), named, run.commit)
if not asked_units or not set(asked_units) - named:
notes.append(f"Not asked, no unit it names can be asked about, or no other unit can: {run.heading}")
return None
asked = questions(code, asked_units, run.commit)
reply = ask(top, run.commit, asked, model)
if isinstance(reply, Failure):
return reply
given, tokens, cost, root = reply
missed = misses(asked, given, root)
log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit], top)
if isinstance(log, Failure):
return log
static = bench(sample_units(units, asked_units), places, 0, co_changed(log))
assert static, "sampled() asks about named units and others alike"
named_misses = [missed[unit] for unit in asked_units if unit in named]
rest_misses = [missed[unit] for unit in asked_units if unit not in named]
scores = {"question misses": Score(auc(named_misses, rest_misses), top_k(named_misses, rest_misses), len(set(missed.values())) == 1), **static.scores}
answer_score = 1 - statistics.mean(missed.values())
return Answered(len(asked_units), len(named_misses), run.overall, answer_score, tokens, cost, scores)
def read_code(run: ScoringRun, top: str, tracked: list[str], notes: list[str]) -> tuple[list[Unit], Code] | Failure:
"""The run's units with their metrics, and the code its answers rest on; a file that does not parse is noted and left out."""
units: list[Unit] = []
code = Code([], {})
for path in (path for path in tracked if path.endswith(".py")):
source = git(["show", f"{run.commit}:{path}"], top)
if isinstance(source, Failure):
return source
if not measured(path):
names = referred(path, source)
if isinstance(names, Failure):
notes.append(f"Left out of {run.heading}: {names.reason}")
else:
code.tests[path] = names
continue
found, called = python_units(path, source), calls(path, source)
if isinstance(found, Failure):
notes.append(f"Left out of {run.heading}: {found.reason}")
elif not isinstance(called, Failure):
units += found
code.calls.extend(called)
return units, code
def ask(top: str, commit: str, asked: list[Question], model: str | None) -> tuple[list[list[str]], int, float, str] | Failure:
"""claude's answers in a worktree of the commit, the new input tokens it took in, its cost and the worktree's path."""
with tempfile.TemporaryDirectory() as parent:
root = str(pathlib.Path(parent, "checkout"))
added = git(["worktree", "add", "--detach", root, commit], top)
if isinstance(added, Failure):
return added
try:
return run_claude(root, asked, model)
finally:
git(["worktree", "remove", "--force", root], top)
def run_claude(root: str, asked: list[Question], model: str | None) -> tuple[list[list[str]], int, float, str] | Failure:
# --safe-mode keeps the user's CLAUDE.md, skills and plugins out of the answers; --restricted keeps the tools to the worktree.
args = ["-p", "--safe-mode", "--restricted", "--strict-mcp-config", "--tools", "Read,Grep,Glob", "--no-session-persistence", "--output-format", "json", "--json-schema", json.dumps(answer_schema(len(asked)))]
try:
ran = subprocess.run(["claude", *args, *(["--model", model] if model else [])], capture_output=True, cwd=root, encoding="utf-8", errors="replace", input=prompt(asked))
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
try:
reply = json.loads(ran.stdout)
answers = reply["structured_output"]["answers"]
usage = reply["usage"]
tokens = usage["input_tokens"] + usage["cache_creation_input_tokens"]
cost = float(reply["total_cost_usd"])
except (json.JSONDecodeError, KeyError, TypeError, ValueError):
return Failure(f"claude exited {ran.returncode} without answers: {(ran.stderr or ran.stdout).strip()[-500:]}")
if len(answers) != len(asked) or not all(isinstance(answer, list) and all(isinstance(item, str) for item in answer) for answer in answers):
return Failure(f"claude gave {len(answers)} answers to {len(asked)} questions, or an answer that is not a list of strings")
return answers, tokens, cost, root
COLUMNS = ["question misses", *METRICS]
def table(rows: list[tuple[str, Answered]]) -> str:
head = ["Scoring run", "Units", "Named", "Panel overall", "Answer score", "New input tokens", "Cost USD", *COLUMNS]
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
for heading, run in rows:
overall = "" if run.overall is None else f"{run.overall:.2f}"
lines.append("| " + " | ".join([heading, str(run.units), str(run.named), overall, f"{run.answer_score:.2f}", str(run.tokens), f"{run.cost:.2f}", *(cell(run.scores[column]) for column in COLUMNS)]) + " |")
runs = [run for _, run in rows]
medianed = [cell(Score(statistics.median(run.scores[column].auc for run in runs), statistics.median(run.scores[column].top_k for run in runs), all(run.scores[column].constant for run in runs))) for column in COLUMNS]
lines.append("| " + " | ".join(["Median", "", "", "", f"{statistics.median(run.answer_score for run in runs):.2f}", str(int(statistics.median(run.tokens for run in runs))), f"{statistics.median(run.cost for run in runs):.2f}", *medianed]) + " |")
return "\n".join(lines)
+130
View File
@@ -0,0 +1,130 @@
import ast
import dataclasses
import hashlib
from failure import Failure
from metric_bench.python_units import FUNCTION, Unit
Key = tuple[str, str]
@dataclasses.dataclass(frozen=True)
class Code:
"""What the questions' answers rest on: for each measured unit, the names its calls end in, and for each test file, the names its code refers to."""
calls: list[tuple[Key, set[str]]]
tests: dict[str, set[str]]
@dataclasses.dataclass(frozen=True)
class Question:
unit: Key
text: str
truth: frozenset[str]
# The rules each answer follows, given to the agent as they are applied here.
RULES = """A unit is a module-level function, or a method of a module-level class, in a Python file git tracks outside the tests; a nested function belongs to the unit around it. A test file is a tracked `test_*.py` or `*_test.py`, or a `.py` under a `tests/` folder. A unit calls a name when its body holds a call `name(…)` or `anything.name(…)`. Write a unit as `path:name`, the path from the repository's root and the name without its class."""
def calls(path: str, source: str) -> list[tuple[Key, set[str]]] | Failure:
"""Each unit in source, with the last name of each call in its body; a method and a function may share a key."""
try:
tree = ast.parse(source)
except (SyntaxError, ValueError) as failure:
return Failure(f"{path} does not parse: {failure}")
nodes = [node for node in tree.body if isinstance(node, FUNCTION)]
nodes += [method for node in tree.body if isinstance(node, ast.ClassDef) for method in node.body if isinstance(method, FUNCTION)]
return [((path, node.name), {name for call in ast.walk(node) if (name := called(call))}) for node in nodes]
def called(node: ast.AST) -> str | None:
if not isinstance(node, ast.Call):
return None
if isinstance(node.func, ast.Name):
return node.func.id
return node.func.attr if isinstance(node.func, ast.Attribute) else None
def referred(path: str, source: str) -> set[str] | Failure:
"""The names a test file's code refers to: names, attributes and imported names, not strings or comments."""
try:
tree = ast.parse(source)
except (SyntaxError, ValueError) as failure:
return Failure(f"{path} does not parse: {failure}")
names = set()
for node in ast.walk(tree):
if isinstance(node, ast.Name):
names.add(node.id)
elif isinstance(node, ast.Attribute):
names.add(node.attr)
elif isinstance(node, ast.alias):
names.add(node.name.rpartition(".")[2])
return names
def askable(code: Code) -> list[Key]:
"""The units whose name no other unit shares, so a call by that name means that unit; dunder methods, which Python calls implicitly, are left out."""
names = [name for (_, name), _ in code.calls]
return sorted(key for key, _ in code.calls if names.count(key[1]) == 1 and not key[1].startswith("__"))
def sampled(units: list[Key], named: set[Key], commit: str) -> list[Key]:
"""Each askable unit the seats named, and as many others, picked by a hash of the commit so a rerun asks the same."""
asked = [unit for unit in units if unit in named]
others = sorted((unit for unit in units if unit not in named), key=lambda unit: digest(commit, *unit))
return asked + others[:len(asked)]
def questions(code: Code, units: list[Key], commit: str) -> list[Question]:
"""Three questions on each unit, in an order hashed from the commit, so the named units do not come first."""
defined = {name for (_, name), _ in code.calls}
called_by = dict(code.calls)
asked = []
for unit in units:
path, name = unit
asked += [
Question(unit, f"Which units call `{name}`, defined in `{path}`?", frozenset(f"{caller}:{other}" for (caller, other), names in code.calls if name in names)),
Question(unit, f"Which unit names does `{path}:{name}` call? Answer each as the bare name.", frozenset(called_by[unit] & defined)),
Question(unit, f"Which test files refer to `{name}` in their code, not only in a string or comment?", frozenset(test for test, names in code.tests.items() if name in names)),
]
return sorted(asked, key=lambda question: digest(commit, question.text))
def digest(*parts: str) -> str:
return hashlib.sha256(" ".join(parts).encode()).hexdigest()
def prompt(asked: list[Question]) -> str:
listed = "\n".join(f"{number}. {question.text}" for number, question in enumerate(asked, 1))
return f"Answer each question about the code in this repository. {RULES} Answer each question with every item it asks for, and an empty list when there is none; answer question n in the nth entry of `answers`.\n\n{listed}"
def answer_schema(count: int) -> dict:
answer = {"type": "array", "items": {"type": "string"}}
return {"type": "object", "properties": {"answers": {"type": "array", "items": answer, "minItems": count, "maxItems": count}}, "required": ["answers"]}
def agreement(truth: frozenset[str], given: list[str], root: str) -> float:
"""The Jaccard index of the answer and the truth, 1.0 when both are empty; a path is read from the repository's root whether given absolute or relative."""
answer = {normal(item, root) for item in given}
return len(answer & truth) / len(answer | truth) if answer | truth else 1.0
def normal(item: str, root: str) -> str:
item = item.strip().strip("`").strip()
for prefix in (root.rstrip("/") + "/", "./"):
item = item.removeprefix(prefix)
return item
def misses(asked: list[Question], given: list[list[str]], root: str) -> dict[Key, float]:
"""For each unit asked about, how far its answers fall short: 1 less the mean agreement of its questions."""
agreements: dict[Key, list[float]] = {}
for question, answer in zip(asked, given):
agreements.setdefault(question.unit, []).append(agreement(question.truth, answer, root))
return {unit: 1 - sum(values) / len(values) for unit, values in agreements.items()}
def sample_units(units: list[Unit], asked: list[Key]) -> list[Unit]:
keys = set(asked)
return [unit for unit in units if (unit.path, unit.name) in keys]
+153
View File
@@ -0,0 +1,153 @@
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from question_bench.questions import agreement, askable, calls, Code, misses, prompt, questions, referred, sampled
from failure import Failure
from test_loop_claude_black_box import host_env
TOOL = pathlib.Path(__file__).resolve().parent / "question-bench"
SOURCE = textwrap.dedent("""
def hard(a):
def inner():
return easy()
return inner() + helpers.shared(a)
def easy():
return len([])
class Box:
def __init__(self):
self.shared()
def shared(self):
return hard(1)
def shared():
pass
""")
class Questions(unittest.TestCase):
def code(self) -> Code:
found = calls("a.py", SOURCE)
assert not isinstance(found, Failure)
tests = referred("test_a.py", "from a import hard\n# easy\n\ndef test():\n\tassert a.Box\n\t'easy'\n")
assert not isinstance(tests, Failure)
return Code(found, {"test_a.py": tests})
def test_counts_a_nested_functions_calls_and_attribute_calls_toward_their_unit(self):
self.assertEqual(dict(self.code().calls)[("a.py", "hard")], {"inner", "easy", "shared"})
def test_a_test_file_refers_to_names_in_code_not_strings_or_comments(self):
self.assertEqual(self.code().tests["test_a.py"], {"hard", "a", "Box"})
def test_asks_only_about_units_whose_name_no_other_unit_shares_and_no_dunder(self):
self.assertEqual(askable(self.code()), [("a.py", "easy"), ("a.py", "hard")])
def test_answers_each_question_from_the_syntax_tree(self):
truths = {question.text: set(question.truth) for question in questions(self.code(), [("a.py", "hard")], "abc")}
self.assertEqual(truths, {
"Which units call `hard`, defined in `a.py`?": {"a.py:shared"},
"Which unit names does `a.py:hard` call? Answer each as the bare name.": {"easy", "shared"},
"Which test files refer to `hard` in their code, not only in a string or comment?": {"test_a.py"},
})
def test_samples_every_named_unit_and_as_many_others_the_same_way_each_run(self):
units = [("a.py", name) for name in "abcdef"]
picked = sampled(units, {("a.py", "c")}, "abc")
self.assertEqual((picked[0], len(picked)), (("a.py", "c"), 2))
self.assertEqual(picked, sampled(units, {("a.py", "c")}, "abc"))
def test_numbers_the_questions_in_the_prompt(self):
asked = questions(self.code(), [("a.py", "easy")], "abc")
self.assertIn(f"3. {asked[2].text}", prompt(asked))
def test_scores_an_answer_by_its_jaccard_index_with_paths_read_from_the_root(self):
self.assertEqual(agreement(frozenset({"a.py:x", "a.py:y"}), [" `/tmp/r/a.py:x` ", "./a.py:z"], "/tmp/r"), 1 / 3)
self.assertEqual(agreement(frozenset(), [], "/tmp/r"), 1.0)
def test_a_unit_misses_by_one_less_its_answers_mean_score(self):
asked = questions(self.code(), [("a.py", "easy")], "abc")
self.assertEqual(misses(asked, [sorted(question.truth) for question in asked[:2]] + [["wrong"]], "/r"), {("a.py", "easy"): 1 - 2 / 3})
# Plays claude: answers each question from FAKE_ANSWERS by its text, or fails with FAKE_FAIL.
FAKE_CLAUDE = """#!{python}
import json, os, re, sys
if os.environ.get("FAKE_FAIL"):
sys.exit("out of credit")
answers = json.loads(os.environ["FAKE_ANSWERS"])
texts = re.findall(r"^\\d+\\. (.*)$", sys.stdin.read(), re.M)
print(json.dumps({{"structured_output": {{"answers": [answers.get(text, []) for text in texts]}}, "usage": {{"input_tokens": 5, "cache_creation_input_tokens": 95}}, "total_cost_usd": 0.25}}))
"""
class BlackBox(unittest.TestCase):
def project(self, history: str) -> str:
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
top = str(pathlib.Path(directory.name, "project"))
os.makedirs(pathlib.Path(top, "docs"))
env = host_env()
for args in (["init", "-q"], ["config", "user.email", "t@t"], ["config", "user.name", "t"]):
subprocess.run(["git", *args], cwd=top, check=True, env=env)
pathlib.Path(top, "a.py").write_text("def hard(a):\n\tif a:\n\t\treturn easy()\n\n\ndef easy():\n\treturn 1\n")
pathlib.Path(top, "test_a.py").write_text("from a import hard\n")
subprocess.run(["git", "add", "."], cwd=top, check=True, env=env)
subprocess.run(["git", "commit", "-qm", "a"], cwd=top, check=True, env=env)
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=top, check=True, capture_output=True, text=True, env=env).stdout.strip()
pathlib.Path(top, "docs", "comprehension-history.md").write_text(history.replace("COMMIT", commit))
fakes = pathlib.Path(directory.name, "fakes")
fakes.mkdir()
fake = fakes / "claude"
fake.write_text(FAKE_CLAUDE.format(python=sys.executable))
fake.chmod(0o755)
self.path = f"{fakes}{os.pathsep}{env['PATH']}"
return top
def run_tool(self, top: str, answers: dict[str, list[str]], *args: str, fail: bool = False) -> subprocess.CompletedProcess:
env = {**host_env(), "FAKE_ANSWERS": json.dumps(answers), "PATH": self.path, **({"FAKE_FAIL": "1"} if fail else {})}
return subprocess.run([sys.executable, str(TOOL), *args], cwd=top, capture_output=True, text=True, env=env)
HISTORY = "# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mean | 7.00 | 7.00 | 7.00 | 7.00 | 6.75 |\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n"
def test_prints_the_answer_score_tokens_cost_and_each_ranking_on_each_run(self):
top = self.project(self.HISTORY)
ran = self.run_tool(top, {"Which test files refer to `easy` in their code, not only in a string or comment?": [], "Which unit names does `a.py:easy` call? Answer each as the bare name.": [], "Which units call `easy`, defined in `a.py`?": ["a.py:hard"]})
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("| 2026-10-08T12:50:49Z, PR #1 at ", ran.stdout)
self.assertIn("| 2 | 1 | 6.75 | 0.67 | 100 | 0.25 | AUC 1.00, top k 1.00 |", ran.stdout)
self.assertIn("| Median |", ran.stdout)
self.assertEqual(subprocess.run(["git", "worktree", "list"], cwd=top, capture_output=True, text=True, env=host_env()).stdout.count("\n"), 1)
def test_names_a_run_claude_did_not_answer_and_exits_1_when_none_was(self):
top = self.project(self.HISTORY)
ran = self.run_tool(top, {}, fail=True)
self.assertEqual(ran.returncode, 1)
self.assertIn("Not answered: 2026-10-08T12:50:49Z, PR #1", ran.stderr)
self.assertIn("out of credit", ran.stderr)
def test_names_a_run_with_nothing_to_ask(self):
top = self.project(self.HISTORY.replace("`a.py:1` `hard`", "`README.md:1` \"Install\""))
ran = self.run_tool(top, {})
self.assertEqual(ran.returncode, 1)
self.assertIn("Not asked, no unit it names can be asked about", ran.stderr)
def test_takes_a_model_and_rejects_unknown_arguments(self):
top = self.project(self.HISTORY)
self.assertEqual(self.run_tool(top, {}, "--model", "haiku").returncode, 0)
self.assertEqual(self.run_tool(top, {}, "--x").returncode, 1)
self.assertEqual(self.run_tool(top, {}, "--model").returncode, 1)
+1 -1
View File
@@ -11,5 +11,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "loop_claude", "-p", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "loop_claude", "-p", "metric_bench", "-p", "question_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)