import dataclasses import glob import os import pathlib import shutil import uuid from failure import Failure NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @dataclasses.dataclass(frozen=True) class Session: """Open while its transcript holds something: claude cannot resume an empty one.""" id: uuid.UUID claude_code_transcripts: pathlib.Path name: str def session_named(name: str, claude_code_transcripts: pathlib.Path) -> Session: return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=claude_code_transcripts, name=name) # /-home-me-code-log/.jsonl def transcript_file(session: Session) -> str | None: hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl")) return hit[0] if hit else None def session_open(session: Session) -> bool: path = transcript_file(session) return path is not None and os.path.getsize(path) > 0 def discard_empty_transcript(session: Session) -> Failure | None: """Removes the 0-byte transcript a failed run can leave: claude refuses `--session-id` for an id whose file stands, 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}; claude refuses to start the session while that file stands") return None # .jsonl, /subagents/, and from older Claude Code versions .superseded-*/ and .orphaned-*.jsonl def session_files(transcript: str) -> list[str]: return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")) # /subagents/agent-.jsonl, beside .jsonl def subagent_transcript(session_transcript: str, agent_id: str) -> str: return os.path.join(session_transcript.removesuffix(".jsonl"), "subagents", f"agent-{agent_id}.jsonl") def delete_session(session: Session) -> Failure | None: path = transcript_file(session) if path is None: return None stem = path.removesuffix(".jsonl") # The transcript goes last: a failed delete leaves a session that session_open still sees, never a new session with this id beside the old one's files. for sibling in sorted(session_files(path), key=lambda sibling: sibling == path): try: shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) except OSError as failure: return Failure(f"could not delete {sibling}: {failure.strerror or failure}; delete every file and folder matching {stem}*, then run it again; a run before that resumes the finished chunk's session") return None