Score each item's complexity, and calibrate R, S and C against what finished chunks measured

This commit is contained in:
2026-10-13 11:19:30 +02:00
parent 445f47d5bc
commit 064bfe78f4
16 changed files with 463 additions and 87 deletions
+5 -5
View File
@@ -35,11 +35,11 @@ def said(overall: str, locality: str = "same") -> str:
def item(id_: int, release: tuple[int, int, int], tagline: str = "**Do it.**") -> Item:
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "A": 1, "G": 1}, ("1",))
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "C": 3, "A": 1, "G": 1}, ("1",))
def todo(*rows: str) -> str:
return "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n" + "".join(f"{row}\n" for row in rows)
return "## Items\n\n| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n" + "".join(f"{row}\n" for row in rows)
class Seats(unittest.TestCase):
@@ -188,9 +188,9 @@ class Rounds(unittest.TestCase):
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 | 1 | 1 | 1 | 9.0 |")), [item(3, (0, 1, 0))])
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.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")), Failure)
self.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")), Failure)
def test_is_due_for_an_item_naming_the_floor(self):
plan = [item(1, (0, 1, 0), "**Lift the project to the Comprehension floor.**"), item(2, (0, 1, 0))]
@@ -226,7 +226,7 @@ class LarvReviewTool(unittest.TestCase):
self.checkout = root / "proj"
subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(root / "origin.git")], check=True, env=self.env)
subprocess.run(["git", "clone", "-q", str(root / "origin.git"), str(self.checkout)], check=True, env=self.env, capture_output=True)
self.commit("start", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 1 | 1 | 1 | 9.0 |")})
self.commit("start", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")})
self.git("push", "-q", "origin", "HEAD:main")
self.git("remote", "set-head", "origin", "main")
self.git("switch", "-q", "-c", "chunk")
+9 -6
View File
@@ -26,9 +26,9 @@ A valid todo.md; ## Details and each item's detail are optional:
## Items
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | | **Make the first thing work.** | 2 | 3 | 8 | 9 | 1 | 0 |
| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.1.0 | | **Make the first thing work.** | 2 | 3 | 4 | 8 | 9 | 1 | 0 |
## Details
@@ -40,7 +40,8 @@ A valid todo.md; ## Details and each item's detail are optional:
- The bar is judged on the Score as shown, to one decimal.
- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it.
- The goal weights list README.md's numbered goals in order, a sub-goal such as 1.1 included.
- An item's R, S, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
- An item's R, S, C, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
C, how hard the change is to get right, stays out of the formula.
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect,
principle, question or security. An item docs/decisions.md cites as "`todo.md` item N" must be
exempt, and a row marked decision must be cited there.
@@ -57,7 +58,7 @@ import pathlib
import re
import sys
from todo_table import cells, Item, ITEMS_HEADER, parse_row, table_rows
from todo_table import cells, Item, ITEMS_HEADER, LEGACY_HEADER, parse_row, table_rows
from failure import Failure
from markdown_text import FENCE, sections
from file_writes import replace_file
@@ -186,6 +187,8 @@ 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:
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):
return goals
@@ -367,7 +370,7 @@ def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
def render_item(item: Item, value: float) -> str:
release = ".".join(str(part) for part in item.release)
scores = " | ".join(str(item.scores[name]) for name in "RSAG")
scores = " | ".join(str(item.scores[name]) for name in "RSCAG")
return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
+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", "-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", "-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)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from score_outcomes import main
sys.exit(main.main(sys.argv[1:]))
View File
+116
View File
@@ -0,0 +1,116 @@
"""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]
+120
View File
@@ -0,0 +1,120 @@
import dataclasses
import re
import statistics
from typing import Callable
from larv_review.rounds import round_counts, ROUND
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]
@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
merge: str
merged: str
shipped_with: tuple[int, ...]
lines: int
files: int
rounds: int
red: int | None
yellow: int | None
# Each score, and the outcome it predicts.
MEASURES: dict[str, tuple[str, Callable[[Outcome], int | None]]] = {
"R": ("🔴 findings", lambda outcome: outcome.red),
"S": ("lines changed", lambda outcome: outcome.lines),
"C": ("review rounds", lambda outcome: outcome.rounds),
}
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 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 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)
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."""
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]
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}.")
continue
values = sorted({guess for guess, _ in held})
medians = [(guess, [value for at, value in held if at == guess]) for guess in values]
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} 🟡"
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}"
def plural(count: int, noun: str) -> str:
return f"{count} {noun}{'' if count == 1 else 's'}"
+115
View File
@@ -0,0 +1,115 @@
import os
import pathlib
import subprocess
import sys
import tempfile
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
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"
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)
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]])
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(["Do the work"]))
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])
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,))])
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)
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)]))
class ScoreOutcomesTool(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
root = pathlib.Path(os.path.realpath(temp.name))
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(root)}
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 |")})
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
def commit(self, title, files):
for name, text in files.items():
(self.checkout / name).parent.mkdir(parents=True, exist_ok=True)
(self.checkout / name).write_text(text)
self.git("add", name)
self.git("commit", "-q", "-m", title)
def run_tool(self, *args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
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.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)
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)
if __name__ == "__main__":
unittest.main()
+21 -16
View File
@@ -33,13 +33,13 @@ TODO = """# todo
## Items
| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 0 |
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |
| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 0 |
| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | 0 |
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 0 |
| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 0 |
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 |
| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 0 |
| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | 0 |
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 |
## Details
@@ -63,11 +63,11 @@ class Rank(unittest.TestCase):
def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self):
ranked = self.ranked()
self.assertIn("""| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 1 | 1 | 2.1 | -6.8 |
| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 6 | 8 | 2.1, 1 | 23.0 |
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 10.3 |
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 5.1 |
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 9 | 9 | 1 | 34.8 |
self.assertIn("""| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | -6.8 |
| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 23.0 |
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 10.3 |
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 5.1 |
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 34.8 |
""", ranked.text)
self.assertTrue(ranked.text.endswith("## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n"))
self.assertEqual(ranked.under_bar, [])
@@ -75,7 +75,7 @@ class Rank(unittest.TestCase):
def test_holds_each_item_a_decision_cites_and_says_how_to_settle_a_finished_one(self):
self.assertIsInstance(self.ranked(decisions=DECISIONS + "Until `todo.md` item 4 lands.\n"), rank_todo.Ranked)
gone = self.ranked(TODO.replace("| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 4 | 5 | 2.1 | 0 |\n", ""))
gone = self.ranked(TODO.replace("| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 |\n", ""))
self.assertEqual(gone.reason, "docs/decisions.md cites \"`todo.md` item 5\", which todo.md no longer holds; revise that decision to say what holds now")
def test_names_each_item_under_the_bar_that_is_not_exempt(self):
@@ -94,16 +94,21 @@ class Rank(unittest.TestCase):
self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason)
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "R ** 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R"):
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "R ** 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R"):
with self.subTest(formula=formula):
self.assertIsInstance(self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)), Failure)
def test_asks_for_a_c_column_in_a_table_without_one(self):
legacy = TODO.split("## Items")[0] + "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |\n"
self.assertEqual(self.ranked(legacy, decisions="").reason, "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")
def test_refuses_a_file_off_the_format(self):
row = "| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |"
row = "| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 |"
broken = {
row: row.replace("0.1.0", "0.1"),
"| 2 | 4 | 3 | 5 | 5 |": "| 2 | 4 | 11 | 5 | 5 |",
row + "\n": row.replace("5 | 5", "5 | ²") + "\n",
"| 2.1 | 0 |\n\n## Details": "| 2.1 | 0 |\n\n| 9 | 0.1.0 | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 0 |\n\n## Details",
"| 2.1 | 0 |\n\n## Details": "| 2.1 | 0 |\n\n| 9 | 0.1.0 | | **Stray.** | 1 | 1 | 3 | 1 | 1 | 1 | 0 |\n\n## Details",
"| 4 | 0.1.0 | security |": "| 4 | 0.1.0 | later |",
"| 5 | 0.1.0 | decision |": "| 5 | 0.1.0 | |",
"`Next ID = 6`": "`Next ID = 5`",
+6 -4
View File
@@ -4,7 +4,9 @@ import re
from failure import Failure
EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security")
ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |"
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 |"
@dataclasses.dataclass(frozen=True)
@@ -57,10 +59,10 @@ def cells(row: str, count: int) -> list[str] | Failure:
def parse_row(row: str) -> Item | Failure:
"""An item row, every cell checked but the goals it cites."""
found = cells(row, 10)
found = cells(row, 11)
if isinstance(found, Failure):
return found
id_, release, exempt, tagline, r, s, a, g, goals, _ = found
id_, release, exempt, tagline, r, s, c, a, g, goals, _ = found
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):
@@ -70,7 +72,7 @@ def parse_row(row: str) -> Item | Failure:
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("RSAG", (r, s, a, g)):
for name, value in zip("RSCAG", (r, s, c, a, g)):
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)