diff --git a/.gitignore b/.gitignore index 56844725..aa816f7a 100644 --- a/.gitignore +++ b/.gitignore @@ -57,6 +57,9 @@ !bin/score_outcomes/ !bin/score_outcomes/*.py !bin/shell_command.py +!bin/stability-replay +!bin/stability_replay/ +!bin/stability_replay/*.py !bin/statusline.py !bin/subagent-rung !bin/subagent_rung/ diff --git a/AGENTS.md b/AGENTS.md index 05ce09f4..f9432252 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ Decisions live in `docs/decisions.md`: - routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's R + C picks a rung by fixed bands, counted from the cheapest rung of the project's model, and a chunk's worker may run below that rung, launching its reviewers on that rung; the worker routes each subagent it delegates to by the R + C of the subagent's task - routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it - routing: on a model judge-replay covered, the judge runs on the rung its chunk's item picks, never below the project's rung +- routing: the stability reviewer stays on the project's rung while the worker runs below it, until `stability-replay` finds a rung below it that finds every šŸ”“ and 🟔 the project's rung finds ## Working rules diff --git a/CHANGELOG.md b/CHANGELOG.md index 416470a1..479b5475 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- The new `bin/stability-replay ` replays archived stability reviews of the projects run on the model, each on the code it reviewed, first on the project's rung and then on each rung below, and prints the lowest rung that finds every šŸ”“ and 🟔 finding the project's rung finds. Its first run, on Opus 5.5 projects, found none: Sonnet 5.5 at high missed 13 of 29. So the stability reviewer stays on the project's rung while the worker runs below it. - A `loop-claude` worker hands a task that proves too hard for its rung to a subagent one rung up, edits included, when a trigger fires: a re-score of the item on the project's rung or above picks a higher rung, the same failing test or finding survives two fix attempts, or a review pass reports a šŸ”“ in round 2 or later. Each further trigger climbs one more rung, to at most two rungs above the rung the chunk's `todo.md` item picks, unless you agree. `CLAUDE.md` states the rule, and `loop-claude`'s prompt names the rungs a trigger opens. The worker opens the subagent's prompt with `Escalation trigger :`, and `routing-figures.md` counts the escalations by trigger. Expect a chunk that gets stuck to spend more on the stuck part, and fewer unfinished verdicts. - A reviewer that rules a chunk's work below standard, with systems-architect's BLOCK or a finding against larv-review's `standards/quality.md`, may ask to rerun one rung up, as may a comprehension seat whose vote in a paired ruling `record-ruling` counts as worse. The worker relaunches it once, on the rung `loop-claude`'s prompt names. A relaunched reviewer gets the report that asked and confirms or dismisses each of its findings. The relaunch's report stands in place of the one that asked, in the same round, so it adds no round. The ruling that stands is a fourth escalation trigger in `CLAUDE.md`. Expect a chunk whose work falls below standard to spend more on its review and its fix. - A session or subagent below the project's rung, the cheapest rung of the project's model, no longer scores or reshapes `todo.md`: it drafts each new item and each change to a filed item, and before its next commit one subagent on the project's rung or above applies and scores the drafts and sets their release. It may still remove finished items. `rules/todo-items.md` states the rule. `CLAUDE.md` has a session launch a subagent that files or scores items on the rung the new `bin/subagent-rung --plan ` prints, never below the project's rung, and `loop-claude`'s prompt to a worker below that rung names the command. Expect one extra subagent in a chunk that files items while its worker runs below the project's rung. diff --git a/bin/stability-replay b/bin/stability-replay new file mode 100755 index 00000000..8e99c648 --- /dev/null +++ b/bin/stability-replay @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 +import os +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from stability_replay import main +from loop_claude.effects import system_effects + +sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects())) diff --git a/bin/stability_replay/__init__.py b/bin/stability_replay/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/stability_replay/main.py b/bin/stability_replay/main.py new file mode 100644 index 00000000..158aa594 --- /dev/null +++ b/bin/stability_replay/main.py @@ -0,0 +1,226 @@ +"""Replay archived stability rounds on the rungs below the project's, to find which rungs may run the stability reviewer: docs/decisions.md → `routing: the stability reviewer stays on the project's rung`. + +usage: stability-replay + + is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the +latest 10 archived stability rounds whose report holds a šŸ”“ or 🟔 finding, from the projects that +~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it +reviewed: in a throwaway clone of the project's checkout, at the newest commit of origin/HEAD +authored by the time the round began, on the branch the reviewer started on. The clone's default +branch stands at the newest commit authored before the round's chunk began, so a diff against it +shows the chunk's change. The prompt names the clone in place of the worktree it named, which the +chunk has since removed. A round whose code it cannot find in this way is not replayed. + +It first replays every round on the reference reviewer, the project's rung, which the reviewer +runs on while the worker runs below it. Findings it does not find may rest on code or rules that +have changed since; either way no rung is held to them. It then replays the rest on each rung +below, highest first, down to the rung the lowest R + C picks, and stops at the first rung that +misses one. The project's rung decides, for each replay, which findings on record it reports as +šŸ”“ or 🟔. The tool prints each finding a rung missed and the lowest rung that missed none. Such a +rung is the evidence to route the stability reviewer onto the worker's rung down to it, which +docs/decisions.md → `routing: the stability reviewer stays on the project's rung` records. + +Like the loop, it tries claude three times running before it counts a reply as failed. A failed +review or match finds nothing. Exit 1, saying why, on bad arguments, an unreadable archive or +models file, no archived round to replay, or a usage limit. +""" +import concurrent.futures +import dataclasses +import json +import os +import pathlib +import shutil +import sys +import tempfile +import typing + +from claude_code.entries import hit_limit, limit_said, parse_entry, structured_output +from claude_code.transcript import first_timestamped_line, read_transcript +from failure import Failure +from loop_claude.cycle.retry import first_reply, Limited +from loop_claude.effects import Effects +from loop_claude.project.model_choice import read_models_file +from loop_claude.stop import Stop +from model_routing.ladder import LADDER, picked, position, project_rung, Rung +from project_key import checkout_of +from stability_replay.rounds import authored_by, replayed, report, reviewed_path, Round, round_from, sample, stamp_seconds +from transcript_archive.location import archive_root + +LATEST = 10 +# Reviews replayed at once. +AT_ONCE = 4 +LOWEST_R_PLUS_C = 2 +REVIEWER = "stability-reviewer" +USAGE = "usage: stability-replay , a model on the routing ladder" +MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False} + + +@dataclasses.dataclass(frozen=True) +class Code: + """Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began.""" + path: str + reviewed: str + default: str + base: str + + +def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + anchor = project_rung(argv[0]) if len(argv) == 1 else None + if anchor is None: + print(f"stability-replay: cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; {USAGE}", file=sys.stderr) + return 1 + rounds = archived_rounds(argv[0], archive_root(home, env), home) + if isinstance(rounds, Failure): + print(f"stability-replay: {rounds.reason}", file=sys.stderr) + return 1 + codes = {found: code for found in rounds if not isinstance(code := code_of(found, effects), Failure)} + if not codes: + print(f"stability-replay: no archived stability round of projects on {argv[0]} in {archive_root(home, env)} holds a šŸ”“ or 🟔 on code it can find", file=sys.stderr) + return 1 + chosen = sample(list(codes), LATEST) + candidates = list(LADDER[position(picked(anchor, LOWEST_R_PLUS_C)):position(anchor)])[::-1] + replay = replayed(chosen, anchor, candidates, lambda on, rung: review_all([(found, codes[found]) for found in on], rung, anchor, effects)) + if isinstance(replay, Limited): + print(f"stability-replay: claude hit a usage limit: {replay.said}; replay again once it resets", file=sys.stderr) + return 1 + print(report(argv[0], anchor, chosen, replay)) + return 0 + + +def archived_rounds(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure: + models = read_models_file(home / ".claude" / "loop-claude-models.json") + if isinstance(models, Stop): + return Failure(models.reason) + found = [] + try: + for key in sorted(key for key, on in models.items() if on == model): + for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()): + found += chunk_rounds(checkout_of(key, home), chunk) + except (OSError, UnicodeDecodeError, ValueError) as failure: + return Failure(f"could not read the archive {root}: {failure}") + return found + + +def chunk_rounds(checkout: str, chunk: pathlib.Path) -> list[Round]: + copies = sorted(chunk.glob("*.jsonl")) + began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None + if not began or not isinstance(began.get("timestamp"), str): + return [] + found = [] + for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")): + if json.loads(meta.read_text(encoding="utf-8")).get("agentType") != REVIEWER: + continue + entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl"))) + if not isinstance(entries, Failure) and (one := round_from(checkout, stamp_seconds(began["timestamp"]), entries)): + found.append(one) + return found + + +def code_of(found: Round, effects: Effects) -> Code | Failure: + path = reviewed_path(found.prompt, found.root, os.path.exists) + if path is None: + return Failure("the prompt names no one worktree") + default = git(effects, found.root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD") + if isinstance(default, Failure): + return default + default = default.strip().removeprefix("origin/") + log = git(effects, found.root, "log", "--format=%H %at", "refs/remotes/origin/HEAD") + main_line = git(effects, found.root, "log", "--first-parent", "--format=%H %at", "refs/remotes/origin/HEAD") + if isinstance(log, Failure): + return log + if isinstance(main_line, Failure): + return main_line + reviewed, base = authored_by(commit_log(log), found.seconds), authored_by(commit_log(main_line), found.began) + if reviewed is None or base is None: + return Failure("no commit was authored by then") + return Code(path, reviewed, default, base) + + +def commit_log(listed: str) -> list[tuple[str, float]]: + return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())] + + +def review_all(on: list[tuple[Round, Code]], rung: Rung, anchor: Rung, effects: Effects) -> list[set[int]] | Limited: + print(f"replaying {len(on)} stability rounds on {rung}", file=sys.stderr, flush=True) + with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool: + running = [pool.submit(findings_found, found, code, rung, anchor, effects) for found, code in on] + found_sets = [] + for future in running: + found = future.result() + if isinstance(found, Limited): + pool.shutdown(cancel_futures=True) + return found + found_sets.append(found) + return found_sets + + +def findings_found(found: Round, code: Code, rung: Rung, anchor: Rung, effects: Effects) -> set[int] | Limited: + """The indexes of the round's findings that its replay on rung reports, as the reviewer on anchor matches them.""" + reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, effects)) + if isinstance(reviewed, Limited): + return reviewed + matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, anchor, effects)) + if isinstance(matched, Failure): + print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True) + return set() + return matched + + +def review(found: Round, code: Code, rung: Rung, effects: Effects) -> str | Failure | Limited: + clone = tempfile.mkdtemp(prefix="stability-replay-") + try: + for command in ( + ("clone", "--quiet", "--shared", "--no-checkout", found.root, clone), + ("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base), + ("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base), + ("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed), + ): + if isinstance(ran := git(effects, found.root, *command), Failure): + return ran + args = ["-p", "--agent", REVIEWER, *rung.flags(), "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"] + reply = claude_reply(effects, args, clone, found.prompt.replace(code.path, clone)) + if isinstance(reply, Failure | Limited): + return reply + return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report") + finally: + shutil.rmtree(clone, ignore_errors=True) + + +def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited: + numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1)) + prompt = ( + "A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. " + "List the number of each finding that the other report also raises as šŸ”“ or 🟔: the same defect, at the same place or from the same cause, however it is worded. " + "A finding it raises only as 🟢 or ā“, or not at all, is not listed.\n\n" + f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}" + ) + args = ["-p", "--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions", "--tools", ""] + reply = claude_reply(effects, args, root, prompt) + if isinstance(reply, Failure | Limited): + return reply + output = structured_output(reply) + numbers = output.get("found") if isinstance(output, dict) else None + if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers): + return Failure(f"the match replied: {json.dumps(reply)}") + return {n - 1 for n in numbers if 1 <= n <= len(findings)} + + +def claude_reply(effects: Effects, args: list[str], cwd: str, prompt: str) -> dict | Failure | Limited: + try: + proc = effects.claude(args, cwd, prompt) + except OSError as failure: + return Failure(f"could not start claude: {failure.strerror}") + reply = parse_entry(proc.stdout) or {} + if hit_limit(reply): + return Limited(None, limit_said(reply)) + if proc.returncode != 0: + return Failure(proc.stderr.strip() or f"claude exited {proc.returncode}") + return reply + + +def git(effects: Effects, cwd: str, *args: str) -> str | Failure: + ran = effects.git(list(args), cwd) + return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}") diff --git a/bin/stability_replay/rounds.py b/bin/stability_replay/rounds.py new file mode 100644 index 00000000..e0668e42 --- /dev/null +++ b/bin/stability_replay/rounds.py @@ -0,0 +1,137 @@ +"""Which archived stability rounds to replay, the lowest rung that finds their findings, and the report: docs/decisions.md → `routing: the stability reviewer stays on the project's rung`.""" +import dataclasses +import datetime +import pathlib +import re +import typing + +from claude_code.entries import assistant_parts, content, part_text, parts +from loop_claude.cycle.retry import Limited +from model_routing.ladder import Rung + +# A line that opens with a šŸ”“ or 🟔 mark, after any list, table, heading or bold markup, as review-findings.md has reviewers report them. +FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:šŸ”“|🟔)") +# An absolute path in a prompt, up to the quote, bracket or punctuation that ends it. +PATH = re.compile(r"/[^\s`'\"()<>\[\],;]+") +LINE_OR_STOP = re.compile(r"(?::\d+(?:-\d+)?)?[.:]?$") + + +@dataclasses.dataclass(frozen=True) +class Round: + """One archived stability review of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the šŸ”“ and 🟔 findings its report holds, each with its lines up to the next blank line or finding.""" + root: str + branch: str + at: str + seconds: float + began: float + prompt: str + findings: tuple[str, ...] + + +@dataclasses.dataclass(frozen=True) +class Tried: + """A rung, and each finding it missed that the reference reviewer found, with its round.""" + rung: Rung + missed: list[tuple[Round, str]] + + +@dataclasses.dataclass(frozen=True) +class Replay: + """unfound counts the findings on record the reference reviewer did not find; tried holds each rung tried, highest first; lowest, the lowest rung that missed none of the rest, or None.""" + unfound: int + tried: list[Tried] + lowest: Rung | None + + +def round_from(root: str, began: float, entries: list[dict]) -> Round | None: + """The round a stability reviewer's transcript holds: its first entry's prompt, and its last text. None without a šŸ”“ or 🟔 finding to hold a rung to.""" + reports = [text for found in entries for part in assistant_parts(found) if (text := part_text(part))] + first = entries[0] if entries else {} + if not isinstance(first.get("timestamp"), str) or not reports or not (findings := recorded_findings(reports[-1])): + return None + prompt = content(first) + prompt = prompt if isinstance(prompt, str) else "".join(part_text(part) or "" for part in parts(first)) + return Round(root, first.get("gitBranch", ""), first["timestamp"], stamp_seconds(first["timestamp"]), began, prompt, tuple(findings)) + + +def stamp_seconds(stamp: str) -> float: + return datetime.datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp() + + +def recorded_findings(report_text: str) -> list[str]: + findings: list[list[str]] = [] + open_finding = False + for line in report_text.splitlines(): + if FINDING.match(line): + findings.append([line]) + open_finding = True + elif open_finding and line.strip(): + findings[-1].append(line) + else: + open_finding = False + return ["\n".join(lines) for lines in findings] + + +def reviewed_path(prompt: str, root: str, exists: typing.Callable[[str], bool]) -> str | None: + """Where the reviewer read the code: the one gone directory the prompt names beside the checkout or inside it, as a removed worktree, else the checkout when the prompt names it; None when it names neither, or two gone ones.""" + checkout = pathlib.PurePath(root) + # A path that ends a sentence or names a line, such as /code/p/a.py:3, loses that ending. + named = [LINE_OR_STOP.sub("", path) for path in PATH.findall(prompt)] + gone = set() + for path in map(pathlib.PurePath, named): + first_gone = next((prefix for prefix in [*reversed(path.parents), path][1:] if not exists(str(prefix))), None) + if first_gone and (first_gone.parent == checkout.parent or checkout in first_gone.parents): + gone.add(str(first_gone)) + if len(gone) == 1: + return gone.pop() + return root if not gone and root in named else None + + +def authored_by(log: list[tuple[str, float]], seconds: float) -> str | None: + """The newest commit of log, newest first, authored by then. A rebase keeps author times, so a merged branch's commits still say what it held.""" + return next((commit for commit, authored in log if authored <= seconds), None) + + +def sample(rounds: list[Round], latest: int) -> list[Round]: + """The latest rounds, in the order they ran.""" + return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:] + + +def replayed(rounds: list[Round], reference: Rung, candidates: list[Rung], review_all: typing.Callable[[list[Round], Rung], list[set[int]] | Limited]) -> Replay | Limited: + """Replays the rounds on the reference rung, then each candidate, highest first, on the rounds where the reference found a finding, until one misses a finding it found. + + Going down, every rung at or above the lowest that missed none was tried. + """ + found = review_all(rounds, reference) + if isinstance(found, Limited): + return found + held = [(found_round, kept) for found_round, kept in zip(rounds, found) if kept] + unfound = sum(len(found_round.findings) for found_round in rounds) - sum(len(kept) for _, kept in held) + tried: list[Tried] = [] + lowest = None + # With no finding to hold a rung to, every rung would miss none. + for rung in candidates if held else []: + found = review_all([found_round for found_round, _ in held], rung) + if isinstance(found, Limited): + return found + tried.append(Tried(rung, [(found_round, found_round.findings[n]) for (found_round, kept), on_rung in zip(held, found) for n in sorted(kept - on_rung)])) + if tried[-1].missed: + break + lowest = rung + return Replay(unfound, tried, lowest) + + +def report(model: str, reference: Rung, rounds: list[Round], replay: Replay) -> str: + total = sum(len(found_round.findings) for found_round in rounds) + lines = [ + f"Replayed {len(rounds)} stability rounds of {model} projects, holding {total} šŸ”“ and 🟔 findings.", + f"The reference reviewer, {reference}, found {total - replay.unfound} of them.", + ] + for tried in replay.tried: + lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *(f" {found_round.root} {found_round.at}: {finding.splitlines()[0]}" for found_round, finding in tried.missed)] + if not replay.tried: + lines.append("No rung tried: the reference reviewer found no finding to hold one to.") + else: + lowest = replay.lowest or "none below the project's rung" + lines.append(f"Lowest rung that finds every finding the reference reviewer finds: {lowest}") + return "\n".join(lines) diff --git a/bin/stability_replay/test_stability_replay.py b/bin/stability_replay/test_stability_replay.py new file mode 100644 index 00000000..603bf399 --- /dev/null +++ b/bin/stability_replay/test_stability_replay.py @@ -0,0 +1,217 @@ +import contextlib +import io +import json +import pathlib +import re +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from loop_claude.cycle.retry import Limited +from loop_claude.effects import Effects, system_effects +from model_routing.ladder import Rung +from stability_replay import main +from stability_replay.rounds import authored_by, recorded_findings, replayed, report, reviewed_path, Round, round_from, sample, Replay, Tried + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "stability-replay" +REFERENCE = Rung("claude-opus-5-5", "medium") +MIDDLE = Rung("claude-sonnet-5-5", "high") +CHEAP = Rung("claude-haiku-5-5", "max") + + +def entry(kind, text, **fields): + return {"type": kind, "message": {"content": [{"type": "text", "text": text}]}, **fields} + + +def a_round(at, findings=("šŸ”“ a",)): + return Round("/code/p", "x", f"2026-10-14T10:00:0{at}Z", at, 0, "Review it.", tuple(findings)) + + +class RecordedFindings(unittest.TestCase): + def test_takes_each_red_and_yellow_finding_with_the_lines_up_to_the_next_blank_line_or_finding(self): + report_text = "BLOCK\n\n1 šŸ”“, 2 🟔 in all.\n\n1. šŸ”“ **Loop** at a.py:3\nnever ends.\n- 🟔 b.py:1 slow\n| 🟔 | c.py | odd |\n\n🟢 nit\n### šŸ”“ Heading\n**🟔 Bold**" + self.assertEqual(recorded_findings(report_text), ["1. šŸ”“ **Loop** at a.py:3\nnever ends.", "- 🟔 b.py:1 slow", "| 🟔 | c.py | odd |", "### šŸ”“ Heading", "**🟔 Bold**"]) + + def test_skips_a_count_or_verdict_line_that_names_the_marks(self): + self.assertEqual(recorded_findings("APPROVE\n\nNo šŸ”“ or 🟔 findings.\n0 šŸ”“, 0 🟔"), []) + + +class RoundFrom(unittest.TestCase): + def test_reads_the_prompt_the_last_report_and_when_the_reviewer_started(self): + entries = [ + entry("user", "Review branch x in /code/p-x.", timestamp="2026-10-14T10:00:00.500Z", cwd="/code/p-x", gitBranch="x"), + entry("assistant", "Reading."), + entry("assistant", "BLOCK\n\nšŸ”“ a.py:1 breaks"), + ] + self.assertEqual(round_from("/code/p", 5.0, entries), Round("/code/p", "x", "2026-10-14T10:00:00.500Z", 1791972000.5, 5.0, "Review branch x in /code/p-x.", ("šŸ”“ a.py:1 breaks",))) + + def test_skips_a_round_with_no_red_or_yellow_finding_or_no_report(self): + start = entry("user", "Review.", timestamp="2026-10-14T10:00:00Z", cwd="/code/p", gitBranch="x") + self.assertIsNone(round_from("/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")])) + self.assertIsNone(round_from("/code/p", 5.0, [start])) + self.assertIsNone(round_from("/code/p", 5.0, [])) + + +class ReviewedPath(unittest.TestCase): + def test_names_the_worktree_the_prompt_names_that_is_gone(self): + exists = {"/code", "/code/p", "/code/p/worktrees", "/tmp"}.__contains__ + self.assertEqual(reviewed_path("Review /code/p-x/src/a.py:3-5; the diff is at /tmp/s/x.diff; /code/p is older.", "/code/p", exists), "/code/p-x") + self.assertEqual(reviewed_path("Review `/code/p/worktrees/x`.", "/code/p", exists), "/code/p/worktrees/x") + + def test_names_the_checkout_when_the_prompt_names_no_gone_worktree_and_none_when_it_names_neither_or_two(self): + exists = {"/code", "/code/p"}.__contains__ + self.assertEqual(reviewed_path("Review /code/p.", "/code/p", exists), "/code/p") + self.assertIsNone(reviewed_path("Review the branch.", "/code/p", exists)) + self.assertIsNone(reviewed_path("Review /code/p-x and /code/p-43.", "/code/p", exists)) + + +class AuthoredBy(unittest.TestCase): + def test_takes_the_newest_commit_authored_by_then(self): + log = [("c3", 30), ("c2", 20), ("c1", 10)] + self.assertEqual(authored_by(log, 25), "c2") + self.assertEqual(authored_by(log, 30), "c3") + self.assertIsNone(authored_by(log, 5)) + + +class Sample(unittest.TestCase): + def test_keeps_the_latest_rounds_in_the_order_they_ran(self): + rounds = [a_round(2), a_round(1), a_round(3)] + self.assertEqual(sample(rounds, 2), [rounds[0], rounds[2]]) + + +class Replayed(unittest.TestCase): + def test_holds_each_rung_highest_first_to_what_the_reference_found_and_stops_at_the_first_that_misses(self): + rounds = [a_round(1, ("šŸ”“ a", "🟔 b")), a_round(2, ("šŸ”“ c",))] + found = {REFERENCE: [{0, 1}, set()], MIDDLE: [{0, 1}], CHEAP: [{1}]} + asked = [] + + def review_all(on, rung): + asked.append((len(on), rung)) + return found[rung] + + replay = replayed(rounds, REFERENCE, [MIDDLE, CHEAP, Rung("claude-haiku-5-5", "xhigh")], review_all) + self.assertEqual(replay, Replay(1, [Tried(MIDDLE, []), Tried(CHEAP, [(rounds[0], "šŸ”“ a")])], MIDDLE)) + self.assertEqual(asked, [(2, REFERENCE), (1, MIDDLE), (1, CHEAP)]) + + def test_names_no_rung_when_the_first_misses_or_the_reference_found_nothing(self): + rounds = [a_round(1)] + self.assertEqual(replayed(rounds, REFERENCE, [MIDDLE], lambda on, rung: [{0}] if rung == REFERENCE else [set()]), Replay(0, [Tried(MIDDLE, [(rounds[0], "šŸ”“ a")])], None)) + self.assertEqual(replayed(rounds, REFERENCE, [MIDDLE], lambda on, rung: [set()]), Replay(1, [], None)) + + def test_stops_at_a_usage_limit(self): + limit = Limited(None, "limit") + self.assertEqual(replayed([a_round(1)], REFERENCE, [MIDDLE], lambda on, rung: limit), limit) + self.assertEqual(replayed([a_round(1)], REFERENCE, [MIDDLE], lambda on, rung: [{0}] if rung == REFERENCE else limit), limit) + + +class Report(unittest.TestCase): + def test_counts_the_findings_and_names_each_miss_and_the_lowest_rung_that_missed_none(self): + rounds = [a_round(1, ("šŸ”“ a", "🟔 b")), a_round(2)] + lines = report("claude-opus-5-5", REFERENCE, rounds, Replay(1, [Tried(MIDDLE, []), Tried(CHEAP, [(rounds[0], "šŸ”“ a\nmore")])], MIDDLE)).splitlines() + self.assertEqual(lines, [ + "Replayed 2 stability rounds of claude-opus-5-5 projects, holding 3 šŸ”“ and 🟔 findings.", + "The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.", + "claude-sonnet-5-5 at high effort missed 0.", + "claude-haiku-5-5 at max effort missed 1:", + " /code/p 2026-10-14T10:00:01Z: šŸ”“ a", + "Lowest rung that finds every finding the reference reviewer finds: claude-sonnet-5-5 at high effort", + ]) + self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay(0, [Tried(MIDDLE, [(rounds[1], "šŸ”“ a")])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung") + self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay(3, [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.") + + +def unused(*_): + raise AssertionError("not called") + + +def run_git(cwd, *args): + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=cwd, check=True, capture_output=True) + + +class Main(unittest.TestCase): + """The tool on a temporary home: a chunk that began after the checkout's first commit, and whose stability reviewer reviewed branch x at its second, from a worktree since removed.""" + + def setUp(self): + self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) + (self.home / ".claude").mkdir() + (self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"})) + origin, self.checkout = self.home / "origin.git", self.home / "code" / "proj" + run_git(self.home, "init", "-q", "--bare", "-b", "main", str(origin)) + run_git(self.home, "clone", "-q", str(origin), str(self.checkout)) + for n, stamp in enumerate(("2026-10-14T09:00:00Z", "2026-10-14T09:30:00Z", "2026-10-14T11:00:00Z")): + (self.checkout / "a.txt").write_text(f"{n}\n") + run_git(self.checkout, "add", "a.txt") + run_git(self.checkout, "commit", "-qm", f"c{n}", f"--date={stamp}") + run_git(self.checkout, "push", "-q", "origin", "main") + run_git(self.checkout, "remote", "set-head", "origin", "main") + gone = self.home / "code" / "proj-x" + for key, cwd in (("proj", gone), ("other", self.home / "code" / "other")): + subagents = self.home / ".claude" / "loop-claude-transcripts" / key / "c1" / "session" / "s" / "subagents" + subagents.mkdir(parents=True) + (subagents.parents[2] / "t0.jsonl").write_text(json.dumps({"type": "summary"}) + "\n" + json.dumps(entry("user", "Do the next chunk.", timestamp="2026-10-14T09:15:00Z")) + "\n") + (subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "stability-reviewer"})) + (subagents / "agent-b.meta.json").write_text(json.dumps({"agentType": "prose-reviewer"})) + lines = [entry("user", f"Review branch x in {gone}.", timestamp="2026-10-14T10:00:00Z", cwd=str(cwd), gitBranch="x"), entry("assistant", "BLOCK\n\nšŸ”“ a.txt:1 wrong\n\n🟔 slow")] + for name in ("agent-a.jsonl", "agent-b.jsonl"): + (subagents / name).write_text("".join(json.dumps(line) + "\n" for line in lines)) + self.reviews = [] + + def run_main(self, argv, found): + """found(rung) is the indexes of the recorded findings the reviewer on rung finds.""" + + def claude(args, cwd, prompt): + rung = Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]) + if "--agent" in args: + shown = [subprocess.run(["git", *command], cwd=cwd, capture_output=True, text=True).stdout for command in (["show", "HEAD:a.txt"], ["branch", "--show-current"], ["show", "origin/main:a.txt"])] + self.reviews.append((rung, *shown, prompt, cwd)) + result = {"type": "result", "result": f"review on {rung.model} {rung.effort}"} + else: + reviewed = Rung(*re.search(r"review on (\S+) (\S+)", prompt).groups()) + result = found(reviewed) + result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} + return subprocess.CompletedProcess(args, 0, json.dumps(result), "") + + effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = main.main(argv, {}, self.home, effects) + return code, out.getvalue(), err.getvalue() + + def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self): + code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]}) + self.assertEqual(code, 0, err) + self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP]) + _, reviewed, branch, base, prompt, cwd = self.reviews[0] + # The default branch stands where it stood when the chunk began, so the prompt's diff against it shows the branch's change. + self.assertEqual((reviewed, branch, base), ("1\n", "x\n", "0\n")) + self.assertEqual(prompt, f"Review branch x in {cwd}.") + self.assertFalse(pathlib.Path(cwd).exists()) + self.assertIn("The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.", out) + self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z: 🟔 slow", out) + self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n")) + + def test_exits_1_on_a_usage_limit_bad_arguments_or_no_round_to_replay(self): + code, _, err = self.run_main(["claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"}) + self.assertEqual(code, 1) + self.assertIn("usage limit: You've hit your limit", err) + for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]): + self.assertEqual(self.run_main(argv, unused)[0], 1) + code, _, err = self.run_main(["claude-haiku-5-5"], unused) + self.assertEqual(code, 1) + self.assertIn("no archived stability round of projects on claude-haiku-5-5", err) + + def test_prints_the_help(self): + code, out, _ = self.run_main(["-h"], unused) + self.assertEqual((code, out.splitlines()[2]), (0, "usage: stability-replay ")) + + def test_the_launcher_prints_the_help(self): + ran = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True) + self.assertEqual(ran.returncode, 0) + self.assertIn("usage: stability-replay ", ran.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/decisions.md b/docs/decisions.md index 46bfba4d..2960fa2c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -229,3 +229,13 @@ On 2026-10-15, `bin/judge-replay claude-opus-5-5` replayed the latest 15 archive Only Opus 5.5 was replayed, so the judge of a project on another model keeps the effort its settings give until `judge-replay` covers that model (goal 1.1). Every routed chunk on record had an item of R + C 9, so the replay could not show that the project's rung suffices for harder items, and the judge climbs with the routed item as the worker does. For R + C 11 to 14 it still runs at or below xhigh (goal 1.4); from 15, `routing: one ladder` records that lilleman wants the highest quality at any price. An item the worker takes in later lifts the worker, not the judge, until `todo.md` item 136 routes a chunk on the item its worker takes. Valid while the archived verdicts show what a judge should return, and until a new model joins the ladder: replay then. + +## routing: the stability reviewer stays on the project's rung while the worker runs below it, until `stability-replay` finds a rung below it that finds every šŸ”“ and 🟔 the project's rung finds + +2026-10-15, lilleman proposed running the stability reviewer on the worker's rung; the replay that gates it is the agent's proposal. Serves goals 1.1 and 1.4: the stability pass is the only one that mutation-tests the changed lines, so a defect it misses may merge, and a cheaper reviewer saves money only where it misses nothing. + +`bin/stability-replay ` replays archived stability rounds on the code each reviewed, first on the project's rung, then on each rung below it, highest first, and stops at the first that misses a finding the project's rung found again. A rung qualifies only where it finds every such šŸ”“ and 🟔. + +On 2026-10-15, `bin/stability-replay claude-opus-5-5` replayed the latest 10 rounds holding a šŸ”“ or 🟔, 40 findings in all. Opus 5.5 at medium, the project's rung, found 29 of them again. Sonnet 5.5 at high missed 13 of those 29, 2 of them šŸ”“, so no rung below the project's rung qualifies, and Haiku 5.5, below Sonnet on the ladder, was not tried. So the stability reviewer runs where `routing: one ladder` puts every reviewer: on the project's rung while the worker runs below it. + +Valid until a new model joins the ladder, or the archive holds rounds a new reviewer prompt produced: replay then. diff --git a/todo.md b/todo.md index 73e5be20..4df5517f 100644 --- a/todo.md +++ b/todo.md @@ -26,7 +26,6 @@ Release 0.3.0 takes items 125, 114 and 124 first, whatever their scores: Shape i | ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---|---| -| 145 | 0.1.0 | | **Run the stability reviewer on the worker's rung while the worker runs below the project's rung, once a replay of past stability rounds on that rung finds the šŸ”“ and 🟔 findings on record.** | 4 | 5 | 6 | 6 | 7 | 1.4 | 20.2 | | 143 | 0.1.0 | | **Resume a worker one rung up in the next cycle when its run ends asking for a higher rung and the judge finds the escalation trigger it cites in the transcript.** | 5 | 5 | 7 | 6 | 7 | 1.1, 1.4 | 19.6 | | 136 | 0.1.0 | decision | **Route a chunk on the item its worker says it takes, in place of the next release's first row.** | 2 | 3 | 4 | 4 | 5 | 1.4 | 14.8 | | 105 | 0.2.0 | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 3 | 5 | 6 | 1.4 | 20.0 | @@ -86,14 +85,6 @@ Release 0.3.0 takes items 125, 114 and 124 first, whatever their scores: Shape i ## Details -### 145. Run the stability reviewer on the worker's rung while the worker runs below the project's rung, once a replay of past stability rounds on that rung finds the šŸ”“ and 🟔 findings on record. - -On 2026-10-15 the human proposed running the stability reviewer on the worker's rung; the replay gate is the agent's proposal. Today a worker below the project's rung launches every reviewer on the project's rung. Under this item, the stability reviewer runs on the worker's rung instead. Every other reviewer, the comprehension seats and the security pass's subagent stay on the project's rung, so a change that fires their triggers is still reviewed on that rung. - -The stability pass is the only one that mutation-tests the changed lines, so a defect it misses may merge. Before the switch, replay archived stability rounds on each rung below the project's, as `bin/judge-replay` does for the judge. Route the reviewer onto a rung only where it finds every šŸ”“ and 🟔 on record that a replay on the project's rung also finds. A rung that misses one keeps the reviewer on the project's rung. In the judge's replay on 2026-10-15, Haiku 5.5 at xhigh missed 7 of 31 verdicts, Sonnet 5.5 at high missed 3 interrupts, and Opus 5.5 at medium missed none. - -This revises `docs/decisions.md` → `routing: one ladder`. - ### 143. Resume a worker one rung up in the next cycle when its run ends asking for a higher rung and the judge finds the escalation trigger it cites in the transcript. The human asked for this on 2026-10-15. A worker may end its run asking for a higher rung, citing an escalation trigger of `CLAUDE.md` → "Working with the codebase". The judge looks for that trigger in the transcript. Where it finds it, the next cycle resumes the session one rung up; otherwise the rung holds. The worker never steps down within a chunk, and goes at most two rungs above the rung it started the chunk on unless the human agrees.