"""The lock a loop-claude holds on its worker's session while loop-inbox lists the session's question. loop-inbox reads a held lock as a loop that still runs. The lock is .lock, held with flock, which the kernel frees however the loop ends, killed included. The lock file stays once the loop ends: docs/decisions.md → `loop-inbox: …` says why. """ import contextlib import fcntl import pathlib import typing from failure import Failure from file_writes import make_private def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path: return folder / f"{session}.lock" @contextlib.contextmanager def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]: """Holds the session's lock while the with block runs, or yields a Failure where it cannot. loop-inbox's drop_ended takes the lock for a moment on each ask still on disk, so a loop may find it held.""" try: make_private(folder) except OSError as failure: yield Failure(f"cannot make {folder}: {failure.strerror}") return path = lock_file(folder, session) try: handle = open(path, "a") except OSError as failure: yield Failure(f"cannot open {path}: {failure.strerror}") return with handle: try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: yield Failure(f"another process holds {path}") return except OSError as failure: yield Failure(f"cannot lock {path}: {failure.strerror}") return yield None def running(folder: pathlib.Path, session: str) -> bool: """Whether a loop holds the session's lock; False also where the lock file cannot be opened or locked.""" try: with open(lock_file(folder, session)) as handle: fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB) except BlockingIOError: return True except OSError: return False return False