from typing import Callable import collections import dataclasses import os import statistics from review_rules.comprehension_history 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), } # 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) 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, 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"))) if len(files) > LARGEST_CHANGESET: continue 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], 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] 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(): 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), len(set(named_values + rest_values)) == 1) 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(named: list[int], rest: list[int]) -> float: """The share of the metric's k highest units the seats named, k being how many they named. Units tied at the cut share its remaining slots evenly, as a random order of them would.""" k = len(named) cut = sorted(named + rest, reverse=True)[k - 1] above = sum(value > cut for value in named) slots = k - above - sum(value > cut for value in rest) tied_named = sum(value == cut for value in named) tied = tied_named + sum(value == cut for value in rest) return (above + slots * tied_named / tied) / k 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), all(run.scores[metric].constant for run in runs)) for metric in METRICS} def tracked_places(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]: """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 = "" for place in places: 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)) else: dropped.append(place) return found, dropped