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

This commit is contained in:
2026-10-08 22:52:14 +02:00
parent 6240f82857
commit 1fca6137c2
3 changed files with 57 additions and 35 deletions
+1 -1
View File
@@ -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 <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
+38 -18
View File
@@ -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:
+18 -16
View File
@@ -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)