Files
claude-config/bin/loop_claude/transcript_archive.py
T

122 lines
4.6 KiB
Python

import dataclasses
import hashlib
import os
import pathlib
import re
import sys
import time
from failure import Failure
from loop_claude.claude_code.transcript import first_timestamped_line
from file_writes import make_private, replace_file
from loop_claude.paths import Paths
from loop_claude.claude_code.session import session_files
FINISHED = "Verdict: finished"
UNFINISHED = "Verdict: unfinished"
STAMP = "%Y-%m-%dT%H:%M:%SZ"
STAMPED = r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ"
FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE)
@dataclasses.dataclass(frozen=True)
class FinishedChunk:
folder: str
finished: str
transcript: pathlib.Path
subagents: list[pathlib.Path]
def archive(project_key: str, path: str, task: str, outcome: str, at: float, paths: Paths) -> Failure | None:
try:
with open(path, "rb") as handle:
raw = handle.read()
# Each chunk's first timestamped line is its own: a finished chunk's session is deleted, so the next chunk's transcript starts afresh.
folder = paths.transcript_archive / project_key / hashlib.sha256(first_timestamped_line(raw)).hexdigest()
make_private(folder)
except OSError as failure:
return unarchived(failure.filename, failure.strerror)
for sibling in session_files(path):
if sibling != path and (unkept := mirror(pathlib.Path(sibling), folder / "session" / os.path.basename(sibling))):
return unkept
copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl"
outcomes = copy.with_suffix(".outcomes.md")
stamped = f"{utc(at)} {outcome}"
if copy.exists() and outcomes.exists():
return add_outcome(outcomes, stamped)
# The copy lands last, so a copy on disk always has its outcomes and its session's files beside it.
for dest, data in ((outcomes, f"Task: {task}\n\n{stamped}\n".encode()), (copy, raw)):
if unwritten := replace_file(dest, data):
return unarchived(dest, unwritten.reason)
print(f"transcript: {copy}", file=sys.stderr)
return None
def unarchived(where: object, why: str | None) -> Failure:
return Failure(f"could not archive the transcript: {where}: {why}")
def add_outcome(outcomes: pathlib.Path, outcome: str) -> Failure | None:
try:
kept = outcomes.read_bytes()
except OSError as failure:
return unarchived(failure.filename, failure.strerror)
if unwritten := replace_file(outcomes, kept + f"\n{outcome}\n".encode()):
return unarchived(outcomes, unwritten.reason)
return None
def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None:
try:
files = [source] if source.is_file() else files_under(source)
except OSError as failure:
return unarchived(failure.filename, failure.strerror)
for file in files:
try:
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 unarchived(failure.filename, failure.strerror)
if unwritten := replace_file(copy, data):
return unarchived(copy, unwritten.reason)
return None
# Path.rglob skips a folder it cannot read; os.walk with onerror reports it.
def files_under(folder: pathlib.Path) -> list[pathlib.Path]:
def fail(error: OSError) -> None:
raise error
return sorted(pathlib.Path(root, name) for root, _, names in os.walk(folder, onerror=fail) for name in names)
# 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
def utc(at: float) -> str:
return time.strftime(STAMP, time.gmtime(at))
# One per chunk folder, its latest finished copy, in the order they finished.
def finished_chunks(project_archive: pathlib.Path) -> list[FinishedChunk] | Failure:
found = []
try:
for folder in sorted(path for path in project_archive.glob("*") if path.is_dir()):
copies = sorted((stamps[-1], outcomes) for outcomes in folder.glob("*.outcomes.md") if (stamps := FINISHED_AT.findall(outcomes.read_text(encoding="utf-8"))))
if copies:
finished, outcomes = copies[-1]
found.append(FinishedChunk(folder.name, finished, outcomes.with_name(outcomes.name.removesuffix(".outcomes.md") + ".jsonl"), sorted(folder.glob("session/*/subagents/*.jsonl"))))
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read the archive {project_archive}: {failure}")
return sorted(found, key=lambda chunk: (chunk.finished, chunk.folder))