Answer architecture round 1: 1 🔴, 2 🟡; share one rung search between both replays, searching down from the project's rung, name the sixth git runner in item 114, decline recording the reviewed commit
This commit is contained in:
@@ -24,7 +24,6 @@ Like the loop, it tries claude three times running before it counts a reply as f
|
||||
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
|
||||
@@ -35,23 +34,20 @@ import tempfile
|
||||
import typing
|
||||
|
||||
from transcript_archive.location import archive_root
|
||||
from stability_replay.rounds import authored_by, replayed, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from stability_replay.rounds import authored_by, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from project_key import checkout_of
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from rung_replay.command import down_from, failed, limited_exit, project_rung_or_exit, projects_on
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.retry import first_reply, Limited
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
from claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
|
||||
from model_routing.ladder import LADDER, picked, position, project_rung, Rung
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
from loop_claude.stop import Stop
|
||||
from claude_code.entries import parse_entry, structured_output
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
TOOL = "stability-replay"
|
||||
LATEST = 10
|
||||
# Reviews replayed at once.
|
||||
AT_ONCE = 4
|
||||
LOWEST_R_PLUS_C = 2
|
||||
REVIEWER = "stability-reviewer"
|
||||
USAGE = "usage: stability-replay <model>, a model on the routing ladder"
|
||||
MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False}
|
||||
|
||||
|
||||
@@ -65,38 +61,33 @@ class Code:
|
||||
|
||||
|
||||
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)
|
||||
anchor = project_rung_or_exit(TOOL, argv, __doc__)
|
||||
if isinstance(anchor, int):
|
||||
return anchor
|
||||
rounds = archived_rounds(anchor.model, archive_root(home, env), home)
|
||||
if isinstance(rounds, Failure):
|
||||
print(f"stability-replay: {rounds.reason}", file=sys.stderr)
|
||||
return 1
|
||||
return failed(TOOL, rounds.reason)
|
||||
codes = {found: code for found in rounds if not isinstance(code := code_of(found, effects), Failure)}
|
||||
if len(codes) < len(rounds):
|
||||
print(f"{len(rounds) - len(codes)} of {len(rounds)} rounds holding a 🔴 or 🟡 are left out: their code cannot be found", file=sys.stderr, flush=True)
|
||||
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
|
||||
return failed(TOOL, f"no archived stability round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
||||
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))
|
||||
# The project's rung is the reference, so the candidates start below it.
|
||||
replay = replayed(chosen, anchor, down_from(anchor)[1:], lambda found, rung: findings_found(found, codes[found], rung, anchor, effects), lambda _, found: sorted(found), "stability rounds")
|
||||
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 limited_exit(TOOL, replay)
|
||||
print(report(anchor.model, 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)
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
return projects
|
||||
found = []
|
||||
try:
|
||||
for key in sorted(key for key, on in models.items() if on == model):
|
||||
for key in projects:
|
||||
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:
|
||||
@@ -120,6 +111,10 @@ def chunk_rounds(checkout: str, chunk: pathlib.Path) -> list[Round]:
|
||||
|
||||
|
||||
def code_of(found: Round, effects: Effects) -> Code | Failure:
|
||||
"""The code found's reviewer read, as the archive lets it be found again: the prompt's removed worktree, and the commits authored by then.
|
||||
|
||||
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer findings on record, and no rung is held to those.
|
||||
"""
|
||||
path = reviewed_path(found.prompt, found.root, os.path.exists)
|
||||
if path is None:
|
||||
return Failure("the prompt names no one worktree")
|
||||
@@ -143,20 +138,6 @@ 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))
|
||||
@@ -181,7 +162,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"]
|
||||
reply = claude_reply(effects, args, clone, found.prompt.replace(code.path, clone))
|
||||
reply = claude_reply(effects.claude, args, clone, found.prompt.replace(code.path, clone), "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
|
||||
@@ -198,7 +179,7 @@ def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung,
|
||||
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)
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
output = structured_output(reply)
|
||||
@@ -208,19 +189,6 @@ def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung,
|
||||
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()}")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""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`."""
|
||||
"""Which archived stability rounds to replay, the code each reviewed, and the report: docs/decisions.md → `routing: the stability reviewer stays on the project's rung`."""
|
||||
import dataclasses
|
||||
import datetime
|
||||
import pathlib
|
||||
@@ -6,7 +6,7 @@ import re
|
||||
import typing
|
||||
|
||||
from claude_code.entries import assistant_parts, content, part_text, parts
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from rung_replay.search import Replay
|
||||
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.
|
||||
@@ -28,21 +28,6 @@ class Round:
|
||||
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))]
|
||||
@@ -79,7 +64,9 @@ def reviewed_path(prompt: str, root: str, exists: typing.Callable[[str], bool])
|
||||
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)
|
||||
# The path's directories from the top down, without the filesystem root; the first one gone is what a removed worktree took with it.
|
||||
down_the_path = [*reversed(path.parents), path][1:]
|
||||
first_gone = next((prefix for prefix in down_the_path 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:
|
||||
@@ -97,38 +84,14 @@ def sample(rounds: list[Round], latest: int) -> list[Round]:
|
||||
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:
|
||||
def report(model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> 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.",
|
||||
f"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} 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)]
|
||||
lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *(f" {miss.case.root} {miss.case.at}: {miss.case.findings[miss.item].splitlines()[0]}" for miss in tried.missed)]
|
||||
if not replay.tried:
|
||||
lines.append("No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
else:
|
||||
|
||||
@@ -10,10 +10,10 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from stability_replay.rounds import authored_by, recorded_findings, Replay, replayed, report, reviewed_path, Round, round_from, sample, Tried
|
||||
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 loop_claude.cycle.retry import Limited
|
||||
from stability_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "stability-replay"
|
||||
@@ -82,35 +82,10 @@ class Sample(unittest.TestCase):
|
||||
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()
|
||||
rounds = [a_round(1, ("🔴 a\nmore", "🟡 b")), a_round(2)]
|
||||
lines = report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], 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.",
|
||||
@@ -119,8 +94,8 @@ class Report(unittest.TestCase):
|
||||
" /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.")
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], 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([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
|
||||
|
||||
def unused(*_):
|
||||
|
||||
Reference in New Issue
Block a user