46 lines
2.3 KiB
Python
46 lines
2.3 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 loop names its worker's session after its slot, and the archive and the chunk's route follow the session's transcript (bin/transcript_archive/__init__.py)."""
|
|
import dataclasses
|
|
import os
|
|
import pathlib
|
|
|
|
from failure import Failure
|
|
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
|
|
from machine_load.slots import taken_slot
|
|
|
|
# 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"
|
|
# More loops than one project runs at once: todo.md item 375 runs at most the number the project's config allows.
|
|
MOST = 64
|
|
|
|
|
|
def held_slot(home: pathlib.Path, key: str) -> int | Failure:
|
|
"""The lowest slot no running loop of the project holds, which this loop now holds until it exits, a reload's exec included; or why it could take none."""
|
|
folder = home / SLOTS / key
|
|
try:
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
taken = taken_slot(folder, MOST)
|
|
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 then 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 reload's exec keeps the slot's lock open, so the edited script keeps the slot it is handed."""
|
|
key = project_key(loop_run.root, paths.home)
|
|
slot = held_slot(paths.home, key) 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)
|