Files
claude-config/bin/score_outcomes/main.py
T

117 lines
5.5 KiB
Python

"""Show what finished chunks measured beside the scores their items were guessed at, to score a new item by.
usage: score-outcomes [R S C]
Run it inside a project checkout or one of its worktrees. It fetches origin, when the checkout has
that remote, and reads origin's default branch, or else the local main or master; a failed fetch
reads origin as last fetched and says so on stderr.
Git history is the record. A chunk is a merge commit on the default branch's first-parent line
whose change removed items from todo.md; it shipped those items. Each item's guess is its R, S and
C in the todo.md the merge's first parent held, when the chunk began; C only where that todo.md
scored one. The chunk measures:
- lines changed: lines added plus lines deleted against the first parent, leaving out
docs/comprehension-history.md and docs/reading-cost.md, which tools append to;
- files: the files those lines are in;
- review rounds: each pass's rounds among the branch's `Answer <pass> round <n>:` commit titles,
summed, counted as `larv-review round-count` counts them;
- 🔴 and 🟡 findings: summed over those titles, each opening `<n> 🔴, <n> 🟡` after the colon,
such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`. Unknown where a round title
lacks the counts, or the branch has no round.
A project that merges without merge commits, by fast-forward or squash, has no chunk to measure.
Given R, S and C, it lists the 5 finished items whose guesses sit closest, closest first: the
smallest sum of squared differences, C counted only where the item had one, the newest first among
equals. Each line gives what the item's chunk measured, which items shipped with it, and its tagline.
Then, for each score, the median of the outcome it predicts at each value it was guessed at: R
against 🔴 findings, S against lines changed, C against review rounds. It counts only chunks that
shipped one item, since a chunk measures all its items at once, and reports a score only once 10
such chunks hold it and its outcome.
Exit 1, saying why, on bad arguments, when git cannot start, finds no checkout or reads a shallow
clone, or the default branch cannot be read.
"""
import re
import sys
from failure import Failure
from larv_review.git import default_branch, file_at, git
from score_outcomes.outcomes import guesses, nearest, Outcome, render, report, round_findings, rounds, shipped
# Tools append to these records; their lines are not the chunk's work.
RECORDS = ("docs/comprehension-history.md", "docs/reading-cost.md")
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if argv and (len(argv) != 3 or not all(re.fullmatch(r"[1-9]|10", arg) for arg in argv)):
print(f"score-outcomes: cannot read the arguments {' '.join(argv)}; usage: score-outcomes [R S C], each a whole number from 1 to 10", file=sys.stderr)
return 1
outcomes = read_outcomes()
if isinstance(outcomes, Failure):
print(f"score-outcomes: {outcomes.reason}", file=sys.stderr)
return 1
if argv:
given = dict(zip("RSC", map(int, argv)))
print(f"Finished items nearest R {given['R']}, S {given['S']}, C {given['C']}, closest first:\n")
print("\n".join(render(outcome) for outcome in nearest(outcomes, given)) or "- None: no merge commit on the default branch removed an item from todo.md.")
print()
print("Median outcome at each guessed score, among chunks that shipped one item:\n")
print("\n".join(report(outcomes)))
return 0
def read_outcomes() -> list[Outcome] | Failure:
found = default_branch(stale_ok=True)
if isinstance(found, Failure):
return found
default, note = found
if note:
print(f"score-outcomes: {note}", file=sys.stderr)
shallow = git("rev-parse", "--is-shallow-repository")
if isinstance(shallow, Failure):
return shallow
if shallow.strip() == "true":
return Failure("a shallow clone lacks the merges it measures; run `git fetch --unshallow origin`")
merges = git("log", "--first-parent", "--merges", "--format=%H %h %cs", default, "--", "todo.md")
if isinstance(merges, Failure):
return merges
outcomes: list[Outcome] = []
for line in merges.splitlines():
measured = measure(*line.split())
if isinstance(measured, Failure):
return measured
outcomes += measured
return outcomes
def measure(merge: str, short: str, merged: str) -> list[Outcome] | Failure:
"""What one merge measured, for each item it removed from todo.md; none where either todo.md holds no items table."""
texts = [file_at(f"{merge}^1", "todo.md"), file_at(merge, "todo.md")]
if failed := next((text for text in texts if isinstance(text, Failure)), None):
return failed
before, after = (guesses(text) for text in texts if isinstance(text, str))
if before is None or after is None:
return []
items = shipped(before, after)
if not items:
return []
numstat = git("diff", "--numstat", f"{merge}^1", merge, "--", ".", *(f":(exclude){record}" for record in RECORDS))
if isinstance(numstat, Failure):
return numstat
changed = [row.split("\t") for row in numstat.splitlines()]
# Git counts a binary file's lines as "-".
lines = sum(int(count) for row in changed for count in row[:2] if count.isdigit())
titles = git("log", "--format=%s", f"{merge}^1..{merge}^2")
if isinstance(titles, Failure):
return titles
findings = round_findings(titles.splitlines())
red, yellow = findings if findings else (None, None)
ids = [item.id for item in items]
return [Outcome(item, short, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(changed), rounds(titles.splitlines()), red, yellow) for item in items]