Files
claude-config/bin/loop_claude/loop/chunk_slot.py
T

47 lines
2.4 KiB
Python

"""The slot a loop holds in its project, so that loops of one project, each on its own chunk, run side by side, each in a session named after its slot."""
import dataclasses
import os
import pathlib
from failure import Failure
from machine_load.slots import first_free_slot
from loop_claude.loop.reload import LoopRun
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from claude_code.session import Session, session_named, session_open
# Under the home folder, a folder per project key holds a file per slot, which a running loop keeps locked with flock.
SLOTS = ".local/state/loop-claude"
# A bound no project reaches. Once todo.md item 375 lands, the project's config sets how many loops run at once.
MOST = 64
def held_slot(home: pathlib.Path, key: str, claude_code_transcripts: pathlib.Path) -> int | Failure:
"""The slot this loop takes, or why it could take none: the lowest free slot whose session is open, so that a rerun resumes a chunk left open, or else the lowest free slot. The loop holds it until it exits; a reload's exec keeps the lock."""
folder = home / SLOTS / key
order = sorted(range(MOST), key=lambda slot: not session_open(session_named(session_name(key, slot), claude_code_transcripts)))
try:
folder.mkdir(parents=True, exist_ok=True)
taken = first_free_slot(folder, order)
except OSError as failure:
return Failure(f"cannot take a slot in {folder}: {failure.strerror}")
if taken is None:
return Failure(f"{MOST} loops of this project are running already; `fuser {folder}/slot-*` names them")
slot, fd = taken
os.set_inheritable(fd, True)
return slot
def session_name(key: str, slot: int) -> str:
""""A " is the human's cue in the session picker that the session is the loop's. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots resumes in it."""
return f"A {key} loop-claude" if slot == 0 else f"A {key} loop-claude {slot + 1}"
def slotted(loop_run: LoopRun, paths: Paths) -> tuple[LoopRun, Session] | Failure:
"""loop_run holding its slot, and the worker's session, named after the slot. A reloaded script keeps the slot it is handed."""
key = project_key(loop_run.root, paths.home)
slot = held_slot(paths.home, key, paths.claude_code_transcripts) if loop_run.slot is None else loop_run.slot
if isinstance(slot, Failure):
return slot
return dataclasses.replace(loop_run, slot=slot), session_named(session_name(key, slot), paths.claude_code_transcripts)