Count each finished chunk's later fixes in score-outcomes and the routing figures
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `score-outcomes` now counts each finished chunk's later fixes: the later chunks on the default branch that fixed code it shipped, the defects review let through. A later chunk counts where it ships a `todo.md` item marked `defect` or `security`, or answers a 🔴 a reviewer marked `[misread]`, and its change rewrites or removes lines that `git blame` traces to the earlier chunk. Each finished item shows the count beside its guessed scores, and a new list, after the misread findings, names the chunks that fixed each one, newest first. `routing-figures.md` shows the median per rung in a new column of the routed-chunks table. To find it, loop-claude now reads each archived project's checkout, and the figures name each project whose default branch it could not read.
|
||||
- `loop-claude` now opens every message it prints with the machine's local time, as in `2026-10-28 11:46:01`, so you can see when each happened, such as how long a question has waited. A message of several lines, such as a question, carries the time on its first line only. The `retrying at …` time of a usage-limit wait now also shows seconds, and no longer names the zone.
|
||||
- larv-review now gives each review pass at most two rounds per chunk, where it gave three and then asked for more, and no longer asks: the fixes answering a pass's second round merge once the gate passes. rule-hook's new `round-cap` rule refuses a round commit that would take a pass past round 2, such as `Answer stability round 3: …`, and takes no override. It counts the pass's earlier round commits on the branch, so a third commit titled round 2 is refused too. `larv-review round-count` marks a pass at two rounds as at the cap.
|
||||
- rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n '<A>,<B>p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override.
|
||||
|
||||
@@ -105,7 +105,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, MultiEdit, Read and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
|
||||
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; then each chunk's 🔴 and 🟡 findings with how many a reviewer marked `[misread]`, code health's counter-signal; `score-outcomes --help` states the measures.
|
||||
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; then each chunk's 🔴 and 🟡 findings with how many a reviewer marked `[misread]`, and the later chunks that fixed code it shipped: code health's two counter-signals; `score-outcomes --help` states the measures.
|
||||
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
@@ -125,7 +125,7 @@ pytest_add_cli_args=-k
|
||||
|
||||
Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `routing_figures` imports `score_outcomes`' later fixes, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
|
||||
## Tracking a new file
|
||||
|
||||
|
||||
+7
-7
@@ -109,18 +109,18 @@ def commits_since(tag: str | None, branch: str, cwd: str | None = None) -> int |
|
||||
return count if isinstance(count, Failure) else int(count)
|
||||
|
||||
|
||||
def commit_exists(commit: str, cwd: str | None = None) -> bool:
|
||||
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure)
|
||||
def commit_exists(commit: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> bool:
|
||||
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd, timeout=timeout, guarded=guarded), Failure)
|
||||
|
||||
|
||||
def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure:
|
||||
"""A file's text at a revision, read in cwd, else in the current directory; 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, cwd):
|
||||
def file_at(revision: str, path: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure:
|
||||
"""A file's text at a revision, read in cwd, else in the current directory, each git call run as `git` runs it with timeout and guarded; 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, cwd, timeout, guarded):
|
||||
return ""
|
||||
listed = git("ls-tree", "--name-only", revision, "--", path, cwd=cwd)
|
||||
listed = git("ls-tree", "--name-only", revision, "--", path, cwd=cwd, timeout=timeout, guarded=guarded)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
return git("show", f"{revision}:{path}", cwd=cwd) if listed.strip() else ""
|
||||
return git("show", f"{revision}:{path}", cwd=cwd, timeout=timeout, guarded=guarded) if listed.strip() else ""
|
||||
|
||||
|
||||
def full_history() -> Failure | None:
|
||||
|
||||
@@ -35,7 +35,7 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] |
|
||||
measured = archive.measure_archive(root, str(paths.home), kept.since)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
figures = totals(measured.chunks, measured.skipped)
|
||||
figures = totals(measured.chunks, measured.skipped, measured.unread)
|
||||
found = calls(figures)
|
||||
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, kept.since)):
|
||||
return unwritten
|
||||
|
||||
@@ -8,14 +8,19 @@ import re
|
||||
import typing
|
||||
|
||||
from transcript_archive.read import archived_outcomes, chunk_outcomes, finished_chunks
|
||||
from project_key import checkout_of
|
||||
from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent
|
||||
from git_repo import default_ref
|
||||
from failure import Failure
|
||||
from score_outcomes.later_fixes import Landed, later_fixes
|
||||
from claude_code.entries import parse_entry
|
||||
from file_writes import replace_file
|
||||
from utc_stamp import STAMPED
|
||||
from transcript_archive.outcomes import VERDICT_AT
|
||||
|
||||
FIGURES = "routing-figures.md"
|
||||
# Seconds each git call reading a project's history may take.
|
||||
GIT_TIMEOUT = 60
|
||||
LOCK = "routing-figures.lock"
|
||||
RAISED = "routing-calls-raised.md"
|
||||
RAISED_HEADING = "# Routing calls raised\n"
|
||||
@@ -72,9 +77,10 @@ def last_measured(root: pathlib.Path) -> int | Failure:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Measured:
|
||||
"""skipped names each chunk folder that could not be read whole, such as one another loop is writing."""
|
||||
"""skipped names each chunk folder that could not be read whole, such as one another loop is writing; unread names each project whose default branch could not be read, with why."""
|
||||
chunks: list[ChunkFigures]
|
||||
skipped: tuple[str, ...]
|
||||
unread: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Failure:
|
||||
@@ -85,12 +91,19 @@ def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Fai
|
||||
projects = sorted({root / key for key, _ in listed})
|
||||
found = []
|
||||
skipped = []
|
||||
unread = []
|
||||
for project in projects:
|
||||
key = str(project.relative_to(root))
|
||||
chunks = finished_chunks(project)
|
||||
if isinstance(chunks, Failure):
|
||||
skipped.append(str(project.relative_to(root)))
|
||||
skipped.append(key)
|
||||
continue
|
||||
for chunk in (chunk for chunk in chunks if chunk.finished > since):
|
||||
chunks = [chunk for chunk in chunks if chunk.finished > since]
|
||||
history = branch_history(checkout_of(key, pathlib.Path(home))) if chunks else None
|
||||
if isinstance(history, Failure):
|
||||
unread.append(f"{key}: {history.reason}")
|
||||
history = None
|
||||
for chunk in chunks:
|
||||
folder = project / chunk.folder
|
||||
try:
|
||||
kept = [path.read_text(encoding="utf-8") for path in chunk_outcomes(folder)]
|
||||
@@ -99,8 +112,14 @@ def measure_archive(root: pathlib.Path, home: str, since: str) -> Measured | Fai
|
||||
except (OSError, UnicodeDecodeError):
|
||||
skipped.append(str(folder.relative_to(root)))
|
||||
continue
|
||||
found.append(measured(Chunk(str(project.relative_to(root)), kept, worker, subagents), home))
|
||||
return Measured(found, tuple(skipped))
|
||||
found.append(measured(Chunk(key, kept, worker, subagents), home, history))
|
||||
return Measured(found, tuple(skipped), tuple(unread))
|
||||
|
||||
|
||||
def branch_history(checkout: str) -> list[Landed] | Failure:
|
||||
"""The chunks on the checkout's default branch as last fetched, read guarded, since the checkout's config may name a program."""
|
||||
ref = default_ref(checkout, GIT_TIMEOUT, guarded=True)
|
||||
return ref if isinstance(ref, Failure) else later_fixes(ref, cwd=checkout, guarded=True, timeout=GIT_TIMEOUT)
|
||||
|
||||
|
||||
def entries(path: pathlib.Path) -> list[dict]:
|
||||
|
||||
@@ -8,6 +8,7 @@ import typing
|
||||
from claude_code.entries import assistant_parts, parts, tool_call, tool_result
|
||||
from git_command import commits
|
||||
from model_routing.route import ESCALATION_MARKER, route_from
|
||||
from score_outcomes.later_fixes import Landed
|
||||
from routing_figures.prices import listed
|
||||
from model_routing.ladder import position, Rung
|
||||
from round_titles import round_counts
|
||||
@@ -56,7 +57,7 @@ class Reports:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ChunkFigures:
|
||||
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive."""
|
||||
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive; fixed_later counts the later chunks that fixed code it shipped, None where no chunk on its project's default branch matches it."""
|
||||
dollars: Dollars
|
||||
start: Rung | None
|
||||
rounds_past_first: int
|
||||
@@ -66,11 +67,12 @@ class ChunkFigures:
|
||||
escalated: collections.Counter[int]
|
||||
unattributed: float
|
||||
lacking: int = 0
|
||||
fixed_later: int | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Figures:
|
||||
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole."""
|
||||
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole; unmatched counts the chunks whose later fixes are unknown; unread names each project whose default branch could not be read, with why."""
|
||||
chunks: int
|
||||
dollars: Dollars
|
||||
routed: dict[Rung, list[ChunkFigures]]
|
||||
@@ -79,6 +81,8 @@ class Figures:
|
||||
skipped: tuple[str, ...] = ()
|
||||
unattributed: float = 0.0
|
||||
lacking: int = 0
|
||||
unmatched: int = 0
|
||||
unread: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -97,7 +101,8 @@ class Spent(typing.NamedTuple):
|
||||
message: Message
|
||||
|
||||
|
||||
def measured(chunk: Chunk, home: str) -> ChunkFigures:
|
||||
def measured(chunk: Chunk, home: str, history: list[Landed] | None = None) -> ChunkFigures:
|
||||
"""history is the chunks on the project's default branch, None where it could not be read."""
|
||||
cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0])
|
||||
spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)]
|
||||
launches = agent_calls(chunk.worker)
|
||||
@@ -113,19 +118,31 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
|
||||
spent += [Spent(kind, rung, message) for message in messages(subagent.entries)]
|
||||
dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker))
|
||||
start = route_from(cycles[0][1]) if cycles else None
|
||||
titles = commit_titles(chunk.worker, home)
|
||||
return ChunkFigures(
|
||||
dollars=dollars,
|
||||
start=start.rung if start and start.item else None,
|
||||
rounds_past_first=rounds_past_first(chunk.worker, home),
|
||||
rounds_past_first=sum(max(0, rounds - 1) for rounds in round_counts(titles).values()),
|
||||
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
|
||||
delegated=delegated,
|
||||
reports=reports,
|
||||
escalated=escalations(launches),
|
||||
unattributed=unattributed,
|
||||
lacking=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)),
|
||||
fixed_later=later_fixes_of(titles, history or []),
|
||||
)
|
||||
|
||||
|
||||
def later_fixes_of(titles: list[str], history: list[Landed]) -> int | None:
|
||||
"""How many chunks in history fixed code that the chunks holding one of titles shipped, each counted once and none of those chunks itself; None where no chunk holds one. Only a title no other chunk holds counts, since one such as a round's with no findings recurs."""
|
||||
# A worker's commits may land as several chunks, as a rebase cut by commit time does, and every one of them is its work.
|
||||
holders = collections.Counter(title for landed in history for title in landed.titles)
|
||||
shipped = [landed for landed in history if any(holders[title] == 1 for title in landed.titles.intersection(titles))]
|
||||
if not shipped:
|
||||
return None
|
||||
return len({later for landed in shipped for later in landed.fixed_by} - {landed.label for landed in shipped})
|
||||
|
||||
|
||||
def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]:
|
||||
"""How many of the worker's Agent calls open with each escalation trigger's number."""
|
||||
opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values())
|
||||
@@ -207,15 +224,14 @@ def results(entries: list[dict]) -> dict[str, str]:
|
||||
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
|
||||
|
||||
|
||||
def rounds_past_first(worker: list[dict], home: str) -> int:
|
||||
# A commit retried after a failed hook repeats its title, so each title counts once.
|
||||
titles = dict.fromkeys(
|
||||
def commit_titles(worker: list[dict], home: str) -> list[str]:
|
||||
"""The title of each commit the worker's Bash calls made, in order, each once: a commit retried after a failed hook repeats its title."""
|
||||
return list(dict.fromkeys(
|
||||
commit.messages[0].split("\n", 1)[0]
|
||||
for entry in worker for part in assistant_parts(entry)
|
||||
if (found := tool_call(part)) and found[0] == "Bash" and isinstance(found[1], dict)
|
||||
for commit in commits(simple_commands(str(found[1].get("command", "")), str(entry.get("cwd") or "/"), home), home) if commit.messages
|
||||
)
|
||||
return sum(max(0, rounds - 1) for rounds in round_counts(list(titles)).values())
|
||||
))
|
||||
|
||||
|
||||
def due(cycle: int, last_measured: int) -> bool:
|
||||
@@ -223,7 +239,7 @@ def due(cycle: int, last_measured: int) -> bool:
|
||||
return cycle >= last_measured + CYCLES_PER_CHECK
|
||||
|
||||
|
||||
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures:
|
||||
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tuple[str, ...] = ()) -> Figures:
|
||||
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
||||
for chunk in chunks:
|
||||
for dimension in DIMENSIONS:
|
||||
@@ -236,7 +252,7 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures
|
||||
routed.setdefault(chunk.start, []).append(chunk)
|
||||
for kind, found in chunk.reports.items():
|
||||
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
|
||||
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks))
|
||||
return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks), sum(chunk.fixed_later is None for chunk in chunks), unread)
|
||||
|
||||
|
||||
def calls(figures: Figures) -> list[str]:
|
||||
@@ -257,12 +273,15 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -
|
||||
|
||||
|
||||
def basis(figures: Figures) -> str:
|
||||
"""What the dollars are, what they leave out, and where the archive falls short of the recorded cost."""
|
||||
"""What the dollars and the later fixes are, what they leave out, and where the archive falls short of the recorded cost."""
|
||||
text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's runs are not archived, so their cost is not counted."
|
||||
if figures.unattributed:
|
||||
text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive."
|
||||
if figures.lacking:
|
||||
text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls."
|
||||
text += " A chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, as `score-outcomes` counts them, so a recent chunk has had less time to gather them. What it shipped is each chunk there holding a title of the worker's commits that no other chunk there holds."
|
||||
if figures.unmatched:
|
||||
text += f" The later fixes of {figures.unmatched} of the chunks are unknown, since no chunk on the branch held such a title, or the branch could not be read."
|
||||
return text
|
||||
|
||||
|
||||
@@ -275,8 +294,8 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: str)
|
||||
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
|
||||
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))],
|
||||
"## Routed chunks by the rung they started on",
|
||||
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs", "Escalations by trigger"), [
|
||||
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
|
||||
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, median", "Subagent rungs", "Escalations by trigger"), [
|
||||
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", median_fixes(chunks), subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
|
||||
for rung, chunks in sorted(figures.routed.items(), key=lambda item: position(item[0]))
|
||||
]),
|
||||
"## Escalations by trigger across every chunk, routed or not",
|
||||
@@ -284,6 +303,7 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: str)
|
||||
"## Subagent reports against the searches they ran, in characters",
|
||||
table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(found.subagents), str(found.report), str(found.searches)) for kind, found in sorted(figures.reports.items())]),
|
||||
*(["## Chunks skipped, unreadable", "".join(f"- {folder}\n" for folder in figures.skipped).rstrip("\n")] if figures.skipped else []),
|
||||
*(["## Project histories unread", "".join(f"- {project}\n" for project in figures.unread).rstrip("\n")] if figures.unread else []),
|
||||
]
|
||||
return "\n\n".join(sections) + "\n"
|
||||
|
||||
@@ -292,6 +312,12 @@ def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], colle
|
||||
return sum(map(of, chunks), collections.Counter())
|
||||
|
||||
|
||||
def median_fixes(chunks: list[ChunkFigures]) -> str:
|
||||
"""The median later fixes of the chunks that matched one on their project's default branch, `unknown` where none did."""
|
||||
known = [chunk.fixed_later for chunk in chunks if chunk.fixed_later is not None]
|
||||
return f"{statistics.median(known):.1f}" if known else "unknown"
|
||||
|
||||
|
||||
def subagent_rungs(chunks: list[ChunkFigures]) -> str:
|
||||
"""The rungs the chunks' subagents ran on, most used first, as `claude-opus-5-5 at high effort 2, …`."""
|
||||
return ", ".join(f"{label} {times}" for label, times in summed(chunks, lambda chunk: chunk.delegated).most_common())
|
||||
|
||||
@@ -3,8 +3,10 @@ import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -14,13 +16,16 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from routing_figures import archive
|
||||
from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, render, Reports, Subagent, totals
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from score_outcomes.later_fixes import Landed
|
||||
from transcript_archive import outcomes, write
|
||||
from model_routing.route import Route
|
||||
|
||||
LOW = Rung("claude-opus-5-5", "medium")
|
||||
HIGH = Rung("claude-opus-5-5", "high")
|
||||
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
|
||||
ROUND = "Answer stability round 1: 0 🔴, 0 🟡"
|
||||
|
||||
|
||||
def message(id_, at, *parts, model="claude-opus-5-5", usage=None):
|
||||
@@ -40,6 +45,10 @@ def result(id_, text):
|
||||
return {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": id_, "content": [{"type": "text", "text": text}]}]}}
|
||||
|
||||
|
||||
def commit(id_, title):
|
||||
return message(id_, "2026-10-14T10:00:00Z", call("Bash", command=f"git commit -m '{title}'"))
|
||||
|
||||
|
||||
def stamped(at, outcome):
|
||||
return f"{at} {outcome}\n"
|
||||
|
||||
@@ -87,10 +96,19 @@ class Measured(unittest.TestCase):
|
||||
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").escalated, {2: 2, 3: 1})
|
||||
|
||||
def test_counts_review_rounds_past_each_passs_first_once_per_title(self):
|
||||
commit = lambda id_, title: message(id_, "2026-10-14T10:00:00Z", call("Bash", command=f"git commit -m '{title}'"))
|
||||
worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")]
|
||||
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1)
|
||||
|
||||
def test_counts_the_later_fixes_of_the_landed_chunks_holding_a_title_of_the_workers_commits_no_other_holds(self):
|
||||
worker = [commit("m1", "Ship it"), commit("m2", ROUND)]
|
||||
fixed_later = lambda *history: measured(Chunk("log", [], worker, []), "/h", list(history)).fixed_later
|
||||
self.assertEqual(fixed_later(Landed("b", "2026-10-14T11:00:00Z", frozenset({ROUND}), ("c", "d", "e")), Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it", ROUND}), ("c", "d"))), 2)
|
||||
self.assertEqual(fixed_later(Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it"}), ())), 0)
|
||||
self.assertEqual(fixed_later(Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it"}), ("c", "d")), Landed("b", "2026-10-14T10:20:00Z", frozenset({ROUND}), ("d", "a"))), 2)
|
||||
self.assertIsNone(fixed_later(Landed("b", "2026-10-14T11:00:00Z", frozenset({"Ship it"}), ("c",)), Landed("a", "2026-10-14T10:30:00Z", frozenset({"Ship it"}), ())))
|
||||
self.assertIsNone(fixed_later(Landed("a", "2026-10-14T10:30:00Z", frozenset({"Other"}), ())))
|
||||
self.assertIsNone(measured(Chunk("log", [], worker, []), "/h").fixed_later)
|
||||
|
||||
def test_reads_the_route_of_a_line_loop_claude_wrote_before_it_archived_json(self):
|
||||
older = f"{LOW}, routed by item 7's L of 3 and E + I of 4"
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(older, "m", "j"))
|
||||
@@ -220,17 +238,27 @@ class Calls(unittest.TestCase):
|
||||
self.assertNotIn("no transcript", text)
|
||||
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |", text)
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |", text)
|
||||
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0)
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | unknown | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("| Explore | 2 | 3 | 4 |", text)
|
||||
escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | | trigger 2: 3, trigger 10: 1 |", escalated)
|
||||
self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | unknown | | trigger 2: 3, trigger 10: 1 |", escalated)
|
||||
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\ntrigger 2: 3, trigger 3: 1, trigger 10: 1.\n", escalated)
|
||||
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\nNone.\n", text)
|
||||
self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
|
||||
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))
|
||||
|
||||
def test_renders_the_median_later_fixes_of_the_matched_chunks_and_names_each_history_unread(self):
|
||||
matched = [dataclasses.replace(figures(), fixed_later=fixed) for fixed in (0, 3)]
|
||||
text = render(totals([*matched, figures()], unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn(f"| {LOW} | 3 | 0.0 | 0.0 | 1.5 | | |", text)
|
||||
self.assertIn("as `score-outcomes` counts them", text)
|
||||
self.assertIn("The later fixes of 1 of the chunks are unknown", text)
|
||||
self.assertIn("## Project histories unread\n\n- log: no main branch\n", text)
|
||||
self.assertNotIn("are unknown", render(totals(matched), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertNotIn("histories unread", render(totals(matched), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
|
||||
def test_measures_once_the_count_runs_20_past_the_last_measurement(self):
|
||||
self.assertEqual([due(cycle, 20) for cycle in (39, 40, 41)], [False, True, True])
|
||||
self.assertTrue(due(20, 0))
|
||||
@@ -265,6 +293,36 @@ class Archive(unittest.TestCase):
|
||||
self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0})
|
||||
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z"), archive.Measured([], ()))
|
||||
|
||||
def test_counts_each_chunks_later_fixes_from_its_projects_checkout_and_names_each_history_it_cannot_read(self):
|
||||
home = self.root / "home"
|
||||
checkout = home / "code" / "log"
|
||||
checkout.mkdir(parents=True)
|
||||
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)}
|
||||
git = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=checkout, check=True, env=env, capture_output=True)
|
||||
plan = lambda rows: "# todo\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" + rows
|
||||
|
||||
def merge(branch, title, files):
|
||||
git("switch", "-q", "-c", branch)
|
||||
for name, text in files.items():
|
||||
(checkout / name).write_text(text)
|
||||
git("add", *files)
|
||||
git("commit", "-q", "-m", title)
|
||||
git("switch", "-q", "main")
|
||||
git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
|
||||
git("init", "-q", "-b", "main")
|
||||
(checkout / "todo.md").write_text(plan("| 6 | 0.1.0 | | defect | **Fix six.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |\n"))
|
||||
(checkout / "a.py").write_text("1\n")
|
||||
git("add", "todo.md", "a.py")
|
||||
git("commit", "-q", "-m", "Start")
|
||||
merge("ship", "Ship it", {"a.py": "1\nx\n"})
|
||||
merge("fix", "Fix six", {"a.py": "1\ny\n", "todo.md": plan("")})
|
||||
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [commit("m1", "Ship it")])
|
||||
self.chunk("gone", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [commit("m1", "Ship it")])
|
||||
found = archive.measure_archive(self.root, str(home), "")
|
||||
self.assertEqual([(chunk.dollars["project"].keys(), chunk.fixed_later) for chunk in found.chunks], [({"gone": 0}.keys(), None), ({"log": 0}.keys(), 1)])
|
||||
(unread,) = found.unread
|
||||
self.assertTrue(unread.startswith("gone: "), unread)
|
||||
|
||||
def test_reads_each_cycles_route_from_its_own_outcomes_file(self):
|
||||
transcript = self.root / "t.jsonl"
|
||||
kept = self.root / "archive"
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Each chunk on a default branch, with the later chunks that fixed code it shipped: its escaped defects.
|
||||
|
||||
A later chunk fixed code an earlier chunk shipped where one of its changes removes or rewrites lines that `git blame` traces to a commit the earlier chunk brought. Two kinds of change count: the chunk's whole change, where it ships a todo.md item marked `defect` or `security`; and a round commit of the chunk answering a 🔴 that a reviewer marked `[misread]`. Chunks are cut as score-outcomes cuts them, and each counts at most once against each earlier chunk."""
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from git_repo import file_at, git
|
||||
from round_titles import title_counts
|
||||
from score_outcomes.results import chunk_log, label, NOT_WORK, shipped
|
||||
from utc_stamp import utc
|
||||
|
||||
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
|
||||
FIXES = ("defect", "security")
|
||||
# A todo.md row that may hold one of FIXES, as the extended regex `git log -G` takes; shipped confirms it.
|
||||
FIX_ROW = r"[|] *(defect|security) *[|]"
|
||||
HUNK = re.compile(r"@@ -([0-9]+)(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@")
|
||||
BLAME_HEADER = re.compile(r"([0-9a-f]{40}|[0-9a-f]{64}) [0-9]+ [0-9]+")
|
||||
# Runs git with the given arguments, in the checkout's top.
|
||||
Run = typing.Callable[..., str | Failure]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Landed:
|
||||
"""A chunk: its label as score-outcomes names it, its commit time, the titles of every commit it brought to the default branch, and the labels of the later chunks that fixed code it shipped, newest first."""
|
||||
label: str
|
||||
landed: str
|
||||
titles: frozenset[str]
|
||||
fixed_by: tuple[str, ...]
|
||||
|
||||
|
||||
def later_fixes(default: str, cwd: str | None = None, guarded: bool = False, timeout: float | None = None) -> list[Landed] | Failure:
|
||||
"""Each chunk on default's first-parent line, newest first, read in the checkout holding cwd, else the current directory, each git call run as `git` runs it with timeout and guarded."""
|
||||
top = git("rev-parse", "--show-toplevel", cwd=cwd, timeout=timeout, guarded=guarded)
|
||||
if isinstance(top, Failure):
|
||||
return top
|
||||
# Blame and a pathspec read a path from the current directory, and the diff names each from the top.
|
||||
root = top.strip()
|
||||
|
||||
def run(*args: str) -> str | Failure:
|
||||
return git(*args, cwd=root, timeout=timeout, guarded=guarded)
|
||||
log = run("log", "--format=%x1e%H %h %ct %at %P%x1f%s", default)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
shorts: dict[str, str] = {}
|
||||
parents: dict[str, list[str]] = {}
|
||||
titles: dict[str, str] = {}
|
||||
headers: dict[str, str] = {}
|
||||
for record in log.split("\x1e")[1:]:
|
||||
header, _, title = record.rstrip("\n").partition("\x1f")
|
||||
full, short, committed, authored, *above = header.split()
|
||||
shorts[full], parents[full], titles[full] = short, above, title
|
||||
headers[full] = " ".join([full, committed, authored, *above])
|
||||
# git log prints the commit it starts from first.
|
||||
line = [next(iter(parents))]
|
||||
while parents[line[-1]]:
|
||||
line.append(parents[line[-1]][0])
|
||||
chunks = chunk_log([headers[commit] for commit in line])
|
||||
owner = owners(chunks, line, parents)
|
||||
changes = fixing_changes(chunks, owner, parents, titles, run, lambda revision: file_at(revision, "todo.md", root, timeout, guarded), default)
|
||||
if isinstance(changes, Failure):
|
||||
return changes
|
||||
fixed: dict[int, set[int]] = {}
|
||||
for index, before, tip in changes:
|
||||
traced = traced_to(before, tip, run)
|
||||
if isinstance(traced, Failure):
|
||||
return traced
|
||||
for commit in traced:
|
||||
# A commit no chunk owns cannot be one before can reach; take it as the fixing chunk's own.
|
||||
if owner.get(commit, index) > index:
|
||||
fixed.setdefault(owner[commit], set()).add(index)
|
||||
owned: dict[int, set[str]] = {}
|
||||
for commit, index in owner.items():
|
||||
owned.setdefault(index, set()).add(titles[commit])
|
||||
names = [label(shorts[first], shorts[last]) for first, last, _, _ in chunks]
|
||||
return [Landed(names[index], utc(time), frozenset(owned[index]), tuple(names[later] for later in sorted(fixed.get(index, ())))) for index, (_, _, time, _) in enumerate(chunks)]
|
||||
|
||||
|
||||
def owners(chunks: list, line: list[str], parents: dict[str, list[str]]) -> dict[str, int]:
|
||||
"""Each commit's chunk, as its index in chunks, newest first: the oldest chunk on the first-parent line whose commits reach it."""
|
||||
at = {commit: place for place, commit in enumerate(line)}
|
||||
owner: dict[str, int] = {}
|
||||
for index in reversed(range(len(chunks))):
|
||||
first, last, _, _ = chunks[index]
|
||||
for commit in reversed(line[at[last]:at[first] + 1]):
|
||||
unowned = [commit]
|
||||
while unowned:
|
||||
found = unowned.pop()
|
||||
if found not in owner:
|
||||
owner[found] = index
|
||||
unowned += parents[found]
|
||||
return owner
|
||||
|
||||
|
||||
def fixing_changes(chunks: list, owner: dict[str, int], parents: dict[str, list[str]], titles: dict[str, str], run: Run, plan_at: typing.Callable[[str], str | Failure], default: str) -> list[tuple[int, str, str]] | Failure:
|
||||
"""Each change that fixes a defect, as its chunk's index, the commit before it and its tip: the whole change of each chunk that ships a FIXES item, and each round commit answering a 🔴 a reviewer marked `[misread]`."""
|
||||
touched = run("log", "--first-parent", f"-G{FIX_ROW}", "--format=%H", default, "--", "todo.md")
|
||||
if isinstance(touched, Failure):
|
||||
return touched
|
||||
changes = []
|
||||
for index in sorted({owner[commit] for commit in touched.split()}):
|
||||
first, last, _, _ = chunks[index]
|
||||
if not parents[first]:
|
||||
continue
|
||||
before = parents[first][0]
|
||||
planned, after = plan_at(before), plan_at(last)
|
||||
if isinstance(planned, Failure):
|
||||
return planned
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
if any(item.exempt in FIXES for item in shipped(planned, after)):
|
||||
changes.append((index, before, last))
|
||||
for commit, title in titles.items():
|
||||
counts = title_counts(title)
|
||||
# A title counts misread 🔴 and 🟡 findings together, so it takes one with both a 🔴 and a misread finding to answer a misread 🔴.
|
||||
if counts and counts.red and counts.misread and parents[commit]:
|
||||
changes.append((owner[commit], parents[commit][0], commit))
|
||||
return changes
|
||||
|
||||
|
||||
def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure:
|
||||
"""The commits that last changed each line the change from before to tip removes or rewrites, outside the plan and the records."""
|
||||
# The prefixes and options keep the checkout's diff config out of the output.
|
||||
diff = run("diff", "-U0", "-M", "--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules", "--src-prefix=a/", "--dst-prefix=b/", before, tip)
|
||||
if isinstance(diff, Failure):
|
||||
return diff
|
||||
traced: set[str] = set()
|
||||
for path, spans in removed(diff).items():
|
||||
if path in NOT_WORK:
|
||||
continue
|
||||
# An empty --ignore-revs-file drops a configured one, which blame fails on where the file is missing.
|
||||
blame = run("blame", "--porcelain", "--no-textconv", "--ignore-revs-file=", *(f"-L{start},+{count}" for start, count in spans), before, "--", path)
|
||||
if isinstance(blame, Failure):
|
||||
return blame
|
||||
traced |= blamed(blame)
|
||||
return traced
|
||||
|
||||
|
||||
def removed(diff: str) -> dict[str, list[tuple[int, int]]]:
|
||||
"""The old lines each hunk of a `git diff -U0` removes or rewrites, as its first line and count, by the path the file had before; none for a path git quotes, as it does one holding a byte it cannot print."""
|
||||
spans: dict[str, list[tuple[int, int]]] = {}
|
||||
path, left = None, 0
|
||||
for row in diff.splitlines():
|
||||
if left and row[:1] in ("-", "+", " "):
|
||||
left -= 1
|
||||
elif row.startswith("diff --git "):
|
||||
path, left = None, 0
|
||||
elif row.startswith("--- "):
|
||||
# Git ends a path holding a space with a tab.
|
||||
path = row[len("--- a/"):].removesuffix("\t") if row.startswith("--- a/") else None
|
||||
elif hunk := HUNK.match(row):
|
||||
start, count = int(hunk.group(1)), int(hunk.group(2) or 1)
|
||||
left = count + int(hunk.group(3) or 1)
|
||||
if path and count:
|
||||
spans.setdefault(path, []).append((start, count))
|
||||
return spans
|
||||
|
||||
|
||||
def blamed(porcelain: str) -> set[str]:
|
||||
"""The commit each line of `git blame --porcelain` output comes from."""
|
||||
return {header.group(1) for row in porcelain.splitlines() if (header := BLAME_HEADER.match(row))}
|
||||
+30
-26
@@ -23,7 +23,15 @@ holds R and S, and C too where its table also had A, G and Goals. The chunk meas
|
||||
round title lacks the counts, or the branch has no round;
|
||||
- misread findings: how many of those 🔴 and 🟡 findings a reviewer marked `[misread]`, the
|
||||
`(<j> misread)` after the 🟡 count, summed over the titles. Unknown where a round title lacks
|
||||
that count, as every title written before the count does, or the branch has no round.
|
||||
that count, as every title written before the count does, or the branch has no round;
|
||||
- later fixes: the later chunks that fixed code it shipped, each counted once. A later chunk fixed
|
||||
it where a change of the later chunk removes or rewrites lines, outside todo.md and the records,
|
||||
that `git blame` traces to a commit this chunk brought to the default branch. The change is the
|
||||
later chunk's whole change where it ships a todo.md item whose Exempt cell is `defect` or
|
||||
`security`, or one of its round commits whose title counts a 🔴 and a misread finding, since a
|
||||
title counts misread 🔴 and 🟡 findings together. A fixing chunk that also ships other items
|
||||
counts all of its change, so the count can run high; a fix that ships no such item, and answers
|
||||
no such round, goes uncounted.
|
||||
|
||||
A chunk is marked `by rebase` where a commit in it has a committer time apart from its author time,
|
||||
since a rebase replays a pull request's commits at once, and `never replayed` where none does, since
|
||||
@@ -55,6 +63,10 @@ Then, newest first, each finished chunk's 🔴 and 🟡 findings with its misrea
|
||||
chunk whose round titles count them: code health's counter-signal in
|
||||
~/.claude/CLAUDE.md → "Shared goal".
|
||||
|
||||
Then, newest first, each finished chunk's later fixes, naming the fixing chunks, for every chunk
|
||||
that has any, then how many have none: the defects that reappear in what already shipped, the
|
||||
other half of that counter-signal.
|
||||
|
||||
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; or, after the rest of the report, when the anchors are
|
||||
left out.
|
||||
@@ -64,9 +76,10 @@ import re
|
||||
import sys
|
||||
|
||||
from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_anchors
|
||||
from score_outcomes.results import Chunk, Landing, misreads, nearest, render, report, Result, results_of, shipped
|
||||
from score_outcomes.results import chunk_log, fixed_later, label, Landing, misreads, nearest, render, report, Result, results_of, shipped
|
||||
from git_repo import default_branch, file_at, full_history, git, top
|
||||
from failure import Failure
|
||||
from score_outcomes.later_fixes import later_fixes
|
||||
from todo_table import LEVELS, risk, TOP_SCORE
|
||||
from markdown_text import listed
|
||||
from utc_stamp import utc
|
||||
@@ -107,7 +120,7 @@ def main(argv: list[str]) -> int:
|
||||
|
||||
|
||||
def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
|
||||
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings."""
|
||||
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings, then its later fixes."""
|
||||
sections = []
|
||||
if given is not None:
|
||||
r = risk(given["L"], given["E"], given["I"])
|
||||
@@ -116,6 +129,7 @@ def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[
|
||||
sections.append([f"Anchors in {ANCHORS_PATH}, each level's shipped items:", "", *anchor_lines(anchored, results)])
|
||||
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(results)])
|
||||
sections.append(["🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:", "", *misreads(results)])
|
||||
sections.append(["Later fixes, the later chunks that fixed code each finished chunk shipped, newest first:", "", *fixed_later(results)])
|
||||
if any(result.landed != "merge" for result in results):
|
||||
sections.append(UNMERGED)
|
||||
return "\n\n".join("\n".join(section) for section in sections)
|
||||
@@ -143,9 +157,17 @@ def read_results(default: str) -> list[Result] | Failure:
|
||||
"""What each chunk on the default branch's first-parent line measured."""
|
||||
if partial := full_history():
|
||||
return partial
|
||||
log = git("log", "--first-parent", "--format=%x1e%h %ct %at %p", "--name-only", default)
|
||||
# Both logs read one commit, so a fetch that moves the branch between them cannot cut chunks two ways.
|
||||
tip = git("rev-parse", "--verify", f"{default}^{{commit}}")
|
||||
if isinstance(tip, Failure):
|
||||
return tip
|
||||
log = git("log", "--first-parent", "--format=%x1e%h %ct %at %p", "--name-only", tip.strip())
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
fixes = later_fixes(tip.strip())
|
||||
if isinstance(fixes, Failure):
|
||||
return fixes
|
||||
fixed_by = {landed.label: landed.fixed_by for landed in fixes}
|
||||
# Each commit's part of the log is its line, then the files it changed against its first parent.
|
||||
commits = [part.splitlines() for part in log.split("\x1e")[1:]]
|
||||
headers = [commit[0] for commit in commits]
|
||||
@@ -156,34 +178,16 @@ def read_results(default: str) -> list[Result] | Failure:
|
||||
# Only a chunk that changed todo.md can ship an item, so the others skip measure's git calls.
|
||||
if not any(short in plan for short in hashes[hashes.index(last):hashes.index(first) + 1]):
|
||||
continue
|
||||
label = first if first == last else f"{first}^..{last}"
|
||||
titled = f"{first}^1..{first}^2" if landed == "merge" else f"{first}^1..{last}"
|
||||
measured = measure(f"{first}^1", last, label, utc(committed), titled, landed)
|
||||
named = label(first, last)
|
||||
measured = measure(f"{first}^1", last, named, utc(committed), titled, landed, fixed_by[named])
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
results += measured
|
||||
return results
|
||||
|
||||
|
||||
def chunk_log(lines: list[str]) -> list[Chunk]:
|
||||
"""The chunks `git log --first-parent --format=%h %ct %at %p` lines cut, newest first: each chunk's first and last commit as short hashes, its commit time, and how it reached the branch. A merge commit is a chunk of its own; any other commit joins the run of the newer commit above it when both share a commit time."""
|
||||
chunks: list[Chunk] = []
|
||||
joinable = False
|
||||
for line in lines:
|
||||
short, committed, authored, *parents = line.split()
|
||||
if len(parents) > 1:
|
||||
chunks.append((short, short, int(committed), "merge"))
|
||||
joinable = False
|
||||
elif joinable and chunks[-1][2] == int(committed):
|
||||
_, newest, time, landed = chunks[-1]
|
||||
chunks[-1] = (short, newest, time, "rebase" if landed == "rebase" or committed != authored else "push")
|
||||
else:
|
||||
chunks.append((short, short, int(committed), "rebase" if committed != authored else "push"))
|
||||
joinable = True
|
||||
return chunks
|
||||
|
||||
|
||||
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Result] | Failure:
|
||||
def measure(before: str, tip: str, named: str, merged: str, titled: str, landed: Landing, fixed_by: tuple[str, ...]) -> list[Result] | Failure:
|
||||
"""What one chunk measured for each item it shipped: its change from the commit before it to its tip, and the titles of the commits in the range titled."""
|
||||
planned = file_at(before, "todo.md")
|
||||
if isinstance(planned, Failure):
|
||||
@@ -200,4 +204,4 @@ def measure(before: str, tip: str, label: str, merged: str, titled: str, landed:
|
||||
titles = git("log", "--format=%s", titled)
|
||||
if isinstance(titles, Failure):
|
||||
return titles
|
||||
return results_of(items, label, merged, numstat, titles.splitlines(), landed)
|
||||
return results_of(items, named, merged, numstat, titles.splitlines(), landed, fixed_by)
|
||||
|
||||
@@ -22,7 +22,7 @@ Chunk = tuple[str, str, int, Landing]
|
||||
# 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. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
|
||||
"""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. landed 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 later_fixes counts them."""
|
||||
item: Item
|
||||
merge: str
|
||||
merged: str
|
||||
@@ -32,6 +32,7 @@ class Result:
|
||||
rounds_past_first: int
|
||||
findings: Findings | None
|
||||
landed: Landing
|
||||
fixed_by: tuple[str, ...]
|
||||
|
||||
|
||||
# A measure's name and how to read it from a Result, None where the chunk did not record it.
|
||||
@@ -53,7 +54,7 @@ def shipped(before: str, after: str) -> list[Item]:
|
||||
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
||||
|
||||
|
||||
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Result]:
|
||||
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing, fixed_by: tuple[str, ...]) -> list[Result]:
|
||||
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its 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]
|
||||
@@ -63,7 +64,30 @@ def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, title
|
||||
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 [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
|
||||
return [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed, fixed_by) for item in shipped]
|
||||
|
||||
|
||||
def chunk_log(lines: list[str]) -> list[Chunk]:
|
||||
"""The chunks `git log --first-parent --format=%h %ct %at %p` lines cut, newest first: each chunk's first and last commit as short hashes, its commit time, and how it reached the branch. A merge commit is a chunk of its own; any other commit joins the run of the newer commit above it when both share a commit time."""
|
||||
chunks: list[Chunk] = []
|
||||
joinable = False
|
||||
for line in lines:
|
||||
short, committed, authored, *parents = line.split()
|
||||
if len(parents) > 1:
|
||||
chunks.append((short, short, int(committed), "merge"))
|
||||
joinable = False
|
||||
elif joinable and chunks[-1][2] == int(committed):
|
||||
_, newest, time, landed = chunks[-1]
|
||||
chunks[-1] = (short, newest, time, "rebase" if landed == "rebase" or committed != authored else "push")
|
||||
else:
|
||||
chunks.append((short, short, int(committed), "rebase" if committed != authored else "push"))
|
||||
joinable = True
|
||||
return chunks
|
||||
|
||||
|
||||
def label(first: str, last: str) -> str:
|
||||
"""How the report names a chunk: its one commit's short hash, or its first and last commits' as a range."""
|
||||
return first if first == last else f"{first}^..{last}"
|
||||
|
||||
|
||||
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
|
||||
@@ -109,6 +133,17 @@ def misreads(results: list[Result]) -> list[str]:
|
||||
return lines or ["- None: no chunk's round titles count them."]
|
||||
|
||||
|
||||
def fixed_later(results: list[Result]) -> list[str]:
|
||||
"""Newest first, each finished chunk that later chunks fixed code of, naming them, then how many finished chunks none fixed."""
|
||||
chunks = {result.merge: result for result in results}
|
||||
newest_first = sorted(chunks.values(), key=lambda result: result.merged, reverse=True)
|
||||
lines = [f"- {result.merged} in {result.merge}: {later(result)}, by {listed(result.fixed_by, 'and')}" for result in newest_first if result.fixed_by]
|
||||
if not lines:
|
||||
return ["- None: no later chunk fixed code a finished chunk shipped."]
|
||||
others = len(chunks) - len(lines)
|
||||
return lines + ([f"- The other {plural(others, 'finished chunk')}: none."] if others else [])
|
||||
|
||||
|
||||
def too_few(held: int, name: str, what: str) -> str:
|
||||
chunks = "such chunk records" if held == 1 else "such chunks record"
|
||||
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
|
||||
@@ -132,7 +167,7 @@ def render(result: Result) -> str:
|
||||
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.landed]
|
||||
others = result.shipped_with
|
||||
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
|
||||
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least(result)}{plural(result.rounds_past_first, 'round')} past each pass's first, {counted(result)}; {merged}{together}. {result.item.tagline}"
|
||||
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least(result)}{plural(result.rounds_past_first, 'round')} past each pass's first, {counted(result)}, {later(result)}; {merged}{together}. {result.item.tagline}"
|
||||
|
||||
|
||||
def at_least(result: Result) -> str:
|
||||
@@ -148,5 +183,10 @@ def counted(result: Result) -> str:
|
||||
return f"{at_least(result)}{result.findings.red} 🔴, {result.findings.yellow} 🟡{misread}"
|
||||
|
||||
|
||||
def later(result: Result) -> str:
|
||||
count = len(result.fixed_by)
|
||||
return f"{count} later fix{'' if count == 1 else 'es'}"
|
||||
|
||||
|
||||
def plural(count: int, noun: str) -> str:
|
||||
return f"{count} {noun}{'' if count == 1 else 's'}"
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
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.later_fixes import blamed, Landed, later_fixes, removed
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
|
||||
HEADER = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
ROWS = {
|
||||
4: "| 4 | 0.1.0 | | | **Do four.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
|
||||
5: "| 5 | 0.1.0 | | | **Do five.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
|
||||
6: "| 6 | 0.1.0 | | defect | **Fix six.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
|
||||
7: "| 7 | 0.1.0 | | security | **Close seven.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
|
||||
8: "| 8 | 0.1.0 | | defect | **Fix eight.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
|
||||
9: "| 9 | 0.1.0 | | defect | **Fix nine.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |",
|
||||
}
|
||||
|
||||
|
||||
def todo(*ids: int) -> str:
|
||||
return "# todo\n\n## Items\n\n" + HEADER + "".join(f"{ROWS[id_]}\n" for id_ in ids)
|
||||
|
||||
|
||||
class Removed(unittest.TestCase):
|
||||
def test_reads_the_old_lines_each_hunk_removes_or_rewrites_by_the_path_they_had(self):
|
||||
diff = "\n".join([
|
||||
"diff --git a/a.py b/a.py",
|
||||
"--- a/a.py",
|
||||
"+++ b/a.py",
|
||||
"@@ -2 +2 @@ def f():",
|
||||
"-x",
|
||||
"+y",
|
||||
"@@ -5,3 +4,0 @@",
|
||||
"@@ -9,0 +8,2 @@",
|
||||
"diff --git a/old.py b/new.py",
|
||||
"--- a/old.py",
|
||||
"+++ b/new.py",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"diff --git a/gone.py b/gone.py",
|
||||
"--- a/gone.py",
|
||||
"+++ /dev/null",
|
||||
"@@ -1,4 +0,0 @@",
|
||||
"diff --git a/born.py b/born.py",
|
||||
"--- /dev/null",
|
||||
"+++ b/born.py",
|
||||
"@@ -0,0 +1,3 @@",
|
||||
"diff --git \"a/tab\\there.py\" \"b/tab\\there.py\"",
|
||||
"--- \"a/tab\\there.py\"",
|
||||
"+++ \"b/tab\\there.py\"",
|
||||
"@@ -1 +1 @@",
|
||||
"diff --git a/my file.py b/my file.py",
|
||||
"--- a/my file.py\t",
|
||||
"+++ b/my file.py\t",
|
||||
"@@ -7,2 +7 @@",
|
||||
])
|
||||
self.assertEqual(removed(diff), {"a.py": [(2, 1), (5, 3)], "old.py": [(1, 2)], "gone.py": [(1, 4)], "my file.py": [(7, 2)]})
|
||||
|
||||
def test_reads_a_hunk_line_inside_the_changed_text_as_text(self):
|
||||
diff = "--- a/a.md\n+++ b/a.md\n@@ -3 +3 @@\n---- a/quoted\n+text\n"
|
||||
self.assertEqual(removed(diff), {"a.md": [(3, 1)]})
|
||||
|
||||
|
||||
class Blamed(unittest.TestCase):
|
||||
def test_reads_the_commit_of_each_line_from_porcelain_output(self):
|
||||
first, second = "a" * 40, "b" * 40
|
||||
porcelain = f"{first} 2 2 1\nauthor t\nfilename a.py\n\tx\n{second} 5 5 2\nauthor t\n\ty\n{second} 6 6\n\t{first} 1 1 1\n"
|
||||
self.assertEqual(blamed(porcelain), {first, second})
|
||||
|
||||
|
||||
class LaterFixes(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.checkout = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.checkout)}
|
||||
self.git("init", "-q", "-b", "main")
|
||||
self.commit("Start", {"todo.md": todo(4, 5, 6, 7, 8), "a.py": "1\n2\n3\n"})
|
||||
|
||||
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, at=None):
|
||||
for name, text in files.items():
|
||||
(self.checkout / name).write_text(text)
|
||||
self.git("add", name)
|
||||
dates = {"GIT_COMMITTER_DATE": at, "GIT_AUTHOR_DATE": at} if at else {}
|
||||
self.env.update(dates)
|
||||
self.git("commit", "-q", "-m", title)
|
||||
for name in dates:
|
||||
self.env.pop(name)
|
||||
return self.git("rev-parse", "--short", "HEAD").strip()
|
||||
|
||||
def chunk(self, branch, *commits):
|
||||
"""Merges a branch holding each (title, files) commit, and returns the merge commit's short hash."""
|
||||
self.git("switch", "-q", "-c", branch)
|
||||
for title, files in commits:
|
||||
self.commit(title, files)
|
||||
self.git("switch", "-q", "main")
|
||||
self.git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
|
||||
return self.git("rev-parse", "--short", "HEAD").strip()
|
||||
|
||||
def fixes(self):
|
||||
found = later_fixes("main", cwd=str(self.checkout))
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
return {landed.label: landed.fixed_by for landed in found}
|
||||
|
||||
def test_counts_a_later_chunk_that_ships_a_defect_item_and_rewrites_a_line_an_earlier_chunk_added(self):
|
||||
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
fixed = self.chunk("six", ("Fix six", {"b.py": "x\nY\n", "todo.md": todo(5, 7, 8)}))
|
||||
found = self.fixes()
|
||||
self.assertEqual(found[shipped], (fixed,))
|
||||
self.assertEqual(found[fixed], ())
|
||||
|
||||
def test_counts_a_chunk_that_ships_a_security_item_as_a_fix(self):
|
||||
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
fixed = self.chunk("seven", ("Close seven", {"b.py": "x\n", "todo.md": todo(5, 6, 8)}))
|
||||
self.assertEqual(self.fixes()[shipped], (fixed,))
|
||||
|
||||
def test_counts_no_chunk_whose_shipped_items_are_neither_defect_nor_security(self):
|
||||
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
self.chunk("five", ("Do five", {"b.py": "x\nY\n", "todo.md": todo(6, 7, 8)}))
|
||||
self.assertEqual(self.fixes()[shipped], ())
|
||||
|
||||
def test_counts_no_chunk_that_only_edits_a_defect_items_row(self):
|
||||
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
self.chunk("edit", ("Re-score six", {"b.py": "x\nY\n", "todo.md": todo(5, 6, 7, 8).replace("**Fix six.**", "**Fix six now.**")}))
|
||||
self.assertEqual(self.fixes()[shipped], ())
|
||||
|
||||
def test_leaves_the_plans_row_out_so_a_fix_does_not_trace_to_the_chunk_that_filed_it(self):
|
||||
filed = self.chunk("file", ("File item 9", {"c.py": "c\n", "todo.md": todo(4, 5, 6, 7, 8, 9)}))
|
||||
self.chunk("nine", ("Fix nine", {"d.py": "d\n", "todo.md": todo(4, 5, 6, 7, 8)}))
|
||||
self.assertEqual(self.fixes()[filed], ())
|
||||
|
||||
def test_counts_a_round_commit_that_answers_a_misread_red_finding_and_rewrites_an_earlier_chunks_line(self):
|
||||
shipped = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
fixed = self.chunk("five", ("Do five", {"c.py": "c\n", "todo.md": todo(6, 7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (1 misread); keep y's caller", {"b.py": "x\nY\n"}))
|
||||
self.assertEqual(self.fixes()[shipped], (fixed,))
|
||||
|
||||
def test_counts_no_round_commit_without_both_a_red_and_a_misread_finding(self):
|
||||
shipped = self.chunk("four", ("Do four", {"b.py": "w\nx\ny\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
self.chunk("five", ("Do five", {"c.py": "c\n", "todo.md": todo(6, 7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (0 misread); fix", {"b.py": "W\nx\ny\n"}), ("Answer prose round 1: 0 🔴, 1 🟡 (1 misread); fix", {"b.py": "W\nX\ny\n"}), ("Answer principles round 1: 1 🔴, 0 🟡; fix", {"b.py": "W\nX\nY\n"}))
|
||||
self.assertEqual(self.fixes()[shipped], ())
|
||||
|
||||
def test_counts_no_fix_of_lines_its_own_chunk_wrote(self):
|
||||
self.chunk("six", ("Fix six", {"b.py": "x\ny\n", "todo.md": todo(4, 5, 7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (1 misread); fix", {"b.py": "x\nY\n"}))
|
||||
self.assertEqual(set(self.fixes().values()), {()})
|
||||
|
||||
def test_counts_a_fixing_chunk_once_against_each_chunk_it_fixes_newest_first(self):
|
||||
first = self.chunk("four", ("Do four", {"b.py": "x\ny\n", "d.py": "d\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
second = self.chunk("five", ("Do five", {"c.py": "z\n", "todo.md": todo(6, 7, 8)}))
|
||||
fixed = self.chunk("six", ("Fix six", {"b.py": "X\ny\n", "todo.md": todo(7, 8)}), ("Answer stability round 1: 1 🔴, 0 🟡 (1 misread); fix", {"b.py": "X\nY\n", "c.py": "Z\n"}))
|
||||
again = self.chunk("eight", ("Fix eight", {"b.py": "XX\nY\n", "d.py": "D\n", "todo.md": todo(7)}))
|
||||
found = self.fixes()
|
||||
self.assertEqual(found[first], (again, fixed))
|
||||
self.assertEqual(found[second], (fixed,))
|
||||
self.assertEqual(found[fixed], (again,))
|
||||
|
||||
def test_traces_a_line_to_the_rebased_run_that_added_it_and_labels_runs_as_score_outcomes_does(self):
|
||||
first = self.commit("Do four", {"b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}, at="2026-10-13T09:00:00Z")
|
||||
last = self.commit("Answer stability round 1: 0 🔴, 0 🟡 (0 misread)", {"c.py": "c\n"}, at="2026-10-13T09:00:00Z")
|
||||
fixed = self.commit("Fix six", {"b.py": "x\nY\n", "todo.md": todo(5, 7, 8)}, at="2026-10-13T10:00:00Z")
|
||||
self.assertEqual(self.fixes()[f"{first}^..{last}"], (fixed,))
|
||||
|
||||
def test_holds_each_chunks_commit_titles_and_landing_time(self):
|
||||
self.git("switch", "-q", "-c", "four")
|
||||
self.commit("Do four", {"b.py": "x\n", "todo.md": todo(5, 6, 7, 8)})
|
||||
self.git("switch", "-q", "main")
|
||||
self.env.update({"GIT_COMMITTER_DATE": "2026-10-14T10:00:00Z", "GIT_AUTHOR_DATE": "2026-10-14T10:00:00Z"})
|
||||
self.git("merge", "-q", "--no-ff", "-m", "Merge four", "four")
|
||||
merged = self.git("rev-parse", "--short", "HEAD").strip()
|
||||
newest = later_fixes("main", cwd=str(self.checkout))[0]
|
||||
self.assertEqual(newest, Landed(merged, "2026-10-14T10:00:00Z", frozenset({"Do four", "Merge four"}), ()))
|
||||
|
||||
def test_reads_paths_from_the_checkouts_top_when_run_in_a_folder_of_it(self):
|
||||
(self.checkout / "sub").mkdir()
|
||||
shipped = self.chunk("four", ("Do four", {"sub/b.py": "x\ny\n", "todo.md": todo(5, 6, 7, 8)}))
|
||||
fixed = self.chunk("six", ("Fix six", {"sub/b.py": "x\nY\n", "todo.md": todo(5, 7, 8)}))
|
||||
found = later_fixes("main", cwd=str(self.checkout / "sub"))
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual({landed.label: landed.fixed_by for landed in found}[shipped], (fixed,))
|
||||
|
||||
def test_fails_where_git_cannot_read_the_branch(self):
|
||||
self.assertIsInstance(later_fixes("missing", cwd=str(self.checkout)), Failure)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,18 +8,19 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from score_outcomes.anchors import anchor_lines, parse_anchors
|
||||
from score_outcomes.main import chunk_log, report_text
|
||||
from score_outcomes.results import chunk_log, Landing, nearest, rank_correlation, render, report, Result, results_of, shipped
|
||||
from failure import Failure
|
||||
from round_titles import Findings
|
||||
from test_env import isolated_env
|
||||
from todo_table import Item
|
||||
from score_outcomes.results import Landing, nearest, rank_correlation, render, report, Result, results_of, shipped
|
||||
from score_outcomes.main import report_text
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
|
||||
HEADER = "| ID | Release | Exempt | Item | R | S | C | 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 | 10 | 6 | 7 | 1 | 9.0 |"
|
||||
SECOND = "| 5 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |"
|
||||
FIX = "| 6 | 0.1.0 | defect | **Fix it.** | 1 | 1 | 1 | 6 | 7 | 1 | 9.0 |"
|
||||
|
||||
|
||||
def todo(*rows: str, header: str = HEADER) -> str:
|
||||
@@ -30,8 +31,8 @@ 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, landed: Landing = "merge", misread: int | None = None, merge: str = "aaaaaaa") -> 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), landed)
|
||||
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, landed: 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), landed, fixed_by)
|
||||
|
||||
|
||||
class Shipped(unittest.TestCase):
|
||||
@@ -77,12 +78,12 @@ 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([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge")
|
||||
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge"))
|
||||
found = results_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge", ("def5678",))
|
||||
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",)))
|
||||
self.assertEqual(found[1].shipped_with, (4,))
|
||||
|
||||
def test_measures_no_chunk_that_changed_only_the_plan(self):
|
||||
self.assertEqual(results_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge"), [])
|
||||
self.assertEqual(results_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge", ()), [])
|
||||
|
||||
|
||||
class Nearest(unittest.TestCase):
|
||||
@@ -140,20 +141,24 @@ class Render(unittest.TestCase):
|
||||
self.assertTrue(render(result(4, 3, 3, None, levels={"L": 2, "E": 2, "I": 1})).startswith("- Item 4, L 2, E 2, I 1, R 3, S 3:"))
|
||||
|
||||
def test_names_the_items_shipped_together_and_unknown_findings(self):
|
||||
self.assertEqual(render(result(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
|
||||
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 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
|
||||
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(result(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
|
||||
self.assertEqual(render(result(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
|
||||
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_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"))))
|
||||
|
||||
def test_gives_the_misread_count_where_the_round_titles_do(self):
|
||||
self.assertIn("1 round past each pass's first, 1 🔴, 2 🟡 (1 misread); merged", render(result(4, 2, 3, None, findings=(1, 2), misread=1)))
|
||||
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡 (0 misread); merged", render(result(4, 2, 3, None, misread=0)))
|
||||
self.assertIn("1 round past each pass's first, 1 🔴, 2 🟡 (1 misread), 0 later fixes; merged", render(result(4, 2, 3, None, findings=(1, 2), misread=1)))
|
||||
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡 (0 misread), 0 later fixes; merged", render(result(4, 2, 3, None, misread=0)))
|
||||
|
||||
def test_gives_a_rebase_merged_chunks_rounds_and_findings_as_lower_bounds(self):
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
|
||||
self.assertIn("at least 1 round past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(result(4, 2, 3, None, findings=None, landed="rebase")))
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
|
||||
self.assertIn("at least 1 round past each pass's first, findings unknown, 0 later fixes; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(result(4, 2, 3, None, findings=None, landed="rebase")))
|
||||
|
||||
def test_says_a_chunk_never_replayed_may_be_part_of_a_pull_request(self):
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
|
||||
|
||||
|
||||
ANCHORS_TEXT = "# Score anchors\n\nWhy these.\n\n| Level | Items |\n|---|---|\n| L 1 | 4, 9 |\n| I 3 | 5 |\n"
|
||||
@@ -179,7 +184,7 @@ class Anchors(unittest.TestCase):
|
||||
|
||||
def test_lists_each_anchor_with_what_its_chunk_measured_and_says_which_it_cannot_find(self):
|
||||
lines = anchor_lines([("L 1", (4, 9))], [result(4, 2, 3, None, findings=(1, 2))])
|
||||
self.assertEqual(lines, ["L 1:", "- Item 4, R 2, S 3: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**", "- Item 9: no chunk shipped it."])
|
||||
self.assertEqual(lines, ["L 1:", "- Item 4, R 2, S 3: 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.**", "- Item 9: no chunk shipped it."])
|
||||
|
||||
def test_points_to_the_rules_where_the_project_names_no_anchors(self):
|
||||
self.assertIn("docs/score-anchors.md", anchor_lines([], [])[0])
|
||||
@@ -195,13 +200,13 @@ class ReportText(unittest.TestCase):
|
||||
too_few = "such chunks record"
|
||||
self.assertEqual(report_text(found, [("L 1", (2,))], {"L": 1, "E": 1, "I": 1, "S": 3}), f"""Finished items nearest L 1, E 1, I 1, so R 1, and S 3, closest first:
|
||||
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
- Item 1, R 5, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 1.**
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
- Item 1, R 5, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 1.**
|
||||
|
||||
Anchors in docs/score-anchors.md, each level's shipped items:
|
||||
|
||||
L 1:
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
|
||||
Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:
|
||||
|
||||
@@ -213,7 +218,11 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
|
||||
|
||||
🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:
|
||||
|
||||
- None: no chunk's round titles count them.""")
|
||||
- None: no chunk's round titles count them.
|
||||
|
||||
Later fixes, the later chunks that fixed code each finished chunk shipped, newest first:
|
||||
|
||||
- None: no later chunk fixed code a finished chunk shipped.""")
|
||||
|
||||
def test_lists_each_chunks_findings_with_their_misread_count_newest_first_once_per_chunk(self):
|
||||
found = [result(1, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,)), result(2, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,)), result(3, 5, 3, None, findings=(0, 4), misread=0, merge="ccccccc", merged="2026-10-14T10:00:00Z", landed="rebase"), result(4, 5, 3, None)]
|
||||
@@ -222,6 +231,14 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
|
||||
- 2026-10-14T10:00:00Z in ccccccc: at least 0 🔴, 4 🟡 (0 misread)
|
||||
- 2026-10-12T10:00:00Z in bbbbbbb: 1 🔴, 2 🟡 (1 misread)""", report_text(found, [], None))
|
||||
|
||||
def test_lists_each_chunks_later_fixes_newest_first_once_per_chunk_then_counts_the_others(self):
|
||||
found = [result(1, 5, 3, None, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,), fixed_by=("ddddddd",)), result(2, 5, 3, None, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,), fixed_by=("ddddddd",)), result(3, 5, 3, None, merge="ccccccc", merged="2026-10-14T10:00:00Z", fixed_by=("eeeeeee", "ddddddd")), result(4, 5, 3, None), result(5, 5, 3, None, merge="fffffff")]
|
||||
self.assertTrue(report_text(found, [], None).endswith("""Later fixes, the later chunks that fixed code each finished chunk shipped, newest first:
|
||||
|
||||
- 2026-10-14T10:00:00Z in ccccccc: 2 later fixes, by eeeeeee and ddddddd
|
||||
- 2026-10-12T10:00:00Z in bbbbbbb: 1 later fix, by ddddddd
|
||||
- The other 2 finished chunks: none."""))
|
||||
|
||||
def test_ends_with_how_it_reads_chunks_merged_by_rebase_only_where_it_measured_one(self):
|
||||
text = report_text([result(1, 5, 3, None, landed="rebase")], [], None)
|
||||
self.assertIn("\n\nChunks that left no merge commit:\n\n- Each is the run of commits", text.split("Median outcome")[1])
|
||||
@@ -302,9 +319,24 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
ran = self.run_tool("1", "2", "1", "3")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("Finished items nearest L 1, E 2, I 1, so R 2, and S 3, closest first:", ran.stdout)
|
||||
self.assertIn("- Item 4, R 2, S 3, C 10: 3 lines in 1 file, 0 rounds past each pass's first, 1 🔴, 2 🟡; merged ", ran.stdout)
|
||||
self.assertIn("- Item 4, R 2, S 3, C 10: 3 lines in 1 file, 0 rounds past each pass's first, 1 🔴, 2 🟡, 0 later fixes; merged ", ran.stdout)
|
||||
self.assertNotIn("Item 5", ran.stdout)
|
||||
|
||||
def test_counts_a_later_chunk_that_ships_a_defect_item_and_rewrites_a_line_a_chunk_shipped(self):
|
||||
self.commit("File a fix", {"todo.md": todo(FIRST, SECOND, FIX)})
|
||||
self.git("switch", "-q", "-c", "chunk")
|
||||
self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND, FIX)})
|
||||
self.git("switch", "-q", "main")
|
||||
shipped = self.merge_branch("chunk", "2026-10-13T10:00:00Z")
|
||||
self.git("switch", "-q", "-c", "fix")
|
||||
self.commit("Fix it", {"a.py": "1\n2\n4\n", "todo.md": todo(SECOND)})
|
||||
self.git("switch", "-q", "main")
|
||||
fixed = self.merge_branch("fix", "2026-10-14T10:00:00Z")
|
||||
ran = self.run_tool("1", "2", "1", "3")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn(f"findings unknown, 1 later fix; merged 2026-10-13T10:00:00Z in {shipped}. **Do it.**", ran.stdout)
|
||||
self.assertIn(f"- 2026-10-13T10:00:00Z in {shipped}: 1 later fix, by {fixed}\n- The other 1 finished chunk: none.", ran.stdout)
|
||||
|
||||
def run_on_rebased_history(self):
|
||||
self.commit("Re-score item 4", {"todo.md": todo(FIRST.replace("| 2 | 3 |", "| 1 | 3 |"), SECOND)}, at="2026-10-13T08:00:00Z")
|
||||
first = self.commit("Score item 4 higher", {"todo.md": todo(FIRST, SECOND)}, at="2026-10-13T09:00:00Z")
|
||||
@@ -328,11 +360,11 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
|
||||
def test_labels_a_run_of_commits_that_kept_their_author_time_never_replayed(self):
|
||||
stdout, _, _, _, pushed = self.run_on_rebased_history()
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown; committed 2026-10-13T11:00:00Z in {pushed}, never replayed, so perhaps part of a pull request. **Then this.**", stdout)
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown, 0 later fixes; committed 2026-10-13T11:00:00Z in {pushed}, never replayed, so perhaps part of a pull request. **Then this.**", stdout)
|
||||
|
||||
def test_measures_a_rebase_run_at_one_commit_time_as_one_chunk_whose_rounds_read_at_least(self):
|
||||
_, item_4, first, last, _ = self.run_on_rebased_history()
|
||||
self.assertIn(f"at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", item_4)
|
||||
self.assertIn(f"at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", item_4)
|
||||
|
||||
def test_explains_the_chunks_that_left_no_merge_commit_after_a_rebase(self):
|
||||
stdout, _, _, _, _ = self.run_on_rebased_history()
|
||||
@@ -346,8 +378,8 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
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.assertRegex(ran.stdout, r"- Item 4, R 2, S 3, C 10: 1 line in 1 file, 0 rounds past each pass's first, findings unknown; merged \S+ in [0-9a-f]{7,}\. ")
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown; committed 2026-10-12T09:00:00Z in {drop}, never replayed, so perhaps part of a pull request. **Then this.**", ran.stdout)
|
||||
self.assertRegex(ran.stdout, r"- Item 4, R 2, S 3, C 10: 1 line in 1 file, 0 rounds past each pass's first, findings unknown, 0 later fixes; merged \S+ in [0-9a-f]{7,}\. ")
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown, 0 later fixes; committed 2026-10-12T09:00:00Z in {drop}, never replayed, so perhaps part of a pull request. **Then this.**", ran.stdout)
|
||||
self.assertNotIn("by rebase", ran.stdout)
|
||||
|
||||
def test_labels_a_merge_merge_even_when_its_author_and_commit_times_are_equal(self):
|
||||
@@ -384,7 +416,7 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
self.merge_branch("other", "2026-10-13T10:00:00Z")
|
||||
ran = self.run_tool("1", "2", "1", "3")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn(f"- Item 4, R 2, S 3, C 10: 3 lines in 1 file, at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", ran.stdout)
|
||||
self.assertIn(f"- Item 4, R 2, S 3, C 10: 3 lines in 1 file, at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", ran.stdout)
|
||||
|
||||
def test_lists_the_projects_anchors_with_what_their_chunks_measured(self):
|
||||
self.git("switch", "-q", "-c", "chunk")
|
||||
|
||||
+2
-2
@@ -157,7 +157,7 @@ Valid while no published standard sets either number, the reading-cost window st
|
||||
|
||||
rule-hook's `round-cap` refuses a round commit that would take its pass past round 2, and no override waives it. It counts the pass's round commits on the branch as `larv-review round-count` does, so a third commit titled round 2 is refused too. The hook must not fetch, so it lists the branch's commits since the default branch as last fetched. It follows first parents, so the round commits that a merge of a newer default branch brought in don't count as this chunk's. It leaves out the commit an `--amend` replaces. Where git cannot list the branch's commits, within 5 seconds or because origin records no default branch, it counts the title's own number alone, so a slow or unset lookup doesn't block the commit.
|
||||
|
||||
Valid while the defects that later commits fix in a finished chunk's code, which `todo.md` item 247 counts, don't rise per chunk.
|
||||
Valid while a finished chunk's later fixes, which `score-outcomes` and the routing figures count, don't rise per chunk.
|
||||
|
||||
## review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
|
||||
|
||||
@@ -183,7 +183,7 @@ Valid while the ladder orders its rungs by competence.
|
||||
|
||||
## review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
|
||||
|
||||
2026-10-23, claude. Serves code health (`CLAUDE.md` → "Shared goal"): its counter-signal, reviewers raising blockers because the implementer misunderstood the current system, had no count, since no tool recorded why a finding arose. The reviewer is the one that knows, so it marks the finding (`skills/larv-review/review-findings.md` → "Misread"). The worker counts the marked 🔴 and 🟡 findings in the round's commit title, `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, which `score-outcomes` already reads for the 🔴 and 🟡 counts, so the count needs no record of its own. rule-hook's `round-title-counts` refuses a round title without the count, or with more misread findings than findings, so a title that leaves the count out never reads as zero; titles from before the count read as unknown. Only the reviewers under `agents/` mark findings. `/security-review` marks none, so its round titles count 0 misread, and the count is a floor. A bench of three readers seated as the audience chose `[misread]` right after the severity mark, which stays at a fixed place on a skimmed line, and the parenthesis `(1 misread)`, which reads as a share of the 🔴 and 🟡 counts rather than a third kind of finding, each two to one. The other half of the counter-signal, defects that keep reappearing, waits for the later fixes that `todo.md` item 110 counts. Valid while round titles are where `score-outcomes` reads a chunk's findings.
|
||||
2026-10-23, claude. Serves code health (`CLAUDE.md` → "Shared goal"): its counter-signal, reviewers raising blockers because the implementer misunderstood the current system, had no count, since no tool recorded why a finding arose. The reviewer is the one that knows, so it marks the finding (`skills/larv-review/review-findings.md` → "Misread"). The worker counts the marked 🔴 and 🟡 findings in the round's commit title, `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, which `score-outcomes` already reads for the 🔴 and 🟡 counts, so the count needs no record of its own. rule-hook's `round-title-counts` refuses a round title without the count, or with more misread findings than findings, so a title that leaves the count out never reads as zero; titles from before the count read as unknown. Only the reviewers under `agents/` mark findings. `/security-review` marks none, so its round titles count 0 misread, and the count is a floor. A bench of three readers seated as the audience chose `[misread]` right after the severity mark, which stays at a fixed place on a skimmed line, and the parenthesis `(1 misread)`, which reads as a share of the 🔴 and 🟡 counts rather than a third kind of finding, each two to one. The other half of the counter-signal, defects that keep reappearing, is each chunk's later fixes, which `score-outcomes` lists after the misread findings. Valid while round titles are where `score-outcomes` reads a chunk's findings.
|
||||
|
||||
## review: an ask no user answers leaves the PR unmerged
|
||||
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ paths:
|
||||
- **Name in Moves each achieve goal in `README.md` → `## Goals` the item moves, and how far,** from 1 to 10, judged by its value to the audience in `## Audience`: `1.1 by 8, 1.2 by 5`. Where the item moves code health, the goal in `CLAUDE.md` → "Shared goal", name it as in `code health by 6`, unless the README voids it. Name the most specific goal it moves, and a parent goal only for a move none of its sub-goals covers, never beside its own sub-goal. Leave out every maintain goal, which vetoes, except on an item marked `defect` that restores it: name that goal, and how much of it is broken. `rank_todo.py --help` says how it weighs each goal.
|
||||
- **A table with C, A, G and Goals in place of L, E, I and Moves is in the old shape.** Reshaping it is the project's only work until done, as `CLAUDE.md` → "Working loop" says, and `rank_todo.py` says how. Until then, A is the item's value to the audience and G its value to the goals it cites.
|
||||
- **Score L, E and I against the project's anchors, and check every score against finished chunks.** Guess the scores, then run `~/.claude/bin/score-outcomes <L> <E> <I> <S>` in the project. It lists the finished items guessed nearest and the project's anchors, the shipped items its `docs/score-anchors.md` names for each level, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings. Compare the item with each anchor in turn: is it more or less likely to hold a defect, to let one escape, or to do damage? Give it the level whose anchors it matches; where a level has no anchor, judge by the level's words in the table above. Set S to the value guessed for the finished items whose outcome matches what you expect of this one. Keep your guess when no listed item resembles the one you are scoring.
|
||||
- **Anchor each level of L, E and I with two or three items the project shipped,** in `docs/score-anchors.md`: a table whose Level column names a level, such as `L 1`, and whose Items column lists the anchors' IDs, such as `12, 14`. Choose an L anchor whose chunk, as `score-outcomes` measured it, fits the level's words: its lines changed and the components it touched. Choose an E or I anchor by the level's words and what followed its release, since no tool measures either yet. Leave out a level no shipped item shows. Replace a level's anchors when the items scored at it turn out about ten times more likely, or ten times less likely, than its words say: to hold a defect, to let one escape, or to do damage.
|
||||
- **Anchor each level of L, E and I with two or three items the project shipped,** in `docs/score-anchors.md`: a table whose Level column names a level, such as `L 1`, and whose Items column lists the anchors' IDs, such as `12, 14`. Choose an L anchor whose chunk, as `score-outcomes` measured it, fits the level's words: its lines changed and the components it touched. Choose an E anchor by the level's words and the later fixes `score-outcomes` counts for its chunk, the defects that escaped it. Choose an I anchor by the level's words and what followed its release, since no tool measures I yet. Leave out a level no shipped item shows. Replace a level's anchors when the items scored at it turn out about ten times more likely, or ten times less likely, than its words say: to hold a defect, to let one escape, or to do damage.
|
||||
- **Read the places the comprehension seats found hard before filing an item.** `~/.claude/bin/larv-review places`, run in the project, prints them. Where the item's change touches one, its detail says to make that place easier to read.
|
||||
- **An item scoring under the bar is deleted, with every item that needs it, and a finding under the bar is not filed.** The chunk's summary names each, with its score.
|
||||
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding or an item that restores a maintain goal the project breaks today, `question` for a question only the human can answer, which ranks first in its release, `decision` for an item `docs/decisions.md` cites, `owner` for an item the human told you to keep, and, where no other reason fits, `principle` for a 🟡 finding against a file under `~/.claude/principles/`, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
|
||||
|
||||
@@ -6,13 +6,13 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 251`
|
||||
`Next ID = 252`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 247 | 0.4.0 | | owner | **Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 4 | 1.7 |
|
||||
| 251 | 0.4.0 | | defect | **Have `file_at` in `bin/git_repo.py` read a path from the checkout's top, so `score-outcomes` run in a subfolder of a checkout reads its todo.md.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 243 | 0.4.0 | | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.9 |
|
||||
| 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 |
|
||||
| 248 | 0.5.0 | | question | **Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason.** | 1 | 2 | 1 | 2 | 1 | 1.2 by 2 | 3.3 |
|
||||
@@ -47,7 +47,6 @@
|
||||
| 81 | 0.6.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 5.6 |
|
||||
| 173 | 0.6.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 |
|
||||
| 101 | 0.6.0 | | principle | **Have `larv_review/history_commands.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 5.3 |
|
||||
| 110 | 0.6.0 | | decision | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.** | 3 | 2 | 2 | 5 | 5 | 1.1 by 6, 1.4 by 6 | 4.9 |
|
||||
| 12 | 0.6.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 4.2 |
|
||||
| 102 | 0.6.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 4.2 |
|
||||
| 135 | 0.6.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 4.2 |
|
||||
@@ -79,9 +78,9 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 247. Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures.
|
||||
### 251. Have `file_at` in `bin/git_repo.py` read a path from the checkout's top, so `score-outcomes` run in a subfolder of a checkout reads its todo.md.
|
||||
|
||||
lilleman's call, 2026-10-28. Escaped defects are the counter-signal of goals 1 and 1.1, and nothing counts them, so nobody can tell whether review spending prevents defects or only polishes. A review costs about 56% of a chunk's dollars. Count, for each finished chunk, the later commits on the default branch that fix lines it added: a fix item's chunk, a `defect` item, or a 🔴 marked `[misread]` whose lines `git blame` traces to the earlier chunk. Show the count per chunk and its median per rung in `score-outcomes` and `routing-figures.md`, so a cheaper review pipeline can be judged against it. Measure on every project in loop-claude's archive.
|
||||
Found while building item 247, 2026-10-28. `file_at` lists the path with `git ls-tree <revision> -- <path>`, which reads the path relative to the current directory. Run from `bin/`, `score-outcomes` finds no `todo.md` at any commit, and lists every anchor as shipped by no chunk instead of failing. `bin/larv_review/history_changes.py` calls `file_at` the same way. `ls-tree --full-tree` reads the path from the top, as `git show <revision>:<path>` already does.
|
||||
|
||||
### 243. Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.
|
||||
|
||||
@@ -244,10 +243,6 @@ Raised by the overrides pass of PR #296. The hook imports the main checkout's `r
|
||||
|
||||
Found by the principles audit of PR #242, against "Functional core, imperative shell" (`principles/technical-principles.md`). `bin/larv_review/history_commands.py:87` reads `time.time()`, then checks git (`:90`, `commit_exists`) and the history file (`:92`) inside the function that parses the seats file and decides. A test cannot fix the heading's time, and every test of `read_seats` touches the real checkout.
|
||||
|
||||
### 110. Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.
|
||||
|
||||
`score-outcomes` measures risk only by the 🔴 findings review caught. A serious bug review missed shows later, as a change that fixes code the chunk wrote: the defect that escaped, which E guesses.
|
||||
|
||||
### 12. Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.
|
||||
|
||||
The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word.
|
||||
|
||||
Reference in New Issue
Block a user