Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s
CI / tests (pull_request) Successful in 3m43s
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
"""The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
@@ -116,21 +115,19 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map
|
||||
return config
|
||||
session = loop_session(loop_run.root, paths.home)
|
||||
handed = {name: value for name, value in env.items() if name.startswith(HANDED)}
|
||||
lock = project_lock(loop_run.root, paths.home)
|
||||
try:
|
||||
with starting(lock):
|
||||
windows = tmux.listed(session, effects.tmux)
|
||||
if refused := refusal(session, windows, loop_run.root, effects.tmux):
|
||||
return refused
|
||||
chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects)
|
||||
for chunk in chunks:
|
||||
started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed, [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux)
|
||||
if isinstance(started, Failure):
|
||||
return started
|
||||
windows = started
|
||||
return chunks
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot lock {lock / LOCK}: {failure.strerror}")
|
||||
with starting(project_lock(loop_run.root, paths.home)) as unlocked:
|
||||
if unlocked:
|
||||
return unlocked
|
||||
windows = tmux.listed(session, effects.tmux)
|
||||
if refused := refusal(session, windows, loop_run.root, effects.tmux):
|
||||
return refused
|
||||
chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects)
|
||||
for chunk in chunks:
|
||||
started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed, [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux)
|
||||
if isinstance(started, Failure):
|
||||
return started
|
||||
windows = started
|
||||
return chunks
|
||||
|
||||
|
||||
def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux) -> Failure | None:
|
||||
@@ -165,5 +162,5 @@ def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[i
|
||||
|
||||
def wait_for_starts(root: str, home: pathlib.Path) -> None:
|
||||
"""Returns once no loop of the project is starting windows: start_chunks holds LOCK while it starts them. Where the lock cannot be taken, it returns at once."""
|
||||
with contextlib.suppress(OSError), starting(project_lock(root, home)):
|
||||
with starting(project_lock(root, home)):
|
||||
pass
|
||||
|
||||
@@ -11,7 +11,7 @@ from loop_claude.chunk import chunk_items, fresh_prompt
|
||||
from loop_claude.loop.chunk_windows import chunk_session, item_of, start_chunks
|
||||
from loop_claude.loop.chunk_start import chunk_start, plan_item, scored_plan
|
||||
from chunk_driver.chunk_run import closed_cycle
|
||||
from agent_cycle.run import Cycle, run_cycle
|
||||
from agent_cycle.run import Concluded, Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
@@ -20,6 +20,7 @@ from loop_claude.loop.usage import HELP
|
||||
from chunk_driver.this_loop import Loop
|
||||
from loop_state.paths import Paths
|
||||
from transcript_archive.project_key import project_key
|
||||
from model_routing.ladder import ProjectRung, Rung
|
||||
from chunk_driver.project.premises import read_premises
|
||||
from chunk_driver.project.records import read_records
|
||||
from model_routing.ladder_file import SHIPPED
|
||||
@@ -28,9 +29,31 @@ from agent_cycle.direct_message import tell
|
||||
from agent_cycle import tmux
|
||||
|
||||
|
||||
# Starts the chunks that may start now, as chunk_windows.start_chunks does.
|
||||
StartChunks = typing.Callable[[LoopRun, bool, Paths, typing.Mapping[str, str], pathlib.Path, Effects], list[str] | Failure]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Steps:
|
||||
"""The steps a loop takes, each the function of its name, which main binds."""
|
||||
start_chunks: StartChunks
|
||||
fingerprint: typing.Callable[[pathlib.Path], str]
|
||||
exec_if_edited: typing.Callable[[Loop, str, LoopRun], Stop | None]
|
||||
next_cycle: typing.Callable[[LoopRun, Loop], Cycle | Stop]
|
||||
run_cycle: typing.Callable[[Cycle], Stop | Concluded]
|
||||
closed_cycle: typing.Callable[[LoopRun, ProjectRung | None, Concluded, pathlib.Path, str, Loop], LoopRun | Stop]
|
||||
check_routing: typing.Callable[[pathlib.Path, Rung, Loop], Stop | None]
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
steps = Steps(start_chunks, fingerprint, exec_if_edited, next_cycle, run_cycle, closed_cycle, check_routing)
|
||||
return exit_code(lambda: run_loop(argv, env, paths, launcher, cwd, effects, steps), cwd, effects)
|
||||
|
||||
|
||||
def exit_code(run: typing.Callable[[], Stop], cwd: pathlib.Path, effects: Effects) -> int:
|
||||
"""The exit code of the loop that run runs in cwd, once its stop is said and sent as a DM."""
|
||||
try:
|
||||
stop = run_loop(argv, env, paths, launcher, cwd, effects)
|
||||
stop = run()
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
except Exception as crash:
|
||||
@@ -44,7 +67,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
|
||||
return stop.code
|
||||
|
||||
|
||||
def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> Stop:
|
||||
def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects, steps: Steps) -> Stop:
|
||||
loop_run = loop_run_from(argv, cwd, effects)
|
||||
if isinstance(loop_run, Stop):
|
||||
return loop_run
|
||||
@@ -52,38 +75,38 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
if reason := tmux.unusable(effects.tmux, fresh_prompt.DRIVER):
|
||||
return Stop(1, reason)
|
||||
if loop_run.chunk is None:
|
||||
return windows_opened(loop_run, env, paths, launcher, effects)
|
||||
return windows_opened(loop_run, env, paths, launcher, effects, steps.start_chunks)
|
||||
pane = env.get("TMUX_PANE")
|
||||
if not pane:
|
||||
return Stop(1, f"{CHUNK_FLAG} is how loop-claude starts itself in a tmux window; run loop-claude <task>")
|
||||
baseline = fingerprint(launcher)
|
||||
baseline = steps.fingerprint(launcher)
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
window = tmux.Window(loop_session(loop_run.root, paths.home), loop_run.chunk, pane)
|
||||
loop = Loop(root=loop_run.root, session=chunk_session(key, loop_run.chunk, paths.claude_code_transcripts), window=window, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
while True:
|
||||
if stop := exec_if_edited(loop, baseline, loop_run):
|
||||
if stop := steps.exec_if_edited(loop, baseline, loop_run):
|
||||
return stop
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
cycle = next_cycle(loop_run, loop)
|
||||
cycle = steps.next_cycle(loop_run, loop)
|
||||
if isinstance(cycle, Stop):
|
||||
return cycle
|
||||
concluded = run_cycle(cycle)
|
||||
concluded = steps.run_cycle(cycle)
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, fresh_prompt.DRIVER, loop)
|
||||
closed = steps.closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, fresh_prompt.DRIVER, loop)
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
# Off the ladder the worker runs on the project's model itself, which its route names.
|
||||
if stop := check_routing(archive_root(paths.home, env), cycle.project.rung if cycle.project else cycle.route.rung, loop):
|
||||
if stop := steps.check_routing(archive_root(paths.home, env), cycle.project.rung if cycle.project else cycle.route.rung, loop):
|
||||
return stop
|
||||
if isinstance(concluded.verdict, Finished):
|
||||
return handed_on(loop_run, loop)
|
||||
return handed_on(loop_run, loop, steps.start_chunks)
|
||||
|
||||
|
||||
def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects) -> Stop:
|
||||
"""What the loop-claude the human runs does: starts each chunk that may start now in a window of the project's tmux session, then puts that session on the terminal until the human detaches."""
|
||||
started = start_chunks(loop_run, False, paths, env, launcher, effects)
|
||||
def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, start: StartChunks) -> Stop:
|
||||
"""What the loop-claude the human runs does: starts, through start, each chunk that may start now in a window of the project's tmux session, then puts that session on the terminal until the human detaches."""
|
||||
started = start(loop_run, False, paths, env, launcher, effects)
|
||||
if isinstance(started, Failure):
|
||||
return Stop(1, started.reason)
|
||||
session = loop_session(loop_run.root, paths.home)
|
||||
@@ -95,9 +118,9 @@ def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Path
|
||||
return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if effects.tmux_on_terminal(shown) else Stop(0, "")
|
||||
|
||||
|
||||
def handed_on(loop_run: LoopRun, loop: Loop) -> Stop:
|
||||
"""The stop of a loop whose chunk finished, once it has started each chunk that may start now. Its window closes as it exits."""
|
||||
started = start_chunks(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)
|
||||
def handed_on(loop_run: LoopRun, loop: Loop, start: StartChunks) -> Stop:
|
||||
"""The stop of a loop whose chunk finished, once it has started, through start, each chunk that may start now. Its window closes as it exits."""
|
||||
started = start(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)
|
||||
if isinstance(started, Failure):
|
||||
return Stop(1, f"the chunk finished, but the next could not start: {started.reason}")
|
||||
say(f"the chunk finished; started {', '.join(started) or 'no other, since the chunks running fill what may run now'}", loop.effects, stdout=True)
|
||||
|
||||
@@ -67,6 +67,6 @@ def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) ->
|
||||
if unstarted:
|
||||
return Stop(1, f"could not start claude for the routing calls in {loop.paths.config_clone}, the setup's development clone: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through docs/decisions.md → "Working rules", so it is not asked twice.
|
||||
if unmarked := state.mark_raised(root, new, utc(loop.effects.now())):
|
||||
if unmarked := state.mark_raised(root, new, utc(loop.effects.now()), loop.effects.replace_file):
|
||||
say(f"routing figures: {unmarked.reason}", loop.effects)
|
||||
return None
|
||||
|
||||
@@ -5,7 +5,6 @@ import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
@@ -36,11 +35,23 @@ class RouteSources(unittest.TestCase):
|
||||
# An item that left the plan, as once it shipped.
|
||||
self.assertIsNone(chunk_start.plan_item(plan, 999, FakeEffects().effects()))
|
||||
# A chunk start reads the default branch once, for routing and for scoring the items the worker names.
|
||||
with unittest.mock.patch.object(chunk_start, "session_open", return_value=True), unittest.mock.patch.object(chunk_start, "fetched_plan", return_value=plan) as fetched:
|
||||
loop = a_loop(FakeEffects().effects())
|
||||
self.assertEqual(chunk_start.chunk_start(loop), ("", plan))
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = configured(self, pathlib.Path(root))
|
||||
config = folder / "config.toml"
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
|
||||
(folder / "todo.md").write_text(TODO)
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path(root, "projects"))
|
||||
transcript = pathlib.Path(root, "projects", "-fake", f"{opened.id}.jsonl")
|
||||
transcript.parent.mkdir(parents=True)
|
||||
transcript.write_text("")
|
||||
unread = Failure("no git")
|
||||
fake = FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[1])))
|
||||
self.assertEqual((facts, held.plan), ("", plan_of(TODO)))
|
||||
self.assertEqual([args for args in fake.made("git") if args[0] == "remote"], [["remote"]])
|
||||
# An open session is no fresh chunk, so the human isn't told again of releases the plan cannot show.
|
||||
fetched.assert_called_once_with(loop, False)
|
||||
self.assertEqual(stderr.getvalue(), "")
|
||||
unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8")
|
||||
for plan, said in ((DefaultPlan(plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")):
|
||||
with self.subTest(said=said):
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
@@ -13,11 +14,18 @@ from loop_effects.doubles import assistant, FakeEffects
|
||||
from loop_claude.loop import chunk_windows
|
||||
from project_config.doubles import configured
|
||||
from failure import Failure
|
||||
from git_cli import git_repo
|
||||
from test_env import isolated_env
|
||||
from loop_claude.loop import main
|
||||
from release_plan import next_chunk
|
||||
from loop_state import paths
|
||||
from agent_cycle import tmux
|
||||
from touch_predictions.doubles import plan as touch_plan
|
||||
from touch_predictions.doubles import todo, plan as touch_plan
|
||||
|
||||
|
||||
def plan_text(*touched):
|
||||
"""A todo.md of items 1, 2 and on, each predicted to touch the path given for it."""
|
||||
return todo(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1)))
|
||||
|
||||
|
||||
class ChunkWindows(unittest.TestCase):
|
||||
@@ -76,8 +84,8 @@ class ChunkWindows(unittest.TestCase):
|
||||
self.assertIsNone(chunk_windows.item_of("item-\u0663"))
|
||||
|
||||
def test_starts_only_the_next_item_where_the_touch_predictions_cannot_be_read(self):
|
||||
with unittest.mock.patch.object(chunk_windows, "chunks_beside", return_value="item 1's Touches: list cannot be read"):
|
||||
self.assertEqual(chunk_windows.may_start(self.plan("a.py", "c.py"), [], set(), 3), ["item-1"])
|
||||
items = touch_plan((1, "1.0.0", "", "- a.py"), (2, "1.0.0", "", "- `c.py`"))
|
||||
self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=items, first=items[0], text="", branch_template=""), [], set(), 3), ["item-1"])
|
||||
|
||||
def test_a_chunk_whose_transcript_cannot_be_read_holds_the_item_it_started_from(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
@@ -113,7 +121,7 @@ class StartChunks(unittest.TestCase):
|
||||
self.home = configured(self, self.root).parents[1]
|
||||
self.session = "loop-" + str(self.root).lstrip("/").replace("/", "-").replace(".", "-")
|
||||
# Items 1 and 2 overlap, so 2 waits; 3 runs beside 1.
|
||||
self.plan = ChunkWindows.plan(self, "a.py", "a.py", "c.py")
|
||||
self.plan = plan_text("a.py", "a.py", "c.py")
|
||||
|
||||
def limit(self, chunks):
|
||||
config = self.home / ".claude-projects" / self.root.name / "config.toml"
|
||||
@@ -123,15 +131,31 @@ class StartChunks(unittest.TestCase):
|
||||
"""start_chunks' answer, for a session whose @loop-root names owner, by default this checkout."""
|
||||
fake.owner = str(self.root) if owner is None else owner
|
||||
run = main.LoopRun(0, str(self.root), "ship it", "", chunk=chunk)
|
||||
with unittest.mock.patch.object(chunk_windows, "next_plan", return_value=plan or self.plan) as planned, contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
effects = fake.effects()
|
||||
ran = []
|
||||
effects = dataclasses.replace(fake.effects(), git=self.git_reading(self.plan if plan is None else plan, ran))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home), env or {}, self.LAUNCHER, effects)
|
||||
self.said = said.getvalue()
|
||||
self.planned = planned.call_count
|
||||
if planned.call_count:
|
||||
planned.assert_called_once_with(str(self.root), self.home, effects)
|
||||
fetches = [args for args in ran if args[0] == "fetch"]
|
||||
self.planned = len(fetches)
|
||||
self.assertIn(fetches, ([], [["fetch", "--quiet", "origin"]]))
|
||||
return started
|
||||
|
||||
def git_reading(self, plan, ran):
|
||||
"""A git that notes each call in ran, and reads plan, a todo.md's text, on the checkout's default branch; a Failure answers every call instead, and an error is raised by every call."""
|
||||
if isinstance(plan, str):
|
||||
(self.root / "todo.md").write_text(plan)
|
||||
for command in (["add", "todo.md"], ["-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "--quiet", "--allow-empty", "-m", "plan"]):
|
||||
subprocess.run(["git", "-C", str(self.root), *command], check=True, env=isolated_env())
|
||||
|
||||
def git(*args, **options):
|
||||
ran.append(list(args))
|
||||
if isinstance(plan, BaseException):
|
||||
raise plan
|
||||
return plan if isinstance(plan, Failure) else git_repo.git(*args, **options, env=isolated_env())
|
||||
|
||||
return git
|
||||
|
||||
def starts(self, fake):
|
||||
"""The window starts of fake's tmux calls, each as (command, window name, what it runs)."""
|
||||
return [(call[0], call[call.index("-n") + 1], call[call.index("--") + 1:]) for call in fake.tmux_calls if call[0] in ("new-session", "new-window")]
|
||||
@@ -204,7 +228,7 @@ class StartChunks(unittest.TestCase):
|
||||
def test_a_plan_with_no_item_starts_nothing_beside_a_restarted_chunk(self):
|
||||
self.limit(2)
|
||||
fake = FakeEffects(windows="item-5\t1\t@3\n")
|
||||
self.assertEqual(self.start(fake, plan=next_chunk.NoItem("release 1.0.0 has no items")), ["item-5"])
|
||||
self.assertEqual(self.start(fake, plan=plan_text()), ["item-5"])
|
||||
|
||||
def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self):
|
||||
self.limit(2)
|
||||
@@ -218,7 +242,7 @@ class StartChunks(unittest.TestCase):
|
||||
self.assertEqual(self.start(fake, chunk="item-7", leaving=True), ["item-3"])
|
||||
self.assertEqual([call for call in fake.tmux_calls if call[0] == "kill-window"], [])
|
||||
fake = FakeEffects(windows="item-7\t0\t@1\nno-item\t1\t@3\n")
|
||||
self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=next_chunk.NoItem("release 1.0.0 has no items")), [])
|
||||
self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=plan_text()), [])
|
||||
|
||||
def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self):
|
||||
fake = FakeEffects()
|
||||
@@ -226,8 +250,9 @@ class StartChunks(unittest.TestCase):
|
||||
self.assertIn("starting a chunk without a plan item, since the plan cannot be read: no origin/main", self.said)
|
||||
|
||||
def test_says_why_a_window_could_not_start(self):
|
||||
with unittest.mock.patch.object(tmux, "start_window", return_value=Failure("tmux could not start the window")):
|
||||
self.assertEqual(self.start(FakeEffects()), Failure("tmux could not start the window"))
|
||||
fake = FakeEffects()
|
||||
fake.tmux = lambda args: subprocess.CompletedProcess(args, 1, "", "no room") if args[0] == "new-session" else FakeEffects.tmux(fake, args)
|
||||
self.assertEqual(self.start(fake), Failure(f"tmux could not start the window {self.session}:item-1: no room"))
|
||||
|
||||
def test_says_why_it_cannot_take_the_lock_on_starting_windows(self):
|
||||
(self.home / ".local" / "state").mkdir(parents=True)
|
||||
@@ -236,6 +261,16 @@ class StartChunks(unittest.TestCase):
|
||||
self.assertIsInstance(started, Failure)
|
||||
self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/loop-claude/"), started.reason)
|
||||
|
||||
def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self):
|
||||
with self.assertRaisesRegex(OSError, "the plan's disk is gone"):
|
||||
self.start(FakeEffects(), plan=OSError("the plan's disk is gone"))
|
||||
|
||||
def test_a_chunk_reads_the_other_windows_where_it_cannot_take_the_lock(self):
|
||||
(self.home / ".local" / "state").mkdir(parents=True)
|
||||
(self.home / ".local" / "state" / "loop-claude").write_text("")
|
||||
fake = FakeEffects(windows="item-7\t0\t@1\nitem-9\t1\t@3\n")
|
||||
self.assertEqual(chunk_windows.held_beside("item-7", str(self.root), paths.paths_from(self.home), fake.effects()), [9])
|
||||
|
||||
def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
transcripts = pathlib.Path(temp)
|
||||
|
||||
@@ -108,15 +108,28 @@ class LoopRuns(unittest.TestCase):
|
||||
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
|
||||
|
||||
|
||||
def steps(start_chunks, **others):
|
||||
"""The steps of a loop that starts chunks through start_chunks, and takes each other step through the double given for it, else fails."""
|
||||
def unused(*args):
|
||||
raise AssertionError(args)
|
||||
|
||||
return main.Steps(**{"fingerprint": unused, "exec_if_edited": unused, "next_cycle": unused, "run_cycle": unused, "closed_cycle": unused, "check_routing": unused, **others}, start_chunks=start_chunks)
|
||||
|
||||
|
||||
class WindowStarts(unittest.TestCase):
|
||||
"""The loop-claude the human runs, which starts the windows, and the stop of a window's loop whose chunk finished."""
|
||||
HOME = pathlib.Path("/h")
|
||||
|
||||
def run_loop(self, argv, fake, env=None, started=("item-3", "item-4")):
|
||||
"""run_loop's stop and what it said on stdout, with start_chunks answering `started`; self.asked holds what start_chunks was asked."""
|
||||
with unittest.mock.patch.object(main, "start_chunks", return_value=list(started) if isinstance(started, tuple) else started) as start, contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, fake.effects())
|
||||
self.asked = [call.args[:2] for call in start.call_args_list]
|
||||
self.asked = []
|
||||
|
||||
def start(*args):
|
||||
self.asked.append(args[:2])
|
||||
return list(started) if isinstance(started, tuple) else started
|
||||
|
||||
with contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, fake.effects(), steps(start))
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self):
|
||||
@@ -141,9 +154,10 @@ class WindowStarts(unittest.TestCase):
|
||||
def test_hands_the_window_starts_its_paths_environment_launcher_and_effects(self):
|
||||
fake = FakeEffects(git=["/r\n"], on_terminal=False)
|
||||
effects, env, launcher = fake.effects(), {"LOOP_CLAUDE_X": "1"}, pathlib.Path("/b/loop-claude")
|
||||
with unittest.mock.patch.object(main, "start_chunks", return_value=["item-3"]) as start, contextlib.redirect_stdout(io.StringIO()):
|
||||
main.run_loop(["do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects)
|
||||
self.assertEqual(start.call_args.args, (main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME), env, launcher, effects))
|
||||
asked = []
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
main.run_loop(["do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects, steps(lambda *args: asked.append(args) or ["item-3"]))
|
||||
self.assertEqual(asked, [(main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME), env, launcher, effects)])
|
||||
|
||||
def test_a_window_loop_runs_its_chunk_in_its_own_session_and_window_and_hands_on_once_it_finished(self):
|
||||
fake = FakeEffects(git=["/r\n"])
|
||||
@@ -153,14 +167,15 @@ class WindowStarts(unittest.TestCase):
|
||||
unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished))
|
||||
finished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Finished))
|
||||
closed = [main.LoopRun(1, "/r", "do it", "", chunk="item-3"), main.LoopRun(2, "/r", "do it", "", chunk="item-3")]
|
||||
with unittest.mock.patch.object(main, "fingerprint", return_value=""), unittest.mock.patch.object(main, "exec_if_edited", return_value=None), unittest.mock.patch.object(main, "next_cycle", return_value=cycle) as next_cycle, \
|
||||
unittest.mock.patch.object(main, "run_cycle", side_effect=[unfinished, finished]), unittest.mock.patch.object(main, "closed_cycle", side_effect=closed), \
|
||||
unittest.mock.patch.object(main, "check_routing", return_value=None), unittest.mock.patch.object(main, "handed_on", return_value=Stop(0, "")) as handed_on:
|
||||
stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects)
|
||||
concluded, cycles, started = [unfinished, finished], [], []
|
||||
taken = steps(lambda *args: started.append(args) or [], fingerprint=lambda launcher: "", exec_if_edited=lambda *args: None, next_cycle=lambda *args: cycles.append(args) or cycle,
|
||||
run_cycle=lambda cycle: concluded.pop(0), closed_cycle=lambda *args: closed.pop(0), check_routing=lambda *args: None)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects, taken)
|
||||
loop = this_loop.Loop(root="/r", session=session.session_named("A r loop-claude item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME), env=env, launcher=launcher, effects=effects)
|
||||
self.assertEqual(stop, Stop(0, ""))
|
||||
self.assertEqual([call.args for call in next_cycle.call_args_list], [(main.LoopRun(1, "/r", "do it", "", chunk="item-3"), loop), (main.LoopRun(2, "/r", "do it", "", chunk="item-3"), loop)])
|
||||
handed_on.assert_called_once_with(closed[1], loop)
|
||||
self.assertEqual(cycles, [(main.LoopRun(1, "/r", "do it", "", chunk="item-3"), loop), (main.LoopRun(2, "/r", "do it", "", chunk="item-3"), loop)])
|
||||
self.assertEqual(started, [(main.LoopRun(2, "/r", "do it", "", chunk="item-3"), True, loop.paths, env, launcher, effects)])
|
||||
|
||||
def test_a_window_loop_given_no_task_prints_the_help(self):
|
||||
self.assertEqual(main.loop_run_from(["--chunk", "item-3"], CWD, FakeEffects(git=["/r\n"]).effects()), Stop(1, usage.HELP))
|
||||
@@ -184,8 +199,8 @@ class WindowStarts(unittest.TestCase):
|
||||
def test_stops_where_tmux_cannot_show_the_session(self):
|
||||
fake = FakeEffects(git=["/r\n"])
|
||||
effects = dataclasses.replace(fake.effects(), tmux_on_terminal=lambda args: 1)
|
||||
with unittest.mock.patch.object(main, "start_chunks", return_value=["item-3"]), contextlib.redirect_stdout(io.StringIO()):
|
||||
stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, effects)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, effects, steps(lambda *args: ["item-3"]))
|
||||
self.assertEqual(stop, Stop(1, "`tmux attach-session -t =loop-r` failed; the chunks go on in the tmux session"))
|
||||
|
||||
def test_a_window_loop_outside_tmux_stops(self):
|
||||
@@ -201,11 +216,11 @@ class WindowStarts(unittest.TestCase):
|
||||
loop_run = main.LoopRun(4, "/r", "do it", "", chunk="item-7")
|
||||
for started, said, stop in ((["item-9", "item-12"], "the chunk finished; started item-9, item-12", Stop(0, "")), ([], "the chunk finished; started no other, since the chunks running fill what may run now", Stop(0, "")),
|
||||
(Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan"))):
|
||||
with self.subTest(started=started), unittest.mock.patch.object(main, "start_chunks", return_value=started) as start, contextlib.redirect_stdout(io.StringIO()) as printed:
|
||||
loop = a_loop(FakeEffects().effects(), env={"LOOP_CLAUDE_X": "1"})
|
||||
self.assertEqual(main.handed_on(loop_run, loop), stop)
|
||||
with self.subTest(started=started), contextlib.redirect_stdout(io.StringIO()) as printed:
|
||||
loop, asked = a_loop(FakeEffects().effects(), env={"LOOP_CLAUDE_X": "1"}), []
|
||||
self.assertEqual(main.handed_on(loop_run, loop, lambda *args: asked.append(args) or started), stop)
|
||||
self.assertEqual(printed.getvalue(), f"{STAMP} {said}\n" if said else "")
|
||||
self.assertEqual(start.call_args.args, (loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects))
|
||||
self.assertEqual(asked, [(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)])
|
||||
|
||||
|
||||
class StopDms(unittest.TestCase):
|
||||
@@ -214,28 +229,33 @@ class StopDms(unittest.TestCase):
|
||||
code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "loop-claude"), CWD, fake.effects())
|
||||
return code, said.getvalue()
|
||||
|
||||
def exit_code(self, run, fake):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
|
||||
code = main.exit_code(run, CWD, fake.effects())
|
||||
return code, said.getvalue()
|
||||
|
||||
def raising(self, error):
|
||||
raise error
|
||||
|
||||
def test_dms_the_reason_of_a_stop_with_exit_2_such_as_a_chunk_left_unfinished_too_often(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", return_value=Stop(2, "the human is needed to look at the chunk, but it stayed unfinished")):
|
||||
self.assertEqual(self.run_main(["do it"], fake)[0], 2)
|
||||
self.assertEqual(self.exit_code(lambda: Stop(2, "the human is needed to look at the chunk, but it stayed unfinished"), fake)[0], 2)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"])
|
||||
|
||||
def test_skips_the_dm_of_a_stop_without_a_reason_as_once_the_windows_started(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", return_value=Stop(0, "")):
|
||||
self.assertEqual(self.run_main(["do it"], fake), (0, ""))
|
||||
self.assertEqual(self.exit_code(lambda: Stop(0, ""), fake), (0, ""))
|
||||
self.assertEqual(fake.dms, [])
|
||||
|
||||
def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
|
||||
self.assertEqual(self.run_main(["do it"], fake)[0], 130)
|
||||
self.assertEqual(self.exit_code(lambda: self.raising(KeyboardInterrupt()), fake)[0], 130)
|
||||
self.assertEqual(fake.dms, [])
|
||||
|
||||
def test_dms_a_crash_before_it_reaches_the_terminal(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", side_effect=RuntimeError("boom")), self.assertRaises(RuntimeError):
|
||||
self.run_main(["do it"], fake)
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.exit_code(lambda: self.raising(RuntimeError("boom")), fake)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {CWD} crashed: RuntimeError('boom')"])
|
||||
|
||||
def test_dms_the_reason_where_a_loop_given_a_task_stops_with_exit_1(self):
|
||||
|
||||
@@ -6,7 +6,6 @@ import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
@@ -140,12 +139,14 @@ class RoutingCheck(unittest.TestCase):
|
||||
def test_puts_every_new_call_to_the_human_and_says_one_it_cannot_keep(self):
|
||||
new = [Call("reports", ("Explore",)), Call("rounds", ("x", "y"))]
|
||||
fake = FakeEffects(on_terminal_claude=[0])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, unittest.mock.patch.object(state, "mark_raised", return_value=Failure("full")):
|
||||
self.root.mkdir()
|
||||
fake.replace_file = lambda path, data: Failure("full")
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertIsNone(routing_check.raise_calls(self.root, new, Rung("m", "high"), self.loop(fake)))
|
||||
((args),) = fake.made("claude_on_terminal")
|
||||
self.assertIn(f"don't change anything until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6])
|
||||
self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue())
|
||||
self.assertIn("routing figures: full", said.getvalue())
|
||||
self.assertIn(f"routing figures: could not write {self.root / state.RAISED}: full", said.getvalue())
|
||||
[sent] = fake.dms
|
||||
self.assertTrue(sent.startswith(f"loop-claude in {self.loop(fake).root} asks:\n\nloop-claude's routing figures call for a routing change:\n- {new[0].sentence()}\n"), sent)
|
||||
|
||||
|
||||
@@ -59,8 +59,7 @@ class ExitContract(unittest.TestCase):
|
||||
("chunk_driver/cycle_start.py", "project_routing", "1", "ladder_file.reason", premises_),
|
||||
("chunk_driver/cycle_start.py", "routing_on", "1", "ladder.reason", "the project's routing ladder cannot be read or holds a fault"),
|
||||
("chunk_driver/project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
|
||||
("chunk_driver/project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
|
||||
("chunk_driver/project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
|
||||
("chunk_driver/project/model_choice.py", "get_or_ask_model", "1", "failure.reason", models_),
|
||||
("loop_claude/loop/checkout.py", "checkout_root", "1", "found.reason", git),
|
||||
("loop_claude/loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
|
||||
("loop_claude/loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how loop-claude starts itself", "--chunk is given outside a tmux window"),
|
||||
|
||||
Reference in New Issue
Block a user