"""The files by which a loop-claude shows loop-inbox that it runs, and the todo.md items its chunk takes. A running loop holds .running.lock in Paths.waiting for its whole run, and keeps .running beside it: its checkout, and the ID and tagline of each item its chunk takes. loop-inbox lists a loop only while its lock is held, so a killed loop drops off the list though its file stays. The file is replaced whole on each change, which gives it a new inode, so the lock is a file of its own. """ import contextlib import dataclasses import json import pathlib import typing from loop_claude.effects import Effects, say from failure import Failure from loop_claude.session_lock import held, taken from file_writes import replace_json # How many times, 0.1 s apart, a loop tries to take its lock: loop-inbox takes it for a moment each time it looks whether the loop runs. LOCK_TRIES = 10 @dataclasses.dataclass(frozen=True) class Taken: """A todo.md item a chunk takes.""" id: int # The item's tagline without its bold marks; empty where the default branch's todo.md holds no such item. tagline: str @dataclasses.dataclass(frozen=True) class RunningLoop: session: str # The checkout the loop runs in. root: str # The routed item first; empty before the chunk names one. items: tuple[Taken, ...] Show = typing.Callable[[tuple[Taken, ...]], None] def running_file(folder: pathlib.Path, session: str) -> pathlib.Path: return folder / f"{session}.running" def running_lock(folder: pathlib.Path, session: str) -> pathlib.Path: return folder / f"{session}.running.lock" @contextlib.contextmanager def shown_running(folder: pathlib.Path, session: str, root: str, effects: Effects) -> typing.Iterator[Show]: """Lists the loop in loop-inbox as running while the with block runs, at first with no item, and yields what lists the items its chunk takes. A failure only warns, and the loop runs unlisted.""" with contextlib.ExitStack() as stack: if unlocked := locked_soon(stack, folder, running_lock(folder, session), effects): say(f"loop-inbox cannot list this loop as running: {unlocked.reason}", effects) yield lambda items: None return def show(items: tuple[Taken, ...]) -> None: if unshown := replace_json(running_file(folder, session), {"root": root, "items": [dataclasses.asdict(item) for item in items]}): say(f"loop-inbox cannot list this loop's items: {unshown.reason}", effects) show(()) try: yield show finally: # A file this fails to remove stays, and loop-inbox leaves it out once the lock is let go. with contextlib.suppress(OSError): running_file(folder, session).unlink(missing_ok=True) def locked_soon(stack: contextlib.ExitStack, folder: pathlib.Path, path: pathlib.Path, effects: Effects) -> Failure | None: """Holds the lock at path until stack closes, trying LOCK_TRIES times; the last failure where every try failed.""" for _ in range(LOCK_TRIES): attempt = contextlib.ExitStack() unlocked = attempt.enter_context(held(folder, path)) if not unlocked: stack.enter_context(attempt) return None attempt.close() effects.sleep(0.1) return unlocked def running_loops(folder: pathlib.Path) -> list[RunningLoop]: """The loops that hold their lock, by checkout. A file that cannot be read or parsed is left out.""" try: paths = list(folder.glob("*.running")) except OSError: return [] loops = [loop for path in paths if (loop := read_running(path)) and taken(running_lock(folder, loop.session))] return sorted(loops, key=lambda loop: loop.root) def read_running(path: pathlib.Path) -> RunningLoop | None: try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): return None match data: case {"root": str(root), "items": list(items)} if all(is_item(item) for item in items): return RunningLoop(path.name.removesuffix(".running"), root, tuple(Taken(item["id"], item["tagline"]) for item in items)) return None def is_item(item: object) -> bool: match item: # type(), not isinstance(): JSON true is no ID. case {"id": id_, "tagline": str()} if type(id_) is int: return True return False def chunk_items(routed: int, taken_in: tuple[int, ...]) -> tuple[int, ...]: """The IDs of the items a chunk takes: routed, the item it was routed on, 0 for none, then those the judge found it took in, once each.""" return tuple(dict.fromkeys(([routed] if routed else []) + list(taken_in)))