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: """Exists while its transcript does.""" 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: return transcript_file(session) is not 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 rerun loop-claude; a rerun before that resumes the finished chunk's session") return None