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:
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.waiting import alive, answered, Ask, publish, TalkCommand, Talked, Talking, Typed, withdraw
|
||||
from loop_claude.waiting import answered, Ask, Asking, claude_ended, ClaudeCommand, ClaudeOpening, OpenInInbox, OpenOnTerminal, POLL_SECONDS, publish, Typed, withdraw
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.cycle.states import Talk
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
@@ -18,13 +18,6 @@ ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
TALK = "/talk"
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
# Seconds between looks at whether the claude loop-inbox opened has ended.
|
||||
TALK_POLL = 0.5
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens on loop-claude's terminal."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -37,50 +30,50 @@ class WorkerSession:
|
||||
# What the worker's claude adds to its environment, as the claude /talk opens does.
|
||||
env: dict[str, str]
|
||||
|
||||
def talk_command(self) -> TalkCommand:
|
||||
return TalkCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env)
|
||||
def claude_command(self) -> ClaudeCommand:
|
||||
return ClaudeCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env)
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talk | Talked | Stop:
|
||||
"""Prints question for the human. Where answer_here, shows it in loop-inbox too and returns the first answer: the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; a line typed in loop-inbox; or Talked once the claude loop-inbox opened ends with something typed. Else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
def put_question(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talk | Stop:
|
||||
"""Prints question for the human. Where answer_here, shows it in loop-inbox too and returns the first answer, typed at loop-claude's terminal or in loop-inbox: the line, stripped, or a Talk where they type TALK. Else a Talk at once, on the terminal. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), effects.pid(), Asking(session.claude_command()))
|
||||
if not answer_here:
|
||||
return Talk()
|
||||
ask = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), session.talk_command())
|
||||
return Talk(ask, OpenOnTerminal())
|
||||
shown(paths, ask, effects)
|
||||
answer: str | Talk | Stop | None = None
|
||||
try:
|
||||
answer = first_answer(ask, paths, effects)
|
||||
return answer
|
||||
finally:
|
||||
# A Talk keeps ask listed, under its id, for talk to show loop-inbox where claude opens.
|
||||
if not isinstance(answer, Talk):
|
||||
withdraw(paths.waiting, ask.session)
|
||||
|
||||
|
||||
def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop:
|
||||
try:
|
||||
answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask))
|
||||
if isinstance(answer, Talking | Talked):
|
||||
return talked_in_inbox(ask, answer, session.transcript_path, paths, effects)
|
||||
if isinstance(answer, Typed):
|
||||
say(f"Answered in loop-inbox: {answer.text}", effects)
|
||||
answer = answer.text
|
||||
except EOFError:
|
||||
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
|
||||
return needs_human(ANSWER_QUESTION, "the input ended")
|
||||
finally:
|
||||
withdraw(paths.waiting, ask.session)
|
||||
answer = answer.strip()
|
||||
if not answer:
|
||||
match answer:
|
||||
case ClaudeOpening(pid):
|
||||
return Talk(ask, OpenInInbox(pid))
|
||||
case Typed(text):
|
||||
say(f"Answered in loop-inbox: {text}", effects)
|
||||
case str(text):
|
||||
pass
|
||||
case _:
|
||||
typing.assert_never(answer)
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return needs_human(ANSWER_QUESTION, "nothing was typed")
|
||||
return Talk() if answer == TALK else answer
|
||||
|
||||
|
||||
def talked_in_inbox(ask: Ask, answer: Talking | Talked, transcript_path: str, paths: Paths, effects: Effects) -> Talked | Stop:
|
||||
"""Waits, off the terminal, while the claude that loop-inbox opened on the worker's session runs; the human must type something there."""
|
||||
def waited() -> None:
|
||||
if isinstance(answer, Talked):
|
||||
return
|
||||
# Shows loop-inbox that the loop stopped reading its terminal, so loop-inbox may open claude.
|
||||
shown(paths, dataclasses.replace(ask, talk=None, talking=answer.pid), effects)
|
||||
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
|
||||
while not isinstance(answered(paths.waiting, ask), Talked) and alive(answer.pid):
|
||||
effects.sleep(TALK_POLL)
|
||||
return human_typed(transcript_path, waited) or Talked()
|
||||
return Talk(ask, OpenOnTerminal()) if text == TALK else text
|
||||
|
||||
|
||||
def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
|
||||
@@ -89,19 +82,28 @@ def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
|
||||
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
|
||||
|
||||
|
||||
def talk(question: str, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal, listed in loop-inbox while it runs; the human must type something there."""
|
||||
ask = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), talk=None)
|
||||
shown(paths, ask, effects)
|
||||
def talk(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Holds the loop while the human answers in the worker's claude session, listed in loop-inbox as open where it is; the human must type something there."""
|
||||
try:
|
||||
return human_typed(session.transcript_path, lambda: opened(session, paths, effects))
|
||||
return human_typed(session.transcript_path, lambda: opened(chosen, session, paths, effects))
|
||||
finally:
|
||||
withdraw(paths.waiting, ask.session)
|
||||
withdraw(paths.waiting, chosen.ask.session)
|
||||
|
||||
|
||||
def opened(session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
if unstarted := hand_over(session.rung, ["--resume", str(session.id)], session.root, paths, session.env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
def opened(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Returns once the claude the human answers in has ended: the one it opens on the terminal, or the one loop-inbox opened."""
|
||||
# For loop-inbox, this shows that the loop has stopped reading its terminal, so it may open claude.
|
||||
shown(paths, dataclasses.replace(chosen.ask, state=chosen.where), effects)
|
||||
match chosen.where:
|
||||
case OpenOnTerminal():
|
||||
if unstarted := hand_over(session.claude_command(), paths, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
case OpenInInbox(pid):
|
||||
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
|
||||
while not claude_ended(paths.waiting, chosen.ask) and effects.alive(pid):
|
||||
effects.sleep(POLL_SECONDS)
|
||||
case _:
|
||||
typing.assert_never(chosen.where)
|
||||
return None
|
||||
|
||||
|
||||
@@ -119,11 +121,11 @@ def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
|
||||
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects))
|
||||
def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout command runs in, and each of its worktrees, trusted, then runs claude on the terminal as command says; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(command.cwd, effects), lambda text: say(text, effects))
|
||||
try:
|
||||
effects.claude_on_terminal(claude_args(rung, args), root, env)
|
||||
effects.claude_on_terminal(command.args, command.cwd, command.env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
|
||||
@@ -2,7 +2,7 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, Talk, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.routing import after_ruling, judge_rung
|
||||
from transcript_archive.write import archive
|
||||
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
|
||||
@@ -14,7 +14,7 @@ from loop_claude.cycle.judge import judge, Rejected
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk, Talked, WorkerSession
|
||||
from loop_claude.cycle.interrupt import put_question, talk, WorkerSession
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
@@ -99,8 +99,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _, step_up):
|
||||
return ask(cycle, transcript_path, ruling, step_up)
|
||||
case Talking(transcript_path, question, _):
|
||||
return talk(question, worker_session(cycle, transcript_path), cycle.paths, cycle.effects) or HumanTalked()
|
||||
case Talking(transcript_path, chosen, _):
|
||||
return talk(chosen, worker_session(cycle, transcript_path), cycle.paths, cycle.effects) or HumanTalked()
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
@@ -164,7 +164,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | HumanTalked | Stop:
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
@@ -177,9 +177,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, st
|
||||
case Stop():
|
||||
return answer
|
||||
case Talk():
|
||||
return TalkChosen(question)
|
||||
case Talked():
|
||||
return HumanTalked()
|
||||
return TalkChosen(answer)
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.waiting import Ask, OpenInInbox, OpenOnTerminal
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.escalation_mark import StepUp
|
||||
|
||||
@@ -40,11 +41,17 @@ class Interrupting:
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, open on loop-claude's terminal or in loop-inbox, as where says. ask is the question they were asked, which loop-inbox lists as open there."""
|
||||
ask: Ask
|
||||
where: OpenOnTerminal | OpenInInbox
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal; question is what they were asked."""
|
||||
transcript_path: str
|
||||
question: str
|
||||
talk: Talk
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@@ -82,13 +89,13 @@ class HumanTyped:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk at loop-claude's terminal, or the interrupt is for a release ready to cut."""
|
||||
question: str
|
||||
"""The human typed /talk, at loop-claude's terminal or in loop-inbox, or the interrupt is for a release ready to cut."""
|
||||
talk: Talk
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session, opened on loop-claude's terminal or in loop-inbox."""
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -113,10 +120,10 @@ def transition(state: State, event: Event) -> State:
|
||||
return Closing(transcript_path, verdict)
|
||||
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, step_up)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen(question):
|
||||
return Talking(transcript_path, question, quoted_answers)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen(talk):
|
||||
return Talking(transcript_path, talk, quoted_answers)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, _, quoted_answers) | Interrupting(transcript_path, _, quoted_answers), HumanTalked():
|
||||
case Talking(transcript_path, _, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import select
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.waiting import Answer, POLL_SECONDS
|
||||
import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
# Seconds between calls input_or makes while nothing is typed.
|
||||
POLL_SECONDS = 0.5
|
||||
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
|
||||
PYTHON_TIMEOUT = 600
|
||||
|
||||
@@ -26,6 +27,8 @@ class Streaming(typing.Protocol):
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Effects:
|
||||
# Whether the process with this pid still runs.
|
||||
alive: typing.Callable[[int], bool]
|
||||
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
@@ -33,14 +36,18 @@ class Effects:
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: git_repo.Git
|
||||
input: typing.Callable[[str], str]
|
||||
# Prints a prompt, then returns the line typed at the terminal, or the first value other than None that the callable returns, called every POLL_SECONDS. Raises EOFError where the input ends.
|
||||
input_or: typing.Callable[[str, typing.Callable[[], typing.Any]], typing.Any]
|
||||
# Prints a prompt, then returns the line typed at the terminal, or the first answer from loop-inbox that the callable returns, called every POLL_SECONDS. Raises EOFError where the input ends.
|
||||
input_or: typing.Callable[[str, typing.Callable[[], Answer | None]], str | Answer]
|
||||
# A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock.
|
||||
local_time: typing.Callable[[float], str]
|
||||
# The machine's memory; None where it cannot be read.
|
||||
memory: typing.Callable[[], Memory | None]
|
||||
# A new random id.
|
||||
new_id: typing.Callable[[], str]
|
||||
now: typing.Callable[[], float]
|
||||
on_terminal: typing.Callable[[], bool]
|
||||
# This process's pid.
|
||||
pid: typing.Callable[[], int]
|
||||
# Runs a Python script in a directory, as run_python does.
|
||||
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
@@ -61,8 +68,9 @@ class StreamingClaude:
|
||||
|
||||
def system_effects() -> Effects:
|
||||
return Effects(
|
||||
alive=alive,
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
|
||||
claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode,
|
||||
claude_on_terminal=claude_on_terminal,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
execv=os.execv,
|
||||
git=git_repo.git,
|
||||
@@ -70,14 +78,36 @@ def system_effects() -> Effects:
|
||||
input_or=input_or,
|
||||
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)),
|
||||
memory=read_memory,
|
||||
new_id=lambda: str(uuid.uuid4()),
|
||||
now=time.time,
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
pid=os.getpid,
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
)
|
||||
|
||||
|
||||
def claude_on_terminal(args: list[str], cwd: str, env: dict[str, str]) -> int:
|
||||
"""Runs claude on the terminal in cwd, with env added to its environment, and returns its exit code. While claude runs, Ctrl-C belongs to it: this process shares its terminal, and ignores the key."""
|
||||
# A Python handler, unlike SIG_IGN, is reset to the default as claude starts, so Ctrl-C still reaches claude.
|
||||
previous = signal.signal(signal.SIGINT, lambda number, frame: None)
|
||||
try:
|
||||
return subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, previous)
|
||||
|
||||
|
||||
def alive(pid: int) -> bool:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]:
|
||||
"""Runs a Python script in cwd. One that cannot start, or still runs after timeout seconds and is stopped, reads as exit 1, saying why on stderr."""
|
||||
command = [sys.executable, *args]
|
||||
@@ -89,7 +119,7 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def input_or[T](prompt: str, other: typing.Callable[[], T | None]) -> str | T:
|
||||
def input_or(prompt: str, other: typing.Callable[[], Answer | None]) -> str | Answer:
|
||||
# On stderr, where input prints its prompt on a terminal.
|
||||
print(prompt, end="", file=sys.stderr, flush=True)
|
||||
while True:
|
||||
|
||||
@@ -31,7 +31,7 @@ loop on the machine that waits for the human. The first answer counts, from eith
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
trusted in ~/.claude.json. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
|
||||
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
|
||||
|
||||
@@ -3,9 +3,10 @@ import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
from routing_figures.measure import calls, due, render, totals
|
||||
from loop_claude.cycle.interrupt import claude_args, hand_over
|
||||
from loop_claude.waiting import ClaudeCommand
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.interrupt import hand_over
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
@@ -50,7 +51,7 @@ def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, ef
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects):
|
||||
if unstarted := hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects):
|
||||
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
|
||||
|
||||
@@ -37,7 +37,7 @@ argv = sys.argv[1:]
|
||||
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
|
||||
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
|
||||
steps = json.loads(scenario.read_text())
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role}}
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role, "ctrl_c_ignored": signal.getsignal(signal.SIGINT) == signal.SIG_IGN}}
|
||||
if role == "judge":
|
||||
call["stdin"] = sys.stdin.read()
|
||||
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
|
||||
@@ -98,8 +98,13 @@ if role == "worker":
|
||||
elif role == "judge":
|
||||
print(step["stdout"] if "stdout" in step else json.dumps({{"structured_output": step["verdict"]}}))
|
||||
print(step.get("stderr", ""), file=sys.stderr)
|
||||
elif "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
else:
|
||||
if step.get("ctrl_c"):
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too.
|
||||
os.kill(os.getppid(), signal.SIGINT)
|
||||
time.sleep(0.5)
|
||||
if "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
if step.get("unreadable"):
|
||||
transcript().chmod(0)
|
||||
if step.get("vanish"):
|
||||
@@ -731,7 +736,7 @@ class Interrupt(unittest.TestCase):
|
||||
checkout = Checkout(self)
|
||||
folder = checkout.home / ".local" / "state" / "loop-claude"
|
||||
def answered_in_inbox():
|
||||
[ask] = waiting.waiting(folder)
|
||||
[ask] = waiting.waiting(folder, lambda pid: True)
|
||||
waiting.send(folder, ask, waiting.Typed("B"))
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox))
|
||||
@@ -775,6 +780,14 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory"))
|
||||
|
||||
def test_leaves_ctrl_c_to_the_claude_open_for_talk(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, interrupt(type="B", ctrl_c=True), judge(evidence="B")], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "interrupt", "judge", "worker"]))
|
||||
self.assertFalse(run.calls[2]["ctrl_c_ignored"])
|
||||
self.assertIn("[human] B", run.calls[3]["stdin"])
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
|
||||
@@ -51,6 +51,8 @@ NOW = 1790000000
|
||||
STAMP = f"<{NOW}>"
|
||||
# How git answers in a project's checkout it cannot read, such as one that is gone.
|
||||
UNREAD = Failure("not a git repository")
|
||||
# The id FakeEffects gives each new ask, and its pid for loop-claude's process.
|
||||
ASK_ID, PID = "ask-1", 4242
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -64,8 +66,10 @@ def human(content):
|
||||
class FakeEffects:
|
||||
"""Effects that record each call and answer from a script, one answer per call."""
|
||||
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()):
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), gone=()):
|
||||
self.calls = []
|
||||
# The pids of processes that no longer run.
|
||||
self.gone = set(gone)
|
||||
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
|
||||
# Without a script, every read finds all memory available.
|
||||
self.free_memory = list(free_memory)
|
||||
@@ -75,6 +79,7 @@ class FakeEffects:
|
||||
|
||||
def effects(self):
|
||||
return Effects(
|
||||
alive=lambda pid: pid not in self.gone,
|
||||
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
|
||||
claude_on_terminal=self.on_terminal_claude,
|
||||
discard_typed=lambda: self.calls.append(("discard_typed", None)),
|
||||
@@ -84,8 +89,10 @@ class FakeEffects:
|
||||
input_or=self.input_or,
|
||||
local_time=lambda seconds: f"<{seconds}>",
|
||||
memory=self.memory,
|
||||
new_id=lambda: ASK_ID,
|
||||
now=lambda: NOW,
|
||||
on_terminal=lambda: self.terminal,
|
||||
pid=lambda: PID,
|
||||
python=lambda args, cwd: self.answer("python", (args, cwd)),
|
||||
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
||||
stream_claude=self.stream,
|
||||
@@ -170,6 +177,8 @@ class Streamed:
|
||||
|
||||
|
||||
TYPED = states.TypedAnswer("Which one?", "Use B.")
|
||||
# The human chose to answer in the worker's claude session.
|
||||
TALKED = states.Talk(waiting.Ask("a1", "s1", "/c", "q", NOW, 7, waiting.OpenOnTerminal()), waiting.OpenOnTerminal())
|
||||
|
||||
|
||||
class Transitions(unittest.TestCase):
|
||||
@@ -187,13 +196,10 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen("q"), states.Talking("/t", "q")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen("q"), states.Talking("/t", "q", 3)),
|
||||
(states.Talking("/t", "q"), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", "q", 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
# The human talked in the claude loop-inbox opened.
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(TALKED), states.Talking("/t", TALKED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(TALKED), states.Talking("/t", TALKED, 3)),
|
||||
(states.Talking("/t", TALKED), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", TALKED, 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)),
|
||||
(states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
@@ -203,8 +209,8 @@ class Transitions(unittest.TestCase):
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t", "q"), states.Talking("/t", "q", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen("q"), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t", TALKED), states.Talking("/t", TALKED, 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(TALKED), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
@@ -219,7 +225,7 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)),
|
||||
(states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen("q"), states.Talking("/t", "q")),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(TALKED), states.Talking("/t", TALKED)),
|
||||
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
):
|
||||
with self.subTest(state=state, event=event):
|
||||
@@ -664,7 +670,12 @@ class Interrupts(unittest.TestCase):
|
||||
return put, said.getvalue()
|
||||
|
||||
def asked(self):
|
||||
return waiting.waiting(self.paths.waiting)
|
||||
return waiting.waiting(self.paths.waiting, lambda pid: True)
|
||||
|
||||
def ask(self, question="Which one?", state=None):
|
||||
"""The ask put_question makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session."""
|
||||
resumed = waiting.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
return waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, PID, state or waiting.Asking(resumed))
|
||||
|
||||
def test_stops_off_a_terminal_before_asking(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
@@ -680,7 +691,7 @@ class Interrupts(unittest.TestCase):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
fake = FakeEffects(inputs=typed)
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talk())
|
||||
self.assertEqual(self.put(fake, answer_here)[0], states.Talk(self.ask(), waiting.OpenOnTerminal()))
|
||||
self.assertEqual(len(fake.made("input")), len(typed))
|
||||
self.assertEqual(fake.calls[0], ("discard_typed", None))
|
||||
|
||||
@@ -692,9 +703,7 @@ class Interrupts(unittest.TestCase):
|
||||
|
||||
def test_shows_the_question_in_loop_inbox_while_it_waits_and_only_then(self):
|
||||
def typed(_):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.session, ask.root, ask.question, ask.asked, ask.pid, ask.talking), (str(self.session.id), str(self.home), "Which one?", NOW, os.getpid(), None))
|
||||
self.assertEqual(ask.talk, waiting.TalkCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}))
|
||||
self.assertEqual(self.asked(), [self.ask()])
|
||||
return "Use B."
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed]))[0], "Use B.")
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
@@ -711,56 +720,57 @@ class Interrupts(unittest.TestCase):
|
||||
self.assertEqual(self.put(fake, effects=effects), ("Use C.", f"\n{STAMP} Which one?\n{STAMP} Answered in loop-inbox: Use C. \n"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_waits_off_the_terminal_while_loop_inbox_has_claude_open_and_goes_on_once_the_human_typed_there(self):
|
||||
inbox = os.getpid()
|
||||
def talking(other):
|
||||
def talk(self, chosen, effects):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
stop = interrupt.talk(chosen, self.session, self.paths, effects)
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_makes_way_for_the_claude_loop_inbox_opens_and_goes_on_once_the_human_typed_there(self):
|
||||
inbox = 4343
|
||||
def opening(other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talking(inbox))
|
||||
waiting.send(self.paths.waiting, ask, waiting.ClaudeOpening(inbox))
|
||||
return other()
|
||||
fake = FakeEffects(inputs=[opening])
|
||||
self.assertEqual(self.put(fake), (states.Talk(self.ask(), waiting.OpenInInbox(inbox)), f"\n{STAMP} Which one?\n"))
|
||||
def claude_ran(_):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.talk, ask.talking), (None, inbox))
|
||||
# loop-inbox opens claude only once the loop lists it as open there.
|
||||
self.assertEqual(self.asked(), [self.ask(state=waiting.OpenInInbox(inbox))])
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talked())
|
||||
fake = FakeEffects(inputs=[talking])
|
||||
self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
effects = dataclasses.replace(fake.effects(), sleep=claude_ran)
|
||||
self.assertEqual(self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), effects), (None, f"{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
self.assertEqual((fake.made("claude_on_terminal"), list(self.paths.waiting.iterdir())), ([], []))
|
||||
|
||||
def test_stops_when_loop_inbox_ends_its_claude_or_is_gone_with_nothing_typed(self):
|
||||
gone = subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout.strip()
|
||||
for pid, ended in ((os.getpid(), True), (int(gone), False)):
|
||||
with self.subTest(ended=ended):
|
||||
def talking(other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talking(pid))
|
||||
if ended:
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talked())
|
||||
return other()
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[talking]))[0], Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
inbox = 4343
|
||||
def ended(_):
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
# loop-inbox's claude ends while the loop waits, or loop-inbox is gone before the loop looks.
|
||||
for gone in ((), (inbox,)):
|
||||
with self.subTest(gone=gone):
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(FakeEffects(gone=gone).effects(), sleep=ended))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
|
||||
def ran(args):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.question, ask.talk, ask.talking), ("Cut 0.4.0?", None, None))
|
||||
self.assertEqual(self.asked(), [self.ask("Cut 0.4.0?", waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
fake = FakeEffects(on_terminal_claude=[ran], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
interrupt.talk("Cut 0.4.0?", self.session, self.paths, fake.effects())
|
||||
self.talk(states.Talk(self.ask("Cut 0.4.0?"), waiting.OpenOnTerminal()), fake.effects())
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
stop = interrupt.talk("Which one?", self.session, self.paths, fake.effects())
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), fake.effects())
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
interrupt.talk("Which one?", self.session, self.paths, fake.effects())
|
||||
self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), fake.effects())
|
||||
self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}])
|
||||
|
||||
|
||||
|
||||
+95
-33
@@ -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
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
How it shows the loops and a question was picked on 2026-10-28 by a bench of three readers seated as the README's
|
||||
audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it: a block per
|
||||
loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone stops nothing.
|
||||
loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone doesn't stop the loop.
|
||||
"""
|
||||
import dataclasses
|
||||
import textwrap
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting import Ask
|
||||
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_claude.cycle.interrupt import TALK
|
||||
|
||||
ENTER = "enter"
|
||||
@@ -83,13 +83,13 @@ def picked(shown: tuple[Ask, ...], typed: str) -> Listing | Answering:
|
||||
if not 1 <= number <= len(shown):
|
||||
return Listing(note=f"No loop has the number {number}.")
|
||||
ask = shown[number - 1]
|
||||
if ask.talk is None:
|
||||
return Listing(note=f"{ask.root}: claude is open {where_open(ask)}; answer there.")
|
||||
if not isinstance(ask.state, Asking):
|
||||
return Listing(note=f"{ask.root}: claude is open {where_open(ask.state)}; answer there.")
|
||||
return Answering(ask)
|
||||
|
||||
|
||||
def where_open(ask: Ask) -> str:
|
||||
return "in loop-inbox" if ask.talking else "on its terminal"
|
||||
def where_open(state: OpenOnTerminal | OpenInInbox) -> str:
|
||||
return "in loop-inbox" if isinstance(state, OpenInInbox) else "on its terminal"
|
||||
|
||||
|
||||
def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> list[str]:
|
||||
@@ -98,7 +98,7 @@ def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[floa
|
||||
head = "No loop waits for you." if not count else "1 loop waits for you." if count == 1 else f"{count} loops wait for you, oldest first."
|
||||
lines = [head, ""]
|
||||
for number, ask in enumerate(screen.shown, 1):
|
||||
state = f"; claude is open {where_open(ask)}" if ask.talk is None else ""
|
||||
state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}"
|
||||
lines.append(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}")
|
||||
lines += cut(wrapped(ask.question, width - 4), SHOWN_LINES, " ")
|
||||
lines.append("")
|
||||
|
||||
+28
-56
@@ -24,25 +24,20 @@ bin/loop_claude/waiting.py describes.
|
||||
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
|
||||
"""
|
||||
import curses
|
||||
import os
|
||||
import pathlib
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
|
||||
from loop_claude.waiting import Ask, ask_file, read_ask, send, Talked, Talking, Typed, waiting
|
||||
from loop_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.interrupt import hand_over
|
||||
from loop_claude.paths import Paths, paths_from
|
||||
from loop_claude.effects import system_effects
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
USAGE = "usage: loop-inbox"
|
||||
# Milliseconds between refreshes of the list while no key is pressed.
|
||||
REFRESH_MS = 1000
|
||||
# Seconds loop-inbox waits for a loop to stop reading its terminal before it opens claude for /talk; the loop looks for an answer every half second.
|
||||
MAKE_WAY_SECONDS = 5
|
||||
KEYS = {"\n": ENTER, "\r": ENTER, curses.KEY_ENTER: ENTER, "\x7f": BACKSPACE, "\b": BACKSPACE, curses.KEY_BACKSPACE: BACKSPACE, "\x1b": ESCAPE}
|
||||
|
||||
|
||||
@@ -57,19 +52,19 @@ def main(argv: list[str], home: pathlib.Path) -> int:
|
||||
print("loop-inbox: stdin or stdout is not a terminal; run it on one", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
curses.wrapper(lambda window: run(window, paths_from(home)))
|
||||
curses.wrapper(lambda window: run(window, paths_from(home), system_effects()))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def run(window: curses.window, paths: Paths) -> None:
|
||||
def run(window: curses.window, paths: Paths, effects: Effects) -> None:
|
||||
folder = paths.waiting
|
||||
window.timeout(REFRESH_MS)
|
||||
screen: Screen = Listing()
|
||||
while True:
|
||||
screen = refreshed(screen, folder)
|
||||
draw(window, screen)
|
||||
screen = refreshed(screen, folder, effects.alive)
|
||||
draw(window, screen, effects)
|
||||
try:
|
||||
key = window.get_wch()
|
||||
except curses.error:
|
||||
@@ -80,7 +75,7 @@ def run(window: curses.window, paths: Paths) -> None:
|
||||
case Send(ask, text):
|
||||
screen = Listing(note=sent(folder, ask, text))
|
||||
case Open(ask):
|
||||
screen = Listing(note=talked(window, paths, ask))
|
||||
screen = Listing(note=opened(window, paths, ask, effects))
|
||||
case Listing() | Answering() as next_screen:
|
||||
screen = next_screen
|
||||
|
||||
@@ -90,20 +85,20 @@ def key_name(key: str | int) -> str:
|
||||
return KEYS.get(key, key if isinstance(key, str) else "")
|
||||
|
||||
|
||||
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
|
||||
def refreshed(screen: Screen, folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> Screen:
|
||||
"""screen with the loops as they wait now, unless the human is typing a number; a question that no longer waits leaves the answer screen."""
|
||||
match screen:
|
||||
case Listing(_, "", note):
|
||||
return Listing(tuple(waiting(folder)), "", note)
|
||||
return Listing(tuple(waiting(folder, alive)), "", note)
|
||||
case Answering(ask) if not still_waits(folder, ask):
|
||||
return Listing(note=no_longer_waits(ask))
|
||||
return screen
|
||||
|
||||
|
||||
def draw(window: curses.window, screen: Screen) -> None:
|
||||
def draw(window: curses.window, screen: Screen, effects: Effects) -> None:
|
||||
height, width = window.getmaxyx()
|
||||
now = time.time()
|
||||
lines = listing_lines(screen, now, local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, local_time, width)
|
||||
now = effects.now()
|
||||
lines = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.local_time, width)
|
||||
window.erase()
|
||||
for row, line in enumerate(fitted(lines, height)):
|
||||
# The last cell of the screen cannot be written without an error, so each line stops one short of it.
|
||||
@@ -111,14 +106,10 @@ def draw(window: curses.window, screen: Screen) -> None:
|
||||
window.refresh()
|
||||
|
||||
|
||||
def local_time(seconds: float) -> str:
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds))
|
||||
|
||||
|
||||
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
|
||||
"""Whether ask still waits for an answer from loop-inbox."""
|
||||
now = read_ask(ask_file(folder, ask.session))
|
||||
return now is not None and now.id == ask.id and now.talk is not None
|
||||
return now is not None and now.id == ask.id and isinstance(now.state, Asking)
|
||||
|
||||
|
||||
def no_longer_waits(ask: Ask) -> str:
|
||||
@@ -134,43 +125,24 @@ def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
|
||||
return f"Sent to {ask.root}."
|
||||
|
||||
|
||||
def talked(window: curses.window, paths: Paths, ask: Ask) -> str:
|
||||
"""Opens the worker's claude session on this terminal once the loop has stopped reading its own, and says what came of it."""
|
||||
def opened(window: curses.window, paths: Paths, ask: Ask, effects: Effects) -> str:
|
||||
"""Opens the worker's claude session on this terminal once the loop has made way for it, and says what came of it."""
|
||||
folder = paths.waiting
|
||||
if not still_waits(folder, ask) or ask.talk is None:
|
||||
if not (isinstance(ask.state, Asking) and still_waits(folder, ask)):
|
||||
return no_longer_waits(ask)
|
||||
if unsent := send(folder, ask, Talking(os.getpid())):
|
||||
return f"Could not open claude for {ask.root}: {unsent.reason}"
|
||||
if not made_way(folder, ask):
|
||||
return f"{ask.root} did not make way for claude within {MAKE_WAY_SECONDS} s; it was answered on its terminal, or stopped."
|
||||
claimed = claim_talk(folder, ask, effects.pid(), effects.now, effects.sleep)
|
||||
if isinstance(claimed, Failure):
|
||||
return f"Could not open claude for {ask.root}: {claimed.reason}"
|
||||
if not claimed:
|
||||
return f"{ask.root} did not make way for claude within {MAKE_WAY_SECONDS:g} s; it was answered on its terminal, or stopped."
|
||||
curses.def_prog_mode()
|
||||
curses.endwin()
|
||||
# As loop-claude's hand_over does before it opens claude on its own terminal.
|
||||
trust(paths.claude_json, worktrees(ask.talk.cwd, system_effects()), lambda text: print(f"loop-inbox: {text}", file=sys.stderr))
|
||||
# Ctrl-C belongs to claude while it runs, not to loop-inbox.
|
||||
interrupt = signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
try:
|
||||
subprocess.run(["claude", *ask.talk.args], cwd=ask.talk.cwd, env={**os.environ, **ask.talk.env})
|
||||
said = f"claude for {ask.root} has ended; the loop goes on."
|
||||
except OSError as failure:
|
||||
said = f"Could not start claude for {ask.root}: {failure.strerror}"
|
||||
unstarted = hand_over(ask.state.talk, paths, effects)
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, interrupt)
|
||||
unsent = send(folder, ask, Talked())
|
||||
unsent = send(folder, ask, ClaudeEnded())
|
||||
curses.reset_prog_mode()
|
||||
window.refresh()
|
||||
# Without Talked, the loop goes on only once loop-inbox quits.
|
||||
said = f"Could not start claude for {ask.root}: {unstarted.reason}" if unstarted else f"claude for {ask.root} has ended; the loop goes on."
|
||||
# Without ClaudeEnded, the loop goes on only once loop-inbox quits.
|
||||
return f"{said} Could not tell the loop: {unsent.reason}; quit loop-inbox to let it go on." if unsent else said
|
||||
|
||||
|
||||
def made_way(folder: pathlib.Path, ask: Ask) -> bool:
|
||||
"""Whether the loop shows, within MAKE_WAY_SECONDS, that it has stopped reading its terminal for this loop-inbox."""
|
||||
deadline = time.monotonic() + MAKE_WAY_SECONDS
|
||||
while time.monotonic() < deadline:
|
||||
now = read_ask(ask_file(folder, ask.session))
|
||||
if now is None or now.id != ask.id:
|
||||
return False
|
||||
if now.talking == os.getpid():
|
||||
return True
|
||||
time.sleep(0.1)
|
||||
return False
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -10,15 +8,21 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send
|
||||
from loop_claude.waiting import Ask, TalkCommand, Typed
|
||||
from loop_claude.waiting import Ask, Asking, ClaudeCommand, OpenInInbox, OpenOnTerminal, Typed
|
||||
from loop_inbox import inbox, main
|
||||
from loop_claude import waiting
|
||||
|
||||
TALK = TalkCommand(["--resume", "s"], "/c", {})
|
||||
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
|
||||
# The pids of a running loop, of this loop-inbox, and of a loop that has stopped.
|
||||
LOOP, INBOX, GONE = 4242, 4343, 13
|
||||
|
||||
|
||||
def asked(session, root, question="Which one?", at=100.0, pid=None, talk=TALK, talking=None):
|
||||
return Ask(f"ask-{session}", session, root, question, at, os.getpid() if pid is None else pid, talk, talking)
|
||||
def alive(pid):
|
||||
return pid != GONE
|
||||
|
||||
|
||||
def asked(session, root, question="Which one?", at=100.0, pid=LOOP, state=ASKING):
|
||||
return Ask(f"ask-{session}", session, root, question, at, pid, state)
|
||||
|
||||
|
||||
def keyed(screen, *keys):
|
||||
@@ -27,11 +31,6 @@ def keyed(screen, *keys):
|
||||
return screen
|
||||
|
||||
|
||||
def gone_pid():
|
||||
"""The pid of a process that has exited."""
|
||||
return int(subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout)
|
||||
|
||||
|
||||
class Answers(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
@@ -39,7 +38,7 @@ class Answers(unittest.TestCase):
|
||||
|
||||
def answer(self, number, text):
|
||||
"""Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox."""
|
||||
action = keyed(Listing(tuple(waiting.waiting(self.folder))), *number, ENTER, *text, ENTER)
|
||||
action = keyed(Listing(tuple(waiting.waiting(self.folder, alive))), *number, ENTER, *text, ENTER)
|
||||
self.assertIsInstance(action, Send)
|
||||
return main.sent(self.folder, action.ask, action.text)
|
||||
|
||||
@@ -55,7 +54,7 @@ class Answers(unittest.TestCase):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
for ask in (log, bender):
|
||||
waiting.publish(self.folder, ask)
|
||||
picked = keyed(Listing(tuple(waiting.waiting(self.folder))), "1", ENTER, "A", ENTER)
|
||||
picked = keyed(Listing(tuple(waiting.waiting(self.folder, alive))), "1", ENTER, "A", ENTER)
|
||||
# log is answered on its terminal before the answer typed here is sent; bender is now first.
|
||||
waiting.withdraw(self.folder, "s1")
|
||||
self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered on its terminal, or stopped.")
|
||||
@@ -65,27 +64,45 @@ class Answers(unittest.TestCase):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
typing = keyed(Listing((log, bender)), "2")
|
||||
waiting.publish(self.folder, bender)
|
||||
self.assertEqual(main.refreshed(typing, self.folder), typing)
|
||||
self.assertEqual(main.refreshed(typing, self.folder, alive), typing)
|
||||
self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender))
|
||||
|
||||
def test_a_loop_whose_claude_is_open_takes_no_answer_here(self):
|
||||
for talking, where in ((None, "on its terminal"), (7, "in loop-inbox")):
|
||||
for state, where in ((OpenOnTerminal(), "on its terminal"), (OpenInInbox(7), "in loop-inbox")):
|
||||
with self.subTest(where=where):
|
||||
self.assertEqual(keyed(Listing((asked("s1", "/code/log", talk=None, talking=talking),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there."))
|
||||
self.assertEqual(keyed(Listing((asked("s1", "/code/log", state=state),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there."))
|
||||
|
||||
def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us"))
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), Answering(ask, "Us"))
|
||||
waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask"))
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered on its terminal, or stopped."))
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), Listing(note="/code/log no longer waits for that answer: it was answered on its terminal, or stopped."))
|
||||
|
||||
def test_talk_opens_claude_only_once_the_loop_has_stopped_reading_its_terminal(self):
|
||||
def claim(self, ask, loop_does):
|
||||
"""claim_talk's result for ask, and the seconds it waited; loop_does acts as the loop at claim_talk's first wait."""
|
||||
tenths = [0]
|
||||
def sleep(seconds):
|
||||
if not tenths[0]:
|
||||
loop_does()
|
||||
tenths[0] += round(seconds * 10)
|
||||
return waiting.claim_talk(self.folder, ask, INBOX, lambda: tenths[0] / 10, sleep), tenths[0] / 10
|
||||
|
||||
def test_talk_opens_claude_only_once_the_loop_has_made_way_for_this_loop_inbox(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
waiting.publish(self.folder, dataclasses.replace(ask, talk=None, talking=os.getpid()))
|
||||
self.assertTrue(main.made_way(self.folder, ask))
|
||||
waiting.withdraw(self.folder, "s1")
|
||||
self.assertFalse(main.made_way(self.folder, ask))
|
||||
for loop_does, claimed in (
|
||||
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(INBOX))), (True, 0.1)),
|
||||
(lambda: waiting.withdraw(self.folder, "s1"), (False, 0.1)),
|
||||
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)),
|
||||
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)),
|
||||
(lambda: None, (False, waiting.MAKE_WAY_SECONDS)),
|
||||
):
|
||||
with self.subTest(claimed=claimed):
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(self.claim(ask, loop_does), claimed)
|
||||
# A claim the loop didn't make way for in time is taken back: a loop that reads it late ends its wait at once, as for a claude that has ended.
|
||||
self.assertIsNone(waiting.answered(self.folder, ask))
|
||||
self.assertTrue(waiting.claude_ended(self.folder, ask))
|
||||
|
||||
|
||||
class Keys(unittest.TestCase):
|
||||
@@ -125,27 +142,30 @@ class Keys(unittest.TestCase):
|
||||
class Waiting(unittest.TestCase):
|
||||
def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
late, early, stopped = asked("s1", "/a", at=300), asked("s2", "/b", at=100), asked("s3", "/c", at=50, pid=gone_pid())
|
||||
late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, pid=GONE, state=OpenOnTerminal())
|
||||
for ask in (late, early, stopped):
|
||||
waiting.publish(pathlib.Path(folder), ask)
|
||||
pathlib.Path(folder, "s4.json").write_text("{")
|
||||
pathlib.Path(folder, "s5.json").write_text('{"pid": 0}')
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late])
|
||||
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder), alive), [early, late])
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder), lambda pid: True), [stopped, early, late])
|
||||
|
||||
def test_an_answer_names_the_ask_it_answers(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
ask = asked("s1", "/a")
|
||||
for answer in (Typed("A"), waiting.Talking(7), waiting.Talked()):
|
||||
with self.subTest(answer=answer):
|
||||
waiting.send(pathlib.Path(folder), ask, answer)
|
||||
self.assertEqual(waiting.answered(pathlib.Path(folder), ask), answer)
|
||||
self.assertIsNone(waiting.answered(pathlib.Path(folder), dataclasses.replace(ask, id="another")))
|
||||
def test_a_message_reaches_only_the_ask_it_names(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder, ask = pathlib.Path(temp), asked("s1", "/a")
|
||||
another = dataclasses.replace(ask, id="another")
|
||||
for message, answer, ended in ((Typed("A"), Typed("A"), False), (waiting.ClaudeOpening(7), waiting.ClaudeOpening(7), False), (waiting.ClaudeEnded(), None, True)):
|
||||
with self.subTest(message=message):
|
||||
waiting.send(folder, ask, message)
|
||||
self.assertEqual((waiting.answered(folder, ask), waiting.claude_ended(folder, ask)), (answer, ended))
|
||||
self.assertEqual((waiting.answered(folder, another), waiting.claude_ended(folder, another)), (None, False))
|
||||
|
||||
|
||||
class Shown(unittest.TestCase):
|
||||
def test_the_list_shows_each_loops_checkout_wait_and_the_first_lines_of_its_question(self):
|
||||
log = asked("s1", "/code/log", "Which store should the cache use: Redis or SQLite? Redis is already deployed for sessions.", at=0)
|
||||
cut = asked("s2", "/code/c", "Cut 0.4.0?", at=3600 * 25, talk=None)
|
||||
cut = asked("s2", "/code/c", "Cut 0.4.0?", at=3600 * 25, state=OpenOnTerminal())
|
||||
lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 34)
|
||||
self.assertEqual(lines, [
|
||||
"2 loops wait for you, oldest first.",
|
||||
|
||||
@@ -215,7 +215,7 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
Reference in New Issue
Block a user