Compare commits

...

1 Commits

Author SHA1 Message Date
lilleman 0bf477c630 Start a fresh session where its transcript is empty
CI / tests (pull_request) Failing after 5m31s
2026-11-26 00:34:22 +01:00
6 changed files with 91 additions and 9 deletions
+14 -4
View File
@@ -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)
+10
View File
@@ -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)
+15 -2
View File
@@ -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
# <session id>.jsonl, <session id>/subagents/, and from older Claude Code versions <session id>.superseded-*/ and <session id>.orphaned-*.jsonl
+36 -1
View File
@@ -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)
+2 -2
View File
@@ -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), ([], ""))
+14
View File
@@ -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