Files
claude-config/bin/loop_claude/cycle/archive.py
T

70 lines
2.8 KiB
Python

import hashlib
import pathlib
import sys
from loop_claude.claude_code.transcript import first_timestamped_line
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, task: str, outcome: str, paths: Paths) -> Failure | None:
try:
with open(path, "rb") as handle:
raw = handle.read()
folder = paths.transcript_archive / project_key / hashlib.sha256(first_timestamped_line(raw)).hexdigest()
make_private(folder)
except OSError as failure:
return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}")
# <session id>/ holds the subagents' transcripts and the tool results too long for the transcript.
if unkept := mirror(pathlib.Path(path.removesuffix(".jsonl")), folder):
return unkept
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
verdict = copy.with_suffix(".verdict.md")
if copy.exists():
return add_outcome(verdict, outcome)
# The copy lands last, so a copy on disk always has its verdict and its session folder beside it.
for dest, data in ((verdict, f"Task: {task}\n\n{outcome}\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
def add_outcome(verdict: pathlib.Path, outcome: str) -> Failure | None:
try:
outcomes = verdict.read_bytes()
except OSError as failure:
return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}")
if unwritten := replace_file(verdict, outcomes + f"\n{outcome}\n".encode()):
return Failure(f"could not archive the transcript: {verdict}: {unwritten.reason}")
return None
def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None:
for file in sorted(source.rglob("*")):
try:
if not file.is_file():
continue
data = file.read_bytes()
copy = copy_for(dest / file.relative_to(source), data)
if copy is None:
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
# Claude Code rewrites some files whole, such as custom-title.json, so a copy is replaced only by a file that grew from it.
def copy_for(copy: pathlib.Path, data: bytes) -> pathlib.Path | None:
if not copy.is_file():
return copy
kept = copy.read_bytes()
if data.startswith(kept):
return copy if data != kept else None
beside = copy.with_name(f"{copy.name}.{hashlib.sha256(data).hexdigest()}")
return None if beside.exists() else beside