Files
claude-config/bin/rung_replay/archive.py
T

50 lines
2.5 KiB
Python

"""Keeps each run of judge-replay and review-replay, and the report each prints, in loop-claude's archive: docs/decisions.md → `loop-claude: the archive keeps the raw transcript and each judge run, …`."""
import dataclasses
import hashlib
import json
import pathlib
import re
import subprocess
import time
import typing
from loop_effects.effects import Effects
from failure import Failure
# The type of the first line of a run's file, which holds what the stream lacks: claude's arguments, working directory, prompt, exit code and stderr. No event claude writes has this type.
HEADER = "replay_run"
RESULT = "result.md"
def replay_folder(root: pathlib.Path, tool: str, argv: list[str], now: float) -> pathlib.Path:
"""The folder a replay of tool, run with argv at now, keeps its runs and its result in, under the archive at root. It holds no outcomes file, so no reader of loop-claude's archive takes it for a chunk's."""
name = "-".join([tool, *(arg.lstrip("-") for arg in argv), time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(now))])
return root / "replays" / re.sub(r"[^A-Za-z0-9._-]", "_", name)
def archiving(effects: Effects, folder: pathlib.Path, say: typing.Callable[[str], None]) -> Effects:
"""effects whose claude also writes each run into folder: a header line, then the stream claude printed. A run is kept whether it failed or not, and a run that repeats another word for word is kept once. A folder that can't be written is reported to say, and the replay goes on."""
claude = effects.claude
def run(args: list[str], cwd: str, prompt: str) -> subprocess.CompletedProcess[str]:
proc = claude(args, cwd, prompt)
content = "\n".join([json.dumps({"type": HEADER, "args": args, "cwd": cwd, "prompt": prompt, "returncode": proc.returncode, "stderr": proc.stderr}, ensure_ascii=False), proc.stdout])
try:
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
(folder / f"{hashlib.sha256(content.encode()).hexdigest()}.jsonl").write_text(content, encoding="utf-8")
except OSError as failure:
say(f"could not keep the run in {folder}: {failure}")
return proc
return dataclasses.replace(effects, claude=run)
def kept_report(folder: pathlib.Path, report: str) -> Failure | None:
"""Keeps the report a replay ends with in folder, beside the runs; the Failure where it can't."""
try:
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
(folder / RESULT).write_text(report + "\n", encoding="utf-8")
except OSError as failure:
return Failure(f"could not keep the result in {folder}: {failure}")
return None