Show the size of the code each finished item names beside its S in score-outcomes

This commit is contained in:
2026-11-08 23:10:55 +01:00
parent 0a9a4dc159
commit 6176f72355
10 changed files with 150 additions and 42 deletions
-8
View File
@@ -1,6 +1,5 @@
"""The pure choices the preflight's steps act on."""
import pathlib
import re
from release_plan.release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
from failure import Failure
@@ -82,10 +81,3 @@ def pulls_command(forge: Forge, branch: str) -> list[str]:
if forge == "gh":
return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"]
return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"]
def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]:
"""Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file."""
spans = dict.fromkeys(span.removesuffix("/") for span in re.findall(r"`([^`\s]+)`", text))
held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans)
return [(span, count) for span, count in held if count]
+2 -1
View File
@@ -61,7 +61,8 @@ from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
from release_plan.release_standing import default_plan
from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
from chunk_preflight.choices import forge_of, named_paths, planned, pulls_command, worktree_add, worktree_on
from chunk_preflight.choices import forge_of, planned, pulls_command, worktree_add, worktree_on
from release_plan.named_code import named_paths
from chunk_preflight.facts import render
BIN = pathlib.Path(__file__).resolve().parents[1]
+1 -11
View File
@@ -9,7 +9,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from chunk_preflight.choices import forge_of, named_paths, planned, worktree_add
from chunk_preflight.choices import forge_of, planned, worktree_add
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
from test_env import isolated_env
from release_plan.release_standing import LastCut
@@ -501,16 +501,6 @@ class Plans(unittest.TestCase):
class Gathering(unittest.TestCase):
def test_names_each_tracked_file_or_folder_a_backticked_span_names_once_with_its_files(self):
cases = (
("`src/` and `src`", ["src/app.py", "srcfoo/x.py"], [("src", 1)]),
("`src/`", ["src/app.py", "src/b.py"], [("src", 2)]),
("`src/app.py`, `gone.py` and `run`", ["src/app.py"], [("src/app.py", 1)]),
)
for text, tracked, named in cases:
with self.subTest(text=text):
self.assertEqual(named_paths(text, tracked), named)
def test_adds_the_worktree_on_the_local_branch_else_on_a_new_one_tracking_origins_else_on_a_new_one_off_the_default_branch(self):
path = pathlib.Path("/c/proj-item-3")
self.assertEqual(worktree_add("item-3", path, "origin/main", True, True)[0], ["worktree", "add", "--quiet", "/c/proj-item-3", "item-3"])
+22
View File
@@ -0,0 +1,22 @@
"""The tracked files and folders an item's text names, each as a backticked span such as `bin/rank_todo.py` or `bin/`."""
import re
def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]:
"""Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file."""
held = ((span, sum(holds(span, path) for path in tracked)) for span in spans(text))
return [(span, count) for span, count in held if count]
def named_files(text: str, tracked: list[str]) -> list[str]:
"""Each tracked file that a backticked span in text names, itself or by a folder holding it, once, in tracked's order."""
named = spans(text)
return [path for path in tracked if any(holds(span, path) for span in named)]
def spans(text: str) -> list[str]:
return list(dict.fromkeys(span.removesuffix("/") for span in re.findall(r"`([^`\s]+)`", text)))
def holds(span: str, path: str) -> bool:
return path == span or path.startswith(f"{span}/")
+35
View File
@@ -0,0 +1,35 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.named_code import named_files, named_paths
class NamedPaths(unittest.TestCase):
def test_names_each_tracked_file_or_folder_a_backticked_span_names_once_with_its_files(self):
cases = (
("`src/` and `src`", ["src/app.py", "srcfoo/x.py"], [("src", 1)]),
("`src/`", ["src/app.py", "src/b.py"], [("src", 2)]),
("`src/app.py`, `gone.py` and `run`", ["src/app.py"], [("src/app.py", 1)]),
)
for text, tracked, named in cases:
with self.subTest(text=text):
self.assertEqual(named_paths(text, tracked), named)
class NamedFiles(unittest.TestCase):
def test_lists_each_tracked_file_a_span_names_by_itself_or_its_folder_once(self):
cases = (
("`src` and `src/a.py`", ["b.py", "src/a.py", "src/b.py", "srcfoo/x.py"], ["src/a.py", "src/b.py"]),
("`b.py`, `gone.py` and `run`", ["b.py", "c.py"], ["b.py"]),
("no span", ["b.py"], []),
)
for text, tracked, named in cases:
with self.subTest(text=text):
self.assertEqual(named_files(text, tracked), named)
if __name__ == "__main__":
unittest.main()
+25 -7
View File
@@ -45,7 +45,10 @@ Given L, E and I, on the levels ~/.claude/rules/todo-items.md defines, and S, it
L, E and I, as rank_todo.py does, and lists the 5 finished items whose guesses sit closest, closest
first: the least mean squared difference over the scores both hold, so R and S alone for an item
scored before L, E and I, the newest first among equals. Each line gives what the item's chunk
measured, which items shipped with it, and its tagline.
measured, which items shipped with it, and its tagline. Where the item's tagline or detail names
tracked files or folders, each in backticks such as `bin/rank_todo.py`, the line gives their size
before the chunk beside the item's S: how many files and their lines, which bound what the change
could touch.
Then the project's anchors, the shipped items its docs/score-anchors.md names for each level of L,
E and I, read from the checkout's working tree, each line as above, or that no chunk shipped it. A
@@ -73,6 +76,7 @@ clone, or the default branch cannot be read; or, after the rest of the report, w
left out.
"""
import functools
import os
import pathlib
import re
import sys
@@ -81,9 +85,10 @@ from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_an
from branch_chunks.read import branch_chunks
from git_cli.git_repo import default_branch, full_history, git, top
from failure import Failure
from score_outcomes.results import fixed_later, misreads, nearest, render, report, Result, results_of
from release_plan.todo_table import LEVELS, risk, TOP_SCORE
from score_outcomes.results import file_lines, fixed_later, item_text, misreads, nearest, render, report, Result, results_of
from release_plan.todo_table import item_details, LEVELS, risk, TOP_SCORE
from records.markdown_text import listed
from release_plan.named_code import named_files
# The scores score-outcomes takes, in order.
GIVEN = ("L", "E", "I", "S")
@@ -165,12 +170,25 @@ def read_results(default: str) -> list[Result] | Failure:
chunks = branch_chunks(default, run)
if isinstance(chunks, Failure):
return chunks
empty_tree = run("hash-object", "-t", "tree", os.devnull)
if isinstance(empty_tree, Failure):
return empty_tree
results: list[Result] = []
for chunk in chunks:
if chunk.before is None or not chunk.shipped:
continue
numstat = run("diff", "--numstat", chunk.before, chunk.tip)
if isinstance(numstat, Failure):
return numstat
results += results_of(chunk, numstat)
numstat, plan = run("diff", "--numstat", chunk.before, chunk.tip), run("show", f"{chunk.before}:todo.md")
if isinstance(numstat, Failure) or isinstance(plan, Failure):
return numstat if isinstance(numstat, Failure) else plan
found = item_details(plan)
details = {} if isinstance(found, Failure) else found
tracked = run("ls-tree", "-r", "-z", "--name-only", chunk.before)
if isinstance(tracked, Failure):
return tracked
# Only the files the items name, since counting every file's lines for every chunk doubles the run.
named = list(dict.fromkeys(path for item in chunk.shipped for path in named_files(item_text(item, details), tracked.split("\0")[:-1])))
tree = run("--literal-pathspecs", "diff", "--numstat", empty_tree.strip(), chunk.before, "--", *named) if named else ""
if isinstance(tree, Failure):
return tree
results += results_of(chunk, numstat, details, file_lines(tree))
return results
+34 -4
View File
@@ -6,15 +6,24 @@ from branch_chunks.cut import BranchChunk, Landing, NOT_WORK
from review_rules.round_titles import Findings, round_findings, rounds_past_first
from release_plan.todo_table import Item
from records.markdown_text import listed
from release_plan.named_code import named_files
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
ENOUGH = 10
# An item's size in lines, not an S: no published scale maps lines to S, and the report's S medians already set the S guessed beside the lines changed.
@dataclasses.dataclass(frozen=True)
class NamedCode:
"""The tracked files an item's tagline and detail name, folders by the files they hold, as the chunk that shipped it found them: how many, and their lines, a binary file holding none. They bound what the chunk's change could touch."""
files: int
lines: int
# The tool's name and report call a Result an outcome, a word the code keeps for an entry of a `.outcomes.md` file: docs/decisions.md → `bin/: an outcome is an entry`.
@dataclasses.dataclass(frozen=True)
class Result:
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landing says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed. fixed_by names the later chunks that fixed code it shipped, newest first, as branch_chunks counts them."""
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landing says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed. fixed_by names the later chunks that fixed code it shipped, newest first, as branch_chunks counts them. named is None where the item names no tracked file."""
item: Item
merge: str
merged: str
@@ -25,6 +34,9 @@ class Result:
findings: Findings | None
landing: Landing
fixed_by: tuple[str, ...]
named: NamedCode | None
# A measure's name and how to read it from a Result, None where the chunk did not record it.
@@ -37,8 +49,8 @@ ORDERED = ("L", "E", "I")
SHOWN = ("L", "E", "I", "R", "S", "C")
def results_of(chunk: BranchChunk, numstat: str) -> list[Result]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` of its change; none where it changed nothing but the plan and the records."""
def results_of(chunk: BranchChunk, numstat: str, details: dict[int, str], tree: dict[str, int]) -> list[Result]:
"""What one chunk measured for each item it shipped, from `git diff --numstat` of its change; none where it changed nothing but the plan and the records. details holds each item's detail in the todo.md the chunk started from, and tree each file's lines before the chunk, as file_lines reads them."""
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:
@@ -47,7 +59,23 @@ def results_of(chunk: BranchChunk, numstat: str) -> list[Result]:
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
titles = list(chunk.titles)
ids = [item.id for item in chunk.shipped]
return [Result(item, chunk.label, chunk.merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), rounds_past_first(titles), round_findings(titles), chunk.landing, chunk.fixed_by) for item in chunk.shipped]
return [Result(item, chunk.label, chunk.merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), rounds_past_first(titles), round_findings(titles), chunk.landing, chunk.fixed_by, named_code(item_text(item, details), tree)) for item in chunk.shipped]
def item_text(item: Item, details: dict[int, str]) -> str:
"""The tagline and detail, where the item names the files it changes."""
return f"{item.tagline}\n{details.get(item.id, '')}"
def file_lines(numstat: str) -> dict[str, int]:
"""Each file's lines from `git diff --numstat` against the empty tree, which counts every line as added; git counts a binary file's lines as "-", so it holds none."""
rows = [row.split("\t", 2) for row in numstat.splitlines()]
return {row[2]: int(row[0]) if row[0].isdigit() else 0 for row in rows if len(row) == 3}
def named_code(text: str, tree: dict[str, int]) -> NamedCode | None:
files = named_files(text, list(tree))
return NamedCode(len(files), sum(tree[path] for path in files)) if files else None
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
@@ -126,6 +154,8 @@ def ranks(values: list[int]) -> list[float]:
def render(result: Result) -> str:
scores = ", ".join(f"{name} {result.item.scores[name]}" for name in SHOWN if name in result.item.scores)
if result.named:
scores += f", naming code of {plural(result.named.lines, 'line')} in {plural(result.named.files, 'file')}"
merged = {"merge": f"merged {result.merged} in {result.merge}", "rebase": f"merged {result.merged} by rebase in {result.merge}", "push": f"committed {result.merged} in {result.merge}, never replayed, so perhaps part of a pull request"}[result.landing]
others = result.shipped_with
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
+30 -6
View File
@@ -10,10 +10,10 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from score_outcomes.anchors import anchor_lines, parse_anchors
from branch_chunks.cut import BranchChunk, Landing
from failure import Failure
from score_outcomes.results import file_lines, NamedCode, nearest, rank_correlation, render, report, Result, results_of
from review_rules.round_titles import Findings
from test_env import isolated_env
from release_plan.todo_table import Item
from score_outcomes.results import nearest, rank_correlation, render, report, Result, results_of
from score_outcomes.main import report_text
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
@@ -31,20 +31,30 @@ def item(id_: int, scores: dict[str, int]) -> Item:
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, (("1", None),), ())
def result(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, ...] = (), levels: dict[str, int] | None = None, landing: Landing = "merge", misread: int | None = None, merge: str = "aaaaaaa", fixed_by: tuple[str, ...] = ()) -> Result:
return Result(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), merge, merged, shipped_with, lines, 1, rounds, None if findings is None else Findings(*findings, misread), landing, fixed_by)
def result(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, ...] = (), levels: dict[str, int] | None = None, landing: Landing = "merge", misread: int | None = None, merge: str = "aaaaaaa", fixed_by: tuple[str, ...] = (), named: NamedCode | None = None) -> Result:
return Result(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), merge, merged, shipped_with, lines, 1, rounds, None if findings is None else Findings(*findings, misread), landing, fixed_by, named)
class ResultsOf(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\n0\t1\t2026\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 = results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", tuple(titles), (item(4, {"R": 2}), item(5, {"R": 3})), ("def5678",)), numstat)
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge", ("def5678",)))
found = results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", tuple(titles), (item(4, {"R": 2}), item(5, {"R": 3})), ("def5678",)), numstat, {}, {})
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge", ("def5678",), None))
self.assertEqual(found[1].shipped_with, (4,))
def test_measures_no_chunk_that_changed_only_the_plan(self):
self.assertEqual(results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", (), (item(4, {"R": 2}),), ()), "0\t5\ttodo.md\n"), [])
self.assertEqual(results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", (), (item(4, {"R": 2}),), ()), "0\t5\ttodo.md\n", {}, {}), [])
def test_counts_the_files_an_item_names_in_its_tagline_or_detail_and_their_lines_before_the_chunk(self):
named_in_tagline = Item(6, (0, 1, 0), "", "**Change `c.py`.**", {"R": 1}, (("1", None),), ())
chunk = BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", (), (item(4, {"R": 2}), item(5, {"R": 3}), named_in_tagline), ())
tree = {"src/x.py": 3, "src/y.py": 2, "b.py": 4, "c.py": 9, "logo.png": 0}
found = results_of(chunk, "1\t0\ta.py\n", {4: "Change `src`, `src/x.py`, `b.py` and `gone.py`.", 5: "Nothing named."}, tree)
self.assertEqual([result.named for result in found], [NamedCode(3, 9), None, NamedCode(1, 9)])
def test_reads_each_files_lines_from_a_numstat_against_the_empty_tree_a_binary_file_holding_none(self):
self.assertEqual(file_lines("3\t0\ta.py\n-\t-\tlogo.png\n0\t0\tempty.txt\n"), {"a.py": 3, "logo.png": 0, "empty.txt": 0})
class Nearest(unittest.TestCase):
@@ -106,6 +116,10 @@ class Render(unittest.TestCase):
self.assertEqual(render(result(4, 2, 3, 4, findings=(1, 2))), "- Item 4, R 2, S 3, C 4: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(result(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
def test_gives_the_size_of_the_code_the_item_names_after_its_scores(self):
self.assertTrue(render(result(4, 2, 3, 4, named=NamedCode(2, 40))).startswith("- Item 4, R 2, S 3, C 4, naming code of 40 lines in 2 files: 10 lines in 1 file,"))
self.assertTrue(render(result(4, 2, 3, None, named=NamedCode(1, 1))).startswith("- Item 4, R 2, S 3, naming code of 1 line in 1 file: 10 lines"))
def test_counts_the_later_fixes_of_the_chunk_that_shipped_it(self):
self.assertIn("0 🔴, 0 🟡, 1 later fix; merged", render(result(4, 2, 3, None, fixed_by=("bbbbbbb",))))
self.assertIn("0 🔴, 0 🟡, 2 later fixes; merged", render(result(4, 2, 3, None, fixed_by=("bbbbbbb", "ccccccc"))))
@@ -311,6 +325,16 @@ class ScoreOutcomesTool(unittest.TestCase):
item_4 = [line for line in ran.stdout.splitlines() if line.startswith("- Item 4,")]
return ran.stdout, item_4[0], first, last, pushed
def test_gives_the_lines_of_the_files_an_items_detail_names_as_its_chunk_found_them(self):
self.commit("Detail it", {"a.py": "1\n2\n", "todo.md": todo(FIRST, SECOND) + "\n## Details\n\n### 4. Do it.\n\nChange `a.py`.\n"})
self.git("switch", "-q", "-c", "chunk")
self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND)})
self.git("switch", "-q", "main")
self.git("merge", "-q", "--no-ff", "-m", "Merge chunk", "chunk")
ran = self.run_tool("1", "2", "1", "3")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("- Item 4, R 2, S 3, C 10, naming code of 2 lines in 1 file: 1 line in 1 file, ", ran.stdout)
def test_guesses_a_rebase_chunk_from_the_todo_md_before_its_first_commit(self):
_, item_4, _, _, _ = self.run_on_rebased_history()
self.assertTrue(item_4.startswith("- Item 4, R 1, S 3, C 10: "), item_4)