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

This commit is contained in:
2026-10-08 23:04:12 +02:00
parent 1fca6137c2
commit 527aef3495
6 changed files with 135 additions and 65 deletions
+59 -39
View File
@@ -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: