diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index 98f37707..11d085fc 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -80,7 +80,8 @@ def subagent_name(transcript: pathlib.Path) -> str: except (OSError, UnicodeDecodeError, ValueError): meta = {} meta = meta if isinstance(meta, dict) else {} - kind, description = str(meta.get("agentType") or "subagent"), str(meta.get("description") or "") + # One line for the type, since a line break could forge an archive line such as `Config: `; json.dumps escapes the description's. + kind, description = " ".join(str(meta.get("agentType") or "subagent").split()), str(meta.get("description") or "") return f"{kind} {json.dumps(description, ensure_ascii=False)}" if description else kind diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 9f348cc2..af7f7dba 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -402,6 +402,7 @@ Worker: {OFF_LADDER} for first, then, inputs in ( (judged("interrupt", cost=0.25), judged("finished"), ["Use B."]), (judged("quoted", answer="Use A.", cost=0.25), judged("finished"), []), + (judged("unfinished", cost=0.25), judged("finished"), []), (judged("finished", evidence="never said", cost=0.25), judged("finished"), []), ): with self.subTest(first=first.stdout), tempfile.TemporaryDirectory() as archive: @@ -411,6 +412,36 @@ Worker: {OFF_LADDER} kept = "".join(path.read_text() for path in pathlib.Path(archive).glob("*/*.outcomes.md")) self.assertEqual(kept.count("Judge cost: 0.2500\n"), 1, kept) + def test_stops_with_exit_1_where_a_subagents_transcript_cannot_be_read_for_the_spend(self): + for verdict in ("interrupt", "finished"): + with self.subTest(verdict=verdict), tempfile.TemporaryDirectory() as archive: + unreadable = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" / "agent-x.jsonl" + unreadable.mkdir(parents=True) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged(verdict)], inputs=["Use B."]) + with contextlib.redirect_stderr(io.StringIO()): + stop = run.run_cycle(dataclasses.replace(self.cycle(fake), project_archive=pathlib.Path(archive))) + self.assertEqual((stop.code, stop.reason), (1, f"could not read the transcript {unreadable}: Is a directory")) + shutil.rmtree(unreadable.parent.parent) + (self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl").unlink() + + def test_counts_the_spend_since_the_last_outcome_that_recorded_one_and_archives_the_reversal(self): + transcript = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl" + transcript.parent.mkdir(parents=True) + old = {"type": "assistant", "timestamp": "2026-09-21T14:13:19Z", "message": {"id": "old", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 100}}} + new = {"type": "assistant", "timestamp": "2026-09-21T14:13:21Z", "message": {"id": "new", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 5}}} + transcript.write_text("\n".join(json.dumps(entry) for entry in [{"type": "queue-operation", "timestamp": "2026-09-21T14:00:00Z"}, old, human("No, keep the old name."), new]) + "\n") + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", record=outcomes.Record("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished", reversed="No, keep the old name.")]) + run.run_cycle(self.cycle(fake)) + latest = max(self.archived_outcomes(), key=len) + self.assertIn(f"""Reversed: +> No, keep the old name. + +Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache write 1h, cache read, output: +- worker, claude-opus-5-5: 0, 0, 0, 0, 5 +""", latest) + def test_stops_with_exit_1_asking_nothing_where_an_interrupt_cannot_be_archived(self): self.archive.parent.mkdir(parents=True) self.archive.write_text("") @@ -1620,6 +1651,14 @@ class Spend(unittest.TestCase): self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9}), Tokens(1, 9, 0, 0, 0)) self.assertEqual(tokens_of(None), Tokens()) + def test_counts_a_message_written_in_the_stamped_second_or_without_a_readable_time_as_before_since(self): + thread = [turn("m1", "a", "2026-11-01T10:00:01Z", output_tokens=7), turn("m2", "a", "not a time", output_tokens=3), turn("m3", "a", "2026-11-01T10:00:02Z", output_tokens=1)] + self.assertEqual(spend.spent("2026-11-01T10:00:01Z", thread, [], "j", Tokens()), {("worker", "a"): Tokens(output=1)}) + + def test_sums_two_subagents_of_one_name_on_one_model(self): + helpers = [spend.Subagent("Explore", [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]), spend.Subagent("Explore", [turn("s2", "b", "2026-11-01T10:00:00Z", input_tokens=4)])] + self.assertEqual(spend.spent("", [], helpers, "j", Tokens()), {("Explore", "b"): Tokens(input=7)}) + def test_counts_each_message_once_by_its_id_and_only_after_since(self): thread = [ turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7), @@ -1640,13 +1679,13 @@ class Spend(unittest.TestCase): with tempfile.TemporaryDirectory() as root: folder = pathlib.Path(root, "s", "subagents") folder.mkdir(parents=True) - for name, meta in [("agent-a", {"agentType": "Explore", "description": "Search the hooks"}), ("agent-b", None)]: + for name, meta in [("agent-a", {"agentType": "Explore", "description": "Search the hooks"}), ("agent-b", None), ("agent-c", ["Explore"]), ("agent-d", {"description": "Läs"}), ("agent-e", {"agentType": "Ex\nConfig: x"})]: (folder / f"{name}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"id": name, "model": "m", "content": [], "usage": {"output_tokens": 1}}, "timestamp": "2026-11-01T10:00:00Z"}) + "\n") if meta: (folder / f"{name}.meta.json").write_text(json.dumps(meta)) found = spend.subagents(str(pathlib.Path(root, "s.jsonl"))) - self.assertEqual([subagent.name for subagent in found], ['Explore "Search the hooks"', "subagent"]) - self.assertEqual(spend.spent("", [], found, "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)}) + self.assertEqual([subagent.name for subagent in found], ['Explore "Search the hooks"', "subagent", "subagent", 'subagent "Läs"', "Ex Config: x"]) + self.assertEqual(spend.spent("", [], found[:2], "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)}) self.assertEqual(spend.subagents(str(pathlib.Path(root, "none.jsonl"))), []) def test_renders_the_spend_then_the_list_prices_of_each_model_it_knows(self): @@ -1676,9 +1715,11 @@ class SetupVersion(unittest.TestCase): with unittest.mock.patch.dict(os.environ, isolated): gone = main.setup_version(pathlib.Path(root), git) self.assertRegex(gone, r"^unknown: [^\n]*not a git repository") - for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"], ["tag", "v0.1.0"]): + for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]): self.assertIsInstance(git(*step, cwd=root), str) head = git("rev-parse", "HEAD", cwd=root).strip() + self.assertEqual(main.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})") + git("tag", "v0.1.0", cwd=root) self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})") git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root) head = git("rev-parse", "HEAD", cwd=root).strip() diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index e3ec36d5..4b576894 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -15,6 +15,7 @@ from review_rules.round_titles import Findings from test_env import isolated_env from release_plan.todo_table import Item from transcript_archive import outcomes +from transcript_archive.location import project_archive from score_outcomes.main import report_text from score_outcomes.reversals import reversal_lines @@ -311,6 +312,20 @@ class ScoreOutcomesTool(unittest.TestCase): def run_tool(self, *args, cwd=None): return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.checkout, env=self.env, text=True) + def test_counts_the_reversals_in_loop_claudes_archive_of_the_main_checkout_run_from_a_worktree(self): + archive = pathlib.Path(self.env["HOME"], "archive") + self.env["LOOP_CLAUDE_TRANSCRIPTS"] = str(archive) + chunk_file(project_archive(str(self.checkout), pathlib.Path(self.env["HOME"]), self.env), "a", ("2026-11-02T10:00:00Z", outcomes.finished('{"model": "m", "item": 4}', "e", "j", record=outcomes.Record("c", reversed="No.")))) + worktree = pathlib.Path(self.env["HOME"], "proj-item-4") + self.git("worktree", "add", "-q", str(worktree)) + ran = self.run_tool(cwd=worktree) + self.assertEqual(ran.returncode, 0, ran.stderr) + self.assertTrue(ran.stdout.endswith("newest first:\n\n- 2026-11-02T10:00:00Z, item 4: 1 reversed\n"), ran.stdout[-400:]) + (archive.rglob("a.outcomes.md").__next__()).write_bytes(b"\xff") + ran = self.run_tool() + self.assertEqual(ran.returncode, 1) + self.assertIn("could not read the archive", ran.stderr) + def test_measures_each_merged_chunk_that_removed_an_item(self): self.git("switch", "-q", "-c", "chunk") self.commit("Do it", {"a.py": "1\n2\n3\n", "todo.md": todo(SECOND)}) @@ -490,6 +505,27 @@ class Reversals(unittest.TestCase): chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m"}', "e", "j", record=outcomes.Record("c")))) self.assertEqual(reversal_lines(archive), ["- 2026-11-02T12:00:00Z, item 7: 2 reversed", "- The other 1 finished chunk: none."]) + def test_says_all_chunks_have_none_and_names_no_item_the_worker_line_lacks(self): + with tempfile.TemporaryDirectory() as root: + archive = pathlib.Path(root) + chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished('{"model": "m", "item": 7}', "e", "j", record=outcomes.Record("c")))) + self.assertEqual(reversal_lines(archive), ["- All 1 finished chunk: none."]) + for worker in ('{"model": "m"}', '{"model": "m", "item": true}', '["m"]', "not json"): + with self.subTest(worker=worker): + chunk_file(archive, "reversed", ("2026-11-04T10:00:00Z", outcomes.finished(worker, "e", "j", record=outcomes.Record("c", reversed="No.")))) + self.assertEqual(reversal_lines(archive), ["- 2026-11-04T10:00:00Z: 1 reversed", "- The other 1 finished chunk: none."]) + (archive / "reversed" / "a.outcomes.md").unlink() + (archive / "reversed").rmdir() + + def test_says_which_archive_it_could_not_read(self): + with tempfile.TemporaryDirectory() as root: + archive = pathlib.Path(root) + chunk_file(archive, "kept", ("2026-11-03T10:00:00Z", outcomes.finished("w", "e", "j", record=outcomes.Record("c")))) + (archive / "kept" / "b.outcomes.md").write_bytes(b"\xff") + found = reversal_lines(archive) + self.assertIsInstance(found, Failure) + self.assertTrue(found.reason.startswith(f"could not read the archive {archive}: "), found.reason) + if __name__ == "__main__": unittest.main() diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index be6cba7c..5d1e042e 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -131,7 +131,9 @@ class Outcomes(unittest.TestCase): self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", record=outcomes.Record("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1)) self.assertEqual(read.last_spent(kept, str(transcript)), utc(NOW)) - self.assertIsInstance(read.last_spent(kept, str(pathlib.Path(root, "gone.jsonl"))), Failure) + 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):