Answer architecture round 2: 2 🔴, 3 🟡; route from the ladder by rung, keep a stepped-up rung across reruns and reloads, test the judge's bundled range, and file item 136 for routing on the item taken

This commit is contained in:
2026-10-14 23:06:54 +02:00
parent c75e576773
commit d6e019444d
20 changed files with 305 additions and 148 deletions
+7
View File
@@ -1,9 +1,16 @@
import hashlib
import pathlib
import typing
from claude_code.transcript import first_timestamped_line
from project_key import project_key
def project_archive(checkout_root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path:
archive = pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else home / ".claude" / "loop-claude-transcripts"
return archive / project_key(checkout_root, home)
def chunk_folder(project_archive: pathlib.Path, transcript: bytes) -> pathlib.Path:
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
return project_archive / hashlib.sha256(first_timestamped_line(transcript)).hexdigest()
+20 -4
View File
@@ -5,14 +5,18 @@ from utc_stamp import STAMPED
FINISHED = "Verdict: finished"
FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE)
# An outcome opens with its UTC stamp; a verdict that closes a cycle, or a stop, ends with the worker line.
OUTCOME_AT = re.compile(rf"^({STAMPED}) ", re.MULTILINE)
CLOSES_A_CYCLE = ("Verdict: finished\n", "Verdict: unfinished\n", "Stopped: ")
WORKER = "Worker: "
def finished(worker: str, evidence: str) -> str:
return f"{FINISHED}\n\nWorker: {worker}\n\nEvidence:\n{quoted(evidence)}"
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{WORKER}{worker}"
def unfinished(worker: str, evidence: str) -> str:
return f"Verdict: unfinished\n\nWorker: {worker}\n\nEvidence:\n{quoted(evidence)}"
return f"Verdict: unfinished\n\nEvidence:\n{quoted(evidence)}\n\n{WORKER}{worker}"
def interrupted(question: str, evidence: str) -> str:
@@ -23,5 +27,17 @@ def answered(question: str, sources: str, answer: str, evidence: str) -> str:
return f"Verdict: quoted answer\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}"
def stopped(why: str) -> str:
return f"Stopped: {why}"
def stopped(worker: str, why: str) -> str:
return f"Stopped: {why}\n\n{WORKER}{worker}"
def workers(outcomes: str) -> list[tuple[str, str]]:
"""The UTC stamp and the worker of each outcome that closes a cycle, in the order they were written."""
starts = list(OUTCOME_AT.finditer(outcomes))
found = []
for start, after in zip(starts, [*starts[1:], None]):
outcome = outcomes[start.end():after.start() if after else len(outcomes)].rstrip("\n")
last = outcome.rsplit("\n", 1)[-1]
if outcome.startswith(CLOSES_A_CYCLE) and last.startswith(WORKER):
found.append((start[1], last.removeprefix(WORKER)))
return found
+13 -1
View File
@@ -1,8 +1,9 @@
import dataclasses
import pathlib
from transcript_archive.location import chunk_folder
from failure import Failure
from transcript_archive.outcomes import FINISHED_AT
from transcript_archive.outcomes import FINISHED_AT, workers
@dataclasses.dataclass(frozen=True)
@@ -33,3 +34,14 @@ def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure:
return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)]
except OSError as failure:
return Failure(f"could not read {failure.filename}: {failure.strerror}")
def latest_worker(project_archive: pathlib.Path, transcript: str) -> str | Failure | None:
"""The worker the latest verdict archived for the transcript's chunk names; None before its first verdict."""
try:
with open(transcript, "rb") as handle:
folder = chunk_folder(project_archive, handle.read())
found = sorted(stamped for outcomes in folder.glob("*.outcomes.md") for stamped in workers(outcomes.read_text(encoding="utf-8")))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive {project_archive}: {failure}")
return found[-1][1] if found else None
@@ -8,7 +8,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive import outcomes, write
from failure import Failure
from transcript_archive import outcomes, read, write
from transcript_archive.location import project_archive
from project_key import project_key
from utc_stamp import utc
@@ -26,8 +27,8 @@ class Archive(unittest.TestCase):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("m", "working"), NOW))
(kept_outcomes,) = kept.glob("*/*.outcomes.md")
kept_outcomes.unlink()
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("Ctrl-C"), NOW))
self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n")
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("m", "Ctrl-C"), NOW))
self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: m\n")
class CopyFor(unittest.TestCase):
@@ -46,6 +47,28 @@ class Outcomes(unittest.TestCase):
def test_the_archive_stamps_what_it_reads_back(self):
self.assertRegex(f"{utc(NOW)} {outcomes.finished('m', 'merged')}", outcomes.FINISHED_AT)
def test_reads_back_the_worker_of_each_outcome_that_closes_a_cycle(self):
kept = "Task: Do it.\n\n" + "\n".join(f"{utc(NOW + offset)} {outcome}\n" for offset, outcome in enumerate([
outcomes.unfinished("w1", "Worker: not this"),
outcomes.interrupted("Which one?\nWorker: nor this", "e"),
outcomes.stopped("w2", "the judge failed\nthree times"),
outcomes.finished("w3", "merged"),
]))
self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w1"), (utc(NOW + 2), "w2"), (utc(NOW + 3), "w3")])
def test_names_the_worker_the_latest_outcome_of_the_transcripts_chunk_records(self):
with tempfile.TemporaryDirectory() as root:
kept = pathlib.Path(root, "archive")
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
self.assertIsNone(read.latest_worker(kept, str(transcript)))
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w1", "working"), NOW))
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n{"more": 1}\n')
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w2", "Ctrl-C"), NOW + 1))
self.assertEqual(read.latest_worker(kept, str(transcript)), "w2")
self.assertIsInstance(read.latest_worker(kept, str(pathlib.Path(root, "gone.jsonl"))), Failure)
class Location(unittest.TestCase):
def test_keys_a_project_by_its_path_under_code_or_else_under_the_root(self):
+2 -3
View File
@@ -3,8 +3,8 @@ import os
import pathlib
import sys
from transcript_archive.location import chunk_folder
from failure import Failure
from claude_code.transcript import first_timestamped_line
from file_writes import make_private, replace_file
from claude_code.session import session_files
from utc_stamp import utc
@@ -14,8 +14,7 @@ def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, a
try:
with open(path, "rb") as handle:
raw = handle.read()
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
folder = project_archive / hashlib.sha256(first_timestamped_line(raw)).hexdigest()
folder = chunk_folder(project_archive, raw)
make_private(folder)
except OSError as failure:
return unarchived(failure.filename, failure.strerror)