59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
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}")
|
|
# <session id>/ 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
|
|
|
|
|
|
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
|
|
|
|
|
|
# Every chunk of a project reuses its session id, so a name can recur with other content: only a file that grew from its copy replaces 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
|