49 lines
2.5 KiB
Python
49 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 sys
|
|
import time
|
|
|
|
from loop_effects.effects import Effects
|
|
|
|
# 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) -> 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 on stderr, 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:
|
|
print(f"could not keep the run in {folder}: {failure}", file=sys.stderr, flush=True)
|
|
return proc
|
|
|
|
return dataclasses.replace(effects, claude=run)
|
|
|
|
|
|
def print_report(folder: pathlib.Path, report: str) -> None:
|
|
"""Prints the report a replay ends with, and keeps it in folder, beside the runs."""
|
|
print(report)
|
|
try:
|
|
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
(folder / RESULT).write_text(report + "\n", encoding="utf-8")
|
|
except OSError as failure:
|
|
print(f"could not keep the result in {folder}: {failure}", file=sys.stderr, flush=True)
|