From 0bf477c630da1ee63a5fec5c209fa26b565eda0c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 26 Nov 2026 00:34:22 +0100 Subject: [PATCH] Start a fresh session where its transcript is empty --- bin/agent_cycle/run.py | 18 +++++++++--- bin/agent_cycle/test_run.py | 10 +++++++ bin/claude_code/session.py | 17 +++++++++-- bin/claude_code/test_claude_code.py | 37 +++++++++++++++++++++++- bin/loop_claude/loop/test_chunk_start.py | 4 +-- docs/reading-cost.md | 14 +++++++++ 6 files changed, 91 insertions(+), 9 deletions(-) diff --git a/bin/agent_cycle/run.py b/bin/agent_cycle/run.py index 84205b86..57bb10bc 100644 --- a/bin/agent_cycle/run.py +++ b/bin/agent_cycle/run.py @@ -7,9 +7,10 @@ from transcript_archive.write import archive from agent_cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args from claude_code.output_limits import BASH_CEILING, BASH_CEILING_CHARACTERS from agent_cycle.judge import Brief, judge, Rejected -from claude_code.session import delete_session, Session, session_open, transcript_file +from claude_code.session import delete_session, discard_empty_transcript, Session, session_open, transcript_file from loop_effects.effects import Effects, say from claude_code.entries import Entry +from claude_code.reply import Limited from failure import Failure from agent_cycle.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished, Verdict from agent_cycle.interrupt import interrupt, Talked, WorkerSession @@ -121,8 +122,7 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> WorkerRan | Stop: if isinstance(answered, QuotedAnswer): say(f"\n=== {cycle.prompts.quote_sources} answered: {answered.question} ===\n{answered.answer}", cycle.effects, stdout=True) - # worker_start runs inside the lambda: a failed attempt may have opened the session. - if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, stepped), worker_environment(cycle), cycle.project_archive, cycle.project.rung if cycle.project else cycle.route.rung, cycle.effects), cycle.effects): + if stop := retried("worker", lambda: started_worker(cycle, answered, stepped), cycle.effects): return stop path = transcript_file(cycle.session) return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}") @@ -137,13 +137,23 @@ def worker_session(cycle: Cycle, transcript_path: str, stepped_from: Rung | None return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, stepped_from or cycle.route.rung, transcript_path, worker_environment(cycle)) -def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]: +def started_worker(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> Failure | Limited | None: + """One run of the worker. worker_start runs on each attempt: a failed one may have opened the session, or left it empty.""" + args = worker_start(cycle, answered, stepped) + if isinstance(args, Failure): + return args + return run_worker(cycle.root, args, worker_environment(cycle), cycle.project_archive, cycle.project.rung if cycle.project else cycle.route.rung, cycle.effects) + + +def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str] | Failure: if isinstance(answered, QuotedAnswer): return worker_args(cycle.session, cycle.route.rung, cycle.prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True) if isinstance(answered, TypedAnswer): return worker_args(cycle.session, cycle.route.rung, cycle.prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True) if session_open(cycle.session): return worker_args(cycle.session, cycle.route.rung, cycle.prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True) + if failure := discard_empty_transcript(cycle.session): + return failure return worker_args(cycle.session, cycle.route.rung, cycle.prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False) diff --git a/bin/agent_cycle/test_run.py b/bin/agent_cycle/test_run.py index e8be0e83..e9007ed2 100644 --- a/bin/agent_cycle/test_run.py +++ b/bin/agent_cycle/test_run.py @@ -172,6 +172,16 @@ Worker: {OFF_LADDER} self.assertEqual(workers[1][workers[1].index("-p") + 1], "Resumed: working") self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2) + def test_a_session_whose_transcript_is_empty_starts_fresh_with_its_session_id_where_claude_cannot_resume_it(self): + path = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl" + path.parent.mkdir(parents=True) + path.touch() + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) + worker, = fake.made("stream_claude") + self.assertIn("--session-id", worker) + self.assertNotIn("--resume", worker) + def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3) self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) diff --git a/bin/claude_code/session.py b/bin/claude_code/session.py index 075cba9b..6a8fe190 100644 --- a/bin/claude_code/session.py +++ b/bin/claude_code/session.py @@ -12,7 +12,7 @@ NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @dataclasses.dataclass(frozen=True) class Session: - """Exists while its transcript does.""" + """Open while its transcript holds something: claude cannot resume an empty one.""" id: uuid.UUID claude_code_transcripts: pathlib.Path name: str @@ -29,7 +29,20 @@ def transcript_file(session: Session) -> str | None: def session_open(session: Session) -> bool: - return transcript_file(session) is not None + path = transcript_file(session) + return path is not None and os.path.getsize(path) > 0 + + +def discard_empty_transcript(session: Session) -> Failure | None: + """Removes a 0-byte transcript, which a run that died early leaves: claude refuses `--session-id` for an id whose file exists, and cannot `--resume` it.""" + path = transcript_file(session) + if path is None or os.path.getsize(path) > 0: + return None + try: + os.remove(path) + except OSError as failure: + return Failure(f"could not remove the empty transcript {path}: {failure.strerror or failure}; remove it, then run it again") + return None # .jsonl, /subagents/, and from older Claude Code versions .superseded-*/ and .orphaned-*.jsonl diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index 7ce0780e..7e249e43 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -2,12 +2,14 @@ import json import pathlib import subprocess import sys +import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from claude_code import entries, reply, transcript +from claude_code import entries, reply, session, transcript from failure import Failure +from test_env import assert_not_root def assistant(*parts): @@ -226,3 +228,36 @@ class ClaudeReply(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class EmptyTranscript(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.session = session.session_named("A proj a-driver", pathlib.Path(temp.name)) + self.path = pathlib.Path(temp.name) / "-home-me-code-log" / f"{self.session.id}.jsonl" + self.path.parent.mkdir() + + def test_a_session_is_open_only_where_its_transcript_holds_something(self): + self.assertFalse(session.session_open(self.session)) + self.path.touch() + self.assertFalse(session.session_open(self.session)) + self.path.write_text("{}\n") + self.assertTrue(session.session_open(self.session)) + + def test_discarding_removes_an_empty_transcript_and_keeps_one_that_holds_something(self): + self.path.touch() + self.assertIsNone(session.discard_empty_transcript(self.session)) + self.assertFalse(self.path.exists()) + self.path.write_text("{}\n") + self.assertIsNone(session.discard_empty_transcript(self.session)) + self.assertEqual(self.path.read_text(), "{}\n") + + def test_discarding_says_where_it_could_not_remove_the_file(self): + assert_not_root(self) + self.path.touch() + self.path.parent.chmod(0o500) + self.addCleanup(self.path.parent.chmod, 0o700) + failure = session.discard_empty_transcript(self.session) + self.assertIsInstance(failure, Failure) + self.assertIn(str(self.path), failure.reason) diff --git a/bin/loop_claude/loop/test_chunk_start.py b/bin/loop_claude/loop/test_chunk_start.py index 69b09b2c..f103e9d6 100644 --- a/bin/loop_claude/loop/test_chunk_start.py +++ b/bin/loop_claude/loop/test_chunk_start.py @@ -46,7 +46,7 @@ class RouteSources(unittest.TestCase): opened = session.session_named("A proj loop-claude", pathlib.Path(root, "projects")) transcript = pathlib.Path(root, "projects", "-fake", f"{opened.id}.jsonl") transcript.parent.mkdir(parents=True) - transcript.write_text("") + transcript.write_text("{}\n") unread = Failure("no git") fake = FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]) with contextlib.redirect_stderr(io.StringIO()) as stderr: @@ -176,7 +176,7 @@ class ChunkFacts(unittest.TestCase): self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")], True)) transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") transcript.parent.mkdir(parents=True) - transcript.write_text("") + transcript.write_text("{}\n") resumed = FakeEffects() facts, _ = chunk_start.chunk_start(a_loop(resumed.effects(), session=opened, launcher=self.LAUNCHER)) self.assertEqual((resumed.made("python"), facts), ([], "")) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 9bce7b73..c2a30e9b 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -3587,3 +3587,17 @@ Read most (opens and searches): - `bin/task_bench/plant.py` 1 - `bin/task_bench/planted_mutant.py` 1 - `bin/task_bench/python_bugs.py` 1 + +## Reading cost, chunk ba67f0a271e0, finished 2026-11-25T22:59:03Z + +77868 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/task_bench/test_shipped_features.py` 5 +- `bin/branch_chunks/cut.py` 4 +- `README.md` 2 +- `bin/task_bench/main.py` 2 +- `bin/task_bench/shipped_features.py` 2 +- `bin/branch_chunks/read.py` 1 +- `docs/decisions.md` 1