From 382472bd392267771a890225c8341b6690f7f2db Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 21:28:38 +0200 Subject: [PATCH 01/13] Measure what would lower review's token use: bench static metrics against the panel's hardest places, and rescore item 73 by its reports' measured cost --- .gitignore | 3 + CHANGELOG.md | 1 + README.md | 1 + bin/metric-bench | 9 ++ bin/metric_bench/__init__.py | 0 bin/metric_bench/bench.py | 69 ++++++++++++ bin/metric_bench/main.py | 99 +++++++++++++++++ bin/metric_bench/places.py | 70 ++++++++++++ bin/metric_bench/python_units.py | 151 +++++++++++++++++++++++++ bin/test_citations.py | 2 +- bin/test_metric_bench.py | 182 +++++++++++++++++++++++++++++++ bin/test_types.py | 2 +- todo.md | 49 +++++---- 13 files changed, 617 insertions(+), 21 deletions(-) create mode 100755 bin/metric-bench create mode 100644 bin/metric_bench/__init__.py create mode 100644 bin/metric_bench/bench.py create mode 100644 bin/metric_bench/main.py create mode 100644 bin/metric_bench/places.py create mode 100644 bin/metric_bench/python_units.py create mode 100644 bin/test_metric_bench.py diff --git a/.gitignore b/.gitignore index bcf6e1e2..a4eb7472 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,9 @@ !bin/loop_claude/**/ !bin/loop_claude/**/*.py !bin/markdown_sections.py +!bin/metric-bench +!bin/metric_bench/ +!bin/metric_bench/*.py !bin/rank_todo.py !bin/reading-cost !bin/reading_cost/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 06cfc6ef..da92a9ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- 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. - larv-review runs one security pass on each change: the full scan alone when it runs, else `/security-review`. diff --git a/README.md b/README.md index f55d6009..19fe6931 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit ## Tools - `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. - `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 b/bin/metric-bench new file mode 100755 index 00000000..9d912024 --- /dev/null +++ b/bin/metric-bench @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from metric_bench import main + +sys.exit(main.main(sys.argv[1:])) diff --git a/bin/metric_bench/__init__.py b/bin/metric_bench/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py new file mode 100644 index 00000000..f3d65159 --- /dev/null +++ b/bin/metric_bench/bench.py @@ -0,0 +1,69 @@ +import collections +import dataclasses +import statistics +from typing import Callable + +from metric_bench.places import Place +from metric_bench.python_units import Unit + +METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = { + "cognitive complexity": lambda unit, spread: unit.cognitive, + "length": lambda unit, spread: unit.length, + "shared state": lambda unit, spread: unit.shared_state, + "change spread": lambda unit, spread: spread.get(unit.path, 0), +} + + +@dataclasses.dataclass(frozen=True) +class Score: + auc: float + top_k: float + + +@dataclasses.dataclass(frozen=True) +class RunScores: + units: int + named: int + unmeasured: int + scores: dict[str, Score] + + +def co_changed(log: str) -> dict[str, int]: + """For each file, how many other files changed in a commit with it; log is `git log --format=format:@@ --name-only`.""" + partners: dict[str, set[str]] = collections.defaultdict(set) + for commit in log.split("@@"): + files = set(commit.split()) + for path in files: + partners[path] |= files - {path} + return {path: len(others) for path, others in partners.items()} + + +def bench(units: list[Unit], places: list[Place], spread: dict[str, int]) -> RunScores | None: + """How well each metric ranks the units the seats named above the rest; None when no named place is a measured unit.""" + names = {(place.path, place.name) for place in places} + named = [unit for unit in units if (unit.path, unit.name) in names] + if not named or len(named) == len(units): + return None + rest = [unit for unit in units if (unit.path, unit.name) not in names] + measured = {(unit.path, unit.name) for unit in named} + unmeasured = len({place for place in places if (place.path, place.name) not in measured}) + scores = {} + for metric, value in METRICS.items(): + scores[metric] = Score(auc([value(unit, spread) for unit in named], [value(unit, spread) for unit in rest]), top_k(units, named, lambda unit: value(unit, spread))) + return RunScores(len(units), len(named), unmeasured, scores) + + +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(units: list[Unit], named: list[Unit], value: Callable[[Unit], int]) -> float: + """The share of the metric's top k units the seats named, k being how many they named; a tie at the cut counts in order of the units.""" + top = sorted(units, key=value, reverse=True)[:len(named)] + return sum(unit in named for unit in top) / len(named) + + +def medians(runs: list[RunScores]) -> dict[str, Score]: + return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs)) for metric in METRICS} diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py new file mode 100644 index 00000000..22eb71d2 --- /dev/null +++ b/bin/metric_bench/main.py @@ -0,0 +1,99 @@ +"""Bench cheap static metrics against the places a project's comprehension panel named as hardest. + +usage: metric-bench [history] + +Run it inside a project checkout. history defaults to docs/comprehension-history.md there. For each +scoring run in it, at the commit the seats read, it measures every Python function and method git +tracks, test files left out: cognitive complexity (SonarSource's white paper, read for Python), +length in lines, shared state (attributes on self another method of the class also writes, plus +names declared global or nonlocal), and change spread (how many other files changed in a commit with +the unit's file, up to that commit). It then prints, for each metric, how well it ranks the units +the seats named above the rest: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share +of the metric's k highest units the seats named, k being how many they named). A last row gives the +medians. Places that name no Python function or method, such as a section of a markdown file, are +counted as unmeasured. + +Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the +history cannot be read, a run's commit is missing, or no scoring run names a measured unit. +""" +import pathlib +import subprocess +import sys + +from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score +from failure import Failure +from metric_bench.places import resolved, scoring_runs +from metric_bench.python_units import python_units, Unit + + +def main(argv: list[str]) -> int: + if argv in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + if len(argv) > 1 or argv[:1] and argv[0].startswith("-"): + print(f"unknown arguments {' '.join(argv)}; usage: metric-bench [history]", file=sys.stderr) + return 1 + top = git(["rev-parse", "--show-toplevel"], None) + if isinstance(top, Failure): + return failed(top) + history = pathlib.Path(argv[0]) if argv else pathlib.Path(top.strip(), "docs", "comprehension-history.md") + try: + text = history.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as failure: + return failed(Failure(f"could not read {history}: {failure}")) + rows = [] + for run in scoring_runs(text): + tracked = git(["ls-tree", "-r", "--name-only", run.commit], top.strip()) + if isinstance(tracked, Failure): + return failed(tracked) + units = commit_units(run.commit, tracked.split("\n"), top.strip()) + if isinstance(units, Failure): + return failed(units) + log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top.strip()) + if isinstance(log, Failure): + return failed(log) + if scores := bench(units, resolved(run.places, tracked.split("\n")), co_changed(log)): + rows.append((run.heading, scores)) + if not rows: + return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures")) + print(table(rows)) + return 0 + + +def commit_units(commit: str, tracked: list[str], top: str) -> list[Unit] | Failure: + units = [] + for path in tracked: + name = path.rsplit("/", 1)[-1] + if path.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in path.split("/")[:-1]: + source = git(["show", f"{commit}:{path}"], top) + if isinstance(source, Failure): + return source + units += python_units(path, source) + return units + + +def table(rows: list[tuple[str, RunScores]]) -> str: + head = ["Scoring run", "Units", "Named", "Unmeasured", *METRICS] + lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)] + for heading, run in rows: + lines.append("| " + " | ".join([heading, str(run.units), str(run.named), str(run.unmeasured), *(cell(run.scores[metric]) for metric in METRICS)]) + " |") + medianed = medians([run for _, run in rows]) + lines.append("| " + " | ".join(["Median", "", "", "", *(cell(medianed[metric]) for metric in METRICS)]) + " |") + return "\n".join(lines) + + +def cell(score: Score) -> str: + return f"AUC {score.auc:.2f}, top k {score.top_k:.2f}" + + +def git(args: list[str], cwd: str | None) -> str | Failure: + try: + ran = subprocess.run(["git", *args], capture_output=True, cwd=cwd, encoding="utf-8", errors="replace") + except OSError as failure: + return Failure(f"could not start git: {failure.strerror}") + return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}") + + +def failed(failure: Failure) -> int: + print(failure.reason, file=sys.stderr) + return 1 diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py new file mode 100644 index 00000000..e3ff35d7 --- /dev/null +++ b/bin/metric_bench/places.py @@ -0,0 +1,70 @@ +import dataclasses +import os +import re + +from markdown_sections import sections + +RUN = re.compile(r"^(.+), (.+) at ([0-9a-f]{7,40})$") +SEAT_PLACES = re.compile(r"^.+, (hardest first|would restructure first):$") +# `path:line` or `:line`, then the unit's name where one follows. +PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?") + + +@dataclasses.dataclass(frozen=True) +class Place: + path: str + name: str | None + + +@dataclasses.dataclass(frozen=True) +class ScoringRun: + heading: str + commit: str + places: list[Place] + + +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.""" + 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)])) + return runs + + +def seat_places(body: str) -> list[Place]: + places = [] + listing = False + for line in body.splitlines(): + if SEAT_PLACES.match(line): + listing = True + elif listing and line.startswith("- "): + places += bullet_places(line) + elif not line.startswith(" "): + listing = False + return places + + +def bullet_places(bullet: str) -> list[Place]: + """A `:line` with no path is in the file named before it in the bullet.""" + places = [] + path = "" + for match in PLACE.finditer(bullet): + path = match.group(1) or path + if path: + places.append(Place(path, match.group(2))) + return places + + +def resolved(places: list[Place], tracked: list[str]) -> list[Place]: + """Seats shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one sharing most of the path resolved before it; a place naming no tracked file is dropped.""" + found = [] + before = "" + for place in places: + candidates = [path for path in tracked if path == place.path or path.endswith("/" + place.path)] + if len(candidates) > 1: + candidates = [max(candidates, key=lambda path: len(os.path.commonprefix([path, before])))] + if candidates: + before = candidates[0] + found.append(Place(before, place.name)) + return found diff --git a/bin/metric_bench/python_units.py b/bin/metric_bench/python_units.py new file mode 100644 index 00000000..a1694bd4 --- /dev/null +++ b/bin/metric_bench/python_units.py @@ -0,0 +1,151 @@ +import ast +import collections +import dataclasses + +FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef) + + +@dataclasses.dataclass(frozen=True) +class Unit: + path: str + name: str + cognitive: int + length: int + shared_state: int + + +def python_units(path: str, source: str) -> list[Unit]: + """Each module-level function and each method in source, with its metrics; a source that does not parse has none.""" + try: + tree = ast.parse(source) + except (SyntaxError, ValueError): + return [] + units = [] + for node in tree.body: + if isinstance(node, FUNCTION): + units.append(unit(path, node, 0)) + elif isinstance(node, ast.ClassDef): + shared = shared_writes(node) + units += [unit(path, method, shared[method.name]) for method in node.body if isinstance(method, FUNCTION)] + return units + + +def unit(path: str, node: ast.FunctionDef | ast.AsyncFunctionDef, shared: int) -> Unit: + globals_written = sum(len(statement.names) for statement in ast.walk(node) if isinstance(statement, ast.Global | ast.Nonlocal)) + return Unit(path, node.name, cognitive(node), (node.end_lineno or node.lineno) - node.lineno + 1, shared + globals_written) + + +def shared_writes(cls: ast.ClassDef) -> collections.Counter[str]: + """For each method, how many of the attributes it writes on self another method of the class writes too.""" + writers = collections.defaultdict(set) + for method in cls.body: + if isinstance(method, FUNCTION): + for node in ast.walk(method): + for target in written(node): + if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self": + writers[target.attr].add(method.name) + return collections.Counter(method for methods in writers.values() if len(methods) > 1 for method in methods) + + +def written(node: ast.AST) -> list[ast.expr]: + if isinstance(node, ast.Assign): + return node.targets + return [node.target] if isinstance(node, ast.AugAssign | ast.AnnAssign) else [] + + +# SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition. +def cognitive(function: ast.FunctionDef | ast.AsyncFunctionDef) -> int: + counter = Cognitive(function.name) + counter.within(function.body, 0) + return counter.score + + +class Cognitive(ast.NodeVisitor): + def __init__(self, name: str) -> None: + self.name = name + self.nesting = 0 + self.score = 0 + + def within(self, nodes: list, deeper: int = 1) -> None: + self.nesting += deeper + for node in nodes: + self.visit(node) + self.nesting -= deeper + + def structure(self) -> None: + self.score += 1 + self.nesting + + def visit_If(self, node: ast.If) -> None: + self.structure() + self.branch(node) + + def branch(self, node: ast.If) -> None: + self.visit(node.test) + self.within(node.body) + if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If): + self.score += 1 + self.branch(node.orelse[0]) + elif node.orelse: + self.score += 1 + self.within(node.orelse) + + def loop(self, node: ast.For | ast.AsyncFor | ast.While, head: ast.expr) -> None: + self.structure() + self.visit(head) + self.within(node.body) + if node.orelse: + self.score += 1 + self.within(node.orelse) + + def visit_For(self, node: ast.For | ast.AsyncFor) -> None: + self.loop(node, node.iter) + + visit_AsyncFor = visit_For + + def visit_While(self, node: ast.While) -> None: + self.loop(node, node.test) + + def visit_Try(self, node: ast.Try | ast.TryStar) -> None: + self.within(node.body, 0) + for handler in node.handlers: + self.structure() + self.within(handler.body) + self.within(node.orelse, 0) + self.within(node.finalbody, 0) + + visit_TryStar = visit_Try + + def visit_Match(self, node: ast.Match) -> None: + self.structure() + self.visit(node.subject) + for case in node.cases: + self.within(case.body) + + def visit_IfExp(self, node: ast.IfExp) -> None: + self.structure() + self.within([node.test, node.body, node.orelse]) + + def visit_BoolOp(self, node: ast.BoolOp) -> None: + self.score += 1 + self.generic_visit(node) + + def comprehension(self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp) -> None: + for generator in node.generators: + self.structure() + self.score += len(generator.ifs) + self.within(list(ast.iter_child_nodes(node))) + + visit_DictComp = visit_GeneratorExp = visit_ListComp = visit_SetComp = comprehension + + def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: + self.within(node.body) + + visit_AsyncFunctionDef = visit_FunctionDef + + def visit_Lambda(self, node: ast.Lambda) -> None: + self.within([node.body]) + + def visit_Call(self, node: ast.Call) -> None: + if isinstance(node.func, ast.Name) and node.func.id == self.name: + self.score += 1 + self.generic_visit(node) diff --git a/bin/test_citations.py b/bin/test_citations.py index d830ce74..b3103bce 100644 --- a/bin/test_citations.py +++ b/bin/test_citations.py @@ -8,7 +8,7 @@ CITATION = re.compile(r'`?CLAUDE\.md`? โ†’ ("[^"]+"(?:,? (?:and )?"[^"]+")*)') HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE) LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| โ€”)", re.MULTILINE) NAME = re.compile(r'"([^"]+)"') -STRAY = re.compile(r'CLAUDE\.md(?!`? โ†’ ")[^\n"]{1,5}"') +STRAY = re.compile(r'CLAUDE\.md(?!`? โ†’ "|:\d)[^\n"]{1,5}"') class Citations(unittest.TestCase): diff --git a/bin/test_metric_bench.py b/bin/test_metric_bench.py new file mode 100644 index 00000000..7b78eaba --- /dev/null +++ b/bin/test_metric_bench.py @@ -0,0 +1,182 @@ +import ast +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 metric_bench.bench import auc, bench, co_changed +from metric_bench.places import Place, resolved, scoring_runs +from metric_bench.python_units import cognitive, python_units, Unit +from test_loop_claude_black_box import host_env + +TOOL = pathlib.Path(__file__).resolve().parent / "metric-bench" + + +def scored(source: str) -> int: + function = ast.parse(textwrap.dedent(source)).body[0] + assert isinstance(function, ast.FunctionDef) + return cognitive(function) + + +class Cognitive(unittest.TestCase): + def test_scores_the_white_papers_sum_of_primes_without_its_labelled_continue(self): + self.assertEqual(scored(""" + def sum_of_primes(limit): + total = 0 + for i in range(1, limit + 1): + for j in range(2, i): + if i % j == 0: + break + total += i + return total + """), 6) + + def test_counts_elif_and_else_flat_and_a_nested_ternary_by_its_depth(self): + self.assertEqual(scored(""" + def f(a): + if a: + return 1 if a > 1 else 2 + elif a is None: + return 3 + else: + return 4 + """), 5) + + def test_counts_each_boolean_operator_sequence_a_handler_a_match_and_recursion(self): + self.assertEqual(scored(""" + def f(a, b, c): + try: + if a and b and c or a: + match a: + case 1: + return f(b, c, a) + except ValueError: + pass + """), 1 + 2 + 2 + 1 + 1) + + def test_counts_a_comprehension_as_a_loop_and_its_conditions(self): + self.assertEqual(scored(""" + def f(rows): + return [row for row in rows if row if row > 1] + """), 3) + + +class Units(unittest.TestCase): + def test_measures_functions_and_methods_with_the_state_methods_share(self): + units = python_units("a.py", textwrap.dedent(""" + COUNT = 0 + + def bump(): + global COUNT + COUNT += 1 + + class Box: + def __init__(self): + self.size = 0 + + def grow(self): + self.size += 1 + self.name = "x" + """)) + self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 1)]) + + def test_a_source_that_does_not_parse_has_no_units(self): + self.assertEqual(python_units("a.py", "def ("), []) + + +class Places(unittest.TestCase): + HISTORY = textwrap.dedent(""" + # Comprehension history + + ## 2026-10-08T12:50:49Z, PR #224 at a58a0a8 + + | Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | + |---|---|---|---|---|---| + | Mean | 7 | 7 | 7 | 7 | 7 | + + Junior A, hardest first: + + - `skills/x/SKILL.md:77` "Architecture" + - `bin/tool/cycle/states.py:69` `transition`, with `cycle/run.py:55` `step` and `:90` `close` + + ## 2026-10-08T18:37:21Z, PR #228 at 2682668, against 8c9bf09 + + Mid A, decided by: + + - `bin/tool/cycle/run.py:1` `step` + """) + + def test_reads_each_scoring_runs_places_and_leaves_paired_rulings_out(self): + runs = scoring_runs(self.HISTORY) + self.assertEqual([(run.heading, run.commit) for run in runs], [("2026-10-08T12:50:49Z, PR #224 at a58a0a8", "a58a0a8")]) + self.assertEqual(runs[0].places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close")]) + + def test_resolves_a_shortened_path_to_the_file_nearest_the_one_before_it(self): + tracked = ["bin/tool/cycle/states.py", "bin/tool/cycle/run.py", "bin/other/cycle/run.py"] + places = [Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("gone.py", "x")] + self.assertEqual(resolved(places, tracked), [Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")]) + + +class Bench(unittest.TestCase): + def test_auc_is_one_for_a_perfect_ranking_and_counts_a_tie_half(self): + self.assertEqual(auc([5, 4], [1, 2]), 1.0) + self.assertEqual(auc([3], [3]), 0.5) + + def test_co_changed_counts_each_files_distinct_partners(self): + self.assertEqual(co_changed("@@\na.py\nb.py\n@@\na.py\nc.py\n@@\na.py"), {"a.py": 2, "b.py": 1, "c.py": 1}) + + def test_scores_the_named_units_and_counts_places_no_unit_measures(self): + units = [Unit("a.py", "hard", 9, 40, 0), Unit("a.py", "easy", 1, 5, 0), Unit("b.py", "plain", 2, 6, 0)] + run = bench(units, [Place("a.py", "hard"), Place("doc.md", None)], {"a.py": 1}) + assert run is not None + self.assertEqual((run.units, run.named, run.unmeasured), (3, 1, 1)) + self.assertEqual((run.scores["cognitive complexity"].auc, run.scores["cognitive complexity"].top_k), (1.0, 1.0)) + self.assertEqual(run.scores["shared state"].auc, 0.5) + + def test_a_run_naming_no_measured_unit_is_not_scored(self): + self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("doc.md", None)], {})) + + +class BlackBox(unittest.TestCase): + def project(self, history: str) -> str: + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + top = directory.name + 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\tfor x in a:\n\t\t\tif x:\n\t\t\t\treturn x\n\n\ndef easy():\n\treturn 1\n") + pathlib.Path(top, "test_a.py").write_text("def test_hard():\n\tif 1:\n\t\tpass\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() + os.makedirs(pathlib.Path(top, "docs")) + pathlib.Path(top, "docs", "comprehension-history.md").write_text(history.replace("COMMIT", commit)) + return top + + def run_tool(self, top: str, *args: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, str(TOOL), *args], cwd=top, capture_output=True, text=True, env=host_env()) + + def test_prints_each_metrics_score_on_each_run_and_the_medians(self): + top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n") + ran = self.run_tool(top) + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertIn("| 2026-10-08T12:50:49Z, PR #1 at ", ran.stdout) + self.assertIn("| 2 | 1 | 0 | AUC 1.00, top k 1.00 | AUC 1.00, top k 1.00 | AUC 0.50,", ran.stdout) + self.assertIn("| Median |", ran.stdout) + + def test_exits_1_when_no_run_names_a_measured_unit(self): + top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `README.md:1` \"Install\"\n") + ran = self.run_tool(top) + self.assertEqual((ran.returncode, ran.stdout), (1, "")) + self.assertIn("no scoring run in", ran.stderr) + + def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self): + top = self.project("") + self.assertIn("could not read", self.run_tool(top, "missing.md").stderr) + self.assertEqual(self.run_tool(top, "--x").returncode, 1) diff --git a/bin/test_types.py b/bin/test_types.py index f626d4cb..88d6ea30 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", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline", "-p", "loop_claude"], 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", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/todo.md b/todo.md index ad84b73a..b1e4fc6d 100644 --- a/todo.md +++ b/todo.md @@ -24,8 +24,6 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| -| 73 | 0.1.0 | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 4 | 10 | 8 | 1.4 | 31.4 | -| 77 | 0.1.0 | | **Measure each project with cheap static metrics โ€” cognitive complexity, how far a change spreads, state shared or mutated across methods โ€” and keep only those the panel's history shows tracking comprehension.** | 3 | 7 | 9 | 8 | 1.1, 1.4 | 29.1 | | 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 | @@ -45,32 +43,17 @@ | 68 | 0.1.0 | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 4 | 3 | 5 | 1.1 | 12.9 | | 65 | 0.1.0 | | **Archive each judge reply the loop rejects.** | 3 | 4 | 4 | 5 | 3 | 12.5 | | 82 | 0.1.0 | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 1 | 2 | 3 | 4 | 1.3 | 12.3 | +| 73 | 0.1.0 | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 4 | 4 | 4 | 1.4 | 11.7 | | 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 1.1 | 11.7 | | 51 | 0.1.0 | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 3 | 5 | 3 | 5 | 1.1 | 11.7 | | 50 | 0.1.0 | principle | **Grant the bench's runs only the tools a review needs, in place of skipping every permission.** | 2 | 2 | 3 | 4 | 4 | 9.9 | | 81 | 0.1.0 | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 2 | 2 | 3 | 4 | 4 | 9.9 | | 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 3 | 9.6 | | 52 | 0.1.0 | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 6 | 6 | 3 | 5 | 2 | 7.5 | +| 77 | 0.2.0 | | **Rerun `bin/metric-bench` once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 2 | 4 | 6 | 7 | 1.1, 1.4 | 22.9 | ## Details -### 73. Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries. - -The human ranks review cost first. Across 54 archived chunks the worker's own thread was 54% of spend, mostly cache reads: its context averaged about 350k tokens a turn and peaked near 700k, filled by reviewer reports, each of which arrived twice (the spawn result and the task notification). - -The reports would live in the session's scratchpad, such as `/larv-review/prose-round-1.md`, so no project's checkout sees them, and round counting and the `Answer round :` commits stay as they are. A later round gets the path of that pass's earlier report in place of the findings pasted in. The worker opens the file only for the findings it fixes. - -Measure first, from loop-claude's archive: how often a report still reaches the worker twice (PR #226's prose report, on 2026-10-08, arrived once), and how much of each report the worker acts on. Then choose how a report reaches the file: - -- **Write access.** Grant each reviewer Write. No reviewer under `agents/` holds it today, and an agent's tool list cannot confine Write to one folder. Check whether a PreToolUse hook can tell a subagent's call from the worker's and deny a Write outside the scratchpad; without such a hook, only the prompt keeps its writes inside the scratchpad. -- **A wrapper.** A general-purpose subagent launches the reviewer with its tools unchanged, saves the report and returns only the summary lines. Claude Code's documentation says a subagent cannot start another; drop this route unless a test shows one can. - -This risks goal 1.1: a worker fixing from a one-line summary can miss context it needs. - -### 77. Measure each project with cheap static metrics โ€” cognitive complexity, how far a change spreads, state shared or mutated across methods โ€” and keep only those the panel's history shows tracking comprehension. - -The human wants these explored and benched against the panel, with a global push toward a good state in every project. Candidates: cognitive complexity per function; how far a change spreads (files and modules a typical chunk touches, and files that change together in git history); state shared or mutated across methods (fields written by more than one method of a type, package-level variables written outside init, lack of cohesion between methods). Function and file length are warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces. One harness under `bin/` serves every project; which metrics a project tracks may differ by project. - ### 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. @@ -157,6 +140,19 @@ Goal 3, raised by the principles audit of PR #215: the judge runs with `--no-ses "Deterministic order", in `principles/technical-principles.md`, raised by the principles audit of PR #224: their order carries no meaning, so two chunks adding a decision conflict at the end, and a reader cannot find a title by scanning. +### 73. Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries. + +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. + +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: + +- **Write access.** Grant each reviewer Write. No reviewer under `agents/` holds it today, an agent's tool list cannot confine Write to one folder, and `~/.claude/CLAUDE.md` โ†’ "Working with the codebase" gives a reviewer that only reads no edits. Check whether a PreToolUse hook can tell a subagent's call from the worker's and deny a Write outside the scratchpad. +- **A wrapper.** A general-purpose subagent launches the reviewer, saves the report and returns only the summary lines. Claude Code's documentation says a subagent cannot start another; drop this route unless a test shows one can. + +This risks goal 1.1: a worker fixing from a one-line summary can miss context it needs. + ### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay. Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. @@ -180,3 +176,18 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic ### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in. "One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory. + +### 77. Rerun `bin/metric-bench` once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel. + +2026-10-08, lilleman: no metric enters review until a rerun on more data shows it tracking the panel. + +`bin/metric-bench` measures each Python function and method at each scoring run's commit, and scores how well each metric ranks the units the seats named above the rest. On 2026-10-08 only this repo's history named places: five scoring runs, all that day. The medians: + +| Metric | AUC | Top k | +|---|---|---| +| Cognitive complexity | 0.66 | 0.26 | +| Length | 0.74 | 0.18 | +| Shared state | 0.50 | 0.06 | +| Change spread | 0.64 | 0.17 | + +AUC is 0.5 for a coin toss. Shared state cannot be judged here, since no unit in `bin/` writes state another method shares. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces. -- 2.52.0 From 8a2dbd70f12c249386bbd1fb2c3504eb249b6e78 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 21:35:54 +0200 Subject: [PATCH 02/13] Split metric-bench's main into run_scores and measured, find the checkout from the history, drop an ambiguous shortened path, write places from the repository root, and give item 85 the history's reader --- bin/metric_bench/bench.py | 2 +- bin/metric_bench/main.py | 56 +++++++++++++++++--------------- bin/metric_bench/places.py | 9 +++-- bin/metric_bench/python_units.py | 6 ++++ bin/test_metric_bench.py | 17 ++++++++-- skills/larv-review/SKILL.md | 2 +- todo.md | 2 +- 7 files changed, 56 insertions(+), 38 deletions(-) diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index f3d65159..96a65b8f 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -1,7 +1,7 @@ +from typing import Callable import collections import dataclasses import statistics -from typing import Callable from metric_bench.places import Place from metric_bench.python_units import Unit diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index 22eb71d2..85fe13f1 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -2,8 +2,9 @@ usage: metric-bench [history] -Run it inside a project checkout. history defaults to docs/comprehension-history.md there. For each -scoring run in it, at the commit the seats read, it measures every Python function and method git +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 seats read, it +measures every Python function and method git tracks, test files left out: cognitive complexity (SonarSource's white paper, read for Python), length in lines, shared state (attributes on self another method of the class also writes, plus names declared global or nonlocal), and change spread (how many other files changed in a commit with @@ -22,8 +23,8 @@ import sys from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score from failure import Failure -from metric_bench.places import resolved, scoring_runs -from metric_bench.python_units import python_units, Unit +from metric_bench.python_units import measured, python_units +from metric_bench.places import resolved, scoring_runs, ScoringRun def main(argv: list[str]) -> int: @@ -33,26 +34,22 @@ def main(argv: list[str]) -> int: if len(argv) > 1 or argv[:1] and argv[0].startswith("-"): print(f"unknown arguments {' '.join(argv)}; usage: metric-bench [history]", file=sys.stderr) return 1 - top = git(["rev-parse", "--show-toplevel"], None) - if isinstance(top, Failure): - return failed(top) - history = pathlib.Path(argv[0]) if argv else pathlib.Path(top.strip(), "docs", "comprehension-history.md") + given = pathlib.Path(argv[0]).resolve() if argv else None + found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None) + if isinstance(found, Failure): + return failed(found) + top = found.strip() + history = given or pathlib.Path(top, "docs", "comprehension-history.md") try: text = history.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: return failed(Failure(f"could not read {history}: {failure}")) rows = [] for run in scoring_runs(text): - tracked = git(["ls-tree", "-r", "--name-only", run.commit], top.strip()) - if isinstance(tracked, Failure): - return failed(tracked) - units = commit_units(run.commit, tracked.split("\n"), top.strip()) - if isinstance(units, Failure): - return failed(units) - log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top.strip()) - if isinstance(log, Failure): - return failed(log) - if scores := bench(units, resolved(run.places, tracked.split("\n")), co_changed(log)): + scores = run_scores(run, top) + if isinstance(scores, Failure): + return failed(scores) + if scores: rows.append((run.heading, scores)) if not rows: return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures")) @@ -60,16 +57,21 @@ def main(argv: list[str]) -> int: return 0 -def commit_units(commit: str, tracked: list[str], top: str) -> list[Unit] | Failure: +def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure: + listed = git(["ls-tree", "-r", "--name-only", run.commit], top) + if isinstance(listed, Failure): + return listed + tracked = listed.split("\n") units = [] - for path in tracked: - name = path.rsplit("/", 1)[-1] - if path.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in path.split("/")[:-1]: - source = git(["show", f"{commit}:{path}"], top) - if isinstance(source, Failure): - return source - units += python_units(path, source) - return units + for path in filter(measured, tracked): + source = git(["show", f"{run.commit}:{path}"], top) + if isinstance(source, Failure): + return source + units += python_units(path, source) + log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top) + if isinstance(log, Failure): + return log + return bench(units, resolved(run.places, tracked), co_changed(log)) def table(rows: list[tuple[str, RunScores]]) -> str: diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py index e3ff35d7..f38412a8 100644 --- a/bin/metric_bench/places.py +++ b/bin/metric_bench/places.py @@ -57,14 +57,13 @@ def bullet_places(bullet: str) -> list[Place]: def resolved(places: list[Place], tracked: list[str]) -> list[Place]: - """Seats shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one sharing most of the path resolved before it; a place naming no tracked file is dropped.""" + """Seats shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped.""" found = [] before = "" for place in places: candidates = [path for path in tracked if path == place.path or path.endswith("/" + place.path)] - if len(candidates) > 1: - candidates = [max(candidates, key=lambda path: len(os.path.commonprefix([path, before])))] - if candidates: - before = candidates[0] + nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates + if len(nearest) == 1: + before = nearest[0] found.append(Place(before, place.name)) return found diff --git a/bin/metric_bench/python_units.py b/bin/metric_bench/python_units.py index a1694bd4..7f1d5a3a 100644 --- a/bin/metric_bench/python_units.py +++ b/bin/metric_bench/python_units.py @@ -14,6 +14,12 @@ class Unit: shared_state: int +def measured(path: str) -> bool: + """A Python file outside the tests.""" + folders, _, name = path.rpartition("/") + return name.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in folders.split("/") + + def python_units(path: str, source: str) -> list[Unit]: """Each module-level function and each method in source, with its metrics; a source that does not parse has none.""" try: diff --git a/bin/test_metric_bench.py b/bin/test_metric_bench.py index 7b78eaba..cdcf60a4 100644 --- a/bin/test_metric_bench.py +++ b/bin/test_metric_bench.py @@ -10,9 +10,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from metric_bench.bench import auc, bench, co_changed -from metric_bench.places import Place, resolved, scoring_runs -from metric_bench.python_units import cognitive, python_units, Unit +from metric_bench.python_units import cognitive, measured, python_units, Unit from test_loop_claude_black_box import host_env +from metric_bench.places import Place, resolved, scoring_runs TOOL = pathlib.Path(__file__).resolve().parent / "metric-bench" @@ -85,6 +85,9 @@ class Units(unittest.TestCase): """)) self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 1)]) + def test_measures_python_files_outside_the_tests(self): + self.assertEqual([path for path in ["a.py", "bin/test_a.py", "a_test.py", "tests/b.py", "e2e-tests/c.py", "README.md"] if measured(path)], ["a.py", "e2e-tests/c.py"]) + def test_a_source_that_does_not_parse_has_no_units(self): self.assertEqual(python_units("a.py", "def ("), []) @@ -121,6 +124,9 @@ class Places(unittest.TestCase): places = [Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("gone.py", "x")] self.assertEqual(resolved(places, tracked), [Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")]) + def test_drops_a_shortened_path_two_files_match_with_no_place_before_it(self): + self.assertEqual(resolved([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), []) + class Bench(unittest.TestCase): def test_auc_is_one_for_a_perfect_ranking_and_counts_a_tie_half(self): @@ -178,5 +184,10 @@ class BlackBox(unittest.TestCase): def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self): top = self.project("") - self.assertIn("could not read", self.run_tool(top, "missing.md").stderr) + self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr) self.assertEqual(self.run_tool(top, "--x").returncode, 1) + + def test_reads_the_checkout_that_holds_a_history_named_from_elsewhere(self): + top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n") + ran = self.run_tool(tempfile.gettempdir(), str(pathlib.Path(top, "docs", "comprehension-history.md"))) + self.assertEqual(ran.returncode, 0, ran.stderr) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index a5048da2..4aeba287 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -108,7 +108,7 @@ Fix a worse ruling at the places the seats voting worse name, and the floor at t Two files of the project keep the records: -- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, appended and never edited. Each opens with a `## , at ` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against `. A paired ruling holds a `Ruling: ` line, a table of each seat's vote, and under each seat, labelled `, decided by:`, its places. A scoring run holds a table of each seat's five scores, with a last row holding the four seats' mean of each, and under each seat, labelled `, hardest first:` or, for the architect, `, would restructure first:`, its places. A place is `path:line` and the unit's name. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. +- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, appended and never edited. Each opens with a `## , at ` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against `. A paired ruling holds a `Ruling: ` line, a table of each seat's vote, and under each seat, labelled `, decided by:`, its places. A scoring run holds a table of each seat's five scores, with a last row holding the four seats' mean of each, and under each seat, labelled `, hardest first:` or, for the architect, `, would restructure first:`, its places. A place is `path:line`, the path written from the repository's root, and the unit's name. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. - **Entry.** `docs/decisions.md` keeps one entry whose title opens `comprehension floor:`. It holds each decision to ship under the floor, with its scores. A `comprehension floor:` entry written before the history may still hold a scoring run's five scores. The next scoring run moves them, and only them, into the history as its first run: a heading of the date or time the entry gives and whatever it names the run by, its commit included where named, and a table with the mean alone. The rest of the entry stays. diff --git a/todo.md b/todo.md index b1e4fc6d..22728911 100644 --- a/todo.md +++ b/todo.md @@ -60,7 +60,7 @@ A hand-written question bank goes stale as the project grows and leaves everythi ### 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 the items that lower token use (73, 77, 78). 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. +2026-10-08, lilleman: next after the items that lower token use (73, 77, 78). 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. -- 2.52.0 From 7d440c6ee17196e2e0b410a271492f3bee0662b0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 21:48:05 +0200 Subject: [PATCH 03/13] Answer architecture round 1: make cognitive complexity a pure recursion, share a tied top-k cut evenly, count unresolved places, skip a run whose commit is gone, fail on a file that does not parse, link the history's format and its reader both ways, reword item 85's order, and record the worse ruling --- README.md | 2 + bin/metric_bench/bench.py | 25 +++--- bin/metric_bench/main.py | 25 ++++-- bin/metric_bench/places.py | 1 + bin/metric_bench/python_units.py | 129 +++++++++---------------------- bin/test_metric_bench.py | 47 ++++++++--- bin/test_types.py | 2 +- docs/comprehension-history.md | 27 +++++++ skills/larv-review/SKILL.md | 2 +- todo.md | 6 +- 10 files changed, 143 insertions(+), 123 deletions(-) diff --git a/README.md b/README.md index 19fe6931..96db5ea4 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,8 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit ## Tools +Run each from `~/.claude/bin/`; Install puts only `loop-claude` on `PATH`. + - `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. - `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format. diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index 96a65b8f..b3dcf31c 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -38,18 +38,20 @@ def co_changed(log: str) -> dict[str, int]: return {path: len(others) for path, others in partners.items()} -def bench(units: list[Unit], places: list[Place], spread: dict[str, int]) -> RunScores | None: - """How well each metric ranks the units the seats named above the rest; None when no named place is a measured unit.""" +def bench(units: list[Unit], places: list[Place], unresolved: int, spread: dict[str, int]) -> RunScores | None: + """How well each metric ranks the units the seats named above the rest; None when the named units are none or all of them. unresolved counts the places that named no tracked file.""" names = {(place.path, place.name) for place in places} named = [unit for unit in units if (unit.path, unit.name) in names] if not named or len(named) == len(units): return None rest = [unit for unit in units if (unit.path, unit.name) not in names] - measured = {(unit.path, unit.name) for unit in named} - unmeasured = len({place for place in places if (place.path, place.name) not in measured}) + found = {(unit.path, unit.name) for unit in named} + unmeasured = unresolved + len({place for place in places if (place.path, place.name) not in found}) scores = {} for metric, value in METRICS.items(): - scores[metric] = Score(auc([value(unit, spread) for unit in named], [value(unit, spread) for unit in rest]), top_k(units, named, lambda unit: value(unit, spread))) + named_values = [value(unit, spread) for unit in named] + rest_values = [value(unit, spread) for unit in rest] + scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values)) return RunScores(len(units), len(named), unmeasured, scores) @@ -59,10 +61,15 @@ def auc(named: list[int], rest: list[int]) -> float: return wins / (len(named) * len(rest)) -def top_k(units: list[Unit], named: list[Unit], value: Callable[[Unit], int]) -> float: - """The share of the metric's top k units the seats named, k being how many they named; a tie at the cut counts in order of the units.""" - top = sorted(units, key=value, reverse=True)[:len(named)] - return sum(unit in named for unit in top) / len(named) +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 seats evenly, as a random order of them would.""" + k = len(named) + cut = sorted(named + rest, reverse=True)[k - 1] + above = sum(value > cut for value in named) + seats = k - above - sum(value > cut for value in rest) + tied_named = sum(value == cut for value in named) + tied = tied_named + sum(value == cut for value in rest) + return (above + seats * tied_named / tied) / k def medians(runs: list[RunScores]) -> dict[str, Score]: diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index 85fe13f1..e932ec81 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -15,7 +15,9 @@ medians. Places that name no Python function or method, such as a section of a m counted as unmeasured. Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the -history cannot be read, a run's commit is missing, or no scoring run names a measured unit. +history cannot be read, a measured file does not parse, or no scoring run names a measured unit. A +run whose commit the checkout lacks, such as a deleted branch's, is skipped and named below the +table. """ import pathlib import subprocess @@ -23,7 +25,7 @@ import sys from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score from failure import Failure -from metric_bench.python_units import measured, python_units +from metric_bench.python_units import measured, python_units, Unit from metric_bench.places import resolved, scoring_runs, ScoringRun @@ -45,15 +47,20 @@ def main(argv: list[str]) -> int: except (OSError, UnicodeDecodeError) as failure: return failed(Failure(f"could not read {history}: {failure}")) rows = [] + gone = [] for run in scoring_runs(text): + if isinstance(git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure): + gone.append(run.heading) + continue scores = run_scores(run, top) if isinstance(scores, Failure): return failed(scores) if scores: rows.append((run.heading, scores)) + skipped = "".join(f"\nSkipped, its commit is not in {top}: {heading}" for heading in gone) if not rows: - return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures")) - print(table(rows)) + return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md โ†’ \"History\"{skipped}")) + print(table(rows) + ("\n" + skipped if skipped else "")) return 0 @@ -62,16 +69,20 @@ def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure: if isinstance(listed, Failure): return listed tracked = listed.split("\n") - units = [] + units: list[Unit] = [] for path in filter(measured, tracked): source = git(["show", f"{run.commit}:{path}"], top) if isinstance(source, Failure): return source - units += python_units(path, source) + found = python_units(path, source) + if isinstance(found, Failure): + return found + units += found log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top) if isinstance(log, Failure): return log - return bench(units, resolved(run.places, tracked), co_changed(log)) + places = resolved(run.places, tracked) + return bench(units, places, len(run.places) - len(places), co_changed(log)) def table(rows: list[tuple[str, RunScores]]) -> str: diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py index f38412a8..4cb3e016 100644 --- a/bin/metric_bench/places.py +++ b/bin/metric_bench/places.py @@ -4,6 +4,7 @@ import re from markdown_sections import sections +# The format: skills/larv-review/SKILL.md ยง3 โ†’ "History", which names this reader. RUN = re.compile(r"^(.+), (.+) at ([0-9a-f]{7,40})$") SEAT_PLACES = re.compile(r"^.+, (hardest first|would restructure first):$") # `path:line` or `:line`, then the unit's name where one follows. diff --git a/bin/metric_bench/python_units.py b/bin/metric_bench/python_units.py index 7f1d5a3a..926ce687 100644 --- a/bin/metric_bench/python_units.py +++ b/bin/metric_bench/python_units.py @@ -1,6 +1,9 @@ import ast import collections import dataclasses +import sys + +from failure import Failure FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef) @@ -20,12 +23,12 @@ def measured(path: str) -> bool: return name.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in folders.split("/") -def python_units(path: str, source: str) -> list[Unit]: - """Each module-level function and each method in source, with its metrics; a source that does not parse has none.""" +def python_units(path: str, source: str) -> list[Unit] | Failure: + """Each module-level function and each method in source, with its metrics.""" try: tree = ast.parse(source) - except (SyntaxError, ValueError): - return [] + except (SyntaxError, ValueError) as failure: + return Failure(f"could not parse {path} on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}") units = [] for node in tree.body: if isinstance(node, FUNCTION): @@ -61,97 +64,37 @@ def written(node: ast.AST) -> list[ast.expr]: # SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition. def cognitive(function: ast.FunctionDef | ast.AsyncFunctionDef) -> int: - counter = Cognitive(function.name) - counter.within(function.body, 0) - return counter.score + return sum(score(node, 0, function.name) for node in function.body) -class Cognitive(ast.NodeVisitor): - def __init__(self, name: str) -> None: - self.name = name - self.nesting = 0 - self.score = 0 +def score(node: ast.AST, nesting: int, name: str) -> int: + """The cognitive complexity node adds at nesting depth nesting, its children included; name is the function's own, a call to it counting as recursion.""" + def inside(nodes: list, depth: int = nesting + 1) -> int: + return sum(score(child, depth, name) for child in nodes) - def within(self, nodes: list, deeper: int = 1) -> None: - self.nesting += deeper - for node in nodes: - self.visit(node) - self.nesting -= deeper + if isinstance(node, ast.If): + return 1 + nesting + branches(node, nesting, name) + if isinstance(node, ast.For | ast.AsyncFor | ast.While): + head = node.test if isinstance(node, ast.While) else node.iter + return 1 + nesting + score(head, nesting, name) + inside(node.body) + (1 + inside(node.orelse) if node.orelse else 0) + if isinstance(node, ast.Try | ast.TryStar): + handlers = sum(1 + nesting + inside(handler.body) for handler in node.handlers) + return inside(node.body, nesting) + handlers + inside(node.orelse, nesting) + inside(node.finalbody, nesting) + if isinstance(node, ast.Match): + return 1 + nesting + score(node.subject, nesting, name) + sum(inside(case.body) for case in node.cases) + if isinstance(node, ast.IfExp): + return 1 + nesting + inside([node.test, node.body, node.orelse]) + if isinstance(node, ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp): + return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node))) + if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda): + return inside(node.body if isinstance(node.body, list) else [node.body]) + own = 1 if isinstance(node, ast.BoolOp) or isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name else 0 + return own + inside(list(ast.iter_child_nodes(node)), nesting) - def structure(self) -> None: - self.score += 1 + self.nesting - def visit_If(self, node: ast.If) -> None: - self.structure() - self.branch(node) - - def branch(self, node: ast.If) -> None: - self.visit(node.test) - self.within(node.body) - if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If): - self.score += 1 - self.branch(node.orelse[0]) - elif node.orelse: - self.score += 1 - self.within(node.orelse) - - def loop(self, node: ast.For | ast.AsyncFor | ast.While, head: ast.expr) -> None: - self.structure() - self.visit(head) - self.within(node.body) - if node.orelse: - self.score += 1 - self.within(node.orelse) - - def visit_For(self, node: ast.For | ast.AsyncFor) -> None: - self.loop(node, node.iter) - - visit_AsyncFor = visit_For - - def visit_While(self, node: ast.While) -> None: - self.loop(node, node.test) - - def visit_Try(self, node: ast.Try | ast.TryStar) -> None: - self.within(node.body, 0) - for handler in node.handlers: - self.structure() - self.within(handler.body) - self.within(node.orelse, 0) - self.within(node.finalbody, 0) - - visit_TryStar = visit_Try - - def visit_Match(self, node: ast.Match) -> None: - self.structure() - self.visit(node.subject) - for case in node.cases: - self.within(case.body) - - def visit_IfExp(self, node: ast.IfExp) -> None: - self.structure() - self.within([node.test, node.body, node.orelse]) - - def visit_BoolOp(self, node: ast.BoolOp) -> None: - self.score += 1 - self.generic_visit(node) - - def comprehension(self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp) -> None: - for generator in node.generators: - self.structure() - self.score += len(generator.ifs) - self.within(list(ast.iter_child_nodes(node))) - - visit_DictComp = visit_GeneratorExp = visit_ListComp = visit_SetComp = comprehension - - def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: - self.within(node.body) - - visit_AsyncFunctionDef = visit_FunctionDef - - def visit_Lambda(self, node: ast.Lambda) -> None: - self.within([node.body]) - - def visit_Call(self, node: ast.Call) -> None: - if isinstance(node.func, ast.Name) and node.func.id == self.name: - self.score += 1 - self.generic_visit(node) +def branches(node: ast.If, nesting: int, name: str) -> int: + """An if's test and bodies; an elif or else adds 1 at no extra depth.""" + total = score(node.test, nesting, name) + sum(score(child, nesting + 1, name) for child in node.body) + if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If): + return total + 1 + branches(node.orelse[0], nesting, name) + return total + (1 + sum(score(child, nesting + 1, name) for child in node.orelse) if node.orelse else 0) diff --git a/bin/test_metric_bench.py b/bin/test_metric_bench.py index cdcf60a4..662a6015 100644 --- a/bin/test_metric_bench.py +++ b/bin/test_metric_bench.py @@ -9,8 +9,9 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from metric_bench.bench import auc, bench, co_changed +from metric_bench.bench import auc, bench, co_changed, top_k from metric_bench.python_units import cognitive, measured, python_units, Unit +from failure import Failure from test_loop_claude_black_box import host_env from metric_bench.places import Place, resolved, scoring_runs @@ -59,6 +60,16 @@ class Cognitive(unittest.TestCase): pass """), 1 + 2 + 2 + 1 + 1) + def test_nests_a_while_a_lambda_and_an_inner_function(self): + self.assertEqual(scored(""" + def f(a): + while a: + g = lambda b: 1 if b else 2 + def h(): + if a: + pass + """), 1 + 3 + 3) + def test_counts_a_comprehension_as_a_loop_and_its_conditions(self): self.assertEqual(scored(""" def f(rows): @@ -88,8 +99,10 @@ class Units(unittest.TestCase): def test_measures_python_files_outside_the_tests(self): self.assertEqual([path for path in ["a.py", "bin/test_a.py", "a_test.py", "tests/b.py", "e2e-tests/c.py", "README.md"] if measured(path)], ["a.py", "e2e-tests/c.py"]) - def test_a_source_that_does_not_parse_has_no_units(self): - self.assertEqual(python_units("a.py", "def ("), []) + def test_a_source_that_does_not_parse_is_a_failure_naming_it(self): + failure = python_units("a.py", "def (") + assert isinstance(failure, Failure) + self.assertIn("could not parse a.py", failure.reason) class Places(unittest.TestCase): @@ -107,6 +120,10 @@ class Places(unittest.TestCase): - `skills/x/SKILL.md:77` "Architecture" - `bin/tool/cycle/states.py:69` `transition`, with `cycle/run.py:55` `step` and `:90` `close` + Inherited architect, would restructure first: + + - `bin/tool/cycle/judge.py:31` `run_judge` + ## 2026-10-08T18:37:21Z, PR #228 at 2682668, against 8c9bf09 Mid A, decided by: @@ -117,7 +134,7 @@ class Places(unittest.TestCase): def test_reads_each_scoring_runs_places_and_leaves_paired_rulings_out(self): runs = scoring_runs(self.HISTORY) self.assertEqual([(run.heading, run.commit) for run in runs], [("2026-10-08T12:50:49Z, PR #224 at a58a0a8", "a58a0a8")]) - self.assertEqual(runs[0].places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close")]) + self.assertEqual(runs[0].places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close"), Place("bin/tool/cycle/judge.py", "run_judge")]) def test_resolves_a_shortened_path_to_the_file_nearest_the_one_before_it(self): tracked = ["bin/tool/cycle/states.py", "bin/tool/cycle/run.py", "bin/other/cycle/run.py"] @@ -136,16 +153,21 @@ class Bench(unittest.TestCase): def test_co_changed_counts_each_files_distinct_partners(self): self.assertEqual(co_changed("@@\na.py\nb.py\n@@\na.py\nc.py\n@@\na.py"), {"a.py": 2, "b.py": 1, "c.py": 1}) + def test_top_k_shares_the_seats_at_a_tied_cut_evenly(self): + self.assertEqual(top_k([0, 0], [0, 0, 0, 0]), 1 / 3) + self.assertEqual(top_k([5, 1], [1, 1]), 2 / 3) + def test_scores_the_named_units_and_counts_places_no_unit_measures(self): units = [Unit("a.py", "hard", 9, 40, 0), Unit("a.py", "easy", 1, 5, 0), Unit("b.py", "plain", 2, 6, 0)] - run = bench(units, [Place("a.py", "hard"), Place("doc.md", None)], {"a.py": 1}) + run = bench(units, [Place("a.py", "hard"), Place("doc.md", None)], 2, {"a.py": 1}) assert run is not None - self.assertEqual((run.units, run.named, run.unmeasured), (3, 1, 1)) + self.assertEqual((run.units, run.named, run.unmeasured), (3, 1, 3)) self.assertEqual((run.scores["cognitive complexity"].auc, run.scores["cognitive complexity"].top_k), (1.0, 1.0)) - self.assertEqual(run.scores["shared state"].auc, 0.5) + self.assertEqual((run.scores["shared state"].auc, run.scores["shared state"].top_k), (0.5, 1 / 3)) - def test_a_run_naming_no_measured_unit_is_not_scored(self): - self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("doc.md", None)], {})) + def test_a_run_naming_no_unit_or_every_unit_is_not_scored(self): + self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("doc.md", None)], 0, {})) + self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("a.py", "f")], 0, {})) class BlackBox(unittest.TestCase): @@ -187,6 +209,13 @@ class BlackBox(unittest.TestCase): self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr) self.assertEqual(self.run_tool(top, "--x").returncode, 1) + def test_skips_and_names_a_run_whose_commit_the_checkout_lacks(self): + top = self.project("# Comprehension history\n\n## 2026-10-07T12:00:00Z, PR #0 at 0123456\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n") + ran = self.run_tool(top) + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertIn("Skipped, its commit is not in", ran.stdout) + self.assertIn("PR #0 at 0123456", ran.stdout.split("Skipped")[1]) + def test_reads_the_checkout_that_holds_a_history_named_from_elsewhere(self): top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n") ran = self.run_tool(tempfile.gettempdir(), str(pathlib.Path(top, "docs", "comprehension-history.md"))) diff --git a/bin/test_types.py b/bin/test_types.py index 88d6ea30..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", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline", "-p", "loop_claude"], 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) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 30cc0f08..2e832819 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -368,3 +368,30 @@ Inherited architect, decided by: - `skills/larv-review/SKILL.md:35`, `:98` and `:120`: the trigger three times, and seven concepts where there were three - `AGENTS.md:35` "Scoring run": the heading not renamed with the file - `skills/larv-review/SKILL.md:64` "Re-entry" and `:40` the Prose row, `:37` and `:124` "Security", better + +## 2026-10-08T19:48:05Z, PR #229 at 8a2dbd7, against 12d6d75 + +Ruling: worse + +| Seat | Vote | +|---|---| +| Mid A | worse | +| Inherited architect | worse | + +Mid A, decided by: + +- `skills/larv-review/SKILL.md:93` "Paired ruling" โ†’ "Base": the base found by a prose `git log` search with two fallbacks +- `skills/larv-review/SKILL.md:95` "Seats" and "Ruling": vote arithmetic written as prose, with no example +- `skills/larv-review/SKILL.md:89` "Architecture": two kinds of run, each with its own trigger, seats and block +- `CLAUDE.md:40` "Quality": a clause folded into a noun phrase +- `bin/metric_bench/places.py:7` `RUN`, `SEAT_PLACES`, `PLACE` and `:30` `scoring_runs`: a second reader of a format defined only in prose, linked from neither side + +Inherited architect, decided by: + +- `skills/larv-review/SKILL.md:93` "Paired ruling" โ†’ "Base": "worse than what?" means running the base search in your head +- `skills/larv-review/SKILL.md:95` "Seats" and "Ruling": a two-stage panel and vote arithmetic with nothing to run or test it +- `skills/larv-review/SKILL.md:35`, `:98` "Scoring run" and `:120` "Suspended": the scoring run's trigger written out in four places +- `skills/larv-review/SKILL.md:36` the Full scan and Security rows: each row's trigger depends on the other +- `bin/metric_bench/places.py:7` `RUN`, `SEAT_PLACES`, `PLACE`: a regex reader of the history linked from neither side +- `bin/metric_bench/places.py:59` `resolved`: a result that depends on the place resolved before it +- `bin/metric_bench/python_units.py:69` `Cognitive`: nesting bookkeeping spread over its methods diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 4aeba287..47dbf1b1 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -108,7 +108,7 @@ Fix a worse ruling at the places the seats voting worse name, and the floor at t Two files of the project keep the records: -- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, appended and never edited. Each opens with a `## , at ` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against `. A paired ruling holds a `Ruling: ` line, a table of each seat's vote, and under each seat, labelled `, decided by:`, its places. A scoring run holds a table of each seat's five scores, with a last row holding the four seats' mean of each, and under each seat, labelled `, hardest first:` or, for the architect, `, would restructure first:`, its places. A place is `path:line`, the path written from the repository's root, and the unit's name. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. +- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, appended and never edited. Each opens with a `## , at ` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against `. A paired ruling holds a `Ruling: ` line, a table of each seat's vote, and under each seat, labelled `, decided by:`, its places. A scoring run holds a table of each seat's five scores, with a last row holding the four seats' mean of each, and under each seat, labelled `, hardest first:` or, for the architect, `, would restructure first:`, its places. A place is `path:line`, the path written from the repository's root, and the unit's name. `bin/metric_bench/places.py` reads this format: change both together. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. - **Entry.** `docs/decisions.md` keeps one entry whose title opens `comprehension floor:`. It holds each decision to ship under the floor, with its scores. A `comprehension floor:` entry written before the history may still hold a scoring run's five scores. The next scoring run moves them, and only them, into the history as its first run: a heading of the date or time the entry gives and whatever it names the run by, its commit included where named, and a table with the mean alone. The rest of the entry stays. diff --git a/todo.md b/todo.md index 22728911..410faec5 100644 --- a/todo.md +++ b/todo.md @@ -60,7 +60,7 @@ A hand-written question bank goes stale as the project grows and leaves everythi ### 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 the items that lower token use (73, 77, 78). 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: next after the items that lower token use (73, 77, 78). Later that day lilleman rescored 73 below this item, and 77 moved to 0.2.0 to wait for data, so only 78 goes first. 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. @@ -187,7 +187,7 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic |---|---|---| | Cognitive complexity | 0.66 | 0.26 | | Length | 0.74 | 0.18 | -| Shared state | 0.50 | 0.06 | -| Change spread | 0.64 | 0.17 | +| Shared state | 0.50 | 0.10 | +| Change spread | 0.64 | 0.15 | AUC is 0.5 for a coin toss. Shared state cannot be judged here, since no unit in `bin/` writes state another method shares. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces. -- 2.52.0 From 6240f82857f53e8bb71a021d429f6d6242a96c8c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 22:49:45 +0200 Subject: [PATCH 04/13] Answer security round 1: nothing to fix -- 2.52.0 From 1fca6137c24e9680215cb6b77c2980a89d0889c9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 22:52:14 +0200 Subject: [PATCH 05/13] Answer architecture round 2: split main into read_history and bench_runs, state why score dispatches in one function and lift inside out of it, count unresolved places once, name git's reason for a skipped run, and say to call each tool by its path --- README.md | 2 +- bin/metric_bench/main.py | 56 ++++++++++++++++++++++---------- bin/metric_bench/python_units.py | 34 ++++++++++--------- 3 files changed, 57 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 96db5ea4..67b2bb7c 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit ## Tools -Run each from `~/.claude/bin/`; Install puts only `loop-claude` on `PATH`. +Call each by its path, such as `~/.claude/bin/metric-bench`, from the project's checkout; Install puts only `loop-claude` on `PATH`. - `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. diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index e932ec81..856a1f5b 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -11,8 +11,8 @@ names declared global or nonlocal), and change spread (how many other files chan the unit's file, up to that commit). It then prints, for each metric, how well it ranks the units the seats named above the rest: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share of the metric's k highest units the seats named, k being how many they named). A last row gives the -medians. Places that name no Python function or method, such as a section of a markdown file, are -counted as unmeasured. +medians. Unmeasured counts the distinct places that name no Python function or method, such as a +section of a markdown file, or no single tracked file. Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history cannot be read, a measured file does not parse, or no scoring run names a measured unit. A @@ -36,32 +36,51 @@ def main(argv: list[str]) -> int: if len(argv) > 1 or argv[:1] and argv[0].startswith("-"): print(f"unknown arguments {' '.join(argv)}; usage: metric-bench [history]", file=sys.stderr) return 1 - given = pathlib.Path(argv[0]).resolve() if argv else None + read = read_history(pathlib.Path(argv[0]).resolve() if argv else None) + if isinstance(read, Failure): + return failed(read) + top, history, text = read + benched = bench_runs(text, top) + if isinstance(benched, Failure): + return failed(benched) + rows, gone = benched + if not rows: + return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md โ†’ \"History\"{skipped(gone, top)}")) + print(table(rows) + skipped(gone, top)) + return 0 + + +def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | Failure: + """The checkout that holds the history, the history's path and its text.""" found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None) if isinstance(found, Failure): - return failed(found) - top = found.strip() - history = given or pathlib.Path(top, "docs", "comprehension-history.md") + return found + history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md") try: - text = history.read_text(encoding="utf-8") + return found.strip(), history, history.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: - return failed(Failure(f"could not read {history}: {failure}")) + return Failure(f"could not read {history}: {failure}") + + +def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[str]] | Failure: + """Each scored run's heading and scores, and the headings of the runs whose commit the checkout lacks.""" rows = [] gone = [] for run in scoring_runs(text): - if isinstance(git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure): - gone.append(run.heading) + if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure): + gone.append(f"{run.heading} ({missing.reason})") continue scores = run_scores(run, top) if isinstance(scores, Failure): - return failed(scores) + return scores if scores: rows.append((run.heading, scores)) - skipped = "".join(f"\nSkipped, its commit is not in {top}: {heading}" for heading in gone) - if not rows: - return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md โ†’ \"History\"{skipped}")) - print(table(rows) + ("\n" + skipped if skipped else "")) - return 0 + return rows, gone + + +def skipped(gone: list[str], top: str) -> str: + lines = [f"Skipped, its commit is not in {top}: {run}" for run in gone] + return "\n\n" + "\n".join(lines) if lines else "" def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure: @@ -81,8 +100,9 @@ def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure: log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top) if isinstance(log, Failure): return log - places = resolved(run.places, tracked) - return bench(units, places, len(run.places) - len(places), co_changed(log)) + named = list(dict.fromkeys(run.places)) + places = resolved(named, tracked) + return bench(units, places, len(named) - len(places), co_changed(log)) def table(rows: list[tuple[str, RunScores]]) -> str: diff --git a/bin/metric_bench/python_units.py b/bin/metric_bench/python_units.py index 926ce687..f58df8f5 100644 --- a/bin/metric_bench/python_units.py +++ b/bin/metric_bench/python_units.py @@ -64,37 +64,39 @@ def written(node: ast.AST) -> list[ast.expr]: # SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition. def cognitive(function: ast.FunctionDef | ast.AsyncFunctionDef) -> int: - return sum(score(node, 0, function.name) for node in function.body) + return inside(function.body, 0, function.name) +# One case per node type, as the white paper's table has one row per structure: split, the rules would scatter. def score(node: ast.AST, nesting: int, name: str) -> int: - """The cognitive complexity node adds at nesting depth nesting, its children included; name is the function's own, a call to it counting as recursion.""" - def inside(nodes: list, depth: int = nesting + 1) -> int: - return sum(score(child, depth, name) for child in nodes) - + """The cognitive complexity node adds at depth nesting, its children included; name is the function's own, a call to it counting as recursion.""" if isinstance(node, ast.If): return 1 + nesting + branches(node, nesting, name) if isinstance(node, ast.For | ast.AsyncFor | ast.While): head = node.test if isinstance(node, ast.While) else node.iter - return 1 + nesting + score(head, nesting, name) + inside(node.body) + (1 + inside(node.orelse) if node.orelse else 0) + return 1 + nesting + score(head, nesting, name) + inside(node.body, nesting + 1, name) + (1 + inside(node.orelse, nesting + 1, name) if node.orelse else 0) if isinstance(node, ast.Try | ast.TryStar): - handlers = sum(1 + nesting + inside(handler.body) for handler in node.handlers) - return inside(node.body, nesting) + handlers + inside(node.orelse, nesting) + inside(node.finalbody, nesting) + handlers = sum(1 + nesting + inside(handler.body, nesting + 1, name) for handler in node.handlers) + return inside(node.body + node.orelse + node.finalbody, nesting, name) + handlers if isinstance(node, ast.Match): - return 1 + nesting + score(node.subject, nesting, name) + sum(inside(case.body) for case in node.cases) + return 1 + nesting + score(node.subject, nesting, name) + sum(inside(case.body, nesting + 1, name) for case in node.cases) if isinstance(node, ast.IfExp): - return 1 + nesting + inside([node.test, node.body, node.orelse]) + return 1 + nesting + inside([node.test, node.body, node.orelse], nesting + 1, name) if isinstance(node, ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp): - return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node))) + return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node)), nesting + 1, name) if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda): - return inside(node.body if isinstance(node.body, list) else [node.body]) - own = 1 if isinstance(node, ast.BoolOp) or isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name else 0 - return own + inside(list(ast.iter_child_nodes(node)), nesting) + return inside(node.body if isinstance(node.body, list) else [node.body], nesting + 1, name) + recursion = isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name + return (isinstance(node, ast.BoolOp) or recursion) + inside(list(ast.iter_child_nodes(node)), nesting, name) + + +def inside(nodes: list, nesting: int, name: str) -> int: + return sum(score(node, nesting, name) for node in nodes) def branches(node: ast.If, nesting: int, name: str) -> int: """An if's test and bodies; an elif or else adds 1 at no extra depth.""" - total = score(node.test, nesting, name) + sum(score(child, nesting + 1, name) for child in node.body) + total = score(node.test, nesting, name) + inside(node.body, nesting + 1, name) if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If): return total + 1 + branches(node.orelse[0], nesting, name) - return total + (1 + sum(score(child, nesting + 1, name) for child in node.orelse) if node.orelse else 0) + return total + (1 + inside(node.orelse, nesting + 1, name) if node.orelse else 0) -- 2.52.0 From 527aef3495dc53b310375b09ac8838f30d92f4ca Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:04:12 +0200 Subject: [PATCH 06/13] Answer stability, product-owner and architecture round 3: resolve every place in order and count the dropped ones once, let a full path win, name unparsed files and unscored runs below the table, show chance and constant metrics, leave sweeps of more than 30 files out of change spread, count tuple and loop writes and self recursion, and say what a missing history or folder means --- bin/metric_bench/bench.py | 17 ++++-- bin/metric_bench/main.py | 98 +++++++++++++++++++------------- bin/metric_bench/places.py | 11 ++-- bin/metric_bench/python_units.py | 28 +++++++-- bin/test_metric_bench.py | 40 ++++++++++--- todo.md | 6 +- 6 files changed, 135 insertions(+), 65 deletions(-) diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index b3dcf31c..70f54d8d 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -14,10 +14,15 @@ METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = { } +# Code Maat's default --max-changeset-size: a sweep across the tree couples every file to every other. +LARGEST_CHANGESET = 30 + + @dataclasses.dataclass(frozen=True) class Score: auc: float top_k: float + constant: bool @dataclasses.dataclass(frozen=True) @@ -29,10 +34,12 @@ class RunScores: def co_changed(log: str) -> dict[str, int]: - """For each file, how many other files changed in a commit with it; log is `git log --format=format:@@ --name-only`.""" + """For each file, how many other files changed in a commit with it, commits of more than LARGEST_CHANGESET files left out; log is `git log --format=format:@@ --name-only`.""" partners: dict[str, set[str]] = collections.defaultdict(set) - for commit in log.split("@@"): - files = set(commit.split()) + for commit in log.split("@@\n"): + files = set(filter(None, commit.split("\n"))) + if len(files) > LARGEST_CHANGESET: + continue for path in files: partners[path] |= files - {path} return {path: len(others) for path, others in partners.items()} @@ -51,7 +58,7 @@ def bench(units: list[Unit], places: list[Place], unresolved: int, spread: dict[ for metric, value in METRICS.items(): named_values = [value(unit, spread) for unit in named] rest_values = [value(unit, spread) for unit in rest] - scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values)) + scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values), len(set(named_values + rest_values)) == 1) return RunScores(len(units), len(named), unmeasured, scores) @@ -73,4 +80,4 @@ def top_k(named: list[int], rest: list[int]) -> float: def medians(runs: list[RunScores]) -> dict[str, Score]: - return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs)) for metric in METRICS} + return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs), all(run.scores[metric].constant for run in runs)) for metric in METRICS} diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index 856a1f5b..c69199f9 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -4,22 +4,32 @@ usage: metric-bench [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 seats read, it -measures every Python function and method git -tracks, test files left out: cognitive complexity (SonarSource's white paper, read for Python), -length in lines, shared state (attributes on self another method of the class also writes, plus -names declared global or nonlocal), and change spread (how many other files changed in a commit with -the unit's file, up to that commit). It then prints, for each metric, how well it ranks the units -the seats named above the rest: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share -of the metric's k highest units the seats named, k being how many they named). A last row gives the -medians. Unmeasured counts the distinct places that name no Python function or method, such as a -section of a markdown file, or no single tracked file. +measures each module-level function and each method of a module-level class in the Python files git +tracks, leaving out test_*.py, *_test.py and anything under a tests/ folder: -Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the -history cannot be read, a measured file does not parse, or no scoring run names a measured unit. A -run whose commit the checkout lacks, such as a deleted branch's, is skipped and named below the -table. +- cognitive complexity: SonarSource's white paper, read for Python; +- length: lines; +- shared state: attributes on self that another method of the class also writes, plus names + declared global or nonlocal; +- change spread: how many other files changed in a commit with the unit's file, up to that commit, + leaving out commits of more than 30 files. + +It then prints, for each metric, how well it ranks the units the seats named above the rest: AUC +(0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share of the metric's k highest units +the seats named, k being how many they named; Chance is what top k scores at random). A metric that +gave every unit one value reads "constant". A last row gives the medians. Unmeasured counts the +distinct places that name no Python function or method, such as a section of a markdown file, or no +single tracked file. + +Below the table it names each run it skipped, its commit not in the checkout, each run it could not +score, its places naming no measured unit or every one, and each file that does not parse on this +Python, left out of its run. + +Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history +cannot be read, or no scoring run names a measured unit. """ import pathlib +import statistics import subprocess import sys @@ -43,19 +53,23 @@ def main(argv: list[str]) -> int: benched = bench_runs(text, top) if isinstance(benched, Failure): return failed(benched) - rows, gone = benched + rows, notes = benched if not rows: - return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md โ†’ \"History\"{skipped(gone, top)}")) - print(table(rows) + skipped(gone, top)) + return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md โ†’ \"History\"{noted(notes)}")) + print(table(rows) + noted(notes)) return 0 def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | Failure: """The checkout that holds the history, the history's path and its text.""" + if given and not given.parent.is_dir(): + return Failure(f"could not read {given}: no folder {given.parent}") found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None) if isinstance(found, Failure): return found history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md") + if not history.exists(): + return Failure(f"no comprehension history at {history}; larv-review writes one at a project's first paired ruling or scoring run") try: return found.strip(), history, history.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: @@ -63,60 +77,66 @@ def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[str]] | Failure: - """Each scored run's heading and scores, and the headings of the runs whose commit the checkout lacks.""" + """Each scored run's heading and scores, and a note for each run skipped or not scored and each file left out.""" rows = [] - gone = [] + notes = [] for run in scoring_runs(text): if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure): - gone.append(f"{run.heading} ({missing.reason})") + notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})") continue - scores = run_scores(run, top) - if isinstance(scores, Failure): - return scores + scored = run_scores(run, top) + if isinstance(scored, Failure): + return scored + scores, unparsed = scored + notes += [f"Left out of {run.heading}: {reason}" for reason in unparsed] if scores: rows.append((run.heading, scores)) - return rows, gone + else: + notes.append(f"Not scored, its places name no measured unit or every one: {run.heading}") + return rows, notes -def skipped(gone: list[str], top: str) -> str: - lines = [f"Skipped, its commit is not in {top}: {run}" for run in gone] - return "\n\n" + "\n".join(lines) if lines else "" +def noted(notes: list[str]) -> str: + return "\n\n" + "\n".join(notes) if notes else "" -def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure: - listed = git(["ls-tree", "-r", "--name-only", run.commit], top) +def run_scores(run: ScoringRun, top: str) -> tuple[RunScores | None, list[str]] | Failure: + """The run's scores, and why each file that does not parse was left out.""" + listed = git(["ls-tree", "-r", "-z", "--name-only", run.commit], top) if isinstance(listed, Failure): return listed - tracked = listed.split("\n") + tracked = list(filter(None, listed.split("\0"))) units: list[Unit] = [] + unparsed = [] for path in filter(measured, tracked): source = git(["show", f"{run.commit}:{path}"], top) if isinstance(source, Failure): return source found = python_units(path, source) if isinstance(found, Failure): - return found - units += found - log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top) + unparsed.append(found.reason) + else: + units += found + log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top) if isinstance(log, Failure): return log - named = list(dict.fromkeys(run.places)) - places = resolved(named, tracked) - return bench(units, places, len(named) - len(places), co_changed(log)) + places, dropped = resolved(run.places, tracked) + return bench(units, places, len(set(dropped)), co_changed(log)), unparsed def table(rows: list[tuple[str, RunScores]]) -> str: - head = ["Scoring run", "Units", "Named", "Unmeasured", *METRICS] + head = ["Scoring run", "Units", "Named", "Unmeasured", "Chance", *METRICS] lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)] for heading, run in rows: - lines.append("| " + " | ".join([heading, str(run.units), str(run.named), str(run.unmeasured), *(cell(run.scores[metric]) for metric in METRICS)]) + " |") + lines.append("| " + " | ".join([heading, str(run.units), str(run.named), str(run.unmeasured), f"top k {run.named / run.units:.2f}", *(cell(run.scores[metric]) for metric in METRICS)]) + " |") medianed = medians([run for _, run in rows]) - lines.append("| " + " | ".join(["Median", "", "", "", *(cell(medianed[metric]) for metric in METRICS)]) + " |") + chance = statistics.median(run.named / run.units for _, run in rows) + lines.append("| " + " | ".join(["Median", "", "", "", f"top k {chance:.2f}", *(cell(medianed[metric]) for metric in METRICS)]) + " |") return "\n".join(lines) def cell(score: Score) -> str: - return f"AUC {score.auc:.2f}, top k {score.top_k:.2f}" + return "constant" if score.constant else f"AUC {score.auc:.2f}, top k {score.top_k:.2f}" def git(args: list[str], cwd: str | None) -> str | Failure: diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py index 4cb3e016..a9fcb913 100644 --- a/bin/metric_bench/places.py +++ b/bin/metric_bench/places.py @@ -57,14 +57,17 @@ def bullet_places(bullet: str) -> list[Place]: return places -def resolved(places: list[Place], tracked: list[str]) -> list[Place]: - """Seats shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped.""" +def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]: + """Seats shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones.""" found = [] + dropped = [] before = "" for place in places: - candidates = [path for path in tracked if path == place.path or path.endswith("/" + place.path)] + candidates = [place.path] if place.path in tracked else [path for path in tracked if path.endswith("/" + place.path)] nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates if len(nearest) == 1: before = nearest[0] found.append(Place(before, place.name)) - return found + else: + dropped.append(place) + return found, dropped diff --git a/bin/metric_bench/python_units.py b/bin/metric_bench/python_units.py index f58df8f5..fdde70dd 100644 --- a/bin/metric_bench/python_units.py +++ b/bin/metric_bench/python_units.py @@ -24,11 +24,11 @@ def measured(path: str) -> bool: def python_units(path: str, source: str) -> list[Unit] | Failure: - """Each module-level function and each method in source, with its metrics.""" + """Each module-level function and each method of a module-level class in source, with its metrics.""" try: tree = ast.parse(source) except (SyntaxError, ValueError) as failure: - return Failure(f"could not parse {path} on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}") + return Failure(f"{path} does not parse on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}") units = [] for node in tree.body: if isinstance(node, FUNCTION): @@ -58,8 +58,14 @@ def shared_writes(cls: ast.ClassDef) -> collections.Counter[str]: def written(node: ast.AST) -> list[ast.expr]: if isinstance(node, ast.Assign): - return node.targets - return [node.target] if isinstance(node, ast.AugAssign | ast.AnnAssign) else [] + targets = node.targets + elif isinstance(node, ast.AugAssign | ast.AnnAssign | ast.For | ast.AsyncFor | ast.comprehension): + targets = [node.target] + elif isinstance(node, ast.withitem) and node.optional_vars: + targets = [node.optional_vars] + else: + return [] + return [leaf for target in targets for leaf in ast.walk(target) if isinstance(leaf, ast.Attribute)] # SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition. @@ -86,8 +92,18 @@ def score(node: ast.AST, nesting: int, name: str) -> int: return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node)), nesting + 1, name) if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda): return inside(node.body if isinstance(node.body, list) else [node.body], nesting + 1, name) - recursion = isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name - return (isinstance(node, ast.BoolOp) or recursion) + inside(list(ast.iter_child_nodes(node)), nesting, name) + return (isinstance(node, ast.BoolOp) or called(node) == name) + inside(list(ast.iter_child_nodes(node)), nesting, name) + + +def called(node: ast.AST) -> str | None: + """The function a call names, or the method it calls on self.""" + if not isinstance(node, ast.Call): + return None + if isinstance(node.func, ast.Name): + return node.func.id + if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id == "self": + return node.func.attr + return None def inside(nodes: list, nesting: int, name: str) -> int: diff --git a/bin/test_metric_bench.py b/bin/test_metric_bench.py index 662a6015..57ecad0a 100644 --- a/bin/test_metric_bench.py +++ b/bin/test_metric_bench.py @@ -70,6 +70,12 @@ class Cognitive(unittest.TestCase): pass """), 1 + 3 + 3) + def test_counts_a_call_to_itself_on_self_as_recursion(self): + self.assertEqual(scored(""" + def walk(self, node): + return self.walk(node.child) + """), 1) + def test_counts_a_comprehension_as_a_loop_and_its_conditions(self): self.assertEqual(scored(""" def f(rows): @@ -93,8 +99,11 @@ class Units(unittest.TestCase): def grow(self): self.size += 1 self.name = "x" + + def rename(self): + self.name, self.other = "y", 1 """)) - self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 1)]) + self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 2), Unit("a.py", "rename", 0, 2, 1)]) def test_measures_python_files_outside_the_tests(self): self.assertEqual([path for path in ["a.py", "bin/test_a.py", "a_test.py", "tests/b.py", "e2e-tests/c.py", "README.md"] if measured(path)], ["a.py", "e2e-tests/c.py"]) @@ -102,7 +111,7 @@ class Units(unittest.TestCase): def test_a_source_that_does_not_parse_is_a_failure_naming_it(self): failure = python_units("a.py", "def (") assert isinstance(failure, Failure) - self.assertIn("could not parse a.py", failure.reason) + self.assertIn("a.py does not parse on Python", failure.reason) class Places(unittest.TestCase): @@ -139,10 +148,18 @@ class Places(unittest.TestCase): def test_resolves_a_shortened_path_to_the_file_nearest_the_one_before_it(self): tracked = ["bin/tool/cycle/states.py", "bin/tool/cycle/run.py", "bin/other/cycle/run.py"] places = [Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("gone.py", "x")] - self.assertEqual(resolved(places, tracked), [Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")]) + self.assertEqual(resolved(places, tracked), ([Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")], [Place("gone.py", "x")])) + + def test_a_full_path_wins_over_a_file_in_the_folder_before_it(self): + self.assertEqual(resolved([Place("pkg/x.py", "a"), Place("main.py", "f")], ["pkg/x.py", "main.py", "pkg/main.py"])[0][-1], Place("main.py", "f")) + + def test_resolves_a_shortened_path_after_a_repeated_place_by_the_repeat(self): + tracked = ["bin/a/main.py", "bin/b/main.py", "bin/b/bench.py"] + places = [Place("bin/a/main.py", "main"), Place("bin/b/bench.py", "bench"), Place("bin/a/main.py", "main"), Place("main.py", "figures")] + self.assertEqual(resolved(places, tracked)[0][-1], Place("bin/a/main.py", "figures")) def test_drops_a_shortened_path_two_files_match_with_no_place_before_it(self): - self.assertEqual(resolved([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), []) + self.assertEqual(resolved([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), ([], [Place("cycle/run.py", "step")])) class Bench(unittest.TestCase): @@ -150,8 +167,9 @@ class Bench(unittest.TestCase): self.assertEqual(auc([5, 4], [1, 2]), 1.0) self.assertEqual(auc([3], [3]), 0.5) - def test_co_changed_counts_each_files_distinct_partners(self): - self.assertEqual(co_changed("@@\na.py\nb.py\n@@\na.py\nc.py\n@@\na.py"), {"a.py": 2, "b.py": 1, "c.py": 1}) + def test_co_changed_counts_each_files_distinct_partners_past_a_sweep(self): + sweep = "".join(f"f{i}.py\n" for i in range(31)) + self.assertEqual(co_changed(f"@@\na.py\nmy b.py\n@@\na.py\nc.py\n@@\na.py\n@@\n{sweep}"), {"a.py": 2, "my b.py": 1, "c.py": 1}) def test_top_k_shares_the_seats_at_a_tied_cut_evenly(self): self.assertEqual(top_k([0, 0], [0, 0, 0, 0]), 1 / 3) @@ -195,7 +213,7 @@ class BlackBox(unittest.TestCase): ran = self.run_tool(top) self.assertEqual(ran.returncode, 0, ran.stderr) self.assertIn("| 2026-10-08T12:50:49Z, PR #1 at ", ran.stdout) - self.assertIn("| 2 | 1 | 0 | AUC 1.00, top k 1.00 | AUC 1.00, top k 1.00 | AUC 0.50,", ran.stdout) + self.assertIn("| 2 | 1 | 0 | top k 0.50 | AUC 1.00, top k 1.00 | AUC 1.00, top k 1.00 | constant | constant |", ran.stdout) self.assertIn("| Median |", ran.stdout) def test_exits_1_when_no_run_names_a_measured_unit(self): @@ -206,7 +224,8 @@ class BlackBox(unittest.TestCase): def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self): top = self.project("") - self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr) + self.assertIn("no comprehension history at", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr) + self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "gone", "x.md"))).stderr) self.assertEqual(self.run_tool(top, "--x").returncode, 1) def test_skips_and_names_a_run_whose_commit_the_checkout_lacks(self): @@ -216,6 +235,11 @@ class BlackBox(unittest.TestCase): self.assertIn("Skipped, its commit is not in", ran.stdout) self.assertIn("PR #0 at 0123456", ran.stdout.split("Skipped")[1]) + def test_names_a_run_it_cannot_score_below_the_table(self): + top = self.project("# Comprehension history\n\n## 2026-10-07T12:00:00Z, PR #0 at COMMIT\n\nJunior A, hardest first:\n\n- `README.md:1` \"Install\"\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n") + ran = self.run_tool(top) + self.assertIn("Not scored, its places name no measured unit or every one: 2026-10-07T12:00:00Z, PR #0", ran.stdout) + def test_reads_the_checkout_that_holds_a_history_named_from_elsewhere(self): top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n") ran = self.run_tool(tempfile.gettempdir(), str(pathlib.Path(top, "docs", "comprehension-history.md"))) diff --git a/todo.md b/todo.md index 410faec5..72411eb8 100644 --- a/todo.md +++ b/todo.md @@ -187,7 +187,7 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic |---|---|---| | Cognitive complexity | 0.66 | 0.26 | | Length | 0.74 | 0.18 | -| Shared state | 0.50 | 0.10 | -| Change spread | 0.64 | 0.15 | +| Shared state | constant | constant | +| Change spread | 0.67 | 0.18 | -AUC is 0.5 for a coin toss. Shared state cannot be judged here, since no unit in `bin/` writes state another method shares. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces. +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. Before the rerun, set the AUC and top-k lift over chance that count as tracking, from a published threshold, so the rerun ends in a decision. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces. -- 2.52.0 From e58c98a30feb6920dbe02ece7fa43cfae3006aa0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:04:12 +0200 Subject: [PATCH 07/13] Answer stability round 1: fixes in 527aef3 -- 2.52.0 From e67c882a08ca6a7ad1d5682750fd007902fd9234 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:04:12 +0200 Subject: [PATCH 08/13] Answer product-owner round 1: fixes in 527aef3 -- 2.52.0 From 737d58ad9f9de0a59d98ccce8c0c0f7d19f5d655 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:09:10 +0200 Subject: [PATCH 09/13] Answer architecture round 4: count only what a target assigns, end each log entry with a newline, and give the larv-review hint only for the default history --- bin/metric_bench/bench.py | 2 +- bin/metric_bench/main.py | 4 ++-- bin/metric_bench/python_units.py | 11 ++++++++++- bin/test_metric_bench.py | 7 +++++-- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index 70f54d8d..038df020 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -34,7 +34,7 @@ class RunScores: def co_changed(log: str) -> dict[str, int]: - """For each file, how many other files changed in a commit with it, commits of more than LARGEST_CHANGESET files left out; log is `git log --format=format:@@ --name-only`.""" + """For each file, how many other files changed in a commit with it, commits of more than LARGEST_CHANGESET files left out; log is `git log --format=tformat:@@ --name-only`.""" partners: dict[str, set[str]] = collections.defaultdict(set) for commit in log.split("@@\n"): files = set(filter(None, commit.split("\n"))) diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index c69199f9..cf10f700 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -68,7 +68,7 @@ def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | if isinstance(found, Failure): return found history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md") - if not history.exists(): + if not given and not history.exists(): return Failure(f"no comprehension history at {history}; larv-review writes one at a project's first paired ruling or scoring run") try: return found.strip(), history, history.read_text(encoding="utf-8") @@ -117,7 +117,7 @@ def run_scores(run: ScoringRun, top: str) -> tuple[RunScores | None, list[str]] unparsed.append(found.reason) else: units += found - log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top) + log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=tformat:@@", "--name-only", run.commit], top) if isinstance(log, Failure): return log places, dropped = resolved(run.places, tracked) diff --git a/bin/metric_bench/python_units.py b/bin/metric_bench/python_units.py index fdde70dd..c7ca8e35 100644 --- a/bin/metric_bench/python_units.py +++ b/bin/metric_bench/python_units.py @@ -65,7 +65,16 @@ def written(node: ast.AST) -> list[ast.expr]: targets = [node.optional_vars] else: return [] - return [leaf for target in targets for leaf in ast.walk(target) if isinstance(leaf, ast.Attribute)] + return [leaf for target in targets for leaf in assigned(target)] + + +def assigned(target: ast.expr) -> list[ast.expr]: + """What a target writes: each part of an unpacking, and for `x[i] = โ€ฆ` the x.""" + if isinstance(target, ast.Tuple | ast.List): + return [leaf for element in target.elts for leaf in assigned(element)] + if isinstance(target, ast.Starred | ast.Subscript): + return assigned(target.value) + return [target] # SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition. diff --git a/bin/test_metric_bench.py b/bin/test_metric_bench.py index 57ecad0a..e922279c 100644 --- a/bin/test_metric_bench.py +++ b/bin/test_metric_bench.py @@ -102,8 +102,9 @@ class Units(unittest.TestCase): def rename(self): self.name, self.other = "y", 1 + self.buf[self.size] = 0 """)) - self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 2), Unit("a.py", "rename", 0, 2, 1)]) + self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 2), Unit("a.py", "rename", 0, 3, 1)]) def test_measures_python_files_outside_the_tests(self): self.assertEqual([path for path in ["a.py", "bin/test_a.py", "a_test.py", "tests/b.py", "e2e-tests/c.py", "README.md"] if measured(path)], ["a.py", "e2e-tests/c.py"]) @@ -224,7 +225,9 @@ class BlackBox(unittest.TestCase): def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self): top = self.project("") - self.assertIn("no comprehension history at", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr) + self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr) + pathlib.Path(top, "docs", "comprehension-history.md").unlink() + self.assertIn("no comprehension history at", self.run_tool(top).stderr) self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "gone", "x.md"))).stderr) self.assertEqual(self.run_tool(top, "--x").returncode, 1) -- 2.52.0 From 84aa3e6b202c5a4d392181f10f825b7eea405a0f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:09:10 +0200 Subject: [PATCH 10/13] Answer stability round 2: fixes in 737d58a -- 2.52.0 From a69cfd262403e910dd77017fa0db7127db2d96f6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:09:10 +0200 Subject: [PATCH 11/13] Answer product-owner round 2: fixes in 737d58a -- 2.52.0 From 5cc37dd8615de984dcb94cbe92428f74eb126c22 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:11:36 +0200 Subject: [PATCH 12/13] Answer prose round 1: allow a bare :line in the history's format, date the shortened paths, say slots for top k, list the notes in --help, say no run could be scored, plainer item 85, 73 and 77 text, and the tools' path line --- README.md | 2 +- bin/metric_bench/bench.py | 6 +++--- bin/metric_bench/main.py | 17 +++++++++-------- bin/metric_bench/places.py | 2 +- bin/metric_bench/python_units.py | 4 ++-- skills/larv-review/SKILL.md | 2 +- todo.md | 14 ++++++++------ 7 files changed, 25 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 67b2bb7c..674e4751 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit ## Tools -Call each by its path, such as `~/.claude/bin/metric-bench`, from the project's checkout; Install puts only `loop-claude` on `PATH`. +Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. - `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. diff --git a/bin/metric_bench/bench.py b/bin/metric_bench/bench.py index 038df020..bcf67aec 100644 --- a/bin/metric_bench/bench.py +++ b/bin/metric_bench/bench.py @@ -69,14 +69,14 @@ def auc(named: list[int], rest: list[int]) -> 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 seats evenly, as a random order of them would.""" + """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] above = sum(value > cut for value in named) - seats = k - above - sum(value > cut for value in rest) + slots = k - above - sum(value > cut for value in rest) tied_named = sum(value == cut for value in named) tied = tied_named + sum(value == cut for value in rest) - return (above + seats * tied_named / tied) / k + return (above + slots * tied_named / tied) / k def medians(runs: list[RunScores]) -> dict[str, Score]: diff --git a/bin/metric_bench/main.py b/bin/metric_bench/main.py index cf10f700..e26712da 100644 --- a/bin/metric_bench/main.py +++ b/bin/metric_bench/main.py @@ -3,7 +3,7 @@ usage: metric-bench [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 seats read, it +the checkout that holds the history. For each scoring run in it, at the commit the panel read, it measures each module-level function and each method of a module-level class in the Python files git tracks, leaving out test_*.py, *_test.py and anything under a tests/ folder: @@ -14,19 +14,20 @@ tracks, leaving out test_*.py, *_test.py and anything under a tests/ folder: - change spread: how many other files changed in a commit with the unit's file, up to that commit, leaving out commits of more than 30 files. -It then prints, for each metric, how well it ranks the units the seats named above the rest: AUC +It then prints, for each metric, how well it ranks the units the panel named above the rest: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share of the metric's k highest units -the seats named, k being how many they named; Chance is what top k scores at random). A metric that +the panel named, k being how many it named; Chance is what top k scores at random). A metric that gave every unit one value reads "constant". A last row gives the medians. Unmeasured counts the distinct places that name no Python function or method, such as a section of a markdown file, or no single tracked file. -Below the table it names each run it skipped, its commit not in the checkout, each run it could not -score, its places naming no measured unit or every one, and each file that does not parse on this -Python, left out of its run. +Below the table it names: +- each run it skipped because its commit is not in the checkout; +- each run it could not score because its places name no measured unit, or every one; +- each file left out of its run because it does not parse on this Python. Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history -cannot be read, or no scoring run names a measured unit. +cannot be read, or no scoring run could be scored. """ import pathlib import statistics @@ -55,7 +56,7 @@ def main(argv: list[str]) -> int: return failed(benched) rows, notes = benched if not rows: - return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md โ†’ \"History\"{noted(notes)}")) + return failed(Failure(f"no scoring run in {history} could be scored; its format: ~/.claude/skills/larv-review/SKILL.md โ†’ \"History\"{noted(notes)}")) print(table(rows) + noted(notes)) return 0 diff --git a/bin/metric_bench/places.py b/bin/metric_bench/places.py index a9fcb913..3d22fbc5 100644 --- a/bin/metric_bench/places.py +++ b/bin/metric_bench/places.py @@ -58,7 +58,7 @@ def bullet_places(bullet: str) -> list[Place]: def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]: - """Seats shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones.""" + """Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones.""" found = [] dropped = [] before = "" diff --git a/bin/metric_bench/python_units.py b/bin/metric_bench/python_units.py index c7ca8e35..ccd383ea 100644 --- a/bin/metric_bench/python_units.py +++ b/bin/metric_bench/python_units.py @@ -82,9 +82,9 @@ def cognitive(function: ast.FunctionDef | ast.AsyncFunctionDef) -> int: return inside(function.body, 0, function.name) -# One case per node type, as the white paper's table has one row per structure: split, the rules would scatter. +# One case per node type, as the white paper gives one rule per structure. def score(node: ast.AST, nesting: int, name: str) -> int: - """The cognitive complexity node adds at depth nesting, its children included; name is the function's own, a call to it counting as recursion.""" + """The cognitive complexity `node` adds, its children included, at nesting depth `nesting`; a call to `name`, the function's own, counts as recursion.""" if isinstance(node, ast.If): return 1 + nesting + branches(node, nesting, name) if isinstance(node, ast.For | ast.AsyncFor | ast.While): diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 47dbf1b1..72bedbbc 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -108,7 +108,7 @@ Fix a worse ruling at the places the seats voting worse name, and the floor at t Two files of the project keep the records: -- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, appended and never edited. Each opens with a `## , at ` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against `. A paired ruling holds a `Ruling: ` line, a table of each seat's vote, and under each seat, labelled `, decided by:`, its places. A scoring run holds a table of each seat's five scores, with a last row holding the four seats' mean of each, and under each seat, labelled `, hardest first:` or, for the architect, `, would restructure first:`, its places. A place is `path:line`, the path written from the repository's root, and the unit's name. `bin/metric_bench/places.py` reads this format: change both together. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. +- **History.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, appended and never edited. Each opens with a `## , at ` heading naming when the seats finished and the commit they read; a paired ruling's heading ends `, against `. A paired ruling holds a `Ruling: ` line, a table of each seat's vote, and under each seat, labelled `, decided by:`, its places. A scoring run holds a table of each seat's five scores, with a last row holding the four seats' mean of each, and under each seat, labelled `, hardest first:` or, for the architect, `, would restructure first:`, its places. A place is `path:line` and the unit's name, the path written from the repository's root. A bare `:line` is in the path named before it in the same bullet. `bin/metric_bench/places.py` reads this format: change both together. Appending re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. - **Entry.** `docs/decisions.md` keeps one entry whose title opens `comprehension floor:`. It holds each decision to ship under the floor, with its scores. A `comprehension floor:` entry written before the history may still hold a scoring run's five scores. The next scoring run moves them, and only them, into the history as its first run: a heading of the date or time the entry gives and whatever it names the run by, its commit included where named, and a table with the mean alone. The rest of the entry stays. diff --git a/todo.md b/todo.md index 72411eb8..d3c4f860 100644 --- a/todo.md +++ b/todo.md @@ -50,7 +50,7 @@ | 81 | 0.1.0 | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 2 | 2 | 3 | 4 | 4 | 9.9 | | 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 3 | 9.6 | | 52 | 0.1.0 | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 6 | 6 | 3 | 5 | 2 | 7.5 | -| 77 | 0.2.0 | | **Rerun `bin/metric-bench` once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 2 | 4 | 6 | 7 | 1.1, 1.4 | 22.9 | +| 77 | 0.2.0 | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 3 | 6 | 6 | 7 | 1.1, 1.4 | 21.4 | ## Details @@ -60,7 +60,7 @@ A hand-written question bank goes stale as the project grows and leaves everythi ### 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 the items that lower token use (73, 77, 78). Later that day lilleman rescored 73 below this item, and 77 moved to 0.2.0 to wait for data, so only 78 goes first. 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: 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. ### 1. Say in README โ†’ Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume. @@ -148,7 +148,7 @@ Measured over the 68 transcripts in loop-claude's archive on 2026-10-08, matchin 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: -- **Write access.** Grant each reviewer Write. No reviewer under `agents/` holds it today, an agent's tool list cannot confine Write to one folder, and `~/.claude/CLAUDE.md` โ†’ "Working with the codebase" gives a reviewer that only reads no edits. Check whether a PreToolUse hook can tell a subagent's call from the worker's and deny a Write outside the scratchpad. +- **Write access.** Grant each reviewer Write. No reviewer under `agents/` holds it today, an agent's tool list cannot confine Write to one folder, and `~/.claude/CLAUDE.md` โ†’ "Working with the codebase" denies edits to a reviewer that only reads. Check whether a PreToolUse hook can tell a subagent's call from the worker's and deny a Write outside the scratchpad. - **A wrapper.** A general-purpose subagent launches the reviewer, saves the report and returns only the summary lines. Claude Code's documentation says a subagent cannot start another; drop this route unless a test shows one can. This risks goal 1.1: a worker fixing from a one-line summary can miss context it needs. @@ -177,11 +177,13 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic "One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory. -### 77. Rerun `bin/metric-bench` once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel. +### 77. Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel. 2026-10-08, lilleman: no metric enters review until a rerun on more data shows it tracking the panel. -`bin/metric-bench` measures each Python function and method at each scoring run's commit, and scores how well each metric ranks the units the seats named above the rest. On 2026-10-08 only this repo's history named places: five scoring runs, all that day. The medians: +Before the rerun, set the AUC and top-k lift over chance that count as tracking, from a published threshold, so the rerun ends in a decision. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces. + +On 2026-10-08 only this repo's history named places: five scoring runs, all that day. The medians: | Metric | AUC | Top k | |---|---|---| @@ -190,4 +192,4 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic | Shared state | constant | constant | | 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. Before the rerun, set the AUC and top-k lift over chance that count as tracking, from a published threshold, so the rerun ends in a decision. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces. +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. -- 2.52.0 From 37db225514d1d8664ff3358df5a2b0b38979c377 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 8 Oct 2026 23:14:15 +0200 Subject: [PATCH 13/13] Rescore: PR #229's paired ruling is worse on PR #228's rules; lilleman ships it below the ratchet, as for PR #228 --- docs/comprehension-history.md | 27 +++++++++++++++++++++++++++ docs/decisions.md | 1 + 2 files changed, 28 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 2e832819..ee87e816 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -395,3 +395,30 @@ Inherited architect, decided by: - `bin/metric_bench/places.py:7` `RUN`, `SEAT_PLACES`, `PLACE`: a regex reader of the history linked from neither side - `bin/metric_bench/places.py:59` `resolved`: a result that depends on the place resolved before it - `bin/metric_bench/python_units.py:69` `Cognitive`: nesting bookkeeping spread over its methods + +## 2026-10-08T21:14:15Z, PR #229 at 5cc37dd, against 12d6d75 + +Ruling: worse + +| Seat | Vote | +|---|---| +| Mid A | worse | +| Inherited architect | worse | + +Mid A, decided by: + +- `skills/larv-review/SKILL.md:93` "Paired ruling" โ†’ "Base": a rule over git history, a `git log` command and two fallbacks to hold at once +- `CLAUDE.md:40` "Quality": a garden-path sentence read three times +- `skills/larv-review/SKILL.md:89` "Architecture": two kinds of run, each with its own trigger, meeting "Fresh", "Suspended" and "Round cap" +- `bin/metric_bench/places.py:60` `resolved`: order-dependent, readable only with the history format in mind +- `bin/metric_bench/main.py:43` `main`, better: the shape of `bin/reading_cost/main.py`, one for one +- `skills/larv-review/SKILL.md:111` "History", better: the format and its reader name each other + +Inherited architect, decided by: + +- `skills/larv-review/SKILL.md:93` "Paired ruling" โ†’ "Base": the ratchet's outcome rests on state spread across many past commits +- `skills/larv-review/SKILL.md:89` "Architecture": one mechanism became two, with different triggers and blocks +- `CLAUDE.md:40` "Quality": a clause folded into a noun phrase +- `bin/metric_bench/places.py:7` `RUN`, `SEAT_PLACES`, `PLACE` and `:60` `resolved`: a regex reader of a prose format, and a historical quirk to know first +- `AGENTS.md:35` "Scoring run": the section's name no longer covers its use by paired rulings +- `skills/larv-review/SKILL.md:64` "Re-entry", better: which passes a fix reruns is explicit diff --git a/docs/decisions.md b/docs/decisions.md index b4592d1c..e0146ca4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -51,6 +51,7 @@ lilleman decided to ship each of these under the floor on the day listed. Each l - 2026-10-08, PR #224: 7.00, 6.50, 7.00, 6.50, 6.75. lilleman shipped it below the ratchet as well: its 20 lines of skill prose left the code as it was, so the fall is the panel's noise between runs, which the paired ruling cancels. - 2026-10-08, PR #225: 7.25, 6.75, 7.00, 6.88, 6.88. Above PR #224's run on every score but Shape, which held. - 2026-10-08, PR #228: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet: the seats blamed the new ratchet's own rules, which `todo.md` item 85 moves into a tested tool. +- 2026-10-08, PR #229: no scoring run; its last paired ruling, against 12d6d75, was worse, 2 votes to 0. lilleman shipped it below the ratchet for PR #228's reason: the seats' decisive places were still PR #228's rules, which item 85 moves into a tested tool. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes -- 2.52.0