Answer architecture round 1: 1 🔴, 6 🟡 (0 misread); open claude through one hand_over, route loop-inbox's /talk through the Talking state, give Ask one state

This commit is contained in:
2026-10-28 23:57:33 +01:00
parent a7fe878631
commit 3409ab3d07
17 changed files with 374 additions and 258 deletions
+95 -33
View File
@@ -1,33 +1,62 @@
"""The files by which a loop-claude that waits for the human shows its question in loop-inbox, and takes an answer typed there.
A waiting loop keeps one file per session, <session id>.json, in Paths.waiting, and removes it once answered or stopped.
Its state says whether it waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox.
loop-inbox answers by replacing <session id>.answer. The answer names the ask it answers by its id, so an answer
meant for an earlier question, or sent as the loop took an answer on its terminal, never answers a later one.
/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
1. loop-inbox writes Talking, with its pid.
2. The loop stops reading its terminal and republishes its ask with talking set to that pid; loop-inbox opens claude only once it reads that.
3. loop-inbox writes Talked once claude exits. The loop also stops waiting if loop-inbox's process is gone.
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
2. The loop stops reading its terminal and republishes its ask as OpenInInbox with that pid. claim_talk returns True
once it reads that, and loop-inbox opens claude.
3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with claude_ended. The loop also stops waiting
if loop-inbox's process is gone.
"""
import dataclasses
import json
import os
import pathlib
import typing
from failure import Failure
from file_writes import make_private, replace_json
# Seconds between a loop's looks for an answer from loop-inbox, and for the end of the claude loop-inbox opened.
POLL_SECONDS = 0.5
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
MAKE_WAY_SECONDS = 10 * POLL_SECONDS
@dataclasses.dataclass(frozen=True)
class TalkCommand:
"""How loop-inbox runs claude on the worker's session: claude's arguments, its folder and what it adds to the environment."""
class ClaudeCommand:
"""How claude opens on a terminal: its arguments, its folder and what it adds to the environment."""
args: list[str]
cwd: str
env: dict[str, str]
@dataclasses.dataclass(frozen=True)
class Asking:
"""The ask waits for an answer; talk opens the worker's claude session for /talk."""
talk: ClaudeCommand
@dataclasses.dataclass(frozen=True)
class OpenOnTerminal:
"""claude is open for the ask on the loop's own terminal, and takes no answer from loop-inbox."""
@dataclasses.dataclass(frozen=True)
class OpenInInbox:
"""claude is open for the ask in the loop-inbox whose process is pid."""
pid: int
AskState = Asking | OpenOnTerminal | OpenInInbox
@dataclasses.dataclass(frozen=True)
class Ask:
"""An interrupt's question, as loop-inbox lists it."""
id: str
session: str
# The checkout the loop runs in.
@@ -36,10 +65,7 @@ class Ask:
# When the loop asked, in seconds since the epoch.
asked: float
pid: int
# How loop-inbox opens claude for /talk; None while claude is open for this question, which then takes no answer from loop-inbox.
talk: TalkCommand | None
# The pid of the loop-inbox that has claude open for this question; None while claude is open on the loop's own terminal, or not open.
talking: int | None = None
state: AskState
@dataclasses.dataclass(frozen=True)
@@ -48,16 +74,19 @@ class Typed:
@dataclasses.dataclass(frozen=True)
class Talking:
class ClaudeOpening:
"""loop-inbox, whose process is pid, asks the loop to make way for the claude it opens for /talk."""
pid: int
@dataclasses.dataclass(frozen=True)
class Talked:
pass
class ClaudeEnded:
"""The claude loop-inbox opened for the ask has ended."""
Answer = Typed | Talking | Talked
# What answers a waiting ask.
Answer = Typed | ClaudeOpening
Message = Answer | ClaudeEnded
def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path:
@@ -73,7 +102,7 @@ def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
make_private(folder)
except OSError as failure:
return Failure(f"cannot make {folder}: {failure.strerror}")
return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask))
return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask) | {"state": tagged(ask.state)})
def withdraw(folder: pathlib.Path, session: str) -> None:
@@ -82,7 +111,7 @@ def withdraw(folder: pathlib.Path, session: str) -> None:
path.unlink(missing_ok=True)
def waiting(folder: pathlib.Path) -> list[Ask]:
def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]:
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out, as is one being replaced."""
try:
paths = sorted(folder.glob("*.json"))
@@ -95,21 +124,45 @@ def waiting(folder: pathlib.Path) -> list[Ask]:
def read_ask(path: pathlib.Path) -> Ask | None:
try:
data = json.loads(path.read_text(encoding="utf-8"))
talk = data["talk"] and TalkCommand(**data["talk"])
ask = Ask(**{**data, "talk": talk})
ask = Ask(**{**data, "state": ask_state(data["state"])})
except (OSError, ValueError, TypeError, KeyError):
return None
# A pid of 0 or below would name a process group to alive.
return ask if isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None
def send(folder: pathlib.Path, ask: Ask, answer: Answer) -> Failure | None:
kind = dataclasses.asdict(answer) | {"kind": type(answer).__name__}
return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **kind})
def ask_state(data: object) -> AskState:
match data:
case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}}:
return Asking(ClaudeCommand(args, cwd, env))
case {"kind": "OpenOnTerminal"}:
return OpenOnTerminal()
case {"kind": "OpenInInbox", "pid": int(pid)}:
return OpenInInbox(pid)
raise ValueError(f"not an ask's state: {data!r}")
def send(folder: pathlib.Path, ask: Ask, message: Message) -> Failure | None:
return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **tagged(message)})
def tagged(value: AskState | Message) -> dict[str, object]:
"""value's fields, with its kind, which read_ask and received read it back by."""
return dataclasses.asdict(value) | {"kind": type(value).__name__}
def answered(folder: pathlib.Path, ask: Ask) -> Answer | None:
"""The answer loop-inbox sent to this ask; None for none, or one meant for another ask of the session."""
message = received(folder, ask)
return message if isinstance(message, Typed | ClaudeOpening) else None
def claude_ended(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether loop-inbox said the claude it opened for this ask has ended."""
return isinstance(received(folder, ask), ClaudeEnded)
def received(folder: pathlib.Path, ask: Ask) -> Message | None:
try:
data = json.loads(answer_file(folder, ask.session).read_text(encoding="utf-8"))
except (OSError, ValueError):
@@ -119,18 +172,27 @@ def answered(folder: pathlib.Path, ask: Ask) -> Answer | None:
match data:
case {"kind": "Typed", "text": str(text)}:
return Typed(text)
case {"kind": "Talking", "pid": int(pid)}:
return Talking(pid)
case {"kind": "Talked"}:
return Talked()
case {"kind": "ClaudeOpening", "pid": int(pid)}:
return ClaudeOpening(pid)
case {"kind": "ClaudeEnded"}:
return ClaudeEnded()
return None
def alive(pid: int) -> bool:
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure:
"""loop-inbox's side of /talk: asks the loop to make way for a claude that the loop-inbox whose process is pid opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, or stopped, or didn't make way in time."""
if unsent := send(folder, ask, ClaudeOpening(pid)):
return unsent
deadline = now() + MAKE_WAY_SECONDS
while now() < deadline:
current = read_ask(ask_file(folder, ask.session))
if current is None or current.id != ask.id:
return False
if current.state == OpenInInbox(pid):
return True
if not isinstance(current.state, Asking):
return False
sleep(0.1)
# Takes the claim back: a loop that reads it late waits for no claude, and one that made way late, or failed to show it had, ends its wait.
send(folder, ask, ClaudeEnded())
return False