Files

277 lines
17 KiB
Python

import contextlib
import hashlib
import io
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from transcript_archive.project_key import checkout_of, project_key
from text_files.doubles import compress
from failure import Failure
from transcript_archive.judge_run import JudgeRun
from transcript_archive import outcomes, read, write
from transcript_archive.location import project_archive
from text_files.file_writes import replace_file
from text_files.utc_stamp import utc
NOW = 1790000000
class Archive(unittest.TestCase):
def test_writes_afresh_a_copy_whose_outcomes_file_is_missing(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')
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("m", "working", "j", ""), NOW, replace=replace_file))
(kept_outcomes,) = kept.glob("*/*.outcomes.md")
kept_outcomes.unlink()
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("m", "Ctrl-C"), NOW, replace=replace_file))
self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: m\n")
class JudgeRuns(unittest.TestCase):
judged = JudgeRun("The prompt.", {"structured_output": {"finished": True}, "total_cost_usd": 0.5})
def test_a_run_is_kept_once_in_the_chunk_folder_under_the_hash_of_its_content(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')
with contextlib.redirect_stderr(io.StringIO()):
for offset in (0, 1):
outcome = outcomes.finished("w", "merged", "j", judge_run=self.judged)
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcome, NOW + offset, judge_run=self.judged, replace=replace_file))
(folder,) = kept.glob("*/")
(file,) = folder.glob("judge/*")
self.assertEqual(file, folder / self.judged.file)
self.assertEqual(file.name, hashlib.sha256(file.read_bytes()).hexdigest() + ".json")
self.assertEqual(json.loads(file.read_text()), {"prompt": "The prompt.", "reply": {"structured_output": {"finished": True}, "total_cost_usd": 0.5}})
self.assertEqual(JudgeRun.read(file), self.judged)
def test_names_the_run_on_the_line_after_the_judge_lines_and_reads_the_name_back(self):
outcome = outcomes.finished("w", "e", "j", judge_cost=0.5, judge_run=self.judged)
self.assertEqual(outcome, f"Verdict: finished\n\nEvidence:\n> e\n\nJudge: j\nJudge cost: 0.5000\nJudge run: {self.judged.file}\nWorker: w")
self.assertEqual(outcomes.rejected("why", "{}", "j", judge_run=self.judged), f"Judge reply rejected: why\n\nReply:\n> {{}}\n\nJudge: j\nJudge run: {self.judged.file}")
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcome}\n"), [(utc(NOW), "w")])
self.assertEqual(outcomes.judge_costs(f"{utc(NOW)} {outcome}\n"), [("j", 0.5)])
kept = f"Task: Do it.\n\n{utc(NOW)} {outcomes.stopped('w', 'Ctrl-C')}\n\n{utc(NOW + 1)} {outcome}\n\n{utc(NOW + 2)} {outcomes.finished('w', 'e', 'j')}\n"
self.assertEqual(outcomes.judge_run_at(kept, utc(NOW + 1)), self.judged.file)
self.assertIsNone(outcomes.judge_run_at(kept, utc(NOW + 2)))
def test_keeps_a_run_as_readable_utf_8_json_indented_by_one_space(self):
run = JudgeRun("Prompt é.", {"a": 1})
self.assertEqual(run.content(), b'{\n "prompt": "Prompt \xc3\xa9.",\n "reply": {\n "a": 1\n }\n}')
def test_reads_a_file_that_is_no_run_as_a_failure(self):
with tempfile.TemporaryDirectory() as root:
for text in ("not json", '{"prompt": "P"}', '{"prompt": 1, "reply": {}}', '{"prompt": "P", "reply": []}'):
with self.subTest(text=text):
path = pathlib.Path(root, "run.json")
path.write_text(text)
self.assertRegex(JudgeRun.read(path).reason, f"^could not read the archived judge run {path}: ")
def test_reads_no_path_that_leaves_the_judge_folder_from_an_outcome(self):
outcome = f"{utc(NOW)} Verdict: finished\n\nJudge run: judge/../../secret.json\n"
self.assertIsNone(outcomes.judge_run_at(outcome, utc(NOW)))
def test_names_the_run_on_each_kind_of_outcome_that_has_a_judge(self):
named = f"Judge: j\nJudge run: {self.judged.file}\n"
kept = [
outcomes.unfinished("w", "e", "j", "", judge_run=self.judged),
outcomes.interrupted("Q?", "e", "j", "", "w", judge_run=self.judged),
outcomes.answered(question="Q?", sources="S", answer="a", evidence="e", escalation="", judge="j", worker="w", judge_run=self.judged),
]
self.assertEqual([named in outcome for outcome in kept], [True, True, True])
def test_names_the_folder_it_cannot_make_in_the_failure_to_keep_a_run(self):
with tempfile.TemporaryDirectory() as root:
(pathlib.Path(root) / "judge").write_text("a file where the folder should be")
failure = write.keep_judge_run(pathlib.Path(root), self.judged, replace_file)
self.assertRegex(failure.reason, f"^could not archive the transcript: {root}/judge: ")
self.assertNotIn("None", failure.reason)
def test_writes_no_outcome_where_the_run_cannot_be_kept(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')
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "x"), NOW, replace=replace_file))
(folder,) = kept.glob("*/")
(folder / "judge").write_text("a file where the folder should be")
failure = write.archive(kept, str(transcript), "Do it.", outcomes.finished("w", "e", "j", judge_run=self.judged), NOW + 1, judge_run=self.judged, replace=replace_file)
self.assertIsInstance(failure, Failure)
self.assertNotIn("Verdict: finished", next(folder.glob("*.outcomes.md")).read_text())
class CopyFor(unittest.TestCase):
def test_skips_a_version_already_kept_beside_its_copy(self):
with tempfile.TemporaryDirectory() as temp:
copy = pathlib.Path(temp, "custom-title.json")
copy.write_bytes(b"first")
beside = write.copy_for(copy, b"second")
self.assertEqual(beside, copy.with_name(f"custom-title.json.{hashlib.sha256(b'second').hexdigest()}"))
beside.write_bytes(b"second")
self.assertIsNone(write.copy_for(copy, b"second"))
self.assertEqual(write.copy_for(copy, b"first, grown"), copy)
def test_reads_a_compressed_copy_as_the_kept_version(self):
with tempfile.TemporaryDirectory() as temp:
copy = pathlib.Path(temp, "agent-a.jsonl")
copy.write_bytes(b"first\n")
self.assertIsNone(compress(copy))
self.assertIsNone(write.copy_for(copy, b"first\n"))
self.assertEqual(write.copy_for(copy, b"first\nsecond\n"), copy)
self.assertEqual(write.copy_for(copy, b"other\n"), copy.with_name(f"agent-a.jsonl.{hashlib.sha256(b'other' + bytes([10])).hexdigest()}"))
class Compressed(unittest.TestCase):
"""The archive, its transcript copies and subagents' transcripts gzipped as compress-archives leaves them."""
def archived(self, root: str) -> pathlib.Path:
kept = pathlib.Path(root, "archive")
transcript = pathlib.Path(root, "t.jsonl")
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
subagent = pathlib.Path(root, "t", "subagents", "agent-a.jsonl")
subagent.parent.mkdir(parents=True)
subagent.write_text('{"sub": 1}\n')
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.finished("w", "merged", "j"), NOW, replace=replace_file))
for copy in kept.rglob("*.jsonl"):
self.assertIsNone(compress(copy))
return transcript
def test_a_compressed_copy_takes_the_next_outcome_and_is_not_copied_again(self):
with tempfile.TemporaryDirectory() as root:
transcript = self.archived(root)
kept = pathlib.Path(root, "archive")
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1, replace=replace_file))
self.assertEqual([path.name.endswith(".gz") for path in kept.rglob("*.jsonl*")], [True, True])
self.assertIn("Stopped: Ctrl-C", next(kept.glob("*/*.outcomes.md")).read_text())
def test_reads_a_finished_chunk_whose_copies_are_compressed(self):
with tempfile.TemporaryDirectory() as root:
self.archived(root)
(chunk,) = read.finished_chunks(pathlib.Path(root, "archive"))
self.assertEqual(read.read_threads(chunk), [b'{"timestamp": "2026-10-03T00:00:00Z"}\n', b'{"sub": 1}\n'])
class Outcomes(unittest.TestCase):
def test_the_archive_stamps_what_it_reads_back(self):
self.assertRegex(f"{utc(NOW)} {outcomes.finished('m', 'merged', 'j')}", outcomes.FINISHED_AT)
def test_reads_back_the_worker_of_each_outcome_that_names_one(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", "j", ""),
outcomes.interrupted("Which one?\nWorker: nor this", "e", "j", "", "w1b"),
outcomes.stopped("w2", "the judge failed\nthree times"),
outcomes.finished("w3", "merged", "j"),
]))
self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w1"), (utc(NOW + 1), "w1b"), (utc(NOW + 2), "w2"), (utc(NOW + 3), "w3")])
def test_archives_the_escalation_an_unfinished_verdict_quotes_beside_its_evidence(self):
self.assertEqual(outcomes.unfinished("w", "e", "j", "round 2: 🔴"), "Verdict: unfinished\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
self.assertEqual(outcomes.unfinished("w", "e", "j", ""), "Verdict: unfinished\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
def test_a_recorded_judge_cost_follows_the_judge_line_and_reads_back_with_its_rung(self):
self.assertEqual(outcomes.finished("w", "e", "j", judge_cost=0.12345), "Verdict: finished\n\nEvidence:\n> e\n\nJudge: j\nJudge cost: 0.1235\nWorker: w")
self.assertEqual(outcomes.rejected("why", "{}", "j", judge_cost=2.0), "Judge reply rejected: why\n\nReply:\n> {}\n\nJudge: j\nJudge cost: 2.0000")
kept = f"{utc(NOW)} " + outcomes.unfinished("w", "e", "j", "", judge_cost=0.5) + "\n" + f"{utc(NOW)} " + outcomes.finished("w", "e", "k") + "\n" + f"{utc(NOW)} " + outcomes.rejected("why", "{}", "k", judge_cost=0.25)
self.assertEqual(outcomes.judge_costs(kept), [("j", 0.5), ("k", 0.25)])
self.assertEqual(outcomes.workers(f"{utc(NOW)} " + outcomes.finished("w", "e", "j", judge_cost=0.5)), [(utc(NOW), "w")])
def test_archives_the_escalation_an_interrupt_quotes_beside_its_evidence(self):
self.assertEqual(outcomes.interrupted("q?", "e", "j", "round 2: 🔴", "w"), "Verdict: interrupt\n\nq?\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
self.assertEqual(outcomes.interrupted("q?", "e", "j", "", "w"), "Verdict: interrupt\n\nq?\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
def test_archives_the_escalation_and_the_worker_a_quoted_answer_names(self):
self.assertEqual(outcomes.answered(question="q?", sources="AGENTS.md", answer="A.", evidence="e", escalation="round 2: 🔴", judge="j", worker="w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
self.assertEqual(outcomes.answered(question="q?", sources="AGENTS.md", answer="A.", evidence="e", escalation="", judge="j", worker="w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcomes.answered(question='q?', sources='AGENTS.md', answer='A.', evidence='e', escalation='', judge='j', worker='w')}\n"), [(utc(NOW), "w")])
def test_reads_no_worker_from_an_outcome_written_before_the_worker_line(self):
kept = f"Task: Do it.\n\n{utc(NOW)} Stopped: Ctrl-C\n\n{utc(NOW)} Verdict: unfinished\n\nEvidence:\n> Worker: no\n"
self.assertEqual(outcomes.workers(kept), [])
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcomes.stepped_up('w')}\n"), [(utc(NOW), "w")])
self.assertEqual(outcomes.workers(f"{utc(NOW)} Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nJudge: j\n"), [])
def test_takes_the_outcome_written_last_within_one_second(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')
with contextlib.redirect_stderr(io.StringIO()):
for worker in ("z-first", "a-last"):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished(worker, "working", "j", ""), NOW, replace=replace_file))
self.assertEqual(read.latest_worker(kept, str(transcript)), "a-last")
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", "j", ""), NOW, replace=replace_file))
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, replace=replace_file))
self.assertEqual(read.latest_worker(kept, str(transcript)), "w2")
self.assertIsInstance(read.latest_worker(kept, str(pathlib.Path(root, "gone.jsonl"))), Failure)
def test_a_record_quotes_the_reversal_then_the_spend_then_the_config_before_the_judge(self):
record = outcomes.Annotation("v0.8.0 (abc)", "Spent since the chunk began, in tokens of x:\n- worker, m: 1", "No, keep it.\nUse X.")
self.assertEqual(outcomes.finished("w", "e", "j", annotation=record), "Verdict: finished\n\nEvidence:\n> e\n\nReversed:\n> No, keep it.\n> Use X.\n\nSpent since the chunk began, in tokens of x:\n- worker, m: 1\n\nConfig: v0.8.0 (abc)\nJudge: j\nWorker: w")
self.assertEqual(outcomes.finished("w", "e", "j", annotation=outcomes.Annotation("v0.8.0 (abc)")), "Verdict: finished\n\nEvidence:\n> e\n\nConfig: v0.8.0 (abc)\nJudge: j\nWorker: w")
def test_reads_back_each_reversal_and_the_stamps_of_the_outcomes_that_record_a_spend(self):
spent = outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1", "No, keep it.\nUse X.")
kept = "Task: Do it.\n\n" + "\n".join(f"{utc(NOW + offset)} {outcome}\n" for offset, outcome in enumerate([
outcomes.unfinished("w", "e", "j", "", annotation=spent),
outcomes.stopped("w", "Ctrl-C"),
outcomes.finished("w", "e", "j", annotation=outcomes.Annotation("c", "Spent since x, in tokens of x:\n- judge, m: 1")),
]))
self.assertEqual(outcomes.reversals(kept), ["No, keep it.\nUse X."])
self.assertEqual(outcomes.spent_stamps(kept), [utc(NOW), utc(NOW + 2)])
self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w"), (utc(NOW + 1), "w"), (utc(NOW + 2), "w")])
def test_the_last_spend_is_the_latest_outcome_of_the_chunk_that_records_one(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.assertEqual(read.last_spent(kept, str(transcript)), "")
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW, replace=replace_file))
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1, replace=replace_file))
self.assertEqual(read.last_spent(kept, str(transcript)), utc(NOW))
gone = read.last_spent(kept, str(pathlib.Path(root, "gone.jsonl")))
self.assertIsInstance(gone, Failure)
self.assertTrue(gone.reason.startswith(f"could not read the archive {kept}: "), gone.reason)
class Location(unittest.TestCase):
def test_keys_a_project_by_its_path_under_code_or_else_under_the_root(self):
home = pathlib.Path("/h")
self.assertEqual(project_key("/h/code/log", home), "log")
self.assertEqual(project_key("/h/code", home), "h/code")
self.assertEqual(project_key("/srv/log", home), "srv/log")
self.assertEqual(project_archive("/h/code/log", home, {}), pathlib.Path("/h/.claude/loop-claude-transcripts/log"))
self.assertEqual(project_archive("/h/code/log", home, {"LOOP_CLAUDE_TRANSCRIPTS": "/a"}), pathlib.Path("/a/log"))
def test_finds_the_checkout_a_key_names_under_code_or_else_under_the_root(self):
with tempfile.TemporaryDirectory() as home:
(pathlib.Path(home) / "code" / "log").mkdir(parents=True)
self.assertEqual(checkout_of("log", pathlib.Path(home)), f"{home}/code/log")
self.assertEqual(checkout_of("home/me/.claude", pathlib.Path(home)), "/home/me/.claude")
if __name__ == "__main__":
unittest.main()