55 lines
2.0 KiB
Python
55 lines
2.0 KiB
Python
import dataclasses
|
|
import glob
|
|
import os
|
|
import pathlib
|
|
import shutil
|
|
import uuid
|
|
|
|
from failure import Failure
|
|
from loop_claude.paths import Paths
|
|
|
|
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_for(project_key: str, paths: Paths) -> Session:
|
|
# "A " is the human's cue in the session picker that the session is the loop's.
|
|
name = f"A {project_key} loop-claude"
|
|
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
|
|
|
|
|
|
# <claude_code_transcripts>/-home-me-code-log/<session id>.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
|
|
|
|
|
|
# <session id>.jsonl, <session id>/subagents/, and from older Claude Code versions <session id>.superseded-*/ and <session id>.orphaned-*.jsonl
|
|
def session_files(transcript: str) -> list[str]:
|
|
return sorted(glob.glob(glob.escape(transcript.removesuffix(".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
|