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
+12 -5
View File
@@ -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}
+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:
+7 -4
View File
@@ -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
+22 -6
View File
@@ -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:
+32 -8
View File
@@ -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")))
+3 -3
View File
@@ -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.