import dataclasses import pathlib from transcript_archive.location import chunk_folder from failure import Failure from transcript_archive.outcomes import FINISHED_AT, workers @dataclasses.dataclass(frozen=True) class FinishedChunk: folder: str finished: str transcript: pathlib.Path subagents: list[pathlib.Path] # 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)) def read_threads(chunk: FinishedChunk) -> list[bytes] | Failure: """The worker's transcript, then each subagent's.""" try: return [path.read_bytes() for path in (chunk.transcript, *chunk.subagents)] except OSError as failure: return Failure(f"could not read {failure.filename}: {failure.strerror}") def latest_worker(project_archive: pathlib.Path, transcript: str) -> str | Failure | None: """The worker the latest verdict archived for the transcript's chunk names; None before its first verdict.""" try: with open(transcript, "rb") as handle: folder = chunk_folder(project_archive, handle.read()) found = sorted(stamped for outcomes in folder.glob("*.outcomes.md") for stamped in workers(outcomes.read_text(encoding="utf-8"))) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read the archive {project_archive}: {failure}") return found[-1][1] if found else None