From c2a4757d56f72f91725beefa491bb6fcacc64a50 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 15 Oct 2026 20:57:22 +0200 Subject: [PATCH] =?UTF-8?q?Answer=20architecture=20round=202:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1;=20return=20a=20gone=20checkou?= =?UTF-8?q?t's=20git=20failure=20as=20a=20value,=20derive=20a=20round's=20?= =?UTF-8?q?seconds=20from=20its=20stamp,=20let=20claude=5Freply=20own=20th?= =?UTF-8?q?e=20flags=20it=20parses,=20test=20the=20uncovered=20paths,=20wa?= =?UTF-8?q?rn=20to=20sandbox=20the=20replay,=20decline=20injecting=20the?= =?UTF-8?q?=20shell's=20filesystem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/claude_code/reply.py | 8 ++- bin/loop_claude/cycle/judge.py | 6 +- bin/loop_claude/cycle/retry.py | 1 - bin/stability_replay/main.py | 13 +++-- bin/stability_replay/rounds.py | 16 +++++- bin/stability_replay/test_stability_replay.py | 55 ++++++++++++++++++- docs/decisions.md | 2 +- 8 files changed, 84 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index ab05a7a5..a69f96a0 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `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 Bash, Edit, MultiEdit and Write call, and `rule-hook --help` states the rules and the override. - `score-outcomes [R S C]` lists the finished items whose guessed R, S and C sit nearest the given scores, with what their chunks measured, and each score's median outcome; `score-outcomes --help` states the measures. - `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it. -- `stability-replay ` replays archived stability reviews of the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that finds their findings; `stability-replay --help` states the replay. +- `stability-replay ` replays archived stability reviews of the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that finds their findings; `stability-replay --help` states the replay. Run it only in a sandbox, as loop-claude: each replayed reviewer has Bash and skips every permission prompt, and an archived prompt may name paths on the host. - `subagent-rung [--plan] ` prints the Agent tool's model and effort for a subagent's task, picked by its R + C from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule. Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'` diff --git a/bin/claude_code/reply.py b/bin/claude_code/reply.py index 32159deb..878303a5 100644 --- a/bin/claude_code/reply.py +++ b/bin/claude_code/reply.py @@ -17,10 +17,14 @@ class Limited: said: str +# The json reply claude_reply parses; no persistence, so its runs stay out of the session picker; no permission prompt, as no one answers it. +HEADLESS = ["--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"] + + def claude_reply(claude: Claude, args: list[str], cwd: str, prompt: str, who: str) -> dict | Failure | Limited: - """claude's json reply, or why there is none; who names the run in the message for a non-zero exit, such as the judge.""" + """claude's json reply to `claude -p ` and HEADLESS, or why there is none; who names the run in the message for a non-zero exit, such as the judge.""" try: - proc = claude(args, cwd, prompt) + proc = claude(["-p", *args, *HEADLESS], cwd, prompt) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") reply = parse_entry(proc.stdout) or {} diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 871037c2..f715ac9b 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -133,14 +133,10 @@ def judge_once(root: str, task: str, premises: str, records: str, rendered_trans def judge_args(rung: Rung) -> list[str]: # --json-schema has claude check its reply against the schema and return it as the json result's structured_output. - # No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker. + # No tools, so the verdict rests on the transcript grounded() checks it against. return [ - "-p", "--json-schema", json.dumps(JUDGE_SCHEMA), *rung.flags(), - "--no-session-persistence", - "--output-format", "json", - "--permission-mode", "bypassPermissions", "--tools", "", ] diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index fdf9a79c..32c16aa3 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -40,4 +40,3 @@ def limit_wait(limited: Limited, now: float) -> float: if limited.resets_at is not None and limited.resets_at + PAST_RESET > now: return limited.resets_at + PAST_RESET - now return UNKNOWN_RESET_POLL - diff --git a/bin/stability_replay/main.py b/bin/stability_replay/main.py index 74047655..3ee06c9b 100644 --- a/bin/stability_replay/main.py +++ b/bin/stability_replay/main.py @@ -102,7 +102,8 @@ def chunk_rounds(checkout: str, chunk: pathlib.Path) -> list[Round]: return [] found = [] for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")): - if json.loads(meta.read_text(encoding="utf-8")).get("agentType") != REVIEWER: + described = json.loads(meta.read_text(encoding="utf-8")) + if not isinstance(described, dict) or described.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)): @@ -150,6 +151,7 @@ def findings_found(found: Round, code: Code, rung: Rung, anchor: Rung, effects: return matched +# The shell: it makes and removes the clone itself, and the tests run it on a temporary home, as judge-replay's do; rounds.py's core takes the filesystem as an argument. def review(found: Round, code: Code, rung: Rung, effects: Effects) -> str | Failure | Limited: clone = tempfile.mkdtemp(prefix="stability-replay-") try: @@ -161,7 +163,7 @@ def review(found: Round, code: Code, rung: Rung, effects: Effects) -> str | Fail ): 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"] + args = ["--agent", REVIEWER, *rung.flags()] reply = claude_reply(effects.claude, args, clone, found.prompt.replace(code.path, clone), "claude") if isinstance(reply, Failure | Limited): return reply @@ -178,7 +180,7 @@ def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, "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", ""] + args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""] reply = claude_reply(effects.claude, args, root, prompt, "claude") if isinstance(reply, Failure | Limited): return reply @@ -190,5 +192,8 @@ def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, def git(effects: Effects, cwd: str, *args: str) -> str | Failure: - ran = effects.git(list(args), cwd) + try: + ran = effects.git(list(args), cwd) + except OSError as failure: + return Failure(f"git {' '.join(args)} could not start in {cwd}: {failure.strerror}") 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 index a62b976c..bbb3cfc8 100644 --- a/bin/stability_replay/rounds.py +++ b/bin/stability_replay/rounds.py @@ -22,21 +22,31 @@ class Round: root: str branch: str at: str - seconds: float began: float prompt: str findings: tuple[str, ...] + @property + def seconds(self) -> float: + return stamp_seconds(self.at) + 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])): + if not stamped(first) 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)) + return Round(root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings)) + + +def stamped(entry: dict) -> bool: + try: + return isinstance(entry.get("timestamp"), str) and bool(stamp_seconds(entry["timestamp"])) + except ValueError: + return False def stamp_seconds(stamp: str) -> float: diff --git a/bin/stability_replay/test_stability_replay.py b/bin/stability_replay/test_stability_replay.py index a48988ec..23a0aa38 100644 --- a/bin/stability_replay/test_stability_replay.py +++ b/bin/stability_replay/test_stability_replay.py @@ -1,8 +1,10 @@ import contextlib +import dataclasses import io import json import pathlib import re +import shutil import subprocess import sys import tempfile @@ -12,6 +14,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from stability_replay.rounds import authored_by, recorded_findings, report, reviewed_path, Round, round_from, sample from loop_claude.effects import Effects, system_effects +from failure import Failure from stability_replay import main from rung_replay.search import Miss, Replay, Tried from model_routing.ladder import Rung @@ -27,7 +30,7 @@ def entry(kind, 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)) + return Round("/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings)) class RecordedFindings(unittest.TestCase): @@ -46,13 +49,15 @@ class RoundFrom(unittest.TestCase): 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",))) + self.assertEqual(round_from("/code/p", 5.0, entries), Round("/code/p", "x", "2026-10-14T10:00:00.500Z", 5.0, "Review branch x in /code/p-x.", ("šŸ”“ a.py:1 breaks",))) + self.assertEqual(round_from("/code/p", 5.0, entries).seconds, 1791972000.5) 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, [])) + self.assertIsNone(round_from("/code/p", 5.0, [{**start, "timestamp": "yesterday"}, entry("assistant", "šŸ”“ a")])) class ReviewedPath(unittest.TestCase): @@ -98,6 +103,27 @@ class Report(unittest.TestCase): self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.") +class Match(unittest.TestCase): + def run_match(self, stdout): + effects = dataclasses.replace(system_effects(), claude=lambda args, cwd, prompt: subprocess.CompletedProcess(args, 0, stdout, "")) + return main.match(("šŸ”“ a", "🟔 b"), "the other report", "/code/p", REFERENCE, effects) + + def test_takes_the_numbers_in_range_and_fails_on_a_reply_of_another_shape(self): + self.assertEqual(self.run_match(json.dumps({"type": "result", "structured_output": {"found": [2, 0, 3, 1]}})), {0, 1}) + for output in ({"found": ["1"]}, {"found": 1}, [1]): + with self.subTest(output): + self.assertIsInstance(self.run_match(json.dumps({"type": "result", "structured_output": output})), Failure) + + +class Git(unittest.TestCase): + def test_says_why_git_cannot_start_in_a_directory_that_is_gone(self): + def gone(args, cwd): + raise FileNotFoundError(2, "No such file or directory") + + ran = main.git(dataclasses.replace(system_effects(), git=gone), "/code/gone", "log") + self.assertEqual(ran, Failure("git log could not start in /code/gone: No such file or directory")) + + def unused(*_): raise AssertionError("not called") @@ -134,6 +160,18 @@ class Main(unittest.TestCase): (subagents / name).write_text("".join(json.dumps(line) + "\n" for line in lines)) self.reviews = [] + def rewrite_round(self, change): + path = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" / "session" / "s" / "subagents" / "agent-a.jsonl" + lines = [json.loads(line) for line in path.read_text().splitlines()] + change(lines[0]) + path.write_text("".join(json.dumps(line) + "\n" for line in lines)) + + def set_branch(self, branch): + self.rewrite_round(lambda first: first.update(gitBranch=branch)) + + def set_prompt(self, prompt): + self.rewrite_round(lambda first: first["message"]["content"][0].update(text=prompt)) + def run_main(self, argv, found): """found(rung) is the indexes of the recorded findings the reviewer on rung finds.""" @@ -168,6 +206,19 @@ class Main(unittest.TestCase): 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_checks_out_the_commit_detached_when_the_reviewer_started_on_the_default_branch(self): + self.set_branch("main") + self.assertEqual(self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0) + self.assertEqual(self.reviews[0][1:3], ("1\n", "")) + + def test_leaves_out_a_round_whose_code_it_cannot_find(self): + for gone in (lambda: self.set_prompt("Review the branch."), lambda: subprocess.run(["git", "remote", "set-head", "origin", "-d"], cwd=self.checkout, check=True), lambda: shutil.rmtree(self.checkout)): + with self.subTest(gone): + gone() + code, _, err = self.run_main(["claude-opus-5-5"], unused) + self.assertEqual(code, 1) + self.assertIn("1 of 1 rounds holding a šŸ”“ or 🟔 are left out", err) + 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) diff --git a/docs/decisions.md b/docs/decisions.md index 2960fa2c..9c6f61d1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -236,6 +236,6 @@ Valid while the archived verdicts show what a judge should return, and until a n `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. +On 2026-10-15, `bin/stability-replay claude-opus-5-5` replayed the latest 10 rounds holding a šŸ”“ or 🟔, 40 findings in all, 8 of the rounds from this repo. 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.