Answer principles round 1: 0 🔴, 3 🟡 (0 misread); return withdraw's failure as a warning, check every field read_ask reads, test loop-inbox's /talk end, move TALK to waiting.py

This commit is contained in:
2026-10-29 00:09:05 +01:00
parent ba8a0df807
commit 4d6926e790
6 changed files with 124 additions and 24 deletions
+9 -4
View File
@@ -3,7 +3,7 @@ import sys
import typing
import uuid
from loop_claude.waiting import answered, Ask, Asking, claude_ended, ClaudeCommand, ClaudeOpening, OpenInInbox, OpenOnTerminal, POLL_SECONDS, publish, Typed, withdraw
from loop_claude.waiting import answered, Ask, Asking, claude_ended, ClaudeCommand, ClaudeOpening, OpenInInbox, OpenOnTerminal, POLL_SECONDS, publish, TALK, Typed, withdraw
from loop_claude.effects import Effects, say
from failure import Failure
from claude_code.transcript import human_turns, read_transcript
@@ -16,7 +16,6 @@ from loop_claude.project.checkout import worktrees
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): "
@@ -52,7 +51,7 @@ def put_question(question: str, answer_here: bool, session: WorkerSession, paths
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)
withdrawn(paths, ask, effects)
def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop:
@@ -82,12 +81,18 @@ def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
def withdrawn(paths: Paths, ask: Ask, effects: Effects) -> None:
"""Takes ask out of loop-inbox. A failure only warns: loop-inbox drops the ask once the loop's process ends."""
if unwithdrawn := withdraw(paths.waiting, ask.session):
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", 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(chosen, session, paths, effects))
finally:
withdraw(paths.waiting, chosen.ask.session)
withdrawn(paths, chosen.ask, effects)
def opened(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
+9
View File
@@ -720,6 +720,15 @@ 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_takes_the_answer_typed_on_its_terminal_where_loop_inbox_cannot_list_the_question(self):
self.paths.waiting.parent.mkdir(parents=True)
self.paths.waiting.write_text("")
answer, said = self.put(FakeEffects(inputs=["Use B."]))
self.assertEqual(answer, "Use B.")
self.assertIn(f"loop-inbox may still list this question: cannot remove {self.paths.waiting / f'{self.session.id}.json'}: Not a directory", said)
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), FakeEffects(on_terminal_claude=[0], git=[""]).effects())
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
def talk(self, chosen, effects):
with contextlib.redirect_stderr(io.StringIO()) as said:
stop = interrupt.talk(chosen, self.session, self.paths, effects)
+12 -4
View File
@@ -24,6 +24,8 @@ from file_writes import make_private, replace_json
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
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; interrupt.py says who picked it.
TALK = "/talk"
@dataclasses.dataclass(frozen=True)
@@ -105,10 +107,14 @@ def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask) | {"state": tagged(ask.state)})
def withdraw(folder: pathlib.Path, session: str) -> None:
def withdraw(folder: pathlib.Path, session: str) -> Failure | None:
"""Removes the session's ask and any answer to it."""
for path in (ask_file(folder, session), answer_file(folder, session)):
path.unlink(missing_ok=True)
try:
path.unlink(missing_ok=True)
except OSError as failure:
return Failure(f"cannot remove {path}: {failure.strerror}")
return None
def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]:
@@ -122,18 +128,20 @@ def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[A
def read_ask(path: pathlib.Path) -> Ask | None:
"""The ask in path; None where a field has the wrong type, or names another session than path does."""
try:
data = json.loads(path.read_text(encoding="utf-8"))
ask = Ask(**{**data, "state": ask_state(data["state"])})
except (OSError, ValueError, TypeError, KeyError):
return None
texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question))
# 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
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None
def ask_state(data: object) -> AskState:
match data:
case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}}:
case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}} if all(isinstance(text, str) for text in [*args, *env.values()]):
return Asking(ClaudeCommand(args, cwd, env))
case {"kind": "OpenOnTerminal"}:
return OpenOnTerminal()
+1 -2
View File
@@ -8,8 +8,7 @@ import dataclasses
import textwrap
import typing
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_claude.cycle.interrupt import TALK
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, TALK
ENTER = "enter"
BACKSPACE = "backspace"
+21 -11
View File
@@ -23,6 +23,7 @@ bin/loop_claude/waiting.py describes.
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
"""
import contextlib
import curses
import pathlib
import sys
@@ -75,7 +76,7 @@ def run(window: curses.window, paths: Paths, effects: Effects) -> None:
case Send(ask, text):
screen = Listing(note=sent(folder, ask, text))
case Open(ask):
screen = Listing(note=opened(window, paths, ask, effects))
screen = Listing(note=opened(lambda: off_screen(window), paths, ask, effects))
case Listing() | Answering() as next_screen:
screen = next_screen
@@ -125,8 +126,8 @@ def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
return f"Sent to {ask.root}."
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."""
def opened(screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, ask: Ask, effects: Effects) -> str:
"""Opens the worker's claude session on this terminal, inside screen_off, once the loop has made way for it, and says what came of it."""
folder = paths.waiting
if not (isinstance(ask.state, Asking) and still_waits(folder, ask)):
return no_longer_waits(ask)
@@ -135,14 +136,23 @@ def opened(window: curses.window, paths: Paths, ask: Ask, effects: Effects) -> s
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()
try:
unstarted = hand_over(ask.state.talk, paths, effects)
finally:
unsent = send(folder, ask, ClaudeEnded())
curses.reset_prog_mode()
window.refresh()
with screen_off():
try:
unstarted = hand_over(ask.state.talk, paths, effects)
finally:
unsent = send(folder, ask, ClaudeEnded())
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
@contextlib.contextmanager
def off_screen(window: curses.window) -> typing.Iterator[None]:
"""Hands the terminal to another program, and draws loop-inbox again once it ends."""
curses.def_prog_mode()
curses.endwin()
try:
yield
finally:
curses.reset_prog_mode()
window.refresh()
+72 -3
View File
@@ -1,4 +1,7 @@
import contextlib
import dataclasses
import io
import json
import pathlib
import shutil
import sys
@@ -9,7 +12,10 @@ 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, Asking, ClaudeCommand, OpenInInbox, OpenOnTerminal, Typed
from failure import Failure
from loop_inbox import inbox, main
from loop_claude.paths import paths_from
from loop_claude.effects import system_effects
from loop_claude import waiting
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
@@ -100,9 +106,48 @@ class Answers(unittest.TestCase):
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))
def test_a_claim_the_loop_did_not_make_way_for_in_time_is_taken_back(self):
ask = asked("s1", "/code/log")
waiting.publish(self.folder, ask)
self.claim(ask, lambda: None)
# A loop that reads it late ends its wait at once, as for a claude that has ended.
self.assertEqual((waiting.answered(self.folder, ask), waiting.claude_ended(self.folder, ask)), (None, True))
class Opens(unittest.TestCase):
def setUp(self):
home = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, home)
self.paths = paths_from(home)
def open(self, claude):
"""What /talk in loop-inbox says for an ask whose loop makes way at once; claude stands in for claude_on_terminal. Sets self.ended to whether it told the loop that claude ended."""
ask = asked("s1", "/code/log")
waiting.publish(self.paths.waiting, ask)
def made_way(_):
waiting.publish(self.paths.waiting, dataclasses.replace(ask, state=OpenInInbox(INBOX)))
effects = dataclasses.replace(system_effects(), claude_on_terminal=claude, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way)
try:
with contextlib.redirect_stderr(io.StringIO()):
return main.opened(contextlib.nullcontext, self.paths, ask, effects)
finally:
self.ended = waiting.claude_ended(self.paths.waiting, ask)
def test_tells_the_loop_once_claude_ends_or_cannot_start(self):
def unstarted(args, cwd, env):
raise OSError(2, "No such file or directory")
for claude, said in ((lambda args, cwd, env: 0, "claude for /code/log has ended; the loop goes on."), (unstarted, "Could not start claude for /code/log: No such file or directory")):
with self.subTest(said=said):
self.assertEqual(self.open(claude), said)
self.assertTrue(self.ended)
def test_tells_the_loop_when_claude_is_interrupted(self):
def interrupted(args, cwd, env):
raise KeyboardInterrupt
with self.assertRaises(KeyboardInterrupt):
self.open(interrupted)
self.assertTrue(self.ended)
class Keys(unittest.TestCase):
@@ -151,6 +196,30 @@ class Waiting(unittest.TestCase):
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_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_another_sessions_name(self):
with tempfile.TemporaryDirectory() as temp:
path = waiting.ask_file(pathlib.Path(temp), "s1")
waiting.publish(path.parent, asked("s1", "/a"))
good = json.loads(path.read_text())
self.assertEqual(waiting.read_ask(path), asked("s1", "/a"))
for field, value in (
("id", 1),
("session", "s2"),
("root", None),
("question", 3),
("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}),
("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}),
):
with self.subTest(field=field, value=value):
path.write_text(json.dumps(good | {field: value}))
self.assertIsNone(waiting.read_ask(path))
def test_withdraw_says_what_it_cannot_remove(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp, "a file")
folder.write_text("")
self.assertEqual(waiting.withdraw(folder, "s1"), Failure(f"cannot remove {folder / 's1.json'}: Not a directory"))
def test_a_message_reaches_only_the_ask_it_names(self):
with tempfile.TemporaryDirectory() as temp:
folder, ask = pathlib.Path(temp), asked("s1", "/a")