Answer architecture round 1: 3 🔴, 13 🟡; one items-table reader, a pure measuring core, shared git and round-title modules, and a hook rule for round counts

This commit is contained in:
2026-10-13 11:36:49 +02:00
parent 228478061e
commit 8abec93269
27 changed files with 427 additions and 305 deletions
+69
View File
@@ -0,0 +1,69 @@
"""Run git in the current directory, and read the checkout, its default branch and its files."""
import re
import subprocess
from failure import Failure
def git(*args: str) -> str | Failure:
try:
ran = subprocess.run(["git", *args], capture_output=True, text=True)
except (OSError, ValueError) as failure:
return Failure(f"git could not start: {failure}")
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
def top() -> str | Failure:
found = git("rev-parse", "--show-toplevel")
return found if isinstance(found, Failure) else found.strip()
def default_branch(stale_ok: bool) -> tuple[str, str | None] | Failure:
"""The default branch's ref, `origin/<branch>` after a fetch with that remote, else the local main or master, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so."""
remotes = git("remote")
if isinstance(remotes, Failure):
return remotes
if "origin" in remotes.split():
fetch = git("fetch", "--quiet", "origin")
if isinstance(fetch, Failure) and not stale_ok:
return fetch
note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None
default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD")
named = default.strip() if not isinstance(default, Failure) else origin_head()
return named if isinstance(named, Failure) else (named, note)
for branch in ("main", "master"):
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure):
return branch, None
return Failure("no origin remote, and no main or master branch to take as the default branch")
def origin_head() -> str | Failure:
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
listed = git("ls-remote", "--symref", "origin", "HEAD")
if isinstance(listed, Failure):
return listed
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
return f"origin/{named.group(1)}"
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
def commit_exists(commit: str) -> bool:
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}"), Failure)
def file_at(revision: str, path: str) -> str | Failure:
"""A file's text at a revision, empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
if not commit_exists(revision):
return ""
listed = git("ls-tree", "--name-only", revision, "--", path)
if isinstance(listed, Failure):
return listed
return git("show", f"{revision}:{path}") if listed.strip() else ""
def full_history() -> Failure | None:
"""Why the checkout lacks the history a tool reads, None when it holds it all."""
shallow = git("rev-parse", "--is-shallow-repository")
if isinstance(shallow, Failure):
return shallow
return Failure("a shallow clone lacks the history this reads; run `git fetch --unshallow origin`") if shallow.strip() == "true" else None
+3 -64
View File
@@ -1,73 +1,12 @@
import re
import subprocess
from failure import Failure
from git_repo import file_at, full_history, git
from comprehension_history import HISTORY, HistoryChange
def git(*args: str) -> str | Failure:
try:
ran = subprocess.run(["git", *args], capture_output=True, text=True)
except (OSError, ValueError) as failure:
return Failure(f"git could not start: {failure}")
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
def top() -> str | Failure:
found = git("rev-parse", "--show-toplevel")
return found if isinstance(found, Failure) else found.strip()
def default_branch(stale_ok: bool) -> tuple[str, str | None] | Failure:
"""The default branch's ref, `origin/<branch>` after a fetch with that remote, else the local main or master, and a note for stderr. With stale_ok, a failed fetch reads origin as last fetched, and the note says so."""
remotes = git("remote")
if isinstance(remotes, Failure):
return remotes
if "origin" in remotes.split():
fetch = git("fetch", "--quiet", "origin")
if isinstance(fetch, Failure) and not stale_ok:
return fetch
note = f"reading origin as last fetched: {fetch.reason}" if isinstance(fetch, Failure) else None
default = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD")
named = default.strip() if not isinstance(default, Failure) else origin_head()
return named if isinstance(named, Failure) else (named, note)
for branch in ("main", "master"):
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}"), Failure):
return branch, None
return Failure("no origin remote, and no main or master branch to take as the default branch")
def origin_head() -> str | Failure:
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
listed = git("ls-remote", "--symref", "origin", "HEAD")
if isinstance(listed, Failure):
return listed
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
return f"origin/{named.group(1)}"
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
def commit_exists(commit: str) -> bool:
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}"), Failure)
def file_at(revision: str, path: str) -> str | Failure:
"""A file's text at a revision, empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
if not commit_exists(revision):
return ""
listed = git("ls-tree", "--name-only", revision, "--", path)
if isinstance(listed, Failure):
return listed
return git("show", f"{revision}:{path}") if listed.strip() else ""
def history_changes(default: str) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first; a merge commit counts as one change against its first parent."""
shallow = git("rev-parse", "--is-shallow-repository")
if isinstance(shallow, Failure):
return shallow
if shallow.strip() == "true":
return Failure("a shallow clone lacks the commits the base search reads; run `git fetch --unshallow origin`")
if partial := full_history():
return partial
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
if isinstance(commits, Failure):
return commits
+3 -2
View File
@@ -88,11 +88,12 @@ import sys
import typing
from larv_review.ruling_base import base
from larv_review.rounds import CAP, PASSES, round_counts
from larv_review.git import default_branch, file_at, git, history_changes
from round_titles import CAP, PASSES, round_counts
from git_repo import default_branch, file_at, git
from failure import Failure
from larv_review.scoring import FLOOR
from comprehension_history import HISTORY
from larv_review.git import history_changes
from larv_review.plan import plan_reasons
from larv_review.record import record_ruling, record_scoring
+6 -3
View File
@@ -1,8 +1,9 @@
import pathlib
from failure import Failure
from larv_review.git import file_at, landed_since_release, top
from todo_table import Item, items, ITEMS_HEADER, LEGACY_HEADER
from git_repo import file_at, top
from todo_table import Item, items
from larv_review.git import landed_since_release
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str] | Failure:
@@ -42,10 +43,12 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read todo.md: {failure}")
# While a chunk reshapes todo.md into one table, the default branch's todo.md has no items table.
planned = items(before) if {ITEMS_HEADER, LEGACY_HEADER} & set(before.splitlines()) else []
planned = items(before) or []
if isinstance(planned, Failure):
return Failure(f"{default}'s todo.md: {planned.reason}")
chunk = items(after)
if chunk is None:
return Failure("the checkout's todo.md has no items table; rank_todo.py --help shows one")
if isinstance(chunk, Failure):
return Failure(f"the checkout's todo.md: {chunk.reason}")
landed = landed_since_release(default)
+1 -1
View File
@@ -2,7 +2,7 @@ import pathlib
import time
from comprehension_history import appended, DIMENSIONS, heading, Heading, HISTORY, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from larv_review.git import commit_exists, top
from git_repo import commit_exists, top
from larv_review.ruling import counted, fallen, overall, ruling, split, votes
from failure import Failure
from larv_review.scoring import fall_ruling, FLOOR, means, under_floor
-17
View File
@@ -1,17 +0,0 @@
import re
CAP = 3
PASSES = ("architecture", "full scan", "security", "overrides", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
def round_counts(titles: list[str]) -> dict[str, int]:
"""Each pass's round count among the branch's `Answer <pass> round <n>:` commit titles: the highest <n>, or the number of such commits where that is more, so a repeated number still counts. A pass with none has 0, and a title naming no known pass adds its name. Case is ignored."""
highest: dict[str, int] = dict.fromkeys(PASSES, 0)
commits: dict[str, int] = dict.fromkeys(PASSES, 0)
for title in titles:
if named := ROUND.match(title):
name = named.group(1).lower()
highest[name] = max(highest.get(name, 0), int(named.group(2)))
commits[name] = commits.get(name, 0) + 1
return {name: max(highest[name], commits[name]) for name in highest}
+1 -14
View File
@@ -18,7 +18,6 @@ from failure import Failure
from larv_review.scoring import fall_ruling, means, under_floor
from test_env import isolated_env
from todo_table import Item, items
from larv_review.rounds import round_counts
from larv_review.seats import score_line, scores, seats_file
from larv_review.plan import scoring_run_due
@@ -174,22 +173,10 @@ class Base(unittest.TestCase):
self.assertIsNone(first_ruling(SCORING))
class Rounds(unittest.TestCase):
def test_counts_each_passs_highest_round(self):
counts = round_counts(["Answer prose round 1: x", "Answer full scan round 2: y", "Answer full scan round 1: z", "Answer stability: no round", "Answer stabilty round 1: typo", "Answer security round 1: rename round 2: x", "Rescore: w"])
self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"], counts["stabilty"], counts["security"]), (1, 2, 0, 0, 1, 1))
def test_counts_a_mis_cased_title_under_its_pass(self):
self.assertEqual(round_counts(["Answer Architecture round 4: x", "Answer architecture round 3: y"])["architecture"], 4)
def test_counts_a_repeated_round_number_as_a_round_of_its_own(self):
self.assertEqual(round_counts(["Answer stability round 3: x", "Answer stability round 3: y", "Answer stability round 2: z", "Answer stability round 1: w"])["stability"], 4)
class ScoringRunDue(unittest.TestCase):
def test_reads_each_rows_id_release_and_tagline(self):
self.assertEqual(items(todo("| 3 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
self.assertIsInstance(items("# todo\n"), Failure)
self.assertIsNone(items("# todo\n"))
self.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")), Failure)
def test_reads_a_table_from_before_c_joined_it(self):
+2 -2
View File
@@ -58,7 +58,7 @@ import pathlib
import re
import sys
from todo_table import cells, Item, ITEMS_HEADER, LEGACY_HEADER, parse_row, table_rows
from todo_table import cells, Item, ITEMS_HEADER, parse_row, table_rows, WITHOUT_C
from failure import Failure
from markdown_text import FENCE, sections
from file_writes import replace_file
@@ -187,7 +187,7 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure:
if ITEMS_HEADER not in lines and "## Items" not in lines:
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
if LEGACY_HEADER in lines:
if WITHOUT_C in lines:
return Failure("todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
goals = readme_goals(readme)
if isinstance(goals, Failure):
+1
View File
@@ -11,6 +11,7 @@ from utc_stamp import STAMPED
FIGURE = re.compile(rf"^Reading cost, chunk (\w+), finished ({STAMPED})$")
FIGURE_PLACE = re.compile(r"^- `(.+)` (\d+)$")
PLACES_KEPT = 10
RECORD = "docs/reading-cost.md"
RESET = "Reading cost reset, "
RESET_AT = re.compile(rf"^{RESET}({STAMPED})$")
TOKENS = re.compile(r"^(\d+) new input tokens before the first commit\.$")
+2 -2
View File
@@ -31,7 +31,7 @@ import time
from reading_cost.measure import Checkout, measure, Reading
from failure import Failure
from reading_cost.figures import figure, merged, readings_of, RESET, trend, unheld
from reading_cost.figures import figure, merged, readings_of, RECORD, RESET, trend, unheld
from transcript_archive.read import finished_chunks, read_threads
from transcript_archive.location import project_archive
from file_writes import replace_file
@@ -57,7 +57,7 @@ def main(argv: list[str]) -> int:
return failed(checkout)
home = pathlib.Path.home()
archive = project_archive(checkout.main_root, home, os.environ)
record = pathlib.Path(given[0]) if given else pathlib.Path(checkout.current_root, "docs", "reading-cost.md")
record = pathlib.Path(given[0]) if given else pathlib.Path(checkout.current_root, RECORD)
updated = update(record, archive, checkout, str(home), utc(time.time()) if reset else None)
if isinstance(updated, Failure):
return failed(updated)
+1 -1
View File
@@ -15,5 +15,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-p", "reading_cost", "-p", "rule_hook", "-p", "score_outcomes", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-m", "round_titles", "-p", "reading_cost", "-p", "rule_hook", "-p", "score_outcomes", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+38
View File
@@ -0,0 +1,38 @@
"""The titles of larv-review's round commits, `Answer <pass> round <n>: <n> 🔴, <n> 🟡; <summary>`: each pass's round count, and the findings the rounds reported."""
import re
CAP = 3
PASSES = ("architecture", "full scan", "security", "overrides", "stability", "product-owner", "prose")
ROUND = re.compile(r"^Answer (.+?) round ([0-9]+):", re.IGNORECASE)
# What follows a round title's colon: the round's 🔴 and 🟡 counts, then `;` and its summary, if any.
FINDINGS = re.compile(r" ([0-9]+) 🔴, ([0-9]+) 🟡(?:;|$)")
def round_counts(titles: list[str]) -> dict[str, int]:
"""Each pass's round count among the branch's `Answer <pass> round <n>:` commit titles: the highest <n>, or the number of such commits where that is more, so a repeated number still counts. A pass with none has 0, and a title naming no known pass adds its name. Case is ignored."""
highest: dict[str, int] = dict.fromkeys(PASSES, 0)
commits: dict[str, int] = dict.fromkeys(PASSES, 0)
for title in titles:
if named := ROUND.match(title):
name = named.group(1).lower()
highest[name] = max(highest.get(name, 0), int(named.group(2)))
commits[name] = commits.get(name, 0) + 1
return {name: max(highest[name], commits[name]) for name in highest}
def lacks_counts(title: str) -> bool:
"""Whether title is a round's, without the counts after its colon."""
named = ROUND.match(title)
return named is not None and not FINDINGS.match(title, named.end())
def round_findings(titles: list[str]) -> tuple[int, int] | None:
"""The 🔴 and 🟡 counts summed over the round titles among titles; None where a round title lacks them, or no title is a round."""
counts = []
for title in titles:
if named := ROUND.match(title):
found = FINDINGS.match(title, named.end())
if not found:
return None
counts.append((int(found.group(1)), int(found.group(2))))
return (sum(red for red, _ in counts), sum(yellow for _, yellow in counts)) if counts else None
+2 -2
View File
@@ -96,7 +96,7 @@ def print_overrides(directory: str) -> int:
if unread:
print(f"rule-hook overrides cannot read the branch's reflog, so it cannot tell which overrides are this chunk's: {unread.reason}", file=sys.stderr)
return 1
default = default_branch(directory)
default = local_default_branch(directory)
log = pathlib.Path(common) / LOG
entries = [parsed_entry(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else []
on_default = (lambda commit: holds(directory, default, commit)) if default else (lambda commit: False)
@@ -115,7 +115,7 @@ def unread_reflog(reflog: str | Failure, head: str | Failure) -> Failure | None:
return None if head in reflog.split() else Failure("it does not hold HEAD")
def default_branch(directory: str) -> str | None:
def local_default_branch(directory: str) -> str | None:
return next((name for name in ("origin/HEAD", "main", "master") if not isinstance(git(directory, "rev-parse", "--verify", "--quiet", name), Failure)), None)
+8 -1
View File
@@ -4,9 +4,10 @@ import re
import typing
from git_command import commits
from round_titles import lacks_counts
from shell_command import Simple
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "round-title-counts", "todo-rank-check"]
@dataclasses.dataclass(frozen=True)
@@ -36,6 +37,10 @@ RULES: dict[RuleName, Rule] = {
"no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
"a git, gh or tea command, and any file written",
),
"round-title-counts": Rule(
"a larv-review round's commit title gives the 🔴 and 🟡 findings the round reported, such as `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`, since score-outcomes counts them",
"a git commit whose message opens `Answer <pass> round <n>:`",
),
"todo-rank-check": Rule(
"while todo.md has changes, staged or not, a git commit waits until ~/.claude/bin/rank_todo.py --check passes on it",
"a git commit in a checkout whose todo.md has changes",
@@ -99,6 +104,8 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', not from a file", commit.directory))
elif len(commit.messages) > 1 or any("\n" in message.strip() for message in commit.messages):
breaches.append(Breach("commit-one-line", "pass the message as one -m '<line>', with no heredoc, second -m or newline", commit.directory))
if any(lacks_counts(message) for message in commit.messages):
breaches.append(Breach("round-title-counts", "open the summary after the round's colon with `<n> 🔴, <n> 🟡;`", commit.directory))
return breaches
+7 -1
View File
@@ -78,6 +78,12 @@ class CommandBreaches(unittest.TestCase):
with self.subTest(command):
self.assertEqual(checked(command), ["commit-one-line"])
def test_a_round_title_without_its_counts_breaks_round_title_counts(self):
self.assertEqual(checked("git commit -m 'Answer stability round 1: fix the parser'"), ["round-title-counts"])
self.assertEqual(checked("git commit --allow-empty -m 'Answer prose round 2: 0 🔴, 0 🟡'"), [])
self.assertEqual(checked("git commit -m 'Answer stability round 1: 1 🔴, 2 🟡; fix the parser'"), [])
self.assertEqual(checked("git commit -m 'Answer the question in the README'"), [])
def test_an_attribution_breaks_only_in_a_git_gh_or_tea_command(self):
self.assertEqual(checked(f"tea pr create --description '{TRAILER}'"), ["no-ai-attribution"])
self.assertEqual(checked(f"grep -rn '{TRAILER}' ."), [])
@@ -275,5 +281,5 @@ class Hook(unittest.TestCase):
def test_help_lists_every_rule(self):
helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "todo-rank-check"]:
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "round-title-counts", "todo-rank-check"]:
self.assertIn(f" {rule}\n The rule: ", helped)
+43 -48
View File
@@ -7,15 +7,15 @@ that remote, and reads origin's default branch, or else the local main or master
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:
whose change removed items from todo.md, and changed more than todo.md and the records below; 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;
- lines changed: lines added plus lines deleted against the first parent, leaving out todo.md and
the records tools append to, docs/comprehension-history.md and docs/reading-cost.md;
- 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;
- review rounds past each pass's first: among the branch's `Answer <pass> round <n>:` commit
titles, each pass's rounds as `larv-review round-count` counts them, less one, summed;
- 🔴 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.
@@ -23,11 +23,11 @@ scored one. The chunk measures:
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.
least mean squared difference over the scores both hold, C 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
against 🔴 findings, S against lines changed, C against review rounds past each pass's first. 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.
@@ -37,12 +37,10 @@ clone, or the default branch cannot be read.
import re
import sys
from git_repo import default_branch, file_at, full_history, git
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")
from score_outcomes.outcomes import nearest, Outcome, outcomes_of, render, report, shipped
from utc_stamp import utc
def main(argv: list[str]) -> int:
@@ -52,38 +50,40 @@ def main(argv: list[str]) -> int:
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()
found = default_branch(stale_ok=True)
if isinstance(found, Failure):
return failed(found)
default, note = found
if note:
print(f"score-outcomes: {note}", file=sys.stderr)
outcomes = read_outcomes(default)
if isinstance(outcomes, Failure):
print(f"score-outcomes: {outcomes.reason}", file=sys.stderr)
return 1
return failed(outcomes)
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("\n".join(render(outcome) for outcome in nearest(outcomes, given)) or "- None: no merge commit on the default branch shipped 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")
def failed(failure: Failure) -> int:
print(f"score-outcomes: {failure.reason}", file=sys.stderr)
return 1
def read_outcomes(default: str) -> list[Outcome] | Failure:
if partial := full_history():
return partial
merges = git("log", "--first-parent", "--merges", "--format=%H %h %ct", default, "--", "todo.md")
if isinstance(merges, Failure):
return merges
outcomes: list[Outcome] = []
for line in merges.splitlines():
measured = measure(*line.split())
merge, short, time = line.split()
measured = measure(merge, short, utc(int(time)))
if isinstance(measured, Failure):
return measured
outcomes += measured
@@ -91,26 +91,21 @@ def read_outcomes() -> list[Outcome] | Failure:
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 []
"""What one merge measured for each item it shipped."""
before = file_at(f"{merge}^1", "todo.md")
if isinstance(before, Failure):
return before
after = file_at(merge, "todo.md")
if isinstance(after, Failure):
return after
items = shipped(before, after)
# Most merges ship nothing; this spares them two more git calls.
if not items:
return []
numstat = git("diff", "--numstat", f"{merge}^1", merge, "--", ".", *(f":(exclude){record}" for record in RECORDS))
numstat = git("diff", "--numstat", f"{merge}^1", merge)
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]
return outcomes_of(items, short, merged, numstat, titles.splitlines())
+45 -73
View File
@@ -1,119 +1,91 @@
import dataclasses
import re
import statistics
from typing import Callable
import typing
from larv_review.rounds import round_counts, ROUND
from comprehension_history import HISTORY
from todo_table import Item, items
from reading_cost.figures import RECORD
from round_titles import round_counts, round_findings
# Least to be measured before a score's medians show: the count the reading-cost trend waits for, which no published standard sets either.
ENOUGH = 10
FINDINGS = re.compile(r"([0-9]+) 🔴, ([0-9]+) 🟡(;|$)")
@dataclasses.dataclass(frozen=True)
class Guess:
"""An item's tagline and its R, S and C as the plan held them, C only where the plan scored one."""
id: int
tagline: str
scores: dict[str, int]
# The plan, and the records tools append to: none of their lines are the chunk's work.
NOT_WORK = ("todo.md", HISTORY, RECORD)
@dataclasses.dataclass(frozen=True)
class Outcome:
"""What the merge that shipped an item measured; the findings are unknown where a round title lacks their counts."""
guess: Guess
"""What the merge that shipped an item measured. findings holds the 🔴 and 🟡 counts, None where a round title lacks them."""
item: Item
merge: str
merged: str
shipped_with: tuple[int, ...]
lines: int
files: int
rounds: int
red: int | None
yellow: int | None
rounds_past_first: int
findings: tuple[int, int] | None
# Each score, and the outcome it predicts.
MEASURES: dict[str, tuple[str, Callable[[Outcome], int | None]]] = {
"R": ("🔴 findings", lambda outcome: outcome.red),
# Each score, and the outcome it predicts. Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
MEASURES: dict[str, tuple[str, typing.Callable[[Outcome], int | None]]] = {
"R": ("🔴 findings", lambda outcome: outcome.findings[0] if outcome.findings else None),
"S": ("lines changed", lambda outcome: outcome.lines),
"C": ("review rounds", lambda outcome: outcome.rounds),
"C": ("review rounds past each pass's first", lambda outcome: outcome.rounds_past_first),
}
def guesses(todo: str) -> dict[int, Guess] | None:
"""Each item of a todo.md's items table by ID, from any shape of table with ID, Item, R and S columns; None without such a table. A row it cannot read is left out."""
lines = todo.splitlines()
for index, line in enumerate(lines):
header = split(line)
if {"ID", "Item", "R", "S"} <= set(header):
break
else:
return None
found = {}
for row in lines[index + 2:]:
if not row.startswith("|"):
break
named = dict(zip(header, split(row)))
if len(split(row)) != len(header) or not all(re.fullmatch(r"[0-9]+", named.get(name, "0")) for name in ("ID", "R", "S", "C")):
continue
scores: dict[str, int] = {name: int(named[name]) for name in ("R", "S", "C") if name in named}
found[int(named["ID"])] = Guess(int(named["ID"]), named["Item"], scores)
return found
def shipped(before: str, after: str) -> list[Item]:
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
planned, left = items(before), items(after)
if not isinstance(planned, list) or not isinstance(left, list):
return []
kept = {item.id for item in left}
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
def split(row: str) -> list[str]:
return [cell.strip() for cell in re.split(r"(?<!\\)\|", row.strip())[1:-1]] if row.startswith("|") else []
def shipped(before: dict[int, Guess], after: dict[int, Guess]) -> list[Guess]:
return [guess for id_, guess in sorted(before.items()) if id_ not in after]
def round_findings(titles: list[str]) -> tuple[int, int] | None:
"""The 🔴 and 🟡 findings summed over each `Answer <pass> round <n>:` title, which opens with `<n> 🔴, <n> 🟡`; None where a round title does not, or no title is a round."""
counts = []
for title in titles:
if named := ROUND.match(title):
found = FINDINGS.match(title[named.end():].lstrip())
if not found:
return None
counts.append((int(found.group(1)), int(found.group(2))))
return (sum(red for red, _ in counts), sum(yellow for _, yellow in counts)) if counts else None
def rounds(titles: list[str]) -> int:
return sum(round_counts(titles).values())
def outcomes_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str]) -> list[Outcome]:
"""What one merge measured for each item it shipped, from `git diff --numstat` against its first parent and its branch's commit titles; none where it changed nothing but the plan and the records."""
changed = [row.split("\t", 2) for row in numstat.splitlines()]
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
if not work:
return []
# Git counts a binary file's lines as "-".
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
ids = [item.id for item in shipped]
return [Outcome(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles)) for item in shipped]
def nearest(outcomes: list[Outcome], given: dict[str, int], count: int = 5) -> list[Outcome]:
"""The outcomes whose guesses sit closest to the given scores, newest first among equals; C counts only where both hold one."""
def distance(outcome: Outcome) -> int:
return sum((value - outcome.guess.scores[name]) ** 2 for name, value in given.items() if name in outcome.guess.scores)
"""The outcomes whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
def distance(outcome: Outcome) -> float:
shared = [name for name in given if name in outcome.item.scores]
return sum((given[name] - outcome.item.scores[name]) ** 2 for name in shared) / len(shared)
newest_first = sorted(outcomes, key=lambda outcome: outcome.merged, reverse=True)
return sorted(newest_first, key=distance)[:count]
def report(outcomes: list[Outcome]) -> list[str]:
"""For each score, the median outcome of each value it was guessed at, among chunks that shipped one item; a chunk measures several items at once."""
"""For each score, the median outcome at each value it was guessed at, among chunks that shipped one item: a chunk measures all its items at once."""
single = [outcome for outcome in outcomes if not outcome.shipped_with]
lines = []
for name, (what, measure) in MEASURES.items():
held = [(outcome.guess.scores[name], value) for outcome in single if name in outcome.guess.scores and (value := measure(outcome)) is not None]
held = [(outcome.item.scores[name], value) for outcome in single if name in outcome.item.scores and (value := measure(outcome)) is not None]
if len(held) < ENOUGH:
chunks = "chunk that shipped one item records" if len(held) == 1 else "chunks that shipped one item record"
lines.append(f"- {name}, {what}: {len(held)} {chunks} {name} and {what}; the report needs {ENOUGH}.")
lines.append(f"- {name}, {what}: {len(held)} {chunks} {name} and its outcome; the report needs {ENOUGH}.")
continue
values = sorted({guess for guess, _ in held})
medians = [(guess, [value for at, value in held if at == guess]) for guess in values]
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
return lines
def render(outcome: Outcome) -> str:
scores = ", ".join(f"{name} {value}" for name, value in outcome.guess.scores.items())
findings = "findings unknown" if outcome.red is None else f"{outcome.red} 🔴, {outcome.yellow} 🟡"
scores = ", ".join(f"{name} {outcome.item.scores[name]}" for name in MEASURES if name in outcome.item.scores)
findings = f"{outcome.findings[0]} 🔴, {outcome.findings[1]} 🟡" if outcome.findings else "findings unknown"
others = outcome.shipped_with
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
return f"- Item {outcome.guess.id}, {scores}: {plural(outcome.lines, 'line')} in {plural(outcome.files, 'file')}, {plural(outcome.rounds, 'review round')}, {findings}; merged {outcome.merged} in {outcome.merge}{together}. {outcome.guess.tagline}"
return f"- Item {outcome.item.id}, {scores}: {plural(outcome.lines, 'line')} in {plural(outcome.files, 'file')}, {plural(outcome.rounds_past_first, 'round')} past each pass's first, {findings}; merged {outcome.merged} in {outcome.merge}{together}. {outcome.item.tagline}"
def plural(count: int, noun: str) -> str:
+54 -44
View File
@@ -7,67 +7,75 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from score_outcomes.outcomes import Guess, guesses, nearest, Outcome, report, round_findings, shipped
from test_env import isolated_env
from todo_table import Item
from score_outcomes.outcomes import nearest, Outcome, outcomes_of, report, shipped
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
LEGACY = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
FIRST = "| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"
SECOND = "| 5 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |"
def todo(*rows: str, header: str = HEADER) -> str:
return "# todo\n\n## Items\n\n" + header + "".join(f"{row}\n" for row in rows)
def outcome(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, red: int | None = 0, merge: str = "aaaaaaa", shipped_with: tuple[int, ...] = ()) -> Outcome:
scores = {"R": r, "S": s} | ({"C": c} if c else {})
return Outcome(Guess(id_, f"**Item {id_}.**", scores), merge, "2026-10-13", shipped_with, lines, 1, rounds, red, 0 if red is not None else None)
def item(id_: int, scores: dict[str, int]) -> Item:
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, ("1",))
class Guesses(unittest.TestCase):
def test_reads_each_items_r_s_and_c_and_an_older_table_without_c(self):
self.assertEqual(guesses(todo("| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |")), {4: Guess(4, "**Do it.**", {"R": 2, "S": 3, "C": 5})})
self.assertEqual(guesses(todo("| 4 | 0.1.0 | | **A \\| B.** | 2 | 3 | 6 | 7 | 1 | 9.0 |", header=LEGACY)), {4: Guess(4, "**A \\| B.**", {"R": 2, "S": 3})})
def test_reads_no_plan_from_a_file_without_an_items_table(self):
self.assertIsNone(guesses("# todo\n\n- [ ] Do it.\n"))
self.assertEqual(guesses(todo()), {})
def test_skips_a_row_it_cannot_read(self):
self.assertEqual(guesses(todo("| x | 0.1.0 | | **Do it.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |", "| 5 | 0.1.0 | | **Too few.** | 2 |")), {})
def test_ships_each_item_the_change_removed(self):
before = guesses(todo("| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |", "| 5 | 0.1.0 | | **Then this.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"))
after = guesses(todo("| 5 | 0.1.0 | | **Then this.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"))
assert before is not None and after is not None
self.assertEqual(shipped(before, after), [before[4]])
def outcome(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = ()) -> Outcome:
return Outcome(item(id_, {"R": r, "S": s} | ({"C": c} if c else {})), "aaaaaaa", merged, shipped_with, lines, 1, rounds, findings)
class RoundFindings(unittest.TestCase):
def test_sums_the_counts_each_round_title_opens_with(self):
self.assertEqual(round_findings(["Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test", "Answer prose round 1: 0 🔴, 3 🟡", "Merge origin/main"]), (1, 5))
class Shipped(unittest.TestCase):
def test_ships_each_item_the_change_removed_with_the_scores_it_had_before(self):
self.assertEqual([found.id for found in shipped(todo(FIRST, SECOND), todo(SECOND))], [4])
self.assertEqual(shipped(todo(FIRST, SECOND), todo(SECOND))[0].scores, {"R": 2, "S": 3, "C": 5, "A": 6, "G": 7})
def test_knows_no_count_when_a_round_title_or_every_round_lacks_one(self):
self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer prose round 1: fix the README"]))
self.assertIsNone(round_findings(["Do the work"]))
def test_reads_a_table_from_before_c_joined_it(self):
older = "| 4 | 0.1.0 | | **A \\| B.** | 2 | 3 | 6 | 7 | 1 | 9.0 |"
self.assertEqual(shipped(todo(older, header=WITHOUT_C), todo(header=WITHOUT_C))[0].scores, {"R": 2, "S": 3, "A": 6, "G": 7})
def test_ships_nothing_where_either_plan_has_no_table_it_can_read(self):
self.assertEqual(shipped(todo(FIRST), "# todo\n\n- [ ] Do it.\n"), [])
self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), [])
class OutcomesOf(unittest.TestCase):
def test_measures_the_change_less_the_plan_and_the_tool_records_and_counts_binary_files(self):
numstat = "3\t1\ta.py\n-\t-\tlogo.png\n5\t0\ttodo.md\n9\t0\tdocs/reading-cost.md\n4\t0\tdocs/comprehension-history.md\n"
titles = ["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer stability round 2: 0 🔴, 1 🟡; fix", "Answer prose round 1: 0 🔴, 3 🟡", "Do it"]
found = outcomes_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles)
self.assertEqual(found[0], Outcome(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 4, 2, 1, (1, 6)))
self.assertEqual(found[1].shipped_with, (4,))
def test_measures_no_chunk_that_changed_only_the_plan(self):
self.assertEqual(outcomes_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", []), [])
class Nearest(unittest.TestCase):
def test_lists_the_closest_guesses_first_and_counts_c_only_where_an_item_had_one(self):
found = [outcome(1, 9, 9, 9), outcome(2, 3, 4, None), outcome(3, 3, 4, 9), outcome(4, 3, 5, 5)]
self.assertEqual([each.guess.id for each in nearest(found, {"R": 3, "S": 4, "C": 5}, 3)], [2, 4, 3])
def test_lists_the_closest_guesses_first_by_the_mean_over_the_scores_both_hold(self):
found = [outcome(1, 9, 9, 9), outcome(2, 3, 5, None), outcome(3, 3, 4, 6), outcome(4, 3, 4, 9)]
self.assertEqual([each.item.id for each in nearest(found, {"R": 3, "S": 4, "C": 5}, 3)], [3, 2, 4])
def test_lists_the_newest_first_among_equals(self):
found = [outcome(1, 3, 4, 5, merged="2026-10-12T10:00:00Z"), outcome(2, 3, 4, 5, merged="2026-10-13T09:00:00Z")]
self.assertEqual([each.item.id for each in nearest(found, {"R": 3, "S": 4, "C": 5})], [2, 1])
class Report(unittest.TestCase):
def test_gives_each_guessed_values_median_outcome_once_ten_single_item_chunks_hold_it(self):
found = [outcome(id_, 2, 1 + id_ % 2, 4, lines=10 * id_, rounds=id_, merge=f"m{id_}") for id_ in range(1, 11)]
lines = report(found + [outcome(11, 2, 2, None, lines=1000, red=None, merge="mx", shipped_with=(12,))])
found = [outcome(id_, 2, 1 + id_ % 2, 4, lines=10 * id_, rounds=id_) for id_ in range(1, 11)]
lines = report(found + [outcome(11, 2, 2, None, lines=1000, findings=None, shipped_with=(12,))])
self.assertIn("- R, 🔴 findings: 2 → 0 (10 chunks)", lines)
self.assertIn("- S, lines changed: 1 → 60 (5 chunks), 2 → 50 (5 chunks)", lines)
self.assertIn("- C, review rounds: 4 → 5.5 (10 chunks)", lines)
self.assertIn("- C, review rounds past each pass's first: 4 → 5.5 (10 chunks)", lines)
def test_says_how_many_chunks_it_has_under_ten(self):
self.assertIn("- C, review rounds: 1 chunk that shipped one item records C and review rounds; the report needs 10.", report([outcome(1, 2, 2, 4), outcome(2, 2, 2, None)]))
self.assertIn("- C, review rounds past each pass's first: 1 chunk that shipped one item records C and its outcome; the report needs 10.", report([outcome(1, 2, 2, 4), outcome(2, 2, 2, None)]))
class ScoreOutcomesTool(unittest.TestCase):
@@ -79,7 +87,7 @@ class ScoreOutcomesTool(unittest.TestCase):
self.checkout = root / "proj"
self.checkout.mkdir()
self.git("init", "-q", "-b", "main")
self.commit("start", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |", "| 2 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |")})
self.commit("start", {"todo.md": todo(FIRST, SECOND)})
def git(self, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
@@ -96,19 +104,21 @@ class ScoreOutcomesTool(unittest.TestCase):
def test_measures_each_merged_chunk_that_removed_an_item(self):
self.git("switch", "-q", "-c", "chunk")
self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo("| 2 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |")})
self.commit("Answer stability round 1: 1 🔴, 2 🟡; fix", {"a.py": "1\n2\n4\n", "docs/reading-cost.md": "x\n" * 50})
self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND)})
self.commit("Answer stability round 1: 1 🔴, 2 🟡; fix", {"a.py": "1\n2\n4\n"})
self.git("switch", "-q", "main")
self.git("merge", "-q", "--no-ff", "-m", "Merge chunk", "chunk")
ran = self.run_tool("2", "3", "5")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("- Item 1, R 2, S 3, C 5: 4 lines in 2 files, 1 review round, 1 🔴, 2 🟡; merged", ran.stdout)
self.assertNotIn("Item 2", ran.stdout)
self.assertIn("- Item 4, R 2, S 3, C 5: 3 lines in 1 file, 0 rounds past each pass's first, 1 🔴, 2 🟡; merged ", ran.stdout)
self.assertNotIn("Item 5", ran.stdout)
def test_refuses_a_score_outside_one_to_ten(self):
ran = self.run_tool("2", "11", "5")
self.assertEqual(ran.returncode, 1)
self.assertIn("usage: score-outcomes [R S C]", ran.stderr)
def test_refuses_a_score_outside_one_to_ten_or_a_missing_score(self):
for args in (("2", "11", "5"), ("0", "3", "5"), ("2", "3")):
with self.subTest(args):
ran = self.run_tool(*args)
self.assertEqual(ran.returncode, 1)
self.assertIn("usage: score-outcomes [R S C]", ran.stderr)
if __name__ == "__main__":
+39
View File
@@ -0,0 +1,39 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from round_titles import lacks_counts, round_counts, round_findings
class Rounds(unittest.TestCase):
def test_counts_each_passs_highest_round(self):
counts = round_counts(["Answer prose round 1: x", "Answer full scan round 2: y", "Answer full scan round 1: z", "Answer stability: no round", "Answer stabilty round 1: typo", "Answer security round 1: rename round 2: x", "Rescore: w"])
self.assertEqual((counts["prose"], counts["full scan"], counts["stability"], counts["architecture"], counts["stabilty"], counts["security"]), (1, 2, 0, 0, 1, 1))
def test_counts_a_mis_cased_title_under_its_pass(self):
self.assertEqual(round_counts(["Answer Architecture round 4: x", "Answer architecture round 3: y"])["architecture"], 4)
def test_counts_a_repeated_round_number_as_a_round_of_its_own(self):
self.assertEqual(round_counts(["Answer stability round 3: x", "Answer stability round 3: y", "Answer stability round 2: z", "Answer stability round 1: w"])["stability"], 4)
class RoundFindings(unittest.TestCase):
def test_sums_the_counts_each_round_title_opens_with(self):
self.assertEqual(round_findings(["Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test", "Answer prose round 1: 0 🔴, 3 🟡", "Merge origin/main"]), (1, 5))
def test_knows_no_count_when_a_round_title_or_every_round_lacks_one(self):
self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer prose round 1: fix the README"]))
self.assertIsNone(round_findings(["Answer stability round 1: 1 🔴, 2 🟡 fix"]))
self.assertIsNone(round_findings(["Do the work"]))
def test_finds_a_round_title_without_counts(self):
self.assertTrue(lacks_counts("Answer stability round 1: fix"))
self.assertFalse(lacks_counts("Answer stability round 1: 0 🔴, 1 🟡; fix"))
self.assertFalse(lacks_counts("Answer the question"))
if __name__ == "__main__":
unittest.main()
+27 -24
View File
@@ -4,9 +4,10 @@ import re
from failure import Failure
EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |"
# The items header before C joined it, which rank_todo.py asks to have C added.
LEGACY_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
COLUMNS = ("ID", "Release", "Exempt", "Item", "R", "S", "C", "A", "G", "Goals", "Score")
ITEMS_HEADER = "| " + " | ".join(COLUMNS) + " |"
# A table may lack C alone: git history keeps tables written before C joined, which still read.
WITHOUT_C = "| " + " | ".join(column for column in COLUMNS if column != "C") + " |"
@dataclasses.dataclass(frozen=True)
@@ -26,20 +27,22 @@ class Table:
rows: list[str]
def items(todo: str) -> list[Item] | Failure:
"""Each row of a todo.md's items table, or of one from before C joined it."""
def items(todo: str) -> list[Item] | None | Failure:
"""Each row of a todo.md's items table, with C or without it; None where todo.md holds no items table."""
lines = todo.splitlines()
legacy = LEGACY_HEADER in lines
table = table_rows(lines, LEGACY_HEADER if legacy else ITEMS_HEADER)
headers = [header for header in (ITEMS_HEADER, WITHOUT_C) if header in lines]
if not headers:
return None
table = table_rows(lines, headers[0])
if isinstance(table, Failure):
return table
items = []
found = []
for row in table.rows:
item = parse_row(row, legacy)
item = parse_row(row, headers[0])
if isinstance(item, Failure):
return item
items.append(item)
return items
found.append(item)
return found
def table_rows(lines: list[str], header: str) -> Table | Failure:
@@ -59,14 +62,14 @@ def cells(row: str, count: int) -> list[str] | Failure:
return found if len(found) == count else Failure(f"this row needs {count} cells: {row}")
def parse_row(row: str, legacy: bool = False) -> Item | Failure:
"""An item row, every cell checked but the goals it cites; a legacy row has no C."""
found = cells(row, 10 if legacy else 11)
def parse_row(row: str, header: str = ITEMS_HEADER) -> Item | Failure:
"""An item row under header, every cell checked but the goals it cites."""
names = header.strip("| ").split(" | ")
found = cells(row, len(names))
if isinstance(found, Failure):
return found
if legacy:
found.insert(6, "")
id_, release, exempt, tagline, r, s, c, a, g, goals, _ = found
named = dict(zip(names, found))
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release):
@@ -75,13 +78,13 @@ def parse_row(row: str, legacy: bool = False) -> Item | Failure:
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
scores = {}
for name, value in zip("RSCAG", (r, s, c, a, g)):
if legacy and name == "C":
scores: dict[str, int] = {}
for name in ("R", "S", "C", "A", "G"):
if name not in named:
continue
if not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 10:
return Failure(f"item {id_}'s {name} {value!r} is not a whole number from 1 to 10")
scores[name] = int(value)
cited = tuple(goal.strip() for goal in goals.split(","))
if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= 10:
return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to 10")
scores[name] = int(named[name])
cited = tuple(goal.strip() for goal in named["Goals"].split(","))
major, minor, patch = (int(part) for part in release.split("."))
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)