import hashlib import pathlib import sys from loop_claude.failure import Failure from loop_claude.file_writes import make_private, replace_file from loop_claude.paths import Paths def archive(project_key: str, path: str, note: str, paths: Paths) -> Failure | None: folder = paths.transcript_archive / project_key try: with open(path, "rb") as handle: raw = handle.read() make_private(folder) except OSError as failure: return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") # / holds the subagents' transcripts and the tool results too long for the transcript. session_folder = pathlib.Path(path.removesuffix(".jsonl")) if unkept := mirror(session_folder, folder / session_folder.name): return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" # The copy lands last, so a copy on disk always has its verdict and its session folder beside it. if copy.exists(): return None for dest, data in ((copy.with_suffix(".verdict.md"), f"{note}\n".encode()), (copy, raw)): if unwritten := replace_file(dest, data): return Failure(f"could not archive the transcript: {dest}: {unwritten.reason}") print(f"transcript: {copy}", file=sys.stderr) return None # Claude Code only appends to a session folder's files, so overwriting a copy loses nothing. def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: for file in sorted(source.rglob("*")): copy = dest / file.relative_to(source) try: if not file.is_file(): continue data = file.read_bytes() if copy.is_file() and copy.read_bytes() == data: continue make_private(copy.parent) except OSError as failure: return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") if unwritten := replace_file(copy, data): return Failure(f"could not archive the transcript: {copy}: {unwritten.reason}") return None