Answer architecture round 2: 1 🔴, 5 🟡; return a gone checkout's git failure as a value, derive a round's seconds from its stamp, let claude_reply own the flags it parses, test the uncovered paths, warn to sandbox the replay, decline injecting the shell's filesystem

This commit is contained in:
2026-10-15 20:57:22 +02:00
parent 4f722d94f4
commit c2a4757d56
8 changed files with 84 additions and 19 deletions
+1 -1
View File
@@ -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 <model>` 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 <model>` 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] <model> <R+C>` 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'`
+6 -2
View File
@@ -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 <args>` 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 {}
+1 -5
View File
@@ -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", "",
]
-1
View File
@@ -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
+9 -4
View File
@@ -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()}")
+13 -3
View File
@@ -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:
+53 -2
View File
@@ -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)
+1 -1
View File
@@ -236,6 +236,6 @@ Valid while the archived verdicts show what a judge should return, and until a n
`bin/stability-replay <model>` 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.