From 083cc782d0793aa82f874a304aa2cee335688556 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 00:16:45 +0200 Subject: [PATCH 1/5] Bench questions a script answers from the code against the panel's hardest places --- .gitignore | 3 + CHANGELOG.md | 1 + README.md | 1 + bin/metric_bench/bench.py | 8 +- bin/metric_bench/places.py | 16 ++- bin/question-bench | 9 ++ bin/question_bench/__init__.py | 0 bin/question_bench/main.py | 191 ++++++++++++++++++++++++++++++++ bin/question_bench/questions.py | 130 ++++++++++++++++++++++ bin/test_question_bench.py | 153 +++++++++++++++++++++++++ bin/test_types.py | 2 +- 11 files changed, 507 insertions(+), 7 deletions(-) create mode 100755 bin/question-bench create mode 100644 bin/question_bench/__init__.py create mode 100644 bin/question_bench/main.py create mode 100644 bin/question_bench/questions.py create mode 100644 bin/test_question_bench.py diff --git a/.gitignore b/.gitignore index a4eb7472..3f3f1d24 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/CHANGELOG.md b/CHANGELOG.md index da92a9ae..9b27383c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 674e4751..83eac3e9 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `loop-claude ` 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 ] [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. diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index bcf67aec..db18fec6 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -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) diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py index 3d22fbc5..e3af9c00 100644 --- a/bin/metric_bench/places.py +++ b/bin/metric_bench/places.py @@ -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 diff --git a/bin/question-bench b/bin/question-bench new file mode 100755 index 00000000..4b211295 --- /dev/null +++ b/bin/question-bench @@ -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:])) diff --git a/bin/question_bench/__init__.py b/bin/question_bench/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/question_bench/main.py b/bin/question_bench/main.py new file mode 100644 index 00000000..6700367a --- /dev/null +++ b/bin/question_bench/main.py @@ -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 ] [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 ] [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) diff --git a/bin/question_bench/questions.py b/bin/question_bench/questions.py new file mode 100644 index 00000000..07978a72 --- /dev/null +++ b/bin/question_bench/questions.py @@ -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] diff --git a/bin/test_question_bench.py b/bin/test_question_bench.py new file mode 100644 index 00000000..dcf0e7a8 --- /dev/null +++ b/bin/test_question_bench.py @@ -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) diff --git a/bin/test_types.py b/bin/test_types.py index 25721a39..806ef69d 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -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) -- 2.52.0 From a9ec52915818bb52bba1a3daa8929c328ad87cb0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 00:30:01 +0200 Subject: [PATCH 2/5] Record question-bench's run: its misses rank the panel's places at a coin toss, so no question enters review --- todo.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/todo.md b/todo.md index d3c4f860..92fdd4c4 100644 --- a/todo.md +++ b/todo.md @@ -24,7 +24,6 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| -| 78 | 0.1.0 | | **Generate comprehension questions with deterministic scripts โ€” from symbols, the call graph and the tests, each answer checkable by a tool โ€” and bench the scores an agent gets on them against the panel, reading cost and static metrics.** | 3 | 7 | 9 | 8 | 1.1, 1.4 | 29.1 | | 85 | 0.1.0 | decision | **Move larv-review's mechanical rules โ€” the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and the comprehension history's format โ€” into one tested tool under `bin/`, so the skill says only when to run it and what each answer means.** | 4 | 7 | 8 | 9 | 1.1 | 28.1 | | 1 | 0.1.0 | question | **Say in README โ†’ Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 3, 4 | 27.0 | | 62 | 0.1.0 | defect | **Lift Locality, Self-sufficiency and the overall to the comprehension floor, at the places the seats name.** | 4 | 6 | 6 | 8 | 1.1 | 22.3 | @@ -54,10 +53,6 @@ ## Details -### 78. Generate comprehension questions with deterministic scripts โ€” from symbols, the call graph and the tests, each answer checkable by a tool โ€” and bench the scores an agent gets on them against the panel, reading cost and static metrics. - -A hand-written question bank goes stale as the project grows and leaves everything it does not ask about unmeasured. A script that samples symbols at random each run ("what calls X?", "where is Y validated?", "which test fails if Z changes?") covers the whole project over time, and the call graph, grep and the tests hold the answers, so no judge is needed. Each answer names the code it rests on, so a question whose code changed is regenerated. Keep the method only where the bench shows it tracks the panel at a lower cost. - ### 85. Move larv-review's mechanical rules โ€” the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and the comprehension history's format โ€” into one tested tool under `bin/`, so the skill says only when to run it and what each answer means. 2026-10-08, lilleman: next after item 78, which lowers token use. Every comprehension run since PR #224 named `skills/larv-review/SKILL.md` ยง3 "Architecture" the hardest place, and PR #228's paired ruling ruled worse on rules a program should hold: the base's `git log` search and fallbacks, the vote arithmetic, a trigger written out three times, and the round count PR #225's seats said only prose enforces. PR #228's reviewers found about twenty edge cases in that text, among them squash against merge commits, entry order, a vote with no place, and a trigger judged before items are removed; tests can hold each, prose could not. Keep the skill's judgement calls in prose, and give the tool the history's format, so the base search does not hang on the wording of a line. The history's reader in `bin/metric_bench/places.py` moves into that tool, so the format has one reader. @@ -144,7 +139,7 @@ Goal 3, raised by the principles audit of PR #215: the judge runs with `--no-ses 2026-10-08, lilleman: rescored from A10/G8 to A4/G4 on the measurement below, so other items that lower token use go first. -Measured over the 68 transcripts in loop-claude's archive on 2026-10-08, matching each Agent call to its tool result and to any `` naming its tool-use id. No report reached the worker twice: 813 arrived once as the hand-back, and 363 once as a notification after Claude Code ran the agent in the background. Reports took a median 19k tokens per chunk, 8% of the worker's peak context (24% at most). Lines carrying a severity mark are 9โ€“24% of a reviewer's report, and the worker would still open the file for each ๐Ÿ”ด or ๐ŸŸก it fixes. A third of the report volume is the comprehension seats', whose votes and places the worker copies into the history. File reads fill more of the worker's context: `sed -n` output is 30% of its Bash results and `grep` output 11%, which item 78 and `reading-cost` target. +Measured over the 68 transcripts in loop-claude's archive on 2026-10-08, matching each Agent call to its tool result and to any `` naming its tool-use id. No report reached the worker twice: 813 arrived once as the hand-back, and 363 once as a notification after Claude Code ran the agent in the background. Reports took a median 19k tokens per chunk, 8% of the worker's peak context (24% at most). Lines carrying a severity mark are 9โ€“24% of a reviewer's report, and the worker would still open the file for each ๐Ÿ”ด or ๐ŸŸก it fixes. A third of the report volume is the comprehension seats', whose votes and places the worker copies into the history. File reads fill more of the worker's context: `sed -n` output is 30% of its Bash results and `grep` output 11%, which `reading-cost` targets. The reports would live in the session's scratchpad, such as `/larv-review/prose-round-1.md`, so no project's checkout sees them. A later round gets the path of that pass's earlier report in place of the findings pasted in. How a report reaches the file: @@ -193,3 +188,14 @@ On 2026-10-08 only this repo's history named places: five scoring runs, all that | Change spread | 0.67 | 0.18 | AUC is 0.5 for a coin toss, and top k scores 0.10 by chance. Shared state cannot be judged here: every unit in `bin/` scores 0 on it. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. + +On 2026-10-09 `bin/question-bench` asked claude three questions a script answers โ€” which units call a unit, which unit names it calls, which test files refer to it โ€” about each askable unit the same history names and as many others: five runs, the sixth naming no askable unit. Claude's misses ranked the named units at a coin toss, while length ranked them as it did on every unit: + +| Metric | AUC | Top k | +|---|---|---| +| Question misses | 0.49 | 0.50 | +| Cognitive complexity | 0.66 | 0.59 | +| Length | 0.75 | 0.69 | +| Change spread | 0.57 | 0.54 | + +Top k scores 0.50 by chance on these units. Claude scored a median 0.76 of each answer, took in 62,643 new input tokens and cost $0.70 a run. No question enters review. Grep answers these questions whatever the code's shape, so rerun `question-bench` only with questions that take understanding the code, not finding it. -- 2.52.0 From 0050cd6772c1a1c0fe9db5f906b6239ea4d01bdb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 00:46:44 +0200 Subject: [PATCH 3/5] Answer architecture round 1: delete question-bench, keep its run's results in item 77 citing the commit that held it, and correct item 85's mention of item 78 --- .gitignore | 3 - CHANGELOG.md | 1 - README.md | 1 - bin/metric_bench/bench.py | 8 +- bin/metric_bench/places.py | 16 +-- bin/question-bench | 9 -- bin/question_bench/__init__.py | 0 bin/question_bench/main.py | 191 -------------------------------- bin/question_bench/questions.py | 130 ---------------------- bin/test_question_bench.py | 153 ------------------------- bin/test_types.py | 2 +- 11 files changed, 7 insertions(+), 507 deletions(-) delete mode 100755 bin/question-bench delete mode 100644 bin/question_bench/__init__.py delete mode 100644 bin/question_bench/main.py delete mode 100644 bin/question_bench/questions.py delete mode 100644 bin/test_question_bench.py diff --git a/.gitignore b/.gitignore index 3f3f1d24..a4eb7472 100644 --- a/.gitignore +++ b/.gitignore @@ -27,9 +27,6 @@ !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/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b27383c..da92a9ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,6 @@ ## 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. diff --git a/README.md b/README.md index 83eac3e9..674e4751 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,6 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `loop-claude ` 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 ] [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. diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index db18fec6..bcf67aec 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -1,4 +1,4 @@ -from typing import Callable, Sequence +from typing import Callable 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: Sequence[float], rest: Sequence[float]) -> float: +def auc(named: list[int], rest: list[int]) -> 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: Sequence[float], rest: Sequence[float]) -> float: +def top_k(named: list[int], rest: list[int]) -> 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) diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py index e3af9c00..3d22fbc5 100644 --- a/bin/metric_bench/places.py +++ b/bin/metric_bench/places.py @@ -22,29 +22,17 @@ 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, and the seats' mean overall score; 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; 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)], mean_overall("\n".join(bodies)))) + runs.append(ScoringRun(heading, named.group(3), [place for body in bodies for place in seat_places(body)])) 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 diff --git a/bin/question-bench b/bin/question-bench deleted file mode 100755 index 4b211295..00000000 --- a/bin/question-bench +++ /dev/null @@ -1,9 +0,0 @@ -#!/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:])) diff --git a/bin/question_bench/__init__.py b/bin/question_bench/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/bin/question_bench/main.py b/bin/question_bench/main.py deleted file mode 100644 index 6700367a..00000000 --- a/bin/question_bench/main.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Bench questions a script asks about a project's Python against the places its comprehension panel named as hardest. - -usage: question-bench [--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 ] [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) diff --git a/bin/question_bench/questions.py b/bin/question_bench/questions.py deleted file mode 100644 index 07978a72..00000000 --- a/bin/question_bench/questions.py +++ /dev/null @@ -1,130 +0,0 @@ -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] diff --git a/bin/test_question_bench.py b/bin/test_question_bench.py deleted file mode 100644 index dcf0e7a8..00000000 --- a/bin/test_question_bench.py +++ /dev/null @@ -1,153 +0,0 @@ -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) diff --git a/bin/test_types.py b/bin/test_types.py index 806ef69d..25721a39 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -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", "-p", "question_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", "-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) -- 2.52.0 From 243cd676f8bed2bec4ea219b0ab4455cffcd0dce Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 00:47:44 +0200 Subject: [PATCH 4/5] Answer prose round 1: split the question bench's paragraph, count its runs against the history's six, say what the answer score counts, and drop item 85's pointer to item 78 --- todo.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/todo.md b/todo.md index 92fdd4c4..64143776 100644 --- a/todo.md +++ b/todo.md @@ -55,7 +55,7 @@ ### 85. Move larv-review's mechanical rules โ€” the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and the comprehension history's format โ€” into one tested tool under `bin/`, so the skill says only when to run it and what each answer means. -2026-10-08, lilleman: next after item 78, which lowers token use. Every comprehension run since PR #224 named `skills/larv-review/SKILL.md` ยง3 "Architecture" the hardest place, and PR #228's paired ruling ruled worse on rules a program should hold: the base's `git log` search and fallbacks, the vote arithmetic, a trigger written out three times, and the round count PR #225's seats said only prose enforces. PR #228's reviewers found about twenty edge cases in that text, among them squash against merge commits, entry order, a vote with no place, and a trigger judged before items are removed; tests can hold each, prose could not. Keep the skill's judgement calls in prose, and give the tool the history's format, so the base search does not hang on the wording of a line. The history's reader in `bin/metric_bench/places.py` moves into that tool, so the format has one reader. +2026-10-08, lilleman: Every comprehension run since PR #224 named `skills/larv-review/SKILL.md` ยง3 "Architecture" the hardest place, and PR #228's paired ruling ruled worse on rules a program should hold: the base's `git log` search and fallbacks, the vote arithmetic, a trigger written out three times, and the round count PR #225's seats said only prose enforces. PR #228's reviewers found about twenty edge cases in that text, among them squash against merge commits, entry order, a vote with no place, and a trigger judged before items are removed; tests can hold each, prose could not. Keep the skill's judgement calls in prose, and give the tool the history's format, so the base search does not hang on the wording of a line. The history's reader in `bin/metric_bench/places.py` moves into that tool, so the format has one reader. ### 1. Say in README โ†’ Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume. @@ -189,7 +189,9 @@ On 2026-10-08 only this repo's history named places: five scoring runs, all that AUC is 0.5 for a coin toss, and top k scores 0.10 by chance. Shared state cannot be judged here: every unit in `bin/` scores 0 on it. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. -On 2026-10-09 `bin/question-bench` asked claude three questions a script answers โ€” which units call a unit, which unit names it calls, which test files refer to it โ€” about each askable unit the same history names and as many others: five runs, the sixth naming no askable unit. Claude's misses ranked the named units at a coin toss, while length ranked them as it did on every unit: +On 2026-10-09 a question bench asked a headless claude, allowed only Read, Grep and Glob, three questions a script answers from the syntax tree: which units call a unit, which units it calls, and which test files refer to it. It asked them about every unit the history names whose name is unique, plus as many units the history does not name. Five of the history's six scoring runs named such a unit. The tool is in commit 083cc78; it was deleted after the run. + +Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chance on these units: | Metric | AUC | Top k | |---|---|---| @@ -198,4 +200,4 @@ On 2026-10-09 `bin/question-bench` asked claude three questions a script answers | Length | 0.75 | 0.69 | | Change spread | 0.57 | 0.54 | -Top k scores 0.50 by chance on these units. Claude scored a median 0.76 of each answer, took in 62,643 new input tokens and cost $0.70 a run. No question enters review. Grep answers these questions whatever the code's shape, so rerun `question-bench` only with questions that take understanding the code, not finding it. +Claude got a median 76% of each answer's items right. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it. -- 2.52.0 From 45276fc3bf3155e98ef4eaf056a2cb4e49914a77 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 9 Oct 2026 00:47:50 +0200 Subject: [PATCH 5/5] Answer prose round 1: give the answer score as the Jaccard index the bench computed --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 64143776..d48f36e5 100644 --- a/todo.md +++ b/todo.md @@ -200,4 +200,4 @@ Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chan | Length | 0.75 | 0.69 | | Change spread | 0.57 | 0.54 | -Claude got a median 76% of each answer's items right. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it. +Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it. -- 2.52.0