From d488b8a32430bc88b91f8898ff5e4732cbf652c9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 10:34:03 +0100 Subject: [PATCH 01/14] Release review of 0.12.0 -- 2.52.0 From ab8bf249cc726f651793167ec778b21fe4ac2980 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 10:34:11 +0100 Subject: [PATCH 02/14] Record the reading cost before the release review of 0.12.0 --- docs/reading-cost.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 54a3d7b6..9e9b9634 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -3113,3 +3113,20 @@ Read most (opens and searches): - `docs/decisions.md` 2 - `bin/repo_checks/test_import_order.py` 1 - `bin/run-heavy` 1 + +## Reading cost, chunk 9c49e7cd65c6, finished 2026-11-19T09:33:41Z + +104289 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/loop_claude/test_loop_claude.py` 13 +- `bin/loop_effects/test_effects.py` 5 +- `README.md` 4 +- `bin/agent_cycle/judge.py` 4 +- `bin/agent_cycle/lingering_workers.py` 2 +- `bin/agent_cycle/tmux.py` 2 +- `bin/agent_cycle/worker.py` 2 +- `bin/claude_code/reply.py` 2 +- `bin/loop_claude/loop/main.py` 2 +- `bin/loop_claude/loop/usage.py` 2 -- 2.52.0 From b8595db647b2ec08d0e8a2fdd3ded4b113142d1e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 11:14:44 +0100 Subject: [PATCH 03/14] =?UTF-8?q?Answer=20architecture=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=2036=20=F0=9F=9F=A1=20(0=20misread);=20chunk=5Fdr?= =?UTF-8?q?iver=20holds=20what=20both=20drivers=20share,=20and=20Jira=20an?= =?UTF-8?q?d=20review-state=20reads=20have=20one=20home=20each?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 + README.md | 15 +- bin/agent_cycle/__init__.py | 4 +- bin/agent_cycle/run.py | 2 +- bin/agent_cycle/test_interrupt.py | 231 ++++ bin/agent_cycle/test_judge.py | 130 ++ bin/agent_cycle/test_retry.py | 51 + bin/agent_cycle/test_spend.py | 90 ++ bin/agent_cycle/test_states.py | 69 + bin/agent_cycle/test_stuck_workers.py | 2 +- bin/agent_cycle/test_tmux.py | 95 ++ bin/agent_cycle/test_worker.py | 135 ++ bin/agent_cycle/verdicts.py | 4 +- bin/atlassian/jira.py | 137 ++ bin/chunk_driver/__init__.py | 4 + bin/chunk_driver/chunk_run.py | 76 ++ bin/chunk_driver/claims.py | 39 + bin/chunk_driver/cycle_start.py | 114 ++ bin/chunk_driver/drivers.py | 3 + .../project}/__init__.py | 0 .../project/model_choice.py | 0 .../project/premises.py | 0 .../project/records.py | 2 +- bin/chunk_driver/project/test_model_choice.py | 36 + bin/chunk_driver/project/test_records.py | 90 ++ .../project/text_file.py | 0 .../cycle => chunk_driver}/prompts.py | 47 +- bin/chunk_driver/test_cycle_start.py | 40 + .../loop => chunk_driver}/this_loop.py | 6 +- bin/chunk_pr/approval.py | 29 +- bin/chunk_pr/test_chunk_pr.py | 2 +- bin/do_epic/backend/jira.py | 26 +- bin/do_epic/backend/test_jira.py | 5 +- bin/do_epic/chunk_prompt.py | 7 +- bin/do_epic/e2e/sandbox.py | 2 +- bin/do_epic/gates.py | 53 +- bin/do_epic/main.py | 64 +- bin/do_epic/scheduler.py | 6 +- bin/do_epic/test_findings.py | 2 +- bin/do_epic/test_finish.py | 2 +- bin/do_epic/test_human_tasks.py | 2 +- bin/do_epic/test_main.py | 8 +- bin/do_epic/test_planning.py | 2 +- bin/do_epic/test_scheduler.py | 5 +- bin/forge/reviews.py | 86 ++ bin/judge_replay/archived_prompt.py | 7 +- bin/judge_replay/main.py | 11 +- bin/judge_replay/test_judge_replay.py | 11 +- bin/loop_claude/__init__.py | 2 +- .../{project => chunk}/__init__.py | 0 .../{cycle => chunk}/chunk_items.py | 2 +- bin/loop_claude/chunk/fresh_prompt.py | 52 + bin/loop_claude/{project => loop}/checkout.py | 0 bin/loop_claude/loop/chunk_start.py | 40 +- bin/loop_claude/loop/chunk_windows.py | 32 +- bin/loop_claude/loop/close.py | 47 - bin/loop_claude/loop/main.py | 65 +- bin/loop_claude/loop/reload.py | 2 +- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/loop/usage.py | 5 +- bin/loop_claude/test_loop_claude.py | 1209 ++--------------- bin/loop_effects/test_doubles.py | 190 +++ bin/plan_store/jira_epic.py | 118 +- bin/plan_store/test_jira_epic.py | 4 +- bin/repo_checks/test_citations.py | 2 +- bin/repo_checks/test_package_cycles.py | 26 + bin/rung_replay/command.py | 2 +- docs/decisions.md | 8 +- todo.md | 11 +- 69 files changed, 1983 insertions(+), 1592 deletions(-) create mode 100644 bin/agent_cycle/test_interrupt.py create mode 100644 bin/agent_cycle/test_judge.py create mode 100644 bin/agent_cycle/test_retry.py create mode 100644 bin/agent_cycle/test_spend.py create mode 100644 bin/agent_cycle/test_states.py create mode 100644 bin/agent_cycle/test_tmux.py create mode 100644 bin/agent_cycle/test_worker.py create mode 100644 bin/atlassian/jira.py create mode 100644 bin/chunk_driver/__init__.py create mode 100644 bin/chunk_driver/chunk_run.py create mode 100644 bin/chunk_driver/claims.py create mode 100644 bin/chunk_driver/cycle_start.py create mode 100644 bin/chunk_driver/drivers.py rename bin/{loop_claude/cycle => chunk_driver/project}/__init__.py (100%) rename bin/{loop_claude => chunk_driver}/project/model_choice.py (100%) rename bin/{loop_claude => chunk_driver}/project/premises.py (100%) rename bin/{loop_claude => chunk_driver}/project/records.py (98%) create mode 100644 bin/chunk_driver/project/test_model_choice.py create mode 100644 bin/chunk_driver/project/test_records.py rename bin/{loop_claude => chunk_driver}/project/text_file.py (100%) rename bin/{loop_claude/cycle => chunk_driver}/prompts.py (76%) create mode 100644 bin/chunk_driver/test_cycle_start.py rename bin/{loop_claude/loop => chunk_driver}/this_loop.py (52%) create mode 100644 bin/forge/reviews.py rename bin/loop_claude/{project => chunk}/__init__.py (100%) rename bin/loop_claude/{cycle => chunk}/chunk_items.py (96%) create mode 100644 bin/loop_claude/chunk/fresh_prompt.py rename bin/loop_claude/{project => loop}/checkout.py (100%) delete mode 100644 bin/loop_claude/loop/close.py create mode 100644 bin/loop_effects/test_doubles.py diff --git a/.gitignore b/.gitignore index e19d954b..3b58f19f 100644 --- a/.gitignore +++ b/.gitignore @@ -39,6 +39,10 @@ !bin/branch_chunks/*.py !bin/chunk-pr !bin/chunk-preflight +!bin/chunk_driver/ +!bin/chunk_driver/*.py +!bin/chunk_driver/project/ +!bin/chunk_driver/project/*.py !bin/chunk_pr/ !bin/chunk_pr/*.py !bin/chunk_preflight/ diff --git a/README.md b/README.md index a4bdda6c..43e9870f 100644 --- a/README.md +++ b/README.md @@ -222,18 +222,19 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a `bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. -- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` drives it, and `do_epic` will; `agent_cycle` doesn't import either. -- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. +- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. +- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the head of each entry it answers, an issue's links and the transition that finishes it, for `plan_store` and `do_epic`. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. +- `chunk_driver/` holds what `loop_claude` and `do_epic` share as they drive chunks through `agent_cycle`: how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither tool, and `repo_checks` fails any package that imports one of the two. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`. -- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and reads its checks, once or until they settle (`pulls.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. +- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). -- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `loop_claude`'s premises, records and `ANSWER_DESTINATIONS`. +- `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `loop_claude` runs `chunk-preflight` as a process of its own. -- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it. -- `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too. +- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it. `test_doubles.py` holds the doubles their tests share, such as `FakeEffects`. +- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read. - `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`. @@ -246,7 +247,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`. - `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format. - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. -- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `loop_claude`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. +- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. - `test_env.py` serves the tests. - `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. - `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. diff --git a/bin/agent_cycle/__init__.py b/bin/agent_cycle/__init__.py index 87650737..72819dd8 100644 --- a/bin/agent_cycle/__init__.py +++ b/bin/agent_cycle/__init__.py @@ -1,4 +1,4 @@ -"""One cycle of a headless claude worker and the judge of its transcript, for every entry point that drives such cycles: loop-claude today, do-epic next (docs/decisions.md → `do-epic: drives one Jira epic …`). +"""One cycle of a headless claude worker and the judge of its transcript, for every entry point that drives such cycles: loop-claude and do-epic (docs/decisions.md → `do-epic: drives one Jira epic …`). -run.py runs a cycle through the states in states.py: worker.py runs the worker, judge.py rules on its transcript, interrupt.py puts a question to the human in the tmux window tmux.py names, and routing.py picks the rung the worker runs on next. An entry point hands the cycle what is its own: its prompts and file names (worker_prompts.py) and how it reads the plan items a worker took in (run.py's Cycle.taken_in). No module here imports an entry point's package: loop_claude imports this one, so bin/repo_checks/test_package_cycles.py fails on such an import. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that. +run.py runs a cycle through the states in states.py: worker.py runs the worker, judge.py rules on its transcript, interrupt.py puts a question to the human in the tmux window tmux.py names, and routing.py picks the rung the worker runs on next. An entry point hands the cycle what is its own: its prompts and file names (worker_prompts.py) and how it reads the plan items a worker took in (run.py's Cycle.taken_in). What two entry points share beyond the cycle lives in bin/chunk_driver/. No module here imports an entry point's package, and bin/repo_checks/test_package_cycles.py fails on such an import. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that. """ diff --git a/bin/agent_cycle/run.py b/bin/agent_cycle/run.py index 2a8d4c68..70702d4d 100644 --- a/bin/agent_cycle/run.py +++ b/bin/agent_cycle/run.py @@ -34,7 +34,7 @@ class Cycle: Each step reads the few fields it needs by name, so the fields stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows more than seven where a reader finds them by name. """ - # The claude-config release and commit the cycle runs under, such as `v0.8.0 ()`, or why they are unknown: loop/main.py's setup_version. + # The claude-config release and commit the cycle runs under, such as `v0.8.0 ()`, or why they are unknown: chunk_driver/cycle_start.py's setup_version. config: str effects: Effects # What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began. diff --git a/bin/agent_cycle/test_interrupt.py b/bin/agent_cycle/test_interrupt.py new file mode 100644 index 00000000..585c1203 --- /dev/null +++ b/bin/agent_cycle/test_interrupt.py @@ -0,0 +1,231 @@ +import contextlib +import dataclasses +import io +import json +import pathlib +import shutil +import sys +import tempfile +import unittest +import unittest.mock +import uuid + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from loop_effects.test_doubles import assistant, FakeEffects, human, NOW, STAMP, Streamed +from failure import Failure +from agent_cycle import interrupt +from chunk_driver.drivers import LOOP_CLAUDE +from machine_load import memory +from loop_state import paths +from model_routing.ladder import Rung +from agent_cycle.stop import Stop +from agent_cycle import tmux +from text_files.utc_stamp import utc +from agent_cycle.test_tmux import WINDOW + + +class Interrupts(unittest.TestCase): + def setUp(self): + self.home = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.home) + self.paths = paths.paths_from(self.home) + self.transcript = self.home / "t.jsonl" + self.transcript.write_text(json.dumps(human("a")) + "\n") + self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) + + def put(self, fake, answer_here=True, effects=None, question="Which one?"): + """interrupt's answer and what it said, without the bell it rang, which self.bells counts.""" + with contextlib.redirect_stderr(io.StringIO()) as said: + answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, LOOP_CLAUDE, effects or fake.effects()) + self.bells = said.getvalue().count(tmux.BELL) + return answer, said.getvalue().replace(tmux.BELL, "") + + def typed_there(self, args): + """The claude opened on the terminal: the human types a line in the worker's session, and it ends.""" + with open(self.transcript, "a") as handle: + handle.write(json.dumps(human("cut it")) + "\n") + return 0 + + def worked(self, minutes_ago, written_1h=5000, read=70000, written_5m=0): + """Appends the worker's last message, sent minutes_ago before NOW, whose usage wrote written_1h tokens to the hour-long cache, written_5m to the five-minute one, and read read tokens from the cache.""" + said = assistant({"type": "text", "text": "Which one?"}) + said["timestamp"] = utc(NOW - minutes_ago * 60) + said["message"] |= {"id": "msg-1", "model": "m", "usage": {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": written_5m, "ephemeral_1h_input_tokens": written_1h}, "cache_read_input_tokens": read, "output_tokens": 100}} + with open(self.transcript, "a") as handle: + handle.write(json.dumps(said) + "\n") + + def fired(self, fake, answer): + """An input that first fires every timer started, then returns answer as the line the human typed.""" + def typed(prompt): + for _, action in fake.timers: + action() + return answer + return typed + + def test_compacts_the_workers_session_ten_minutes_before_its_hour_long_prompt_cache_expires_and_keeps_waiting(self): + self.worked(minutes_ago=10) + fake = FakeEffects(streams=[Streamed(0)]) + fake.scripts["input"] = [self.fired(fake, "Use B.")] + answer, said = self.put(fake) + self.assertEqual(answer, "Use B.") + self.assertEqual([delay for delay, _ in fake.timers], [40 * 60]) + self.assertEqual([what for seam, what in fake.calls if seam == "stream_claude"], [["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "-p", "/compact", "--resume", str(self.session.id), "--output-format", "stream-json", "--verbose"]]) + self.assertEqual(fake.worker_environments, [self.session.env]) + self.assertEqual(fake.worker_folders, [self.session.root]) + self.assertIn(f"\n{STAMP} compacting the worker's claude session before its prompt cache expires; an answer typed meanwhile is read once that ends\n\n{STAMP} compacted the worker's claude session\n", said) + self.assertNotIn("still waiting", said) + + def test_compacts_on_the_rung_the_worker_ran_on_where_a_ruling_stepped_it_up_and_talk_opens_claude_on_the_new_rung(self): + self.worked(minutes_ago=10) + self.session = dataclasses.replace(self.session, rung=Rung("n", "medium")) + fake = FakeEffects(streams=[Streamed(0)], on_terminal_claude=[self.typed_there]) + fake.scripts["input"] = [self.fired(fake, "/talk")] + self.assertEqual(self.put(fake)[0], interrupt.Talked()) + (compaction,), (opened,) = fake.made("stream_claude"), fake.made("claude_on_terminal") + self.assertEqual(compaction[:4], ["--model", "m", "--effort", "high"]) + self.assertEqual(opened[:4], ["--model", "n", "--effort", "medium"]) + + def test_compacts_until_the_prompt_cache_expires_and_not_from_then_on(self): + for name, late, compactions in (("a second before", 50 * 60 - 1, 1), ("as it expires", 50 * 60, 0)): + with self.subTest(name): + self.transcript.write_text(json.dumps(human("a")) + "\n") + self.worked(minutes_ago=10) + fake = FakeEffects(streams=[Streamed(0)]) + clock = [NOW] + + def typed(prompt): + clock[0] = NOW + late + for _, action in fake.timers: + action() + return "Use B." + fake.scripts["input"] = [typed] + answer, said = self.put(fake, effects=dataclasses.replace(fake.effects(), now=lambda: clock[0])) + self.assertEqual(answer, "Use B.") + self.assertEqual(len(fake.made("stream_claude")), compactions) + self.assertEqual(said.count("compact"), 2 * compactions, said) + + def test_a_compaction_doesnt_wait_for_memory(self): + self.worked(minutes_ago=10) + fake = FakeEffects(streams=[Streamed(0)], free_memory=[memory.Memory(available=3, total=16)]) + fake.scripts["input"] = [self.fired(fake, "Use B.")] + said = self.put(fake)[1] + self.assertEqual([seam for seam, _ in fake.calls if seam in ("memory", "sleep", "stream_claude")], ["stream_claude"]) + self.assertNotIn("waiting to start the worker", said) + + def test_an_answer_before_the_timer_fires_stops_it_and_doesnt_compact_anything(self): + self.worked(minutes_ago=10) + fake = FakeEffects(inputs=["Use B."]) + self.assertEqual(self.put(fake)[0], "Use B.") + self.assertEqual([call for call in fake.calls if call[0] in ("stop_timer", "stream_claude")], [("stop_timer", 40 * 60)]) + + def test_stops_the_timer_before_talk_opens_the_workers_session(self): + self.worked(minutes_ago=10) + fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[self.typed_there]) + self.assertEqual(self.put(fake)[0], interrupt.Talked()) + self.assertEqual([call[0] for call in fake.calls if call[0] in ("stop_timer", "claude_on_terminal")], ["stop_timer", "claude_on_terminal"]) + + def test_starts_no_timer_under_60k_tokens_of_context_past_the_margin_on_a_five_minute_cache_or_where_claude_opens_at_once(self): + for name, minutes_ago, written_1h, written_5m, read, answer_here in (("small", 10, 5000, 0, 54997, True), ("margin begun", 50, 5000, 0, 70000, True), ("five minutes", 1, 0, 5000, 70000, True), ("nothing written", 1, 0, 0, 70000, True), ("opens at once", 10, 5000, 0, 70000, False)): + with self.subTest(name): + self.transcript.write_text(json.dumps(human("a")) + "\n") + self.worked(minutes_ago, written_1h, read, written_5m) + fake = FakeEffects(inputs=["Use B."], on_terminal_claude=[self.typed_there]) + self.put(fake, answer_here=answer_here) + self.assertEqual(fake.timers, []) + + def test_starts_the_timer_at_60k_tokens_of_context(self): + self.worked(minutes_ago=10, read=54998) + fake = FakeEffects(inputs=["Use B."]) + self.put(fake) + self.assertEqual([delay for delay, _ in fake.timers], [40 * 60]) + + def test_starts_no_timer_where_the_transcript_cannot_be_read_and_still_asks(self): + self.transcript.unlink() + fake = FakeEffects(inputs=["Use B."]) + self.assertEqual(self.put(fake)[0], "Use B.") + self.assertEqual(fake.timers, []) + + def test_a_compaction_that_hits_a_usage_limit_says_the_limits_message_and_keeps_waiting(self): + self.worked(minutes_ago=10) + fake = FakeEffects(streams=[Streamed(0, {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"})]) + fake.scripts["input"] = [self.fired(fake, "Use B.")] + answer, said = self.put(fake) + self.assertEqual(answer, "Use B.") + self.assertIn(f"\n{STAMP} could not compact the worker's claude session: You've hit your session limit\n", said) + + def test_a_compaction_that_fails_says_why_and_keeps_waiting(self): + self.worked(minutes_ago=10) + fake = FakeEffects(streams=[Streamed(1)]) + fake.scripts["input"] = [self.fired(fake, "Use B.")] + answer, said = self.put(fake) + self.assertEqual(answer, "Use B.") + self.assertIn(f"\n{STAMP} could not compact the worker's claude session: claude exited 1\n", said) + + def test_stops_off_a_terminal_before_asking(self): + fake = FakeEffects(on_terminal=False) + self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n")) + self.assertEqual(fake.calls, []) + + def test_dms_the_question_naming_the_project_on_a_terminal_or_off_one(self): + for on_terminal in (True, False): + with self.subTest(on_terminal=on_terminal): + fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal) + self.put(fake) + self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks, in the tmux window loop-proj:item-7:\n\nWhich one?"]) + + def test_marks_its_window_and_rings_the_bell_while_it_waits_and_clears_the_mark_once_answered(self): + fake = FakeEffects(inputs=["Use B."]) + answer, said = self.put(fake) + self.assertEqual(answer, "Use B.") + self.assertEqual(self.bells, 1) + self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"]]) + + def test_a_loop_that_stops_unanswered_leaves_its_window_marked(self): + fake = FakeEffects(on_terminal=False) + self.put(fake) + self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"]]) + + def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self): + fake = FakeEffects(inputs=["Use B."]) + seen = [] + effects = dataclasses.replace(fake.effects(), dm=lambda text, directory: seen.append(list(fake.calls))) + self.assertEqual(self.put(fake, effects=effects)[0], "Use B.") + self.assertEqual(seen, [[("discard_typed", None)]]) + + def test_says_why_a_dm_failed_and_still_takes_the_answer(self): + fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")]) + self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n")) + + def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self): + fake = FakeEffects(inputs=[" Use B. "]) + self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n")) + self.assertEqual(fake.calls, [("discard_typed", None), ("input", "Answer (/talk opens claude, Enter stops the loop): ")]) + + def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self): + for typed, answer_here in (([" /talk "], True), ([], False)): + with self.subTest(typed=typed): + fake = FakeEffects(inputs=typed, on_terminal_claude=[self.typed_there]) + self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talked()) + self.assertEqual(len(fake.made("input")), len(typed)) + self.assertEqual(fake.calls[0], ("discard_typed", None)) + + def test_stops_on_an_empty_answer_or_the_inputs_end(self): + for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")): + with self.subTest(why=why): + self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}")) + + def test_stops_when_nothing_was_typed_in_the_session(self): + fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0]) + stop, _ = self.put(fake) + 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 without anything typed")) + + def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self): + fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0]) + self.put(fake) + self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort", "CLAUDE_CODE_SANDBOXED": "1"}]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/agent_cycle/test_judge.py b/bin/agent_cycle/test_judge.py new file mode 100644 index 00000000..fc97cb62 --- /dev/null +++ b/bin/agent_cycle/test_judge.py @@ -0,0 +1,130 @@ +import dataclasses +import pathlib +import sys +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from loop_effects.test_doubles import assistant, FakeEffects, human, judged, kinds +from failure import Failure +from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished +from agent_cycle import judge +from chunk_driver.drivers import LOOP_CLAUDE +from chunk_driver import prompts +from chunk_driver.project import records +from model_routing.ladder import Rung +from agent_cycle.judge import verdict_from + + +class Grounded(unittest.TestCase): + def test_every_verdict_must_quote_the_transcript(self): + self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n")) + self.assertFalse(judge.grounded("invented", "the transcript")) + self.assertFalse(judge.grounded("", "the transcript")) + self.assertFalse(judge.grounded(" ", "the transcript")) + transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it." + self.assertTrue(judge.grounded("Your step:\n```\n./run.sh\n```\nRun it.", transcript)) + self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript)) + self.assertFalse(judge.grounded("**", transcript)) + + def test_an_elided_quote_holds_when_its_fragments_appear_in_order(self): + transcript = "**Decision for you:** security, or not.\n\nI recommend one more round of each.\n\nI recommend skipping it: it costs." + self.assertTrue(judge.grounded("**Decision for you:** security, … ... I recommend one more round of each ... I recommend skipping it: …", transcript)) + self.assertFalse(judge.grounded("I recommend skipping it ... Decision for you", transcript)) + self.assertFalse(judge.grounded("Decision for you ... invented", transcript)) + self.assertFalse(judge.grounded("... …", transcript)) + self.assertTrue(judge.grounded("a ... b ... c", "x a b a c")) + + +class Verdict(unittest.TestCase): + def test_needs_every_field_the_schema_requires(self): + self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Finished("e")) + self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Unfinished("e")) + self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?")) + self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True)) + self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "reversed": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean")) + self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A.")) + self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?")) + self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge quoted an answer without a question")) + self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean")) + self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string")) + self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge interrupted without a question")) + self.assertEqual(verdict_from(None), Failure("the judge returned no reply")) + + def test_carries_the_earlier_answer_an_interrupt_names(self): + reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?", "reversed": ""} + self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", answered_before="Grant one more round.", left_open="one more")) + self.assertEqual(verdict_from({**reply, "interrupt": False, "finished": True}), Finished("e")) + + def test_takes_an_escalation_quote_on_an_unfinished_verdict(self): + reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False} + self.assertEqual(verdict_from(reply), Unfinished("e", "round 2: 🔴")) + self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e")) + self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string")) + + def test_takes_an_escalation_quote_on_an_interrupt(self): + reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False} + self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴")) + + def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self): + shown = "The agent: round 2: 🔴. Which one?" + self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q", "round 2: 🔴")) + self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: … 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q")) + self.assertEqual(judge.quotes_checked(Unfinished("e", "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e")) + + def test_turns_an_interrupt_that_re_asks_a_human_answer_into_that_answer_quoted_back(self): + answer = "Grant one more round; ask again if a 🔴 survives it." + shown = f"[loop] Asked.\n\n[human] {answer}\n\n[step] Round 2: a 🔴 survived." + grounds = judge.Grounds(shown, shown, "") + asking = "Grant a third round? Your answer left open: a 🔴 survives it" + kept = Interrupt("[step] Round 2", asking, answered_before=answer, left_open="a 🔴 survives it") + self.assertEqual(judge.quotes_checked(kept, grounds), kept) + re_asked = Interrupt("[step] Round 2", "Grant a third round?", "Round 2: a 🔴", answered_before=answer, left_open="a 🔴 survives it") + self.assertEqual(judge.quotes_checked(re_asked, grounds), Unfinished(answer, "Round 2: a 🔴")) + self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open=""), grounds), Unfinished(answer)) + self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open="a 🔴 survived"), grounds), Unfinished(answer)) + invented = dataclasses.replace(re_asked, answered_before="Grant two more rounds.") + self.assertEqual(judge.quotes_checked(invented, grounds), invented) + unnamed = Interrupt("[step] Round 2", "Grant a third round?") + self.assertEqual(judge.quotes_checked(unnamed, grounds), unnamed) + + def test_takes_an_escalation_quote_on_a_quoted_answer(self): + reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False} + self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴")) + + def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self): + shown = "The agent: round 2: 🔴. Which one?" + self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.", "round 2: 🔴")) + self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.")) + + def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self): + self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴"), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴")) + + def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self): + self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("s", "q")) + self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "the records"), judge.Grounds("shown", "shown", "From the records: the records")), QuotedAnswer("s", "q", "the records")) + + def test_drops_an_escalation_quote_found_only_in_the_transcript_entries_before_the_workers_last_step_up(self): + entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})] + def judged_on(mark, escalation): + return judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), mark, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects()) + self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", "round 2: 🔴", entries_read=3)) + self.assertEqual(judged_on(1, "round 2: 🔴"), Unfinished("working", entries_read=3)) + self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", "round 3: 🔴", entries_read=3)) + self.assertEqual(judged_on(1, "round 2: 🔴\n\nround 3: 🔴"), Unfinished("working", entries_read=3)) + self.assertEqual(judged_on(3, "round 3: 🔴"), Unfinished("working", entries_read=3)) + + def test_drops_an_escalation_quote_that_only_loop_claudes_prompts_or_the_humans_lines_repeat_after_the_step_up(self): + entries = [assistant({"type": "text", "text": "round 2: 🔴"}), {**human("as the work remaining: round 2: 🔴"), "promptSource": "sdk"}, human("round 2: 🔴 again"), assistant({"type": "text", "text": "working"})] + verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects()) + self.assertEqual(verdict, Unfinished("working", entries_read=4)) + + def test_takes_evidence_from_before_the_workers_last_step_up(self): + entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "working"})] + verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects()) + self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/agent_cycle/test_retry.py b/bin/agent_cycle/test_retry.py new file mode 100644 index 00000000..e0d0c98b --- /dev/null +++ b/bin/agent_cycle/test_retry.py @@ -0,0 +1,51 @@ +import contextlib +import io +import pathlib +import sys +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from loop_effects.test_doubles import FakeEffects, NOW, STAMP +from claude_code.reply import Limited +from agent_cycle import retry +from agent_cycle.stop import Stop + + +class Retried(unittest.TestCase): + def test_retries_a_minute_apart_and_stops_on_the_third_failure(self): + fake = FakeEffects() + results = [Failure("one"), "done"] + self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), "done") + self.assertEqual(fake.calls, [("sleep", 60)]) + fake = FakeEffects() + self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no")) + self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)]) + + def test_hands_each_failure_to_the_keeper_and_stops_where_it_stops(self): + kept = [] + def keep(failure): + kept.append(failure) + return Stop(1, "no room") if len(kept) == 2 else None + fake = FakeEffects() + self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects(), keep), Stop(1, "no room")) + self.assertEqual(kept, [Failure("no")] * 2) + self.assertEqual(fake.calls, [("sleep", 60)]) + + def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self): + fake = FakeEffects() + results = [Failure("one"), Failure("two"), Limited(NOW + 3600, "limit"), Failure("three"), Limited(None, "limit"), Limited(NOW - 600, "limit"), Failure("four"), Failure("five"), Failure("six")] + self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), Stop(1, "the worker failed three times running: six")) + self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60), ("sleep", 3720), ("sleep", 60), ("sleep", 600), ("sleep", 600), ("sleep", 60), ("sleep", 60)]) + + def test_says_what_claude_said_and_when_the_next_try_is_due(self): + results = [Limited(NOW + 3600, "You've hit your session limit"), "done"] + with contextlib.redirect_stderr(io.StringIO()) as said: + retry.retried("judge", lambda: results.pop(0), FakeEffects().effects()) + self.assertEqual(said.getvalue(), f"{STAMP} the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/agent_cycle/test_spend.py b/bin/agent_cycle/test_spend.py new file mode 100644 index 00000000..918e1813 --- /dev/null +++ b/bin/agent_cycle/test_spend.py @@ -0,0 +1,90 @@ +import json +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from claude_code import entries +from loop_effects.test_doubles import FakeEffects, judged, ran +from agent_cycle import judge, spend +from agent_cycle.verdicts import Judged, Unfinished +from transcript_archive import outcomes +from claude_code.tokens import Tokens, tokens_of + + +def turn(message_id, model, at, **usage): + return entries.AssistantTurn(message_id=message_id, model=model, timestamp=at, usage=usage) + + +class Spend(unittest.TestCase): + def test_reads_the_cache_writes_by_lifetime_and_counts_one_without_the_split_as_five_minutes(self): + self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5}), Tokens(1, 2, 3, 4, 5)) + self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9}), Tokens(1, 9, 0, 0, 0)) + self.assertEqual(tokens_of(None), Tokens()) + + def test_counts_a_messages_context_as_every_prompt_token_and_no_output(self): + self.assertEqual(Tokens(1, 2, 3, 4, 5).context(), 10) + + def test_counts_a_message_written_in_the_stamped_second_or_without_a_readable_time_as_before_since(self): + thread = [turn("m1", "a", "2026-11-01T10:00:01Z", output_tokens=7), turn("m2", "a", "not a time", output_tokens=3), turn("m3", "a", "2026-11-01T10:00:02Z", output_tokens=1)] + self.assertEqual(spend.spent("2026-11-01T10:00:01Z", thread, [], "j", Tokens()), {("worker", "a"): Tokens(output=1)}) + + def test_sums_two_subagents_of_one_name_on_one_model(self): + helpers = [spend.Subagent("Explore", [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]), spend.Subagent("Explore", [turn("s2", "b", "2026-11-01T10:00:00Z", input_tokens=4)])] + self.assertEqual(spend.spent("", [], helpers, "j", Tokens()), {("Explore", "b"): Tokens(input=7)}) + + def test_counts_each_message_once_by_its_id_and_only_after_since(self): + thread = [ + turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7), + turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2), + turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2), + turn("m3", "b", "2026-11-01T10:00:03Z", cache_read_input_tokens=5), + ] + self.assertEqual(spend.thread_spend(thread, "2026-11-01T10:00:01Z"), {"a": Tokens(1, 0, 0, 0, 2), "b": Tokens(0, 0, 0, 5, 0)}) + self.assertEqual(spend.thread_spend(thread, ""), {"a": Tokens(1, 0, 0, 0, 9), "b": Tokens(0, 0, 0, 5, 0)}) + + def test_names_each_spender_and_leaves_out_one_that_spent_nothing(self): + worker = [turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7)] + helper = spend.Subagent('Explore "Search"', [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]) + self.assertEqual(spend.spent("", worker, [helper], "j", Tokens()), {("worker", "a"): Tokens(output=7), ('Explore "Search"', "b"): Tokens(input=3)}) + self.assertEqual(spend.spent("", [], [], "j", Tokens(input=1)), {("judge", "j"): Tokens(input=1)}) + + def test_names_a_subagent_by_its_agent_type_and_description(self): + with tempfile.TemporaryDirectory() as root: + folder = pathlib.Path(root, "s", "subagents") + folder.mkdir(parents=True) + for name, meta in [("agent-a", {"agentType": "Explore", "description": "Search the hooks"}), ("agent-b", None), ("agent-c", ["Explore"]), ("agent-d", {"description": "Läs"}), ("agent-e", {"agentType": "Ex\nConfig: x"})]: + (folder / f"{name}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"id": name, "model": "m", "content": [], "usage": {"output_tokens": 1}}, "timestamp": "2026-11-01T10:00:00Z"}) + "\n") + if meta: + (folder / f"{name}.meta.json").write_text(json.dumps(meta)) + found = spend.subagents(str(pathlib.Path(root, "s.jsonl"))) + self.assertEqual([subagent.name for subagent in found], ['Explore "Search the hooks"', "subagent", "subagent", 'subagent "Läs"', "Ex Config: x"]) + self.assertEqual(spend.spent("", [], found[:2], "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)}) + self.assertEqual(spend.subagents(str(pathlib.Path(root, "none.jsonl"))), []) + + def test_renders_the_spend_then_the_list_prices_of_each_model_it_knows(self): + found = {("worker", "claude-opus-5-5"): Tokens(1, 2, 3, 4, 5), ("judge", "unpriced"): Tokens(input=6)} + self.assertEqual(outcomes.spent_block("2026-11-01T10:00:00Z", found), """Spent since 2026-11-01T10:00:00Z, in tokens of input, cache write 5m, cache write 1h, cache read, output: +- worker, claude-opus-5-5: 1, 2, 3, 4, 5 +- judge, unpriced: 6, 0, 0, 0, 0 + +List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output: +- claude-opus-5-5: 4, 5, 8, 0.2, 20""") + self.assertEqual(outcomes.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0") + self.assertEqual(outcomes.spent_block("", {}), "") + + def test_keeps_the_whole_typed_answer_that_holds_the_judges_quote_and_its_tokens(self): + shown = "[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name" + typed = ("Use A.", "No, keep the old name. Use X.") + for quoted, kept in [("No, keep the old name. Use X.", "No, keep the old name. Use X."), ("keep the old name", "No, keep the old name. Use X."), ("Use", "No, keep the old name. Use X."), ("keep the new name", ""), ("No, keep the name.", "")]: + with self.subTest(quoted=quoted): + answer = json.loads(judged("unfinished", reversed=quoted).stdout) + fake = FakeEffects(claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 2, "output_tokens": 3}}))]) + self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds(shown, shown, "", typed), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept))) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/agent_cycle/test_states.py b/bin/agent_cycle/test_states.py new file mode 100644 index 00000000..bb2efccb --- /dev/null +++ b/bin/agent_cycle/test_states.py @@ -0,0 +1,69 @@ +import pathlib +import sys +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished +from model_routing.route import Route +from agent_cycle import routing +from model_routing.ladder import Rung +from agent_cycle import states + + +TYPED = states.TypedAnswer("Which one?", "Use B.") + + +class Transitions(unittest.TestCase): + def test_each_state_moves_on_its_events_and_only_on_them(self): + answered = states.Ruled(QuotedAnswer("e", "Which one?", "A.")) + legal = ( + (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), + (states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.WorkerRan("/t"), states.Judging("/t", 3)), + (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"))), + (states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"), 3)), + (states.Judging("/t"), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 1)), + (states.Judging("/t", 2), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 3)), + (states.Judging("/t", 3), answered, states.Interrupting("/t", QuotedAnswer("e", "Which one?", "A."), 3)), + (states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), + (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.HumanTalked(), states.Judging("/t")), + (states.Interrupting("/t", Interrupt("e", "q"), 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)), + (states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))), + (states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))), + ) + 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.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.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]: + with self.subTest(state=state, event=event), self.assertRaises(ValueError): + states.transition(state, event) + + def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self): + ran_on = Rung("claude-opus-5-5", "xhigh") + stepped = routing.StepUp(Route(ran_on), Route(Rung("claude-fable-5-2", "low"), escalated_at=3)) + interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴") + for state, event, after in ( + (states.Judging("/t"), states.Ruled(quoted, stepped), states.Working(quoted, 1, True)), + (states.Judging("/t", 3), states.Ruled(quoted, stepped), states.Interrupting("/t", quoted, 3, ran_on)), + (states.Judging("/t"), states.Ruled(interrupt, stepped), states.Interrupting("/t", interrupt, 0, ran_on)), + (states.Interrupting("/t", interrupt, 0, ran_on), states.HumanTyped(TYPED), states.Working(TYPED, 0, True)), + (states.Interrupting("/t", interrupt, 0, ran_on), states.HumanTalked(), states.Judging("/t")), + (states.Working(TYPED, 0, True), states.WorkerRan("/t"), states.Judging("/t")), + ): + with self.subTest(state=state, event=event): + self.assertEqual(states.transition(state, event), after) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/agent_cycle/test_stuck_workers.py b/bin/agent_cycle/test_stuck_workers.py index ac93cfb9..14705797 100644 --- a/bin/agent_cycle/test_stuck_workers.py +++ b/bin/agent_cycle/test_stuck_workers.py @@ -6,7 +6,7 @@ import pathlib import tempfile import unittest -from loop_claude.test_loop_claude import FakeEffects, NOW, ran, Streamed +from loop_effects.test_doubles import FakeEffects, NOW, ran, Streamed from model_routing.ladder import Rung from loop_effects.child_shells import Shell from agent_cycle import stuck_workers, worker diff --git a/bin/agent_cycle/test_tmux.py b/bin/agent_cycle/test_tmux.py new file mode 100644 index 00000000..0bfe4dff --- /dev/null +++ b/bin/agent_cycle/test_tmux.py @@ -0,0 +1,95 @@ +import pathlib +import subprocess +import sys +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from loop_effects.test_doubles import FakeEffects +from chunk_driver.drivers import LOOP_CLAUDE +from agent_cycle import tmux + + +WINDOW = tmux.Window("loop-proj", "item-7", "%4") + + +class TmuxCommands(unittest.TestCase): + def test_refuses_a_tmux_older_than_needed_naming_both_versions(self): + for found, reason in (("tmux 3.2", None), ("tmux 3.8", None), ("tmux next-3.4", None), ("tmux 10.0", None), + ("tmux 3.1c", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), + ("tmux 2.9a", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 2.9a"), + ("", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux")): + with self.subTest(found=found): + fake = FakeEffects(tmux_version=found) + self.assertEqual(tmux.unusable(fake.tmux, LOOP_CLAUDE), reason) + self.assertEqual(fake.tmux_calls, [["-V"]]) + + def test_names_the_session_for_the_project(self): + self.assertEqual(tmux.session_name(tmux.LOOP, "claude-config"), "loop-claude-config") + # tmux reads `.` and `:` in a target as separators. + self.assertEqual(tmux.session_name(tmux.LOOP, "my.site:2 x"), "loop-my-site-2-x") + self.assertEqual(tmux.session_name(tmux.LOOP, "Acme/Billing"), "loop-Acme-Billing") + + def test_lists_the_windows_without_the_waiting_mark(self): + fake = FakeEffects(windows="item-372 ?\t0\t@1\nitem-380\t1\t@2\nno-item\t0\t@5\n") + self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False, asks=True), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)]) + self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) + self.assertEqual(tmux.listed("loop-proj", FakeEffects().tmux), []) + failed = lambda args: subprocess.CompletedProcess(args, 1, "item-1\t0\t@1\n", "no server") + self.assertEqual(tmux.listed("loop-proj", failed), []) + + def test_the_first_window_makes_the_session_and_each_later_one_joins_it(self): + fake = FakeEffects() + window = tmux.Window("loop-proj", "item-7", "") + self.assertIsNone(tmux.start_window(window, "/r", {"LOOP_CLAUDE_X": "1"}, ["/b/loop-claude", "--chunk", "item-7", "ship it;"], True, True, fake.tmux)) + self.assertIsNone(tmux.start_window(window, "/r", {}, ["/b/loop-claude"], False, True, fake.tmux)) + self.assertEqual(fake.tmux_calls, [ + ["new-session", "-d", "-s", "loop-proj", "-n", "item-7", "-c", "/r", "-e", "LOOP_CLAUDE_X=1", "-P", "-F", "#{window_id}", "--", "/b/loop-claude", "--chunk", "item-7", "ship it\;"], + ["set-option", "-t", "=loop-proj:", "@loop-root", "/r"], + ["set-option", "-w", "-t", "@9", "@chunk-root", "/r"], + ["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"], + ["new-window", "-d", "-t", "=loop-proj:", "-n", "item-7", "-c", "/r", "-P", "-F", "#{window_id}", "--", "/b/loop-claude"], + ["set-option", "-w", "-t", "@9", "@chunk-root", "/r"], + ["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"], + ]) + + def test_says_why_tmux_started_no_window(self): + failed = lambda args: subprocess.CompletedProcess(args, 1, "", "duplicate session: loop-proj\n") + silent = lambda args: subprocess.CompletedProcess(args, 2, "", "") + window = tmux.Window("loop-proj", "item-7", "") + self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, failed), Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj")) + self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, silent), Failure("tmux could not start the window loop-proj:item-7: it exited 2")) + + def test_fails_where_it_cannot_mark_a_session_it_made_as_the_checkouts_but_not_where_remain_on_exit_fails(self): + def answering(failing: str): + def run(args): + fails = args[:1] == ["set-option"] and failing in args + return subprocess.CompletedProcess(args, 1 if fails else 0, "" if fails else "@9\n", "no such session\n" if fails else "") + return run + window = tmux.Window("loop-proj", "item-7", "") + self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, answering(tmux.OWNER)), Failure("tmux started the session loop-proj but could not mark it as this checkout's: no such session")) + self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], True, True, answering("remain-on-exit"))) + self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], False, True, answering(tmux.OWNER))) + + def test_reads_the_checkout_the_session_names(self): + fake = FakeEffects(owner="/c/proj") + self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj") + self.assertEqual(fake.tmux_calls, [["show-options", "-qv", "-t", "=loop-proj:", "@loop-root"]]) + + def test_marks_a_waiting_window_by_its_pane_and_clears_the_mark(self): + fake = FakeEffects() + tmux.mark(WINDOW, True, fake.tmux) + tmux.mark(WINDOW, False, fake.tmux) + tmux.close(tmux.Listed("item-7", "@3", True), fake.tmux) + self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"], ["kill-window", "-t", "@3"]]) + self.assertEqual(WINDOW.target, "loop-proj:item-7") + + def test_shows_the_session_by_attaching_or_inside_tmux_by_switching(self): + self.assertEqual(tmux.show("loop-proj", False), ["attach-session", "-t", "=loop-proj"]) + self.assertEqual(tmux.show("loop-proj", True), ["switch-client", "-t", "=loop-proj"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/agent_cycle/test_worker.py b/bin/agent_cycle/test_worker.py new file mode 100644 index 00000000..3ee38e72 --- /dev/null +++ b/bin/agent_cycle/test_worker.py @@ -0,0 +1,135 @@ +import contextlib +import dataclasses +import io +import json +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from claude_code import entries +from failure import Failure +from loop_effects.test_doubles import FakeEffects, NOW, ran, Streamed +from agent_cycle import judge, lingering_workers, worker +from claude_code.reply import Limited +from machine_load import memory +from model_routing.ladder import Rung +from loop_effects.child_shells import Shell +from text_files.utc_stamp import utc + + +class Limits(unittest.TestCase): + def test_the_worker_reports_the_latest_reset_its_stream_names(self): + rejected = [{"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}} for resets_at in (NOW + 60, NOW + 600)] + allowed = {"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": NOW + 9000}} + limited = {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"} + fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited)]) + self.assertEqual(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects()), Limited(NOW + 600, "You've hit your session limit")) + + def test_a_limit_outranks_the_exit_code_and_its_message_fits_one_line(self): + def limited(**said): + return {"type": "result", "api_error_status": 429, **said} + self.assertEqual(worker.worker_outcome(-9, limited(result="limit\n resets 7pm"), []), Limited(None, "limit resets 7pm")) + self.assertEqual(worker.worker_outcome(1, limited(result=" \n"), [NOW]), Limited(NOW, "claude gave no message")) + self.assertEqual(worker.worker_outcome(0, limited(), []), Limited(None, "claude gave no message")) + self.assertEqual(worker.worker_outcome(0, None, [NOW]), Failure("claude exited 0 without a result event")) + self.assertIsNone(worker.worker_outcome(0, {"type": "result"}, [NOW])) + + def test_the_judge_reports_a_limit_whatever_its_exit_code(self): + reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"}) + fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")]) + self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds("", "", ""), fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)")) + + def test_reads_only_a_rejecting_events_whole_seconds(self): + for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]: + with self.subTest(info=info): + self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want) + + +class LingeringWorkers(unittest.TestCase): + RESULT = {"type": "result"} + + def worker_with(self, *events, held=()): + """Runs a worker whose claude prints events and holds shells `held`; returns the claude, what loop-claude said and the record's text.""" + clock = [NOW] + streamed = Streamed(0, *events, clock=clock, held=held) + fake = FakeEffects(streams=[streamed]) + effects = dataclasses.replace(fake.effects(), now=lambda: clock[0]) + with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()) as said: + # The archive folder of a project's first stop doesn't exist yet. + archive = pathlib.Path(folder, "transcripts", "project") + worker.run_worker("/r", [], {}, archive, Rung("m"), effects) + record = archive / lingering_workers.RECORD + return streamed, said.getvalue(), record.read_text() if record.exists() else "" + + def shell(self, written=NOW - 1000, runs_busy_tool=False, holds_slot=False): + return Shell(pid=7, started=NOW - 1000, command="until false; do sleep 15; done", written=written, runs_busy_tool=runs_busy_tool, holds_slot=holds_slot) + + def test_a_worker_that_lingers_after_its_result_loses_its_quiet_shell_and_the_stop_is_said_and_recorded_in_utc(self): + shell = self.shell() + streamed, said, record = self.worker_with(self.RESULT, None, held=[shell]) + self.assertEqual(streamed.stopped, [shell]) + line = f"stopped shell 7, which held a worker after its final result; it had run 1300 s and written nothing for 1300 s: {shell.command}" + self.assertEqual(said, f"<{NOW + 300}> {line}\n") + self.assertEqual(record, f"- {utc(NOW + 300)} {line}\n") + + def test_a_worker_keeps_its_shells_where_it_printed_after_its_result_or_printed_none_or_no_check_came_due(self): + for events in ((self.RESULT, {"type": "assistant", "message": {"content": []}}, None), (self.RESULT,), (None,), ({"type": "assistant", "message": {"content": []}}, None)): + with self.subTest(events=events): + streamed, said, record = self.worker_with(*events, held=[self.shell()]) + self.assertEqual((streamed.stopped, said, record), ([], "", "")) + + def test_a_worker_keeps_every_shell_while_one_of_them_writes_output_runs_a_busy_tool_or_holds_a_heavy_slot(self): + for busy in (self.shell(written=NOW + 200), self.shell(runs_busy_tool=True), self.shell(holds_slot=True)): + with self.subTest(busy=busy): + streamed, _, _ = self.worker_with(self.RESULT, None, held=[self.shell(), busy]) + self.assertEqual(streamed.stopped, []) + + def test_a_worker_keeps_a_shell_that_wrote_within_the_quiet_time_and_stops_one_that_wrote_before_it(self): + # The check comes 300 s after the result, so a shell written at NOW + 300 - QUIET is the latest that is still kept. + kept = self.shell(written=NOW + 300 - lingering_workers.QUIET) + stopped = self.shell(written=NOW + 300 - lingering_workers.QUIET - 1) + self.assertEqual(self.worker_with(self.RESULT, None, held=[kept])[0].stopped, []) + self.assertEqual(self.worker_with(self.RESULT, None, held=[stopped])[0].stopped, [stopped]) + + def test_a_worker_reads_on_past_a_check_that_found_it_still_working(self): + clock = [NOW] + effects = dataclasses.replace(FakeEffects(streams=[Streamed(0, None, self.RESULT, clock=clock)]).effects(), now=lambda: clock[0]) + self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), effects)) + + def test_a_stop_that_cannot_be_recorded_is_said_on_stderr_and_every_shell_is_still_stopped(self): + clock = [NOW] + held = [self.shell(), self.shell()] + streamed = Streamed(0, self.RESULT, None, clock=clock, held=held) + effects = dataclasses.replace(FakeEffects(streams=[streamed]).effects(), now=lambda: clock[0]) + with tempfile.NamedTemporaryFile() as blocker, contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as failed: + worker.run_worker("/r", [], {}, pathlib.Path(blocker.name), Rung("m"), effects) + self.assertEqual(streamed.stopped, held) + self.assertIn("could not record the stop", failed.getvalue()) + + def test_every_stop_of_a_check_is_recorded_though_the_archive_folder_exists_after_the_first(self): + held = [self.shell(), self.shell()] + _, said, record = self.worker_with(self.RESULT, None, held=held) + self.assertEqual(record.count("stopped shell 7"), 2) + + +class MemoryWait(unittest.TestCase): + def test_a_worker_starts_only_once_a_quarter_of_memory_is_available(self): + fake = FakeEffects(free_memory=[memory.Memory(available=3, total=16), memory.Memory(available=3, total=16), memory.Memory(available=4, total=16)], streams=[Streamed(0)]) + with contextlib.redirect_stderr(io.StringIO()) as said: + self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects())) + self.assertEqual([seam for seam, _ in fake.calls], ["memory", "sleep", "memory", "sleep", "memory", "stream_claude"]) + self.assertEqual(fake.made("sleep"), [worker.MEMORY_POLL] * 2) + self.assertEqual(said.getvalue().count("waiting"), 1, said.getvalue()) + + def test_a_worker_starts_at_once_where_memory_cannot_be_read(self): + fake = FakeEffects(free_memory=[None], streams=[Streamed(0)]) + self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects())) + self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/agent_cycle/verdicts.py b/bin/agent_cycle/verdicts.py index cbb117b9..e5cf240d 100644 --- a/bin/agent_cycle/verdicts.py +++ b/bin/agent_cycle/verdicts.py @@ -1,4 +1,4 @@ -"""The verdicts cycle.judge.verdict_from builds from the judge's reply; cycle.run.rule then stamps every verdict but Finished with the items the chunk takes. They sit outside cycle/, since routing reads them and cycle imports routing.""" +"""The verdicts judge.verdict_from builds from the judge's reply; run.rule then stamps every verdict but Finished with the items the chunk takes. They sit in a module of their own, since routing.py reads them and run.py imports routing.py.""" import dataclasses from transcript_archive.judge_run import JudgeRun @@ -7,7 +7,7 @@ from claude_code.tokens import Tokens @dataclasses.dataclass(frozen=True) class TakenIn: - """The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it.""" + """The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as the entry point reads them (run.py's Cycle.taken_in). The item the chunk was routed on counts only where the worker names it.""" # The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it. highest_likelihood: int = 0 # The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers. diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py new file mode 100644 index 00000000..fca56fc5 --- /dev/null +++ b/bin/atlassian/jira.py @@ -0,0 +1,137 @@ +"""What every reader of Jira Cloud's REST API version 3 shares: a search read page by page, the head of each entry it answers, an issue's "is blocked by" links, and the transition that finishes an issue.""" +import dataclasses +import re +import typing + +from failure import Failure +from project_config.settings import Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION +from atlassian.client import Http + +ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)") +PAGE = 100 +# The pages one read asks for at most, so an answer that never names a last page ends the read. +MAX_PAGES = 100 +# The key of the status category Jira Cloud gives every done status. +DONE = "done" +# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue. +PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {under} before filing it again" +# What a failed move ends with, for the same reason. +PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again" + + +@dataclasses.dataclass(frozen=True) +class Link: + """One "is blocked by" link of an issue.""" + # The key of the issue that blocks. + blocker: str + # The link's own id, which Jira deletes it by. + id: str + + +@dataclasses.dataclass(frozen=True) +class Entry: + """The head of one entry of a search's answer, which every reader checks alike.""" + key: str + # The entry's `fields`, from which each reader takes the ones it asked for. + fields: dict[str, typing.Any] + links: tuple[Link, ...] + # The issue property the search asked for; empty where the issue has none. A reader checks that it is a JSON object. + held: object + + +def entry_of(raw: object, property_: str) -> Entry | Failure: + """The head of one entry of a search's answer, or which issue is not in the shape Jira documents, and how. property_ names the issue property the search asked for.""" + key = raw.get("key") if isinstance(raw, dict) else None + if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): + return Failure("the search answered an issue without an issue key") + # The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it. + try: + fields = raw["fields"] + return Entry(key, fields, blocked_by_links(fields), raw.get("properties", {}).get(property_, {})) + except (AttributeError, KeyError, TypeError) as failure: + return Failure(unshaped(key, failure)) + + +def unshaped(key: str, failure: Exception) -> str: + """Why the issue named key cannot be read, for a field that is missing or of another type than Jira documents.""" + return f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}" + + +def offer_of(raw: object) -> tuple[str, str, str, str] | None: + """One transition Jira offers, as its ID, its name, the name of the status it leads to and the key of that status's category; None where raw holds no such transition.""" + to = raw.get("to") if isinstance(raw, dict) else None + category = to.get("statusCategory") if isinstance(to, dict) else None + if not isinstance(raw, dict) or not isinstance(to, dict) or not isinstance(category, dict): + return None + id_, name, status, key = raw.get("id"), raw.get("name"), to.get("name"), category.get("key") + return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None + + +def finishing_transition(site: str, key: str, finish: Finish, authorization: str, http: Http) -> str | Failure: + """The ID of the transition finish names, as Jira offers it now for the issue named key, which is a plan item or an epic; or why none of those offered finishes it.""" + offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None) + if isinstance(offered, Failure): + return Failure(f"cannot read {key}'s transitions: {offered.reason}") + return transition_of(offered, key, finish) + + +def move_refusal(site: str, key: str, transition: str, finish: Finish, authorization: str, http: Http) -> str | None: + """Moves the issue named key by the transition with the ID transition, which finishing_transition answered for finish. Why Jira did not take the move; None where it did.""" + moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": transition}}) + return f"cannot move {key} by {finish.transition!r}: {moved.reason}" if isinstance(moved, Failure) else None + + +def transition_of(offered: object, key: str, finish: Finish) -> str | Failure: + """The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item.""" + raw = offered.get("transitions") if isinstance(offered, dict) else None + found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else [] + if not isinstance(raw, list) or len(found) != len(raw): + return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents") + named = [each for each in found if each[1] == finish.transition] + if not named: + others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found) + return Failure(f"{key} has no transition {finish.transition!r} from its status, " + (f"only {others}: move the issue in Jira to a status that has it, or name in `{JIRA_FINISH_TRANSITION}` one that leads to a done status" if found else "nor any other the account may make")) + id_, _, status, category = next((each for each in named if each[2] == finish.status), named[0]) + if status != finish.status: + return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, not to {finish.status!r}, which `{JIRA_FINISH_STATUS}` names") + # `children` reads an issue as finished by its status's category, so a move to any other category would leave the item in the plan. + if category != DONE: + return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status") + return id_ + + +def project_of(key: str) -> str: + """The key of the Jira project an issue key lies in.""" + return key.rpartition("-")[0] + + +def rank_refusal(site: str, key: str, before: str, authorization: str, http: Http) -> str | None: + """Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors.""" + answer = http("PUT", f"{site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before}) + if isinstance(answer, Failure): + return answer.reason + entries = answer.get("entries") if isinstance(answer, dict) else None + refused = [entry for entry in entries if isinstance(entry, dict) and entry.get("status") != 200] if isinstance(entries, list) else [] + return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None + + +def searched(site: str, what: str, jql: str, asked: dict[str, object], authorization: str, http: Http) -> list[object] | Failure: + """Every issue a JQL search on site finds, page by page. The dict asked holds the request's `fields` and `properties` lists. The text what names the issues sought, in the Failure of a search that doesn't end.""" + body: dict[str, object] = {"jql": jql, "maxResults": PAGE} | asked + found: list[object] = [] + for _ in range(MAX_PAGES): + page = http("POST", f"{site}/rest/api/3/search/jql", authorization, body) + if isinstance(page, Failure): + return page + if not isinstance(page, dict) or not isinstance(page.get("issues"), list): + return Failure("the search answered something other than a page of issues") + found += page["issues"] + if not page.get("nextPageToken"): + return found + body = body | {"nextPageToken": page["nextPageToken"]} + return Failure(f"the search for {what} did not end within {MAX_PAGES} pages") + + +def blocked_by_links(fields: dict[str, typing.Any]) -> tuple[Link, ...]: + """The "is blocked by" links among an issue's `issuelinks` field. A field not in the shape Jira documents raises a KeyError or TypeError, which the caller turns into a Failure.""" + return tuple(Link(link["inwardIssue"]["key"], link["id"]) for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by") diff --git a/bin/chunk_driver/__init__.py b/bin/chunk_driver/__init__.py new file mode 100644 index 00000000..0fe82b4d --- /dev/null +++ b/bin/chunk_driver/__init__.py @@ -0,0 +1,4 @@ +"""What the entry points that drive chunks share: loop-claude and do-epic. + +Each runs a chunk as cycles of bin/agent_cycle/. cycle_start.py starts a cycle and chunk_run.py closes it, on the Loop this_loop.py holds, once claims.py has claimed the checkout. prompts.py words what every worker is told, project/ reads a checkout's premises, records and saved models, and drivers.py names the entry points. No module here imports an entry point's package, and bin/repo_checks/test_package_cycles.py fails on such an import. +""" diff --git a/bin/chunk_driver/chunk_run.py b/bin/chunk_driver/chunk_run.py new file mode 100644 index 00000000..cf536edd --- /dev/null +++ b/bin/chunk_driver/chunk_run.py @@ -0,0 +1,76 @@ +"""One chunk's run across its cycles, for every entry point that drives chunks: its state (Run, ChunkRun), and how a cycle closes: the run the next cycle starts from, the step-up an unfinished verdict makes archived, and the stop once a chunk has had UNFINISHED_LIMIT unfinished verdicts running.""" +import dataclasses +import pathlib +import typing + +from agent_cycle.run import archived_step, archived_stop, Concluded +from agent_cycle.verdicts import Finished +from chunk_driver.this_loop import Loop +from agent_cycle.stop import needs_human, Stop +from agent_cycle.routing import next_route, step_up +from model_routing.ladder import ProjectRung +from model_routing.route import Route +from claude_code.session import transcript_file + +# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts. +UNFINISHED_LIMIT = 6 + + +class Run(typing.Protocol): + """What closing a cycle reads and replaces in an entry point's run of one chunk. ChunkRun below is one; loop-claude's LoopRun is another, since it hands the same fields on at a reload.""" + # Every run is a dataclass, which is what lets closing a cycle replace its fields. + __dataclass_fields__: typing.ClassVar[dict[str, typing.Any]] + + @property + def task(self) -> str: ... + @property + def unfinished_evidence(self) -> str: ... + @property + def route(self) -> Route | None: ... + @property + def unfinished_run(self) -> int: ... + + +@dataclasses.dataclass(frozen=True) +class ChunkRun: + """The run of one chunk, for an entry point that never hands it to another process, such as do-epic.""" + cycle_number: int = 0 + task: str = "" + # The evidence of the latest unfinished verdict; empty before the chunk's first one, and once it finishes. + unfinished_evidence: str = "" + # Set by each unfinished verdict; None before the chunk's first one, and once it finishes. + route: Route | None = None + # How many unfinished verdicts the chunk has had running. + unfinished_run: int = 0 + + +def closed_cycle[R: Run](run: R, project: ProjectRung | None, concluded: Concluded, archive_folder: pathlib.Path, driver: str, loop: Loop) -> R | Stop: + """The run after a cycle of driver, the entry point, concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running.""" + after = after_verdict(run, project, concluded) + # A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts. + if after.route is None: + return after + # The unfinished verdict, archived as the cycle closed, names the route its cycle ended on; the step-up names the one the next cycle runs on. + path = transcript_file(loop.session) + if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), loop.effects)): + return Stop(1, failure.reason) + if limit := reached_limit(after, driver): + # Archived with the route the next cycle would run on, so a rerun resumes there. + return archived_stop(archive_folder, loop.session, after.task, after.route, limit, limit.reason, loop.effects) + return after + + +def reached_limit(run: Run, driver: str) -> Stop | None: + """The stop that needs the human once the run holds UNFINISHED_LIMIT unfinished verdicts running.""" + if run.unfinished_run < UNFINISHED_LIMIT: + return None + return needs_human("go on with the chunk", f"the judge ruled it unfinished {run.unfinished_run} cycles running; finish the chunk yourself, or rerun {driver} to give it {UNFINISHED_LIMIT} more cycles") + + +def after_verdict[R: Run](run: R, project: ProjectRung | None, concluded: Concluded) -> R: + """The run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised, and the evidence the judge gave for the verdict; and counts the verdict.""" + verdict = concluded.verdict + if isinstance(verdict, Finished): + return dataclasses.replace(run, route=None, unfinished_evidence="", unfinished_run=0) + route = next_route(project, concluded.route, verdict) + return dataclasses.replace(run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=run.unfinished_run + 1) diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py new file mode 100644 index 00000000..d1204f01 --- /dev/null +++ b/bin/chunk_driver/claims.py @@ -0,0 +1,39 @@ +"""How entry points claim a checkout before they start a chunk in it, so that two never start the same chunk and do-epic never starts one where loop-claude runs. + +An entry point holds `starting` on `project_lock` while it lists the windows of the checkout's chunks and starts new ones. It starts each chunk in a tmux window with CHUNK_FLAG, and hands that window the variables named with HANDED. +""" +import contextlib +import fcntl +import pathlib +import typing + +from transcript_archive.project_key import project_key +from agent_cycle import tmux + +# Under the home folder, a folder per project key holds LOCK. +CLAIMS = ".local/state/loop-claude" +# The file an entry point keeps locked with flock while it lists the windows of a project's chunks and starts new ones. Two loops whose chunks finish together then don't start a chunk twice, and do-epic, which holds the same lock, never starts a chunk in a checkout while loop-claude does. +LOCK = "starting" +# The flag that tells the entry point in a window its chunk, as `--chunk item-372` for loop-claude and `--chunk ABC-34 ABC-12` for do-epic. Nobody types it, so no panel picked it. +CHUNK_FLAG = "--chunk" +# The prefix of the variables both entry points read. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name. +HANDED = "LOOP_CLAUDE_" + + +@contextlib.contextmanager +def starting(folder: pathlib.Path) -> typing.Iterator[None]: + """Holds the LOCK in folder: project_lock's for a project, or do-epic's for an epic. Raises OSError where the file cannot be opened or locked.""" + folder.mkdir(parents=True, exist_ok=True) + with open(folder / LOCK, "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + yield + + +def project_lock(root: str, home: pathlib.Path) -> pathlib.Path: + """The folder of the LOCK that everything starting a chunk in the checkout root holds.""" + return home / CLAIMS / project_key(root, home) + + +def epic_chunks(root: str, run: tmux.Tmux) -> list[tmux.Placed]: + """The windows of do-epic's sessions whose chunks run in the checkout root. A parked chunk doesn't run.""" + return [placed for placed in tmux.everywhere(run) if placed.session.startswith(f"{tmux.EPIC}-") and placed.root == root and not placed.window.dead and not placed.window.parked] diff --git a/bin/chunk_driver/cycle_start.py b/bin/chunk_driver/cycle_start.py new file mode 100644 index 00000000..a5f2c716 --- /dev/null +++ b/bin/chunk_driver/cycle_start.py @@ -0,0 +1,114 @@ +"""How a cycle starts, for every entry point that drives chunks: the models and the ladder it routes on, the route its worker runs on, and the Cycle built from them. + +An entry point starts a cycle in this order: + +1. It reads what it alone knows, such as the premises, the records and the task. +2. `project_routing` or `routing_on` reads the models and the ladder. +3. `announced_route` picks the route and prints the cycle's opening line. +4. `cycle_of` builds the Cycle. + +Each read is made afresh every cycle, so an edit between two cycles takes effect in the next. +""" +import dataclasses +import pathlib +import typing + +from agent_cycle.run import Cycle +from claude_code.entries import Entry +from failure import Failure +from agent_cycle.routing import first_route, judge_rung, kept, Scored +from chunk_driver.project.model_choice import get_or_ask_models, Models +from git_cli.git_repo import Git +from model_routing.ladder import Ladder, ProjectRung, Rung +from transcript_archive.read import latest_worker +from chunk_driver.this_loop import Loop +from transcript_archive.project_key import project_key +from model_routing.ladder_file import project_ladder_file, read_ladder +from model_routing.route import Route, route_from +from loop_effects.effects import say +from agent_cycle.stop import Stop +from agent_cycle.verdicts import TakenIn +from claude_code.session import transcript_file +from agent_cycle.worker_prompts import WorkerPrompts + + +@dataclasses.dataclass(frozen=True) +class Routing: + """What a cycle routes on, as read when it started.""" + # The project's worker and judge models. + models: Models + ladder: Ladder + # The file the ladder was read from: the shipped one, or the project's own. + ladder_file: pathlib.Path + + @property + def project(self) -> ProjectRung | None: + """The project's rung on the ladder; None for a worker model off the ladder.""" + return self.ladder.project_rung(self.models.worker) + + +def project_routing(loop: Loop, driver: str) -> Routing | Stop: + """The routing of the project checked out at the loop's root: its models, asked of the human where none is saved, and its ladder. The stop where one cannot be read.""" + models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, driver, loop.effects) + if isinstance(models, Stop): + return models + ladder_file = project_ladder_file(loop.root, loop.paths.home) + return Stop(1, ladder_file.reason) if isinstance(ladder_file, Failure) else routing_on(models, ladder_file) + + +def routing_on(models: Models, ladder_file: pathlib.Path) -> Routing | Stop: + """The routing of models on the ladder ladder_file holds; the stop where it cannot be read.""" + ladder = read_ladder(ladder_file) + return Stop(1, ladder.reason) if isinstance(ladder, Failure) else Routing(models, ladder, ladder_file) + + +def announced_route(cycle_number: int, kept_route: Route | None, routing: Routing, archive_folder: pathlib.Path, item: typing.Callable[[], Scored | None], loop: Loop) -> Route: + """The route cycle cycle_number runs on, printed with the cycle's opening line. kept_route is the one the chunk's run holds, and item finds what routes a fresh chunk.""" + route = routed(kept_route, routing.project, routing.models.worker, lambda: archived_route(archive_folder, loop), item) + say(f"\n=== cycle {cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True) + return route + + +def routed(route: Route | None, project: ProjectRung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Scored | None]) -> Route: + """The route the cycle runs on. project is the project's rung, and model the project's model. + + Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else what item finds routes the chunk afresh. + """ + if project is None: + return Route(Rung(model)) + route = route or archived() + return route if route and kept(route, project) else first_route(project, item()) + + +def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None: + """The route named by the latest verdict archived for the loop's open chunk; None for a chunk not yet judged.""" + transcript = transcript_file(loop.session) + worker = latest_worker(archive_folder, transcript) if transcript else None + if isinstance(worker, Failure): + say(f"routing the chunk afresh: {worker.reason}", loop.effects) + return None + route = route_from(worker) if worker else None + if worker and route is None: + say(f"routing the chunk afresh: the archive's latest Worker: line names no route that can be read: {worker}", loop.effects) + return route + + +def cycle_of(loop: Loop, routing: Routing, route: Route, archive_folder: pathlib.Path, *, task: str, facts: str, premises: str, records: str, unfinished_evidence: str, prompts: WorkerPrompts, taken_in: typing.Callable[[list[Entry]], TakenIn]) -> Cycle: + """The cycle that runs in the loop's window on route. The keyword arguments are what the entry point alone knows; Cycle says what each is.""" + return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge=judge_rung(routing.ladder, routing.models.judge), premises=premises, project=routing.project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=task, prompts=prompts, taken_in=taken_in, unfinished_evidence=unfinished_evidence, window=loop.window) + + +def setup_version(claude_dir: pathlib.Path, git: Git) -> str: + """The release and commit of this setup that the worker's claude reads, as `v0.8.0 ()`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 ()`. Where git can't tell, `unknown` and why.""" + described = git("describe", "--tags", "--match", "v*", "--always", cwd=str(claude_dir)) + commit = git("rev-parse", "HEAD", cwd=str(claude_dir)) + if isinstance(described, Failure): + return unknown_version(described) + if isinstance(commit, Failure): + return unknown_version(commit) + return f"{described.strip()} ({commit.strip()})" + + +def unknown_version(failure: Failure) -> str: + # One line, since the archive reads the line after it as the judge's. + return f"unknown: {' '.join(failure.reason.split())}" diff --git a/bin/chunk_driver/drivers.py b/bin/chunk_driver/drivers.py new file mode 100644 index 00000000..07898a02 --- /dev/null +++ b/bin/chunk_driver/drivers.py @@ -0,0 +1,3 @@ +"""The entry points that drive chunks, each by its name as its workers, its judge and the human read it. A prompt function that takes a driver takes one of these.""" +LOOP_CLAUDE = "loop-claude" +DO_EPIC = "do-epic" diff --git a/bin/loop_claude/cycle/__init__.py b/bin/chunk_driver/project/__init__.py similarity index 100% rename from bin/loop_claude/cycle/__init__.py rename to bin/chunk_driver/project/__init__.py diff --git a/bin/loop_claude/project/model_choice.py b/bin/chunk_driver/project/model_choice.py similarity index 100% rename from bin/loop_claude/project/model_choice.py rename to bin/chunk_driver/project/model_choice.py diff --git a/bin/loop_claude/project/premises.py b/bin/chunk_driver/project/premises.py similarity index 100% rename from bin/loop_claude/project/premises.py rename to bin/chunk_driver/project/premises.py diff --git a/bin/loop_claude/project/records.py b/bin/chunk_driver/project/records.py similarity index 98% rename from bin/loop_claude/project/records.py rename to bin/chunk_driver/project/records.py index 85da5bd8..14769dd6 100644 --- a/bin/loop_claude/project/records.py +++ b/bin/chunk_driver/project/records.py @@ -2,7 +2,7 @@ import pathlib from failure import Failure from project_config.main import located -from loop_claude.project.text_file import read_utf8 +from chunk_driver.project.text_file import read_utf8 from record_store.stores import store # The records the judge reads beside the premises, by the name that heads each, with the setting in the project's config that places it; then the human's rules below. diff --git a/bin/chunk_driver/project/test_model_choice.py b/bin/chunk_driver/project/test_model_choice.py new file mode 100644 index 00000000..837e59c4 --- /dev/null +++ b/bin/chunk_driver/project/test_model_choice.py @@ -0,0 +1,36 @@ +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from failure import Failure +from loop_effects.test_doubles import FakeEffects +from chunk_driver.drivers import LOOP_CLAUDE +from chunk_driver.project import model_choice +from agent_cycle.stop import Stop + + +class ModelPrompt(unittest.TestCase): + OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")] + + def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self): + self.assertEqual(model_choice.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5") + self.assertEqual(model_choice.model_picked("opus", self.OFFERED), "opus") + self.assertEqual(model_choice.model_picked("3", []), "3") + self.assertEqual(model_choice.model_picked("3", self.OFFERED), Failure("pick 1 to 2")) + self.assertIsNone(model_choice.model_picked(" ", self.OFFERED)) + + def test_asks_again_until_an_answer_picks_a_model(self): + with tempfile.TemporaryDirectory() as empty: + fake = FakeEffects(inputs=["", "my-model"]) + self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), LOOP_CLAUDE, fake.effects()), "my-model") + self.assertEqual(len(fake.made("input")), 2) + fake = FakeEffects(inputs=[EOFError()]) + self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), LOOP_CLAUDE, fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/chunk_driver/project/test_records.py b/bin/chunk_driver/project/test_records.py new file mode 100644 index 00000000..1d0d225f --- /dev/null +++ b/bin/chunk_driver/project/test_records.py @@ -0,0 +1,90 @@ +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from project_config.test_project_config import configured +from failure import Failure +from chunk_driver.project import records + + +class Records(unittest.TestCase): + def test_heads_each_record_by_its_name_the_humans_rules_last(self): + with tempfile.TemporaryDirectory() as root: + claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") + config = configured(self, pathlib.Path(root), home=claude_md.parents[1]) / "config.toml" + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "") + claude_md.parent.mkdir(parents=True) + claude_md.write_text("# Global\n") + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "From ~/.claude/CLAUDE.md:\n# Global") + pathlib.Path(root, "docs").mkdir() + pathlib.Path(root, "docs", "decisions.md").write_text("# Decisions\n") + pathlib.Path(root, "AGENTS.md").write_text("\n# Rules\n") + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global") + pathlib.Path(claude_md.parent, "rules").mkdir() + pathlib.Path(claude_md.parent, "rules", "todo-items.md").write_text("# Todo\n") + pathlib.Path(claude_md.parent, "rules", "goals-and-audience.md").write_text("# Goals\n") + pathlib.Path(claude_md.parent, "rules", "notes.txt").write_text("not a rule\n") + pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True) + pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n") + self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments")) + config.write_text(config.read_text().replace('"~/.claude/skills/larv-review/standards"', '"~/review-standards"')) + pathlib.Path(claude_md.parents[1], "review-standards").mkdir() + pathlib.Path(claude_md.parents[1], "review-standards", "quality.md").write_text("# Ours\n") + self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/review-standards/quality.md:\n# Ours"), "the config's standards folder replaces the default") + config.write_text(config.read_text().replace('"~/review-standards"', f'"{root}/standards"')) + pathlib.Path(root, "standards").mkdir() + pathlib.Path(root, "standards", "quality.md").write_text("# Elsewhere\n") + self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"), "a folder outside home is named in full") + + config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"').replace('"checkout:docs/decisions.md"', '"folder:log/decisions.md"')) + self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"), "the checkout's AGENTS.md and docs/decisions.md are its owners'") + pathlib.Path(config.parent, "log").mkdir() + pathlib.Path(config.parent, "log", "decisions.md").write_text("# Ours\n") + pathlib.Path(config.parent, "AGENTS.md").write_text("# Our rules\n") + self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From AGENTS.md:\n# Our rules\n\nFrom docs/decisions.md:\n# Ours\n\nFrom ~/.claude/CLAUDE.md:\n# Global")) + config.unlink() + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"no config names the checkout {root}: write ~/.claude-projects//config.toml, as `project-config --help` shows - the judge cannot read the records.")) + + def test_puts_the_records_handed_in_first_and_reads_only_the_humans_rules_without_a_checkout(self): + with tempfile.TemporaryDirectory() as root: + claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") + configured(self, pathlib.Path(root), home=claude_md.parents[1]) + claude_md.parent.mkdir(parents=True) + claude_md.write_text("# Global\n") + pathlib.Path(claude_md.parent, "rules").mkdir() + pathlib.Path(claude_md.parent, "rules", "todo-items.md").write_text("# Todo\n") + pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True) + pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n") + pathlib.Path(root, "AGENTS.md").write_text("# Rules\n") + first = (("the epic ABC-1's description, ## Decisions", "Squash.\n"), ("the epic ABC-1's description, ## Scoring", " \n")) + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom AGENTS.md:\n# Rules\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments") + self.assertEqual(records.read_records(None, claude_md.parents[1], claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo") + + def test_stops_on_a_record_it_cannot_read(self): + with tempfile.TemporaryDirectory() as root: + claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") + configured(self, pathlib.Path(root), home=claude_md.parents[1]) + claude_md.mkdir(parents=True) + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records.")) + pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True) + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"cannot read {root}/docs/decisions.md: Is a directory - the judge cannot read the records.")) + pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n") + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records.")) + + + def test_stops_on_a_rule_it_cannot_read(self): + with tempfile.TemporaryDirectory() as root: + claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") + configured(self, pathlib.Path(root), home=claude_md.parents[1]) + rules = pathlib.Path(claude_md.parent, "rules") + rules.mkdir(parents=True) + pathlib.Path(rules, "todo-items.md").write_bytes(b"\xff\n") + self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records.")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/project/text_file.py b/bin/chunk_driver/project/text_file.py similarity index 100% rename from bin/loop_claude/project/text_file.py rename to bin/chunk_driver/project/text_file.py diff --git a/bin/loop_claude/cycle/prompts.py b/bin/chunk_driver/prompts.py similarity index 76% rename from bin/loop_claude/cycle/prompts.py rename to bin/chunk_driver/prompts.py index 3ac26061..365f0206 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/chunk_driver/prompts.py @@ -1,20 +1,17 @@ -"""What loop-claude says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. In a chunk's first prompt, routed_by places them after its routing sentences where an item routed the chunk, and fresh places them alone otherwise. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict.""" +"""What every entry point says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. An entry point places them in a chunk's first prompt, as loop-claude does in bin/loop_claude/chunk/fresh_prompt.py. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict.""" import functools import typing from agent_cycle.worker_prompts import answers_recorded, WorkerPrompts from agent_cycle.escalation_mark import asks_higher_rung from model_routing.review_choice import chosen, ReviewChoice -from loop_claude.cycle.chunk_items import CHUNK_ITEMS from model_routing.route import ESCALATION_MARKER, Route from agent_cycle.routing import escalation_rungs -from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES, RECORDS_NAMED +from chunk_driver.project.records import HUMAN_RULE_NAMES, RECORD_FILES, RECORDS_NAMED from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS from text_files.markdown_text import listed, quoted from model_routing.ladder import ProjectRung, Rung -# loop-claude's name as its workers, its judge and the human read it. A function below that takes a driver words a sentence for any entry point, such as do-epic. -DRIVER = "loop-claude" # Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises. QUOTE_SOURCES = listed(("the goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or") # Where the worker may write an answer the human typed, so it counts as recorded. @@ -28,45 +25,8 @@ THE_SECURITY_PASS = "the security pass's subagent" # Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings. READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context." -# chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`). -NAME_THE_ITEMS = f"Name every plan item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes." -AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' - - -def fresh(driver: str, task: str, premises: str, route: Route, project: ProjectRung | None, facts: str) -> str: - """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" - routed = f"{routed_by(driver, route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(driver, route, project)) - opening = f"{routed}\n\n" if routed else "" - return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's plan items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}" - - -def routed_by(driver: str, route: Route, project: ProjectRung | None) -> str: - return " ".join(( - f"{driver} runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.", - *rung_sentences(driver, route, project), - )) - - -def recount(route: Route) -> str: - """Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code.""" - return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores plan items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1." - - -def preflight_facts(printed: str) -> str: - """What chunk-preflight printed, for the worker to take as found.""" - return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}" - - -def held_by_others(items: list[int]) -> str: - """Keeps a fresh worker off the plan items the project's other chunks hold, running or stopped.""" - return f"\n\nOther chunks of this project, running or stopped, hold {'items ' if len(items) > 1 else 'item '}{', '.join(map(str, items))}. Leave those items out of this chunk, even where the facts above list them as items that may join it." - - -def preflight_failed(reason: str) -> str: - """Has the worker find the facts chunk-preflight would have, its worktree among them.""" - return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}" def review_launches(route: Route, project: ProjectRung | None) -> list[str]: @@ -196,6 +156,3 @@ class RecordNames(typing.NamedTuple): def worker_prompts(driver: str, fresh: typing.Callable[[str, str, Route, ProjectRung | None, str], str], naming: str, names: RecordNames = RecordNames()) -> WorkerPrompts: """The prompts of an entry point's cycles: its own fresh prompt, and the resumed prompt and rung sentences every entry point shares, each naming driver. resumed says what naming is. names is loop-claude's unless the entry point keeps records elsewhere, as do-epic does.""" return WorkerPrompts(driver, fresh, functools.partial(resumed, driver, naming), functools.partial(rungs_held, driver), *names) - - -WORKER = worker_prompts(DRIVER, functools.partial(fresh, DRIVER), NAME_THE_ITEMS) diff --git a/bin/chunk_driver/test_cycle_start.py b/bin/chunk_driver/test_cycle_start.py new file mode 100644 index 00000000..7a6bb8a5 --- /dev/null +++ b/bin/chunk_driver/test_cycle_start.py @@ -0,0 +1,40 @@ +import os +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from chunk_driver import cycle_start +from failure import Failure +from git_cli.git_repo import git + + +class SetupVersion(unittest.TestCase): + def test_names_the_release_and_the_commit_or_why_git_cannot_tell(self): + with tempfile.TemporaryDirectory() as root: + isolated = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root} + with unittest.mock.patch.dict(os.environ, isolated): + gone = cycle_start.setup_version(pathlib.Path(root), git) + self.assertRegex(gone, r"^unknown: [^\n]*not a git repository") + for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]): + self.assertIsInstance(git(*step, cwd=root), str) + head = git("rev-parse", "HEAD", cwd=root).strip() + self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})") + git("tag", "v0.1.0", cwd=root) + self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})") + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root) + head = git("rev-parse", "HEAD", cwd=root).strip() + self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})") + + def test_names_why_git_cannot_name_the_commit_on_one_line(self): + def fake_git(*args, cwd=None): + return Failure("fatal: bad HEAD\nhint: repair it") if args[0] == "rev-parse" else "v0.1.0\n" + + self.assertEqual(cycle_start.setup_version(pathlib.Path("/r"), fake_git), "unknown: fatal: bad HEAD hint: repair it") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/loop/this_loop.py b/bin/chunk_driver/this_loop.py similarity index 52% rename from bin/loop_claude/loop/this_loop.py rename to bin/chunk_driver/this_loop.py index 1093d6db..ea62dff3 100644 --- a/bin/loop_claude/loop/this_loop.py +++ b/bin/chunk_driver/this_loop.py @@ -10,8 +10,8 @@ from agent_cycle.tmux import Window @dataclasses.dataclass(frozen=True) class Loop: - """What stays the same through one run of loop-claude; run_loop builds it once per process, so a reload builds it afresh.""" - # The checkout the loop runs in. LoopRun.root names it too, since a reload hands it on there. + """What stays the same while an entry point drives one chunk in one process. loop-claude builds it once per process, so a reload builds it afresh; do-epic builds one per chunk.""" + # The checkout the loop runs in. loop-claude's LoopRun.root names it too, since a reload hands it on there. root: str # The worker's session. session: Session @@ -19,6 +19,6 @@ class Loop: window: Window paths: Paths env: typing.Mapping[str, str] - # The loop-claude script, whose edits reload the loop and beside which chunk-preflight lies. + # The entry point's script, beside which chunk-preflight lies; an edit of loop-claude's reloads its loop. launcher: pathlib.Path effects: Effects diff --git a/bin/chunk_pr/approval.py b/bin/chunk_pr/approval.py index 61779af0..bb343868 100644 --- a/bin/chunk_pr/approval.py +++ b/bin/chunk_pr/approval.py @@ -1,11 +1,10 @@ """The human approval that `chunk-pr merge` waits for where the project's config sets `wait-for-approval`.""" -import json -import pathlib import time import typing from failure import Failure from forge.commands import Forge, Run +from forge.reviews import github_decision, waiting_threads # A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed. POLL_SECONDS = 60 @@ -21,20 +20,9 @@ def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure: return wait_for_approval -# Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout. -THREADS = """query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { - author { login } - reviewThreads(first: 100) { nodes { isResolved path comments(last: 1) { nodes { author { login } } } } } -} } }""" - - def approval(number: str, run: Run) -> bool | Failure: """Whether GitHub reports pull request number approved, as its branch protection asks, read once: False while it still wants a review. A Failure where a reviewer requested changes, or where the protection asks for no review.""" - viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"]) - try: - decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"] - except (ValueError, KeyError, TypeError): - return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}") + decision = github_decision(number, run) if isinstance(decision, Failure): return decision if decision == "CHANGES_REQUESTED": @@ -73,16 +61,3 @@ def unanswered(number: str, run: Run) -> Failure | None: if not waiting: return None return Failure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again") - - -def waiting_threads(number: str, run: Run) -> list[str] | Failure: - """The files where a reviewer's comment waits for an answer on pull request number, read once: those of each review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again.""" - read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) - if isinstance(read, Failure): - return read - try: - pull = json.loads(read)["data"]["repository"]["pullRequest"] - author = pull["author"]["login"] - return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) - except (ValueError, KeyError, TypeError): - return Failure(f"gh api graphql printed no review threads: {read.strip()[:200]}") diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index 41ca75df..6fdfb43d 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -16,7 +16,7 @@ from failure import Failure from test_env import isolated_env from project_config.settings import ProjectConfig from forge.commands import Run -from chunk_pr.approval import THREADS +from forge.reviews import THREADS TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr" GITHUB = "git@github.com:me/project.git" diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 33cad807..257d07d4 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -5,16 +5,16 @@ import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown -from plan_store.jira_epic import blocked_by_links, DONE, FILED_BY, finishing_transition, ISSUE_KEY, ISSUE_TYPE, move_refusal, PERHAPS_MOVED, project_of, PROPERTY, rank_refusal, scores, searched +from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure +from plan_store.jira_epic import FILED_BY, ISSUE_TYPE, PROPERTY, scores FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"] # How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes. PARENTS_PER_SEARCH = 50 NO_FINISH = "do-epic's settings name no transition to {to} by: set `{transition}` and `{status}` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"" -PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {parent} before filing it again" @dataclasses.dataclass(frozen=True) @@ -74,10 +74,10 @@ class JiraEpic: fields["description"] = description created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": fields | {"issuetype": kind}, "properties": properties}) if isinstance(created, Failure): - return Failure(f"cannot file the issue under {parent}: {created.reason}; {PERHAPS_FILED.format(parent=parent)}") + return Failure(f"cannot file the issue under {parent}: {created.reason}; {PERHAPS_FILED.format(under=parent)}") key = created.get("key") if isinstance(created, dict) else None if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): - return Failure(f"Jira answered the new issue without an issue key; {PERHAPS_FILED.format(parent=parent)}") + return Failure(f"Jira answered the new issue without an issue key; {PERHAPS_FILED.format(under=parent)}") return key def add_label(self, key: str, label: str) -> None | Failure: @@ -129,7 +129,7 @@ class JiraEpic: category = answered["fields"]["status"]["statusCategory"]["key"] # type: ignore[index] except (KeyError, TypeError) as failure: return Failure(f"{self.epic_key}'s status is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") - return bool(category == "done") + return bool(category == DONE) def close(self, summary: str) -> None | Failure: if self.finish is None: @@ -243,19 +243,17 @@ class JiraEpic: def found_of(raw: object) -> Found | Failure: """The issue in one entry of a search's answer, or which issue is not in the shape Jira documents.""" - key = raw.get("key") if isinstance(raw, dict) else None - if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): - return Failure("the search answered an issue without an issue key") - # The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here. + entry = entry_of(raw, PROPERTY) + if isinstance(entry, Failure): + return entry + key, fields, held = entry.key, entry.fields, entry.held + blockers = tuple(link.blocker for link in entry.links) try: - fields = raw["fields"] summary, labels, assignee, status, parent, description = fields["summary"], fields["labels"], fields["assignee"], fields["status"], fields["parent"]["key"], fields["description"] name = assignee["displayName"] if assignee is not None else None - state, done = status["name"], status["statusCategory"]["key"] == "done" - blockers = tuple(link.blocker for link in blocked_by_links(fields)) - held = raw.get("properties", {}).get(PROPERTY, {}) + state, done = status["name"], status["statusCategory"]["key"] == DONE except (AttributeError, KeyError, TypeError) as failure: - return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") + return Failure(unshaped(key, failure)) texts = (summary, *labels, state, parent, *blockers) if isinstance(labels, list) else () if not texts or not all(isinstance(text, str) for text in texts) or not isinstance(name, str | None) or not all(ISSUE_KEY.fullmatch(each) for each in (parent, *blockers)) or not isinstance(description, dict | None): return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its summary, labels, assignee, status, parent, description or a linked issue's key holds another kind of value") diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 762ab246..d8e7b8b5 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -12,7 +12,6 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) from project_config.settings import Epic, Finish from do_epic.backend.contract import EpicStoreContract from failure import Failure -from plan_store import jira_epic from do_epic.backend.jira import JiraEpic from adf_codec.convert import Refused @@ -328,7 +327,7 @@ class Jira(Case): ("ABC-34", "the search answered an issue without an issue key"), ({"fields": valid}, "the search answered an issue without an issue key"), ({"key": "abc-34", "fields": valid}, "the search answered an issue without an issue key"), - ({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}}}, shape + ": KeyError('labels')"), + ({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}, "issuelinks": []}}, shape + ": KeyError('labels')"), *((({"key": "ABC-34", "fields": valid | changed}, shape + ": its summary, labels, assignee, status, parent, description or a linked issue's key holds another kind of value") for changed in ( {"summary": 3}, {"labels": "api"}, {"labels": [3]}, {"assignee": {"displayName": 0}}, {"status": {"name": 0, "statusCategory": {"key": "new"}}}, {"parent": {"key": "ABC"}}, {"parent": {"key": 12}}, {"description": "text"}, {"issuelinks": [linked | {"inwardIssue": {"key": 7}}]}, {"issuelinks": [linked | {"inwardIssue": {"key": "ABC-x"}}]}, ))), @@ -352,7 +351,7 @@ class Jira(Case): children = [store.file("ABC-12", "Count the runs.", "", ()) for _ in range(2)] for _ in range(3): store.file(str(children[0]), "A task.", "", ()) - with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 1): + with unittest.mock.patch("atlassian.jira.MAX_PAGES", 1): self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages")) store.file("ABC-12", "Count the runs.", "", ()) self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages")) diff --git a/bin/do_epic/chunk_prompt.py b/bin/do_epic/chunk_prompt.py index cea698dc..d5d377e2 100644 --- a/bin/do_epic/chunk_prompt.py +++ b/bin/do_epic/chunk_prompt.py @@ -1,19 +1,20 @@ """What a do-epic cycle's worker is told: its task, from the issue, and its first prompt. The resumed prompt and the rung sentences are the ones loop-claude's cycles use, naming do-epic; a chunk that was parked is first told why it resumes, and one whose task follows the epic's state is told that task as it resumes.""" import dataclasses +from chunk_driver.drivers import DO_EPIC from do_epic.backend.protocol import EpicIssue from do_epic import findings -from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES +from chunk_driver.project.records import HUMAN_RULE_NAMES, RECORD_FILES from text_files.markdown_text import listed import pathlib from project_config.settings import ProjectConfig from model_routing.ladder import ProjectRung -from loop_claude.cycle import prompts +from chunk_driver import prompts from model_routing.route import Route from agent_cycle.worker_prompts import WorkerPrompts # The entry point's name as the worker, the judge and the human read it. -DRIVER = "do-epic" +DRIVER = DO_EPIC def shipping(config: ProjectConfig) -> str: diff --git a/bin/do_epic/e2e/sandbox.py b/bin/do_epic/e2e/sandbox.py index 8a085b94..a227364c 100644 --- a/bin/do_epic/e2e/sandbox.py +++ b/bin/do_epic/e2e/sandbox.py @@ -6,7 +6,7 @@ from atlassian.client import basic_auth, Http, jira_json, ToAdf from failure import Failure from adf_codec.convert import markdown_to_adf from do_epic.e2e.settings import Sandbox -from plan_store.jira_epic import searched +from atlassian.jira import searched EPIC_TYPE = "Epic" # How a team-managed project's workflow moves an issue to done, as do-epic's `jira-finish-transition` and `jira-finish-status` name it. diff --git a/bin/do_epic/gates.py b/bin/do_epic/gates.py index eed6ae4a..c73839e2 100644 --- a/bin/do_epic/gates.py +++ b/bin/do_epic/gates.py @@ -2,22 +2,17 @@ A gate is something only time or a person passes: checks that still run, an approval a reviewer has yet to give, or the new review of a reviewer whose requested changes the worker answered. While a chunk's pull request waits on one, its worker doesn't have anything to do, so do-epic parks the chunk (`parked`). Anything else is news the worker acts on.""" import dataclasses -import json import typing +from forge.reviews import ANSWERED, review_decision, waiting_threads from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks from failure import Failure -from forge.commands import forge_of, gitea, Run -from chunk_pr.approval import waiting_threads +from forge.commands import forge_of, Run # What a pull request waits on, as the words after "awaits". CHECKS = "its checks" APPROVAL = "an approval" NEW_REVIEW = "a new review" -# What `review_decision` returns in place of GitHub's `CHANGES_REQUESTED` once the worker answered those changes: GitHub keeps its decision until the reviewer reviews again. -ANSWERED = "CHANGES_ANSWERED" -# What the title of a draft opens with on Gitea, in any case: Gitea's default `WORK_IN_PROGRESS_PREFIXES`. -GITEA_DRAFT = ("WIP:", "[WIP]") @dataclasses.dataclass(frozen=True) @@ -41,7 +36,7 @@ class Open: def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate | Open | Failure: """What the chunk on branch waits on, in a worktree of checkout; at gives the runner of commands in a folder. A Failure where git or the forge cannot be read, which doesn't say anything about the gate. - A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). Changes a reviewer requested are news until the worker answered them (`answered`); from then on the pull request awaits a new review. + A draft never waits on a gate: its worker still works on it. On Gitea only the checks are a gate, since chunk-pr reads approvals on GitHub only (`chunk_pr.approval.awaited`). Changes a reviewer requested are news until the worker answered them (`forge.reviews.answered`); from then on the pull request awaits a new review. """ worktree = worktree_of(branch, at(checkout)) if not isinstance(worktree, str): @@ -56,7 +51,7 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate | pull = open_pull(forge, branch, head, run) if not isinstance(pull, str): return pull or Open(f"no pull request from origin's {branch} is open at {head[:12]}; it may be merged or closed already") - decision = review_decision(pull, head, run) if forge == "gh" else gitea_decision(pull, run) + decision = review_decision(forge, pull, head, run) if not isinstance(decision, str): return decision or Open(f"pull request #{pull} is a draft") required = required_checks(forge, base.removeprefix("origin/"), run) @@ -89,43 +84,3 @@ def worktree_of(branch: str, run: Run) -> str | None | Failure: if f"branch refs/heads/{branch}" in lines and lines[0].startswith("worktree "): return lines[0].removeprefix("worktree ") return None - - -def review_decision(pull: str, head: str, run: Run) -> str | None | Failure: - """GitHub's review decision on the pull request, whose head commit is head, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. ANSWERED in place of `CHANGES_REQUESTED` once the worker answered those changes. None where it is a draft.""" - viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"]) - if isinstance(viewed, Failure): - return viewed - try: - parsed = json.loads(viewed) - if parsed["isDraft"]: - return None - decision = str(parsed["reviewDecision"] or "") - return ANSWERED if decision == "CHANGES_REQUESTED" and answered(parsed, head) else decision - except (ValueError, KeyError, TypeError): - return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}") - - -def answered(pull: dict[str, typing.Any], head: str) -> bool: - """Whether the worker answered the newest review that requested changes on pull, as `gh pr view --json author,reviews,comments` prints it, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. GitHub lists a reply in a thread as a review of its own. False where it lists no review that requested changes. Raises KeyError or TypeError where pull has another shape. - - The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed. - """ - asked = max((review for review in pull["reviews"] if review["state"] == "CHANGES_REQUESTED"), key=lambda review: review["submittedAt"], default=None) - if asked is None: - return False - author = pull["author"]["login"] - # A review the author has yet to submit has no time, and answers nobody. - said = [review["submittedAt"] or "" for review in pull["reviews"] if review["author"]["login"] == author] + [comment["createdAt"] for comment in pull["comments"] if comment["author"]["login"] == author] - return asked["commit"]["oid"] != head or any(at > asked["submittedAt"] for at in said) - - -def gitea_decision(pull: str, run: Run) -> str | None | Failure: - """What stands in for `review_decision` on Gitea, read once: empty, since no review is a gate there, and None where the pull request is a draft, which Gitea tells by its title (GITEA_DRAFT).""" - viewed = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull}") - if isinstance(viewed, Failure): - return viewed - try: - return None if viewed["title"].upper().startswith(GITEA_DRAFT) else "" - except (KeyError, TypeError, AttributeError): - return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}") diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 9e4d5fde..6c79cc70 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -8,12 +8,13 @@ import pathlib import sys import typing -from loop_claude.loop.chunk_start import archived_route, routed +from chunk_driver.cycle_start import announced_route, cycle_of, project_routing, routing_on +from chunk_driver.claims import CHUNK_FLAG from do_epic import chunk_prompt, findings, finish, gates, human_tasks, parked, planning, scheduler, split, status +from chunk_driver.chunk_run import ChunkRun, closed_cycle from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo -from loop_claude.loop.close import closed_cycle from project_config.main import located as config_located -from loop_claude.project.records import CONSEQUENCE, read_records +from chunk_driver.project.records import CONSEQUENCE, read_records from agent_cycle.run import Cycle, run_cycle from do_epic.config import DoEpicConfig, load from loop_effects.effects import Effects, say @@ -23,21 +24,17 @@ from do_epic.backend.protocol import EpicIssue, EpicStore from do_epic.epic_record import EpicRecord from failure import Failure from agent_cycle.verdicts import Finished, TakenIn -from loop_claude.project.model_choice import get_or_ask_models, Models -from plan_store.jira_epic import ISSUE_KEY +from atlassian.jira import ISSUE_KEY from do_epic.backend.jira import JiraEpic -from agent_cycle.routing import judge_rung from claude_code.reply import Limited from do_epic.repos import locate -from loop_claude.loop.this_loop import Loop -from loop_claude.loop.reload import LoopRun +from chunk_driver.this_loop import Loop +from chunk_driver.project.model_choice import Models from loop_state.paths import Paths -from transcript_archive.project_key import project_key -from model_routing.ladder_file import project_ladder_file, read_ladder, SHIPPED -from loop_claude.project.premises import read_premises +from chunk_driver.project.premises import read_premises from forge.commands import Run, runner from claude_code.session import session_named -from loop_claude.loop.main import setup_version +from model_routing.ladder_file import SHIPPED from agent_cycle.stop import Stop from agent_cycle.direct_message import tell from agent_cycle import tmux @@ -110,13 +107,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: if stop.reason: say(stop.reason, effects, stdout=not stop.code) # A chunk's stop is DMed, as loop-claude's is, so a chunk left overnight never ends unseen. - if stop.reason and argv[:1] == [scheduler.CHUNK_FLAG]: + if stop.reason and argv[:1] == [CHUNK_FLAG]: tell(f"do-epic {' '.join(argv)} stopped: {stop.reason}", effects) return stop.code def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend, stdin: typing.TextIO, forge_at: typing.Callable[[str], Run]) -> Stop: - chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == scheduler.CHUNK_FLAG else (None, argv) + chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == CHUNK_FLAG else (None, argv) status_asked = chunk is None and words[1:] == [STATUS_FLAG] words = words[:1] if status_asked else words # What the words after the epic's key write into the epic, where they are a filing or a decision. @@ -242,7 +239,7 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: """Runs the cycles of the chunk of the issue called key until one stops the loop, or the judge rules the chunk finished. For a human's task it runs no cycle: it waits until the task no longer holds up an issue (`human_tasks.awaited`), then starts the next chunks. A chunk in a repo parks after each cycle that leaves its pull request waiting on a gate, and before its first where it was parked when its window last ended, as at a reboot.""" pane = epic.env.get("TMUX_PANE") if not pane: - return Stop(1, f"{scheduler.CHUNK_FLAG} is how do-epic starts itself in a tmux window; run do-epic ") + return Stop(1, f"{CHUNK_FLAG} is how do-epic starts itself in a tmux window; run do-epic ") # None for the epic's finishing, which is no issue. issue = None if key == epic.key else issue_read(key, epic) if isinstance(issue, Stop): @@ -256,24 +253,24 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: root, repo = place session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts) loop = Loop(root=root, session=session, window=tmux.Window(epic.session, key, pane), paths=epic.paths, env=epic.env, launcher=epic.launcher, effects=epic.effects) - loop_run = LoopRun(0, root, "", "", chunk=key) + run = ChunkRun() # What a chunk that was parked is told as it resumes; empty for a chunk that wasn't. news = parked_through(repo, loop, epic, starts=True) if repo is not None else "" while True: if isinstance(news, Stop): return news - loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1) - cycle = next_cycle(loop_run, loop, repo is not None, epic, news) + run = dataclasses.replace(run, cycle_number=run.cycle_number + 1) + cycle = next_cycle(run, loop, repo is not None, epic, news) if isinstance(cycle, Stop): return cycle - loop_run = dataclasses.replace(loop_run, task=cycle.task) + run = dataclasses.replace(run, task=cycle.task) concluded = run_cycle(cycle) if isinstance(concluded, Stop): return concluded - closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, chunk_prompt.DRIVER, loop) + closed = closed_cycle(run, cycle.project, concluded, cycle.project_archive, chunk_prompt.DRIVER, loop) if isinstance(closed, Stop): return closed - loop_run = closed + run = closed news = parked_through(repo, loop, epic, starts=False) if repo is not None else "" # A chunk that was parked has work again, whatever the judge ruled before its pull request passed the gate. if isinstance(concluded.verdict, Finished) and news == "": @@ -399,8 +396,8 @@ def split_items_closed(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue return issues -def next_cycle(loop_run: LoopRun, loop: Loop, in_repo: bool, epic: EpicRun, news: str = "") -> Cycle | Stop: - """The cycle loop_run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder.""" +def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: str = "") -> Cycle | Stop: + """The cycle run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder.""" premises = premises_read(loop.root if in_repo else None, epic) if isinstance(premises, Failure): return Stop(1, premises.reason) @@ -413,21 +410,14 @@ def next_cycle(loop_run: LoopRun, loop: Loop, in_repo: bool, epic: EpicRun, news work = chunk_work(loop.window.name, loop.root if in_repo else None, language or epic.config.language, epic) if isinstance(work, Stop): return work - task, routing = work - models = get_or_ask_models(project_key(loop.root, epic.paths.home), epic.paths, epic.env, chunk_prompt.DRIVER, epic.effects) if in_repo else repoless_models(epic) - if isinstance(models, Stop): - return models - ladder_file = project_ladder_file(loop.root, epic.paths.home) if in_repo else SHIPPED - if isinstance(ladder_file, Failure): - return Stop(1, ladder_file.reason) - ladder = read_ladder(ladder_file) - if isinstance(ladder, Failure): - return Stop(1, ladder.reason) + task, issue = work + routing = project_routing(loop, chunk_prompt.DRIVER) if in_repo else routing_on(repoless_models(epic), SHIPPED) + if isinstance(routing, Stop): + return routing archive_folder = epic.paths.home / ARCHIVE / epic.key - project = ladder.project_rung(models.worker) - route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: routing) - say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", epic.effects, stdout=True) - return Cycle(config=setup_version(epic.paths.claude_dir, epic.effects.git), effects=epic.effects, facts="", judge=judge_rung(ladder, models.judge), premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=task, prompts=chunk_prompt.unparked(news) if news else chunk_prompt.restating(task) if loop_run.chunk == epic.key else chunk_prompt.WORKER, taken_in=lambda entries: TakenIn(), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window) + route = announced_route(run.cycle_number, run.route, routing, archive_folder, lambda: issue, loop) + prompts = chunk_prompt.unparked(news) if news else chunk_prompt.restating(task) if loop.window.name == epic.key else chunk_prompt.WORKER + return cycle_of(loop, routing, route, archive_folder, task=task, facts="", premises=premises, records=records, unfinished_evidence=run.unfinished_evidence, prompts=prompts, taken_in=lambda entries: TakenIn()) def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> tuple[str, RoutingIssue | None] | Stop: diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index a8a42647..59b5d126 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -1,12 +1,12 @@ """Which of an epic's issues run as chunks now, each in its own window of the epic's tmux session (docs/decisions.md → `do-epic: drives one Jira epic …`). -Three limits hold a chunk back: the epic's cap of chunks at once, its repo's `parallel-chunks`, counted across every epic, and a loop-claude that runs chunks in its repo. A parked chunk (`parked`) counts toward none of them: its window only polls the forge, and `resume` gives it a running slot under the same limits once its worker has something to do. do-epic checks a repo and starts a chunk in it while holding the lock loop-claude holds when it starts one (`chunk_windows.starting`), so the two never start chunks in one checkout together.""" +Three limits hold a chunk back: the epic's cap of chunks at once, its repo's `parallel-chunks`, counted across every epic, and a loop-claude that runs chunks in its repo. A parked chunk (`parked`) counts toward none of them: its window only polls the forge, and `resume` gives it a running slot under the same limits once its worker has something to do. do-epic checks a repo and starts a chunk in it while holding the lock loop-claude holds when it starts one (`chunk_driver.claims.starting`), so the two never start chunks in one checkout together.""" import dataclasses import pathlib import typing from do_epic.epic_record import CAP -from loop_claude.loop.chunk_windows import epic_chunks, HANDED, LOCK, project_lock, starting +from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, LOCK, project_lock, starting from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.repo_pick import HumanTask, recorded, Repo @@ -21,8 +21,6 @@ from agent_cycle import tmux STATE = ".local/state/do-epic" # Why a human's task with a live window waits, as the epic's status says. HUMAN_WAIT = "it is a human's task; do-epic polls Jira until you close it" -# The flag that tells the do-epic in a window its chunk, as `--chunk ABC-34 ABC-12`. Nobody types it, so no panel picked it. -CHUNK_FLAG = "--chunk" @dataclasses.dataclass(frozen=True) diff --git a/bin/do_epic/test_findings.py b/bin/do_epic/test_findings.py index d6f97782..f140dc68 100644 --- a/bin/do_epic/test_findings.py +++ b/bin/do_epic/test_findings.py @@ -10,7 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic.test_main import DESCRIPTION, DoEpicTest from do_epic.epic_record import EpicRecord from failure import Failure -from loop_claude.test_loop_claude import FakeEffects +from loop_effects.test_doubles import FakeEffects from record_store.held import Held from do_epic import main from do_epic.backend.fake import MemoryEpic diff --git a/bin/do_epic/test_finish.py b/bin/do_epic/test_finish.py index 4241d546..8365bd31 100644 --- a/bin/do_epic/test_finish.py +++ b/bin/do_epic/test_finish.py @@ -9,7 +9,7 @@ from do_epic.test_main import Description, DESCRIPTION, DoEpicTest, MODELS, UNRE from do_epic.config import DoEpicConfig, load from do_epic.epic_record import EpicRecord from failure import Failure -from loop_claude.test_loop_claude import FakeEffects, judged, Worker +from loop_effects.test_doubles import FakeEffects, judged, Worker from do_epic import findings, finish, main, scheduler from project_config.settings import Finish from do_epic.test_scheduler import issue diff --git a/bin/do_epic/test_human_tasks.py b/bin/do_epic/test_human_tasks.py index 2c251797..5fc9593b 100644 --- a/bin/do_epic/test_human_tasks.py +++ b/bin/do_epic/test_human_tasks.py @@ -10,7 +10,7 @@ from project_config.test_project_config import configured from do_epic.test_main import DESCRIPTION, Description, DoEpicTest, MODELS, UNREAD from do_epic.epic_record import EpicRecord from failure import Failure -from loop_claude.test_loop_claude import FakeEffects +from loop_effects.test_doubles import FakeEffects from do_epic.scheduler import HUMAN_WAIT from do_epic.test_scheduler import issue from do_epic.backend.fake import MemoryEpic diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 43abd1ec..d94de101 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -12,6 +12,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic import chunk_prompt, main +from chunk_driver.chunk_run import ChunkRun from project_config.test_project_config import configured from do_epic.config import DoEpicConfig from project_config.settings import Epic, Finish @@ -19,11 +20,10 @@ from do_epic.backend.protocol import EpicIssue from do_epic.epic_record import EpicRecord from agent_cycle import escalation_mark, judge, tmux from failure import Failure -from loop_claude.test_loop_claude import FakeEffects, judged, Worker +from loop_effects.test_doubles import FakeEffects, judged, Worker from do_epic.test_gates import Forge from do_epic.test_scheduler import issue -from loop_claude.loop.this_loop import Loop -from loop_claude.loop.reload import LoopRun +from chunk_driver.this_loop import Loop from do_epic.backend.fake import MemoryEpic from do_epic import parked from loop_state.paths import paths_from @@ -189,7 +189,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest): root, repo = place loop = Loop(root=root, session=main.session_named("A ABC-12 do-epic ABC-21", paths.claude_code_transcripts), window=tmux.Window("epic-ABC-12", "ABC-21", "%1"), paths=paths, env=env or {}, launcher=pathlib.Path("/b/do-epic"), effects=fake.effects()) with contextlib.redirect_stdout(io.StringIO()): - found = main.next_cycle(LoopRun(1, root, "", "", chunk="ABC-21"), loop, repo is not None, epic) + found = main.next_cycle(ChunkRun(1), loop, repo is not None, epic) assert isinstance(found, main.Cycle), found return found diff --git a/bin/do_epic/test_planning.py b/bin/do_epic/test_planning.py index 5feb2f80..892f7730 100644 --- a/bin/do_epic/test_planning.py +++ b/bin/do_epic/test_planning.py @@ -14,7 +14,7 @@ from do_epic.test_main import Description, DoEpicTest, structured as says from do_epic.backend.protocol import EpicIssue from do_epic.epic_record import EpicRecord from failure import Failure -from loop_claude.test_loop_claude import FakeEffects +from loop_effects.test_doubles import FakeEffects from do_epic.test_scheduler import issue from claude_code.reply import Limited from do_epic.config import load diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index 2d34d90f..34d8424e 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -6,13 +6,14 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from do_epic.scheduler import Chunk, CHUNK_FLAG, chunks, Epic, HUMAN_WAIT, refusal, RepoRoom, resume, start_chunks, Started, Waits +from do_epic.scheduler import Chunk, chunks, Epic, HUMAN_WAIT, refusal, RepoRoom, resume, start_chunks, Started, Waits +from chunk_driver.claims import CHUNK_FLAG from do_epic import chunk_prompt from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.parked import file_of, park, Parked from do_epic.epic_record import parallel_chunks_in -from loop_claude.cycle import prompts +from chunk_driver import prompts from model_routing.route import Route from model_routing.ladder import Rung from project_config import settings diff --git a/bin/forge/reviews.py b/bin/forge/reviews.py new file mode 100644 index 00000000..69f26ba9 --- /dev/null +++ b/bin/forge/reviews.py @@ -0,0 +1,86 @@ +"""A pull request's review state, read once from its forge: the review decision, whether it is a draft, whether the worker answered the changes a reviewer requested, and the review threads that wait for an answer. chunk-pr and do-epic decide on what this reads, and run no review query of their own.""" +import json +import typing + +from failure import Failure +from forge.commands import Forge, gitea, Run + +# What `review_decision` returns in place of GitHub's `CHANGES_REQUESTED` once the worker answered those changes: GitHub keeps its decision until the reviewer reviews again. +ANSWERED = "CHANGES_ANSWERED" +# What the title of a draft opens with on Gitea, in any case: Gitea's default `WORK_IN_PROGRESS_PREFIXES`. +GITEA_DRAFT = ("WIP:", "[WIP]") +# Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout. +THREADS = """query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { + author { login } + reviewThreads(first: 100) { nodes { isResolved path comments(last: 1) { nodes { author { login } } } } } +} } }""" + + +def review_decision(forge: Forge, pull: str, head: str, run: Run) -> str | None | Failure: + """The review decision on the pull request, whose head commit is head: `answered_decision` on GitHub, `gitea_decision` on Gitea. None where it is a draft.""" + return answered_decision(pull, head, run) if forge == "gh" else gitea_decision(pull, run) + + +def github_decision(pull: str, run: Run) -> str | Failure: + """GitHub's review decision on the pull request as it stands, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review.""" + viewed = run(["gh", "pr", "view", pull, "--json", "reviewDecision"]) + if isinstance(viewed, Failure): + return viewed + try: + decision: str = json.loads(viewed)["reviewDecision"] or "" + return decision + except (ValueError, KeyError, TypeError): + return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}") + + +def answered_decision(pull: str, head: str, run: Run) -> str | None | Failure: + """GitHub's review decision on the pull request, whose head commit is head, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. ANSWERED in place of `CHANGES_REQUESTED` once the worker answered those changes. None where it is a draft.""" + viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"]) + if isinstance(viewed, Failure): + return viewed + try: + parsed = json.loads(viewed) + if parsed["isDraft"]: + return None + decision = str(parsed["reviewDecision"] or "") + return ANSWERED if decision == "CHANGES_REQUESTED" and answered(parsed, head) else decision + except (ValueError, KeyError, TypeError): + return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}") + + +def answered(pull: dict[str, typing.Any], head: str) -> bool: + """Whether the worker answered the newest review that requested changes on pull, as `gh pr view --json author,reviews,comments` prints it, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. GitHub lists a reply in a thread as a review of its own. False where it lists no review that requested changes. Raises KeyError or TypeError where pull has another shape. + + The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed. + """ + asked = max((review for review in pull["reviews"] if review["state"] == "CHANGES_REQUESTED"), key=lambda review: review["submittedAt"], default=None) + if asked is None: + return False + author = pull["author"]["login"] + # A review the author has yet to submit has no time, and answers nobody. + said = [review["submittedAt"] or "" for review in pull["reviews"] if review["author"]["login"] == author] + [comment["createdAt"] for comment in pull["comments"] if comment["author"]["login"] == author] + return asked["commit"]["oid"] != head or any(at > asked["submittedAt"] for at in said) + + +def gitea_decision(pull: str, run: Run) -> str | None | Failure: + """What stands in for `answered_decision` on Gitea, read once: empty, since no review is a gate there, and None where the pull request is a draft, which Gitea tells by its title (GITEA_DRAFT).""" + viewed = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull}") + if isinstance(viewed, Failure): + return viewed + try: + return None if viewed["title"].upper().startswith(GITEA_DRAFT) else "" + except (KeyError, TypeError, AttributeError): + return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}") + + +def waiting_threads(number: str, run: Run) -> list[str] | Failure: + """The files where a reviewer's comment waits for an answer on pull request number, read once: those of each review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again.""" + read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) + if isinstance(read, Failure): + return read + try: + pull = json.loads(read)["data"]["repository"]["pullRequest"] + author = pull["author"]["login"] + return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) + except (ValueError, KeyError, TypeError): + return Failure(f"gh api graphql printed no review threads: {read.strip()[:200]}") diff --git a/bin/judge_replay/archived_prompt.py b/bin/judge_replay/archived_prompt.py index bbe9a993..6468f8dc 100644 --- a/bin/judge_replay/archived_prompt.py +++ b/bin/judge_replay/archived_prompt.py @@ -1,17 +1,18 @@ -from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, DRIVER +from chunk_driver.prompts import ANSWER_DESTINATIONS from claude_code.entries import Entry from agent_cycle import escalation_mark from failure import Failure from agent_cycle.judge import Grounds, judge_rules, TASK_HEADING, transcript_heading from claude_code.transcript import human_answers +from chunk_driver.drivers import LOOP_CLAUDE from agent_cycle.worker_prompts import typed_answer def grounds_of(prompt: str, entries: list[Entry]) -> Grounds | Failure: """What the quotes of a judge run on prompt are checked against, as judge_prompt would have made it for the transcript's entries: the premises and the records before the task are quotable, the transcript the judge was shown comes before the rules. The prompt is split on the headings judge_prompt writes, at the first of each; a Failure where it lacks one. Rules of an earlier wording stay part of the transcript, a slack that lets an evidence quote them pass.""" before_task, task_heading, after_task = prompt.partition(f"\n\n{TASK_HEADING}") - heading = transcript_heading(DRIVER) + heading = transcript_heading(LOOP_CLAUDE) _, found_heading, shown = after_task.partition(heading) if not (task_heading and found_heading): return Failure(f"the archived prompt lacks the heading {TASK_HEADING.strip()!r} or {heading.strip()!r}, which judge_prompt writes") - return Grounds(shown.removesuffix(f"\n\n{judge_rules(ANSWER_DESTINATIONS, DRIVER)}"), escalation_mark.after_mark(entries, 0), before_task, tuple(human_answers(entries, typed_answer))) + return Grounds(shown.removesuffix(f"\n\n{judge_rules(ANSWER_DESTINATIONS, LOOP_CLAUDE)}"), escalation_mark.after_mark(entries, 0), before_task, tuple(human_answers(entries, typed_answer))) diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index a9046b16..42bd0a79 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -53,7 +53,7 @@ import pathlib import sys import typing -from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, DRIVER +from chunk_driver.prompts import ANSWER_DESTINATIONS from transcript_archive.location import archive_root, transcript_of from transcript_archive.read import archived_outcomes from rung_replay.archive import archiving, print_report, replay_folder @@ -69,9 +69,10 @@ from judge_replay.archived_prompt import grounds_of from transcript_archive.judge_run import JudgeRun from model_routing.ladder import Ladder, ProjectRung, REVIEW_STEPS, Rung from claude_code.reply import Limited +from chunk_driver.drivers import LOOP_CLAUDE from model_routing.ladder_file import read_ladder, SHIPPED -from loop_claude.project.premises import read_premises -from loop_claude.project.records import read_records, RECORDS_NAMED +from chunk_driver.project.premises import read_premises +from chunk_driver.project.records import read_records, RECORDS_NAMED from claude_code.transcript import read_transcript from agent_cycle.verdicts import Verdict @@ -164,7 +165,7 @@ def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind | grounds = grounds_of(kept.prompt, entries) if isinstance(grounds, Failure): return verdict_kind(grounds) - verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, DRIVER, effects)) + verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, LOOP_CLAUDE, effects)) return verdict if isinstance(verdict, Limited) else verdict_kind(verdict) premises, records = read_premises(case.root, home), read_records(case.root, home, home / ".claude") if isinstance(premises, Failure): @@ -172,5 +173,5 @@ def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind | if isinstance(records, Failure): return verdict_kind(records) # 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count. - verdict = first_reply(lambda: judge_once(case.root, Brief(task=case.task, premises=premises, records=records, records_named=RECORDS_NAMED, answer_destinations=ANSWER_DESTINATIONS, entries=entries, escalated_at=0, driver=DRIVER), rung, effects)) + verdict = first_reply(lambda: judge_once(case.root, Brief(task=case.task, premises=premises, records=records, records_named=RECORDS_NAMED, answer_destinations=ANSWER_DESTINATIONS, entries=entries, escalated_at=0, driver=LOOP_CLAUDE), rung, effects)) return verdict if isinstance(verdict, Limited) else verdict_kind(verdict) diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 0cfa7f3a..b39308f0 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -9,7 +9,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, DRIVER +from chunk_driver.prompts import ANSWER_DESTINATIONS from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED from claude_code.entries import AssistantTurn, HumanTurn, LoopPrompt, Text from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind @@ -20,6 +20,7 @@ from failure import Failure from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished from judge_replay.archived_prompt import grounds_of from agent_cycle.judge import judge_archived, judge_rules, Rejected, TASK_HEADING, transcript_heading +from chunk_driver.drivers import LOOP_CLAUDE from judge_replay import main from rung_replay.search import Miss, Replay, Tried from model_routing.ladder import Rung @@ -330,7 +331,7 @@ class Main(unittest.TestCase): class JudgeArchivedRuns(unittest.TestCase): """judge_archived on a prompt as judge_prompt writes it: the premises, the task, the transcript the judge was shown, and the rules.""" - PROMPT = f"HEAD: Ship fast.\n\n{TASK_HEADING}Do it.\n\n{transcript_heading(DRIVER)}Worker chose option B.\n[human] Use Postgres.\n\n{judge_rules(ANSWER_DESTINATIONS, DRIVER)}" + PROMPT = f"HEAD: Ship fast.\n\n{TASK_HEADING}Do it.\n\n{transcript_heading(LOOP_CLAUDE)}Worker chose option B.\n[human] Use Postgres.\n\n{judge_rules(ANSWER_DESTINATIONS, LOOP_CLAUDE)}" ENTRIES = [AssistantTurn(parts=(Text("Worker chose option B."),)), HumanTurn(text="Use Postgres."), LoopPrompt(text="Keep going.")] def judged(self, prompt=PROMPT, **fields): @@ -344,7 +345,7 @@ class JudgeArchivedRuns(unittest.TestCase): effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) grounds = grounds_of(prompt, self.ENTRIES) - return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, DRIVER, effects)), cwds + return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, LOOP_CLAUDE, effects)), cwds def test_runs_in_the_projects_folder_and_stamps_the_verdict_with_the_entries_read(self): verdict, cwds = self.judged() @@ -363,11 +364,11 @@ class JudgeArchivedRuns(unittest.TestCase): self.assertEqual((type(rejected), rejected.cost), (Rejected, 0.25)) def test_checks_neither_the_task_nor_the_rules_as_the_transcript_or_the_premises(self): - self.assertIsInstance(self.judged(evidence=judge_rules(ANSWER_DESTINATIONS, DRIVER))[0], Rejected) + self.assertIsInstance(self.judged(evidence=judge_rules(ANSWER_DESTINATIONS, LOOP_CLAUDE))[0], Rejected) self.assertIsInstance(self.judged(answer="Do it.", question="Which?")[0], Interrupt) def test_splits_the_prompt_at_the_first_transcript_heading(self): - quoting = self.PROMPT.replace("Worker chose", f"Quoted: {transcript_heading(DRIVER)}Worker chose", 1) + quoting = self.PROMPT.replace("Worker chose", f"Quoted: {transcript_heading(LOOP_CLAUDE)}Worker chose", 1) self.assertIsInstance(self.judged(quoting, evidence="Quoted:")[0], Unfinished) def test_splits_the_prompt_at_the_first_task_heading(self): diff --git a/bin/loop_claude/__init__.py b/bin/loop_claude/__init__.py index 64f69ecb..2ddfc24e 100644 --- a/bin/loop_claude/__init__.py +++ b/bin/loop_claude/__init__.py @@ -1,4 +1,4 @@ """loop-claude: headless claude cycles, judged, that interrupt the human only for a decision that is theirs (loop/usage.py's help). -Its packages hold one concern each: cycle/ words the worker's prompts and reads the items it names, loop/ runs the cycles, and project/ reads a checkout's files. loop-claude's paths live in bin/loop_state/, and its effects in bin/loop_effects/. The cycle itself, its judge, interrupts and routing live in bin/agent_cycle/, which doesn't import this package, so that a second entry point can drive it. routed_item.py, at this level, reads the plan for the item a chunk starts on. +Its packages hold one concern each: chunk/ words a fresh chunk's first prompt and reads the items a worker names, and loop/ runs the cycles. What it shares with do-epic lives in bin/chunk_driver/. loop-claude's paths live in bin/loop_state/, and its effects in bin/loop_effects/. The cycle itself, its judge, interrupts and routing live in bin/agent_cycle/, which doesn't import this package, so that a second entry point can drive it. routed_item.py, at this level, reads the plan for the item a chunk starts on. """ diff --git a/bin/loop_claude/project/__init__.py b/bin/loop_claude/chunk/__init__.py similarity index 100% rename from bin/loop_claude/project/__init__.py rename to bin/loop_claude/chunk/__init__.py diff --git a/bin/loop_claude/cycle/chunk_items.py b/bin/loop_claude/chunk/chunk_items.py similarity index 96% rename from bin/loop_claude/cycle/chunk_items.py rename to bin/loop_claude/chunk/chunk_items.py index 78e74179..eb7520aa 100644 --- a/bin/loop_claude/cycle/chunk_items.py +++ b/bin/loop_claude/chunk/chunk_items.py @@ -7,7 +7,7 @@ from agent_cycle.quotes import plain from plan_store.plans import Plan from agent_cycle.verdicts import TakenIn -# The label opening the line; prompts.NAME_THE_ITEMS asks the worker for it. +# The label opening the line; fresh_prompt.NAME_THE_ITEMS asks the worker for it. CHUNK_ITEMS = "Chunk items:" # A line the worker opens with the label, after any `-` or `>` marker or a backtick; what follows names the items. LINE = re.compile(rf"[\s>`-]*{re.escape(CHUNK_ITEMS)}(.*)") diff --git a/bin/loop_claude/chunk/fresh_prompt.py b/bin/loop_claude/chunk/fresh_prompt.py new file mode 100644 index 00000000..86cf2028 --- /dev/null +++ b/bin/loop_claude/chunk/fresh_prompt.py @@ -0,0 +1,52 @@ +"""What loop-claude alone says to its worker: the first prompt of a chunk, with what chunk-preflight found. The resumed prompt and the rung sentences are chunk_driver.prompts', which do-epic's cycles use too.""" +import functools + +from loop_claude.chunk.chunk_items import CHUNK_ITEMS +from chunk_driver.drivers import LOOP_CLAUDE +from model_routing.ladder import ProjectRung +from chunk_driver.prompts import READING_RULE, rung_sentences, worker_prompts +from model_routing.route import Route + +# loop-claude's name as its workers, its judge and the human read it. A function below that takes a driver words a sentence for any entry point, such as do-epic. +DRIVER = LOOP_CLAUDE +# chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`). +NAME_THE_ITEMS = f"Name every plan item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes." + +AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' + + +def fresh(driver: str, task: str, premises: str, route: Route, project: ProjectRung | None, facts: str) -> str: + """A chunk's first prompt; facts is preflight_facts' or preflight_failed's text.""" + routed = f"{routed_by(driver, route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(driver, route, project)) + opening = f"{routed}\n\n" if routed else "" + return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's plan items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}" + + +def routed_by(driver: str, route: Route, project: ProjectRung | None) -> str: + return " ".join(( + f"{driver} runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.", + *rung_sentences(driver, route, project), + )) + + +def recount(route: Route) -> str: + """Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code.""" + return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores plan items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1." + + +def preflight_facts(printed: str) -> str: + """What chunk-preflight printed, for the worker to take as found.""" + return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}" + + +def held_by_others(items: list[int]) -> str: + """Keeps a fresh worker off the plan items the project's other chunks hold, running or stopped.""" + return f"\n\nOther chunks of this project, running or stopped, hold {'items ' if len(items) > 1 else 'item '}{', '.join(map(str, items))}. Leave those items out of this chunk, even where the facts above list them as items that may join it." + + +def preflight_failed(reason: str) -> str: + """Has the worker find the facts chunk-preflight would have, its worktree among them.""" + return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}" + + +WORKER = worker_prompts(DRIVER, functools.partial(fresh, DRIVER), NAME_THE_ITEMS) diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/loop/checkout.py similarity index 100% rename from bin/loop_claude/project/checkout.py rename to bin/loop_claude/loop/checkout.py diff --git a/bin/loop_claude/loop/chunk_start.py b/bin/loop_claude/loop/chunk_start.py index 5a34cab3..0a653980 100644 --- a/bin/loop_claude/loop/chunk_start.py +++ b/bin/loop_claude/loop/chunk_start.py @@ -1,24 +1,18 @@ """How a cycle starts: the route it runs on, from the archive or the plan, and the facts chunk-preflight finds for a fresh chunk.""" -import pathlib -import typing from git_cli.git_repo import default_ref from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELEASES from loop_effects.effects import Effects, say from failure import Failure -from agent_cycle.routing import first_route, kept, Scored +from loop_claude.chunk import fresh_prompt from loop_claude.loop.chunk_windows import held_beside, item_of from chunk_preflight.main import ITEM from plan.todo_table import Item -from transcript_archive.read import latest_worker from project_config.main import located -from loop_claude.loop.this_loop import Loop +from chunk_driver.this_loop import Loop from plan_store.plans import Plan -from model_routing.ladder import ProjectRung, Rung -from loop_claude.cycle import prompts -from model_routing.route import Route, route_from from loop_claude.routed_item import routed_item -from claude_code.session import session_open, transcript_file +from claude_code.session import session_open # Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung. ORIGIN_TIMEOUT = 60 @@ -32,30 +26,6 @@ def scored_plan(default: DefaultPlan | Failure, effects: Effects) -> Plan | Fail return plan -def routed(route: Route | None, project: ProjectRung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Scored | None]) -> Route: - """The route the cycle runs on. project is the project's rung, and model the project's model. - - Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh. - """ - if project is None: - return Route(Rung(model)) - route = route or archived() - return route if route and kept(route, project) else first_route(project, item()) - - -def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None: - """The route named by the latest verdict archived for the loop's open chunk; None for a chunk not yet judged.""" - transcript = transcript_file(loop.session) - worker = latest_worker(archive_folder, transcript) if transcript else None - if isinstance(worker, Failure): - say(f"routing the chunk afresh: {worker.reason}", loop.effects) - return None - route = route_from(worker) if worker else None - if worker and route is None: - say(f"routing the chunk afresh: the archive's latest Worker: line names no route that can be read: {worker}", loop.effects) - return route - - def chunk_start(loop: Loop) -> tuple[str, DefaultPlan | Failure]: """The facts for a fresh worker's prompt, empty where the session is open, and what the default branch holds, read once for the cycle: it routes the chunk, through plan_item, and scores the items the worker names, through scored_plan. It reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last.""" fresh = not session_open(loop.session) @@ -66,9 +36,9 @@ def chunk_facts(loop: Loop) -> str: """What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run. The chunk of a window named for an item starts from that item, and either ends with the items the project's other chunks hold.""" item = item_of(loop.window.name) done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root) - facts = prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else prompts.preflight_facts(done.stdout.strip()) + facts = fresh_prompt.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else fresh_prompt.preflight_facts(done.stdout.strip()) held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects) - return facts + (prompts.held_by_others(held) if held else "") + return facts + (fresh_prompt.held_by_others(held) if held else "") def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure: diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index ba3e82ad..792853de 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -7,7 +7,8 @@ import re import typing from touch_predictions.beside import Beside, chunks_beside -from loop_claude.cycle import chunk_items +from chunk_driver.claims import CHUNK_FLAG, CLAIMS, epic_chunks, HANDED, LOCK, project_lock, starting +from loop_claude.chunk import chunk_items from git_cli.git_repo import default_ref from loop_effects.effects import Effects, say from failure import Failure @@ -22,18 +23,10 @@ from claude_code.transcript import read_transcript from claude_code.session import Session, session_named, transcript_file from agent_cycle import tmux -# Under the home folder, a folder per project key holds LOCK. -STATE = ".local/state/loop-claude" -# The file an entry point keeps locked with flock while it lists the windows of a project's chunks and starts new ones. Two loops whose chunks finish together then don't start a chunk twice, and do-epic, which holds the same lock, never starts a chunk in a checkout while loop-claude does. -LOCK = "starting" -# The flag that tells the loop in a window its chunk, as `--chunk item-372`. Nobody types it, so no panel picked it. -CHUNK_FLAG = "--chunk" # The chunk of a plan that names no item for the next chunk: a release to plan, a release review, or a task outside the plan. NO_ITEM = "no-item" # Seconds a fetch of origin may take before a chunk starts; past them, the plan reads as last fetched. FETCH_TIMEOUT = 60 -# The prefix of the variables loop-claude reads. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name. -HANDED = "LOOP_CLAUDE_" def window_name(item_id: int) -> str: @@ -51,25 +44,6 @@ def chunk_session(key: str, chunk: str, claude_code_transcripts: pathlib.Path) - return session_named(f"A {key} loop-claude {chunk}", claude_code_transcripts) -@contextlib.contextmanager -def starting(folder: pathlib.Path) -> typing.Iterator[None]: - """Holds the LOCK in folder: project_lock's for a project, or do-epic's for an epic. Raises OSError where the file cannot be opened or locked.""" - folder.mkdir(parents=True, exist_ok=True) - with open(folder / LOCK, "a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - yield - - -def project_lock(root: str, home: pathlib.Path) -> pathlib.Path: - """The folder of the LOCK that everything starting a chunk in the checkout root holds.""" - return home / STATE / project_key(root, home) - - -def epic_chunks(root: str, run: tmux.Tmux) -> list[tmux.Placed]: - """The windows of do-epic's sessions whose chunks run in the checkout root. A parked chunk doesn't run.""" - return [placed for placed in tmux.everywhere(run) if placed.session.startswith(f"{tmux.EPIC}-") and placed.root == root and not placed.window.dead and not placed.window.parked] - - def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]: """The plan items these chunks hold: the one each started from, and those its worker names on its latest `Chunk items:` line so far. A chunk whose transcript cannot be read holds the item it started from.""" held: set[int] = set() @@ -193,5 +167,5 @@ def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[i def wait_for_starts(home: pathlib.Path, key: str) -> 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(home / STATE / key): + with contextlib.suppress(OSError), starting(home / CLAIMS / key): pass diff --git a/bin/loop_claude/loop/close.py b/bin/loop_claude/loop/close.py deleted file mode 100644 index 41531c82..00000000 --- a/bin/loop_claude/loop/close.py +++ /dev/null @@ -1,47 +0,0 @@ -"""How a cycle closes: the loop run the next cycle starts from, the step-up an unfinished verdict makes archived, and the stop once a chunk has had UNFINISHED_LIMIT unfinished verdicts running.""" -import dataclasses -import pathlib - -from agent_cycle.run import archived_step, archived_stop, Concluded -from agent_cycle.verdicts import Finished -from loop_claude.loop.this_loop import Loop -from loop_claude.loop.reload import LoopRun -from agent_cycle.stop import needs_human, Stop -from agent_cycle.routing import next_route, step_up -from model_routing.ladder import ProjectRung -from claude_code.session import transcript_file - -# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts. -UNFINISHED_LIMIT = 6 - - -def closed_cycle(loop_run: LoopRun, project: ProjectRung | None, concluded: Concluded, archive_folder: pathlib.Path, driver: str, loop: Loop) -> LoopRun | Stop: - """The loop run after a cycle of driver, the entry point, concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running.""" - after = after_verdict(loop_run, project, concluded) - # A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts. - if after.route is None: - return after - # The unfinished verdict, archived as the cycle closed, names the route its cycle ended on; the step-up names the one the next cycle runs on. - path = transcript_file(loop.session) - if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), loop.effects)): - return Stop(1, failure.reason) - if limit := reached_limit(after, driver): - # Archived with the route the next cycle would run on, so a rerun resumes there. - return archived_stop(archive_folder, loop.session, after.task, after.route, limit, limit.reason, loop.effects) - return after - - -def reached_limit(loop_run: LoopRun, driver: str) -> Stop | None: - """The stop that needs the human once the loop run holds UNFINISHED_LIMIT unfinished verdicts running.""" - if loop_run.unfinished_run < UNFINISHED_LIMIT: - return None - return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun {driver} to give it {UNFINISHED_LIMIT} more cycles") - - -def after_verdict(loop_run: LoopRun, project: ProjectRung | None, concluded: Concluded) -> LoopRun: - """The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised, and the evidence the judge gave for the verdict; and counts the verdict.""" - verdict = concluded.verdict - if isinstance(verdict, Finished): - return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0) - route = next_route(project, concluded.route, verdict) - return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 090d6438..fed28a68 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -2,28 +2,27 @@ import dataclasses import pathlib import typing +from chunk_driver.cycle_start import announced_route, cycle_of, project_routing from transcript_archive.location import archive_root, project_archive -from loop_claude.loop.chunk_start import archived_route, chunk_start, plan_item, routed, scored_plan from loop_claude.loop.routing_check import check_routing -from loop_claude.project.checkout import checkout_root -from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, item_of, start_chunks -from loop_claude.cycle import chunk_items, prompts -from loop_claude.loop.close import closed_cycle +from loop_claude.loop.checkout import checkout_root +from chunk_driver.claims import CHUNK_FLAG +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 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 from agent_cycle.verdicts import Finished -from loop_claude.project.model_choice import get_or_ask_models -from git_cli.git_repo import Git from loop_claude.loop.usage import HELP -from agent_cycle.routing import judge_rung -from loop_claude.loop.this_loop import Loop +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_file import project_ladder_file, read_ladder, SHIPPED -from loop_claude.project.premises import read_premises -from loop_claude.project.records import read_records +from chunk_driver.project.premises import read_premises +from chunk_driver.project.records import read_records +from model_routing.ladder_file import SHIPPED from agent_cycle.stop import Stop from agent_cycle.direct_message import tell from agent_cycle import tmux @@ -50,7 +49,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if isinstance(loop_run, Stop): return loop_run # Before anything starts: a worktree, a claude session or a tmux window. - if reason := tmux.unusable(effects.tmux, prompts.DRIVER): + 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) @@ -71,7 +70,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc concluded = run_cycle(cycle) if isinstance(concluded, Stop): return concluded - closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, prompts.DRIVER, loop) + closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, fresh_prompt.DRIVER, loop) if isinstance(closed, Stop): return closed loop_run = closed @@ -113,25 +112,17 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop: records = read_records(loop.root, loop.paths.home, loop.paths.claude_dir) if isinstance(records, Failure): return Stop(1, records.reason) - models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, prompts.DRIVER, loop.effects) - if isinstance(models, Stop): - return models - ladder_file = project_ladder_file(loop.root, loop.paths.home) - if isinstance(ladder_file, Failure): - return Stop(1, ladder_file.reason) - ladder = read_ladder(ladder_file) - if isinstance(ladder, Failure): - return Stop(1, ladder.reason) + routing = project_routing(loop, fresh_prompt.DRIVER) + if isinstance(routing, Stop): + return routing archive_folder = project_archive(loop.root, loop.paths.home, loop.env) # After the reads above, so a loop that stops on one makes no worktree. facts, default = chunk_start(loop) - project = ladder.project_rung(models.worker) - route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects)) - say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True) - if ladder_file != SHIPPED: - say(own_ladder(ladder_file, models.worker, project is None), loop.effects) + route = announced_route(loop_run.cycle_number, loop_run.route, routing, archive_folder, lambda: plan_item(default, item_of(loop.window.name), loop.effects), loop) + if routing.ladder_file != SHIPPED: + say(own_ladder(routing.ladder_file, routing.models.worker, routing.project is None), loop.effects) plan = scored_plan(default, loop.effects) - return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge=judge_rung(ladder, models.judge), premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, prompts=prompts.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window) + return cycle_of(loop, routing, route, archive_folder, task=loop_run.task, facts=facts, premises=premises, records=records, unfinished_evidence=loop_run.unfinished_evidence, prompts=fresh_prompt.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan)) def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str: @@ -152,19 +143,3 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR if not (loop_run and loop_run.root and loop_run.task): return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: {' '.join(argv[1:])}") return loop_run - - -def setup_version(claude_dir: pathlib.Path, git: Git) -> str: - """The release and commit of this setup that the worker's claude reads, as `v0.8.0 ()`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 ()`. Where git can't tell, `unknown` and why.""" - described = git("describe", "--tags", "--match", "v*", "--always", cwd=str(claude_dir)) - commit = git("rev-parse", "HEAD", cwd=str(claude_dir)) - if isinstance(described, Failure): - return unknown_version(described) - if isinstance(commit, Failure): - return unknown_version(commit) - return f"{described.strip()} ({commit.strip()})" - - -def unknown_version(failure: Failure) -> str: - # One line, since the archive reads the line after it as the judge's. - return f"unknown: {' '.join(failure.reason.split())}" diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index b395222f..2be138c8 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -5,7 +5,7 @@ import pathlib import sys import typing -from loop_claude.loop.this_loop import Loop +from chunk_driver.this_loop import Loop from model_routing.route import Route, route_of from loop_effects.effects import say from agent_cycle.stop import Stop diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 4f989de7..d938f934 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -6,7 +6,7 @@ from routing_figures.calls import Call, calls, totals from agent_cycle.hand_over import claude_args, ClaudeCommand, hand_over from loop_effects.effects import Effects, say from failure import Failure -from loop_claude.loop.this_loop import Loop +from chunk_driver.this_loop import Loop from loop_state.paths import Paths from model_routing.ladder_file import read_ladder, SHIPPED from routing_figures.render import render diff --git a/bin/loop_claude/loop/usage.py b/bin/loop_claude/loop/usage.py index eb6c9f26..0b73d47f 100644 --- a/bin/loop_claude/loop/usage.py +++ b/bin/loop_claude/loop/usage.py @@ -71,7 +71,7 @@ doesn't write the whole context again. As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree, adding --item in a window named for an item, and quotes what it prints in the first prompt -(prompts.preflight_facts in bin/loop_claude/cycle/prompts.py); chunk-preflight --help says what it +(preflight_facts in bin/loop_claude/chunk/fresh_prompt.py); chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running after 600 s and is stopped, leaves the worker to find the facts itself. @@ -124,7 +124,8 @@ worker names on its `Chunk items:` line an item that picks a higher rung, or whe in the transcript an escalation trigger that fired and the worker asked for a higher rung. The rules are in bin/agent_cycle/routing.py and bin/model_routing/ladder.py, the choice of each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in -bin/loop_claude/cycle/prompts.py and bin/agent_cycle/worker_prompts.py. Each verdict, interrupt, +bin/loop_claude/chunk/fresh_prompt.py, bin/chunk_driver/prompts.py and +bin/agent_cycle/worker_prompts.py. Each verdict, interrupt, quoted answer, stop and step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A plan or an archive that cannot be read or parsed is said on stderr, and the diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 39a90398..52071b67 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -8,52 +8,48 @@ import pathlib import re import shutil import stat -import subprocess import sys import tempfile import types import unittest import unittest.mock -import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive, state from test_env import assert_not_root +from loop_effects.test_doubles import assistant, CWD, FakeEffects, human, judged, kinds, NOW, ran, said, STAMP, Streamed, Worker from claude_code.output_limits import BASH_CEILING_CHARACTERS from routing_figures.calls import Call -from loop_claude.project import checkout, model_choice, records -from loop_claude.cycle import chunk_items -from loop_claude.loop import chunk_start, chunk_windows, close +from loop_claude.chunk import chunk_items +from chunk_driver import chunk_run, cycle_start, prompts, this_loop +from loop_claude.loop import chunk_start, chunk_windows from project_config.test_project_config import configured from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES -from loop_effects.effects import Effects, PYTHON_TIMEOUT from claude_code import entries, reply, session from failure import Failure from agent_cycle.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished -from git_cli.git_repo import git -from agent_cycle import interrupt, judge, lingering_workers, retry, run, spend, states, stuck_workers, worker, worker_prompts -from claude_code.reply import Limited +from loop_claude.chunk import fresh_prompt +from agent_cycle import judge, retry, run, states, stuck_workers, worker, worker_prompts import loop_claude.routed_item -from loop_claude.loop import main, reload, routing_check, this_loop, usage -from machine_load import memory +from loop_claude.loop import main, reload, routing_check, usage from release_plan import next_chunk from transcript_archive import outcomes, write from loop_state import paths from plan_store.todo_md import plan_of from transcript_archive.location import project_archive from model_routing.ladder import ProjectRung, Rung -from loop_claude.cycle import prompts +from loop_effects.effects import PYTHON_TIMEOUT from model_routing.ladder_file import read_ladder, SHIPPED +from chunk_driver.project import records from model_routing.route import Route, route_from, WorkerLine from agent_cycle import routing from loop_effects.child_shells import Shell from agent_cycle.stop import Stop from agent_cycle import tmux -from claude_code.tokens import Tokens, tokens_of from touch_predictions.test_touch_predictions import plan as touch_plan from text_files.utc_stamp import utc -from agent_cycle.judge import verdict_from +from agent_cycle.test_tmux import WINDOW # How the archive records a worker that runs off the ladder. LADDER = read_ladder(SHIPPED) @@ -66,30 +62,10 @@ SONNET_179 = '{"model": "claude-sonnet-5-5", "effort": "high", "item": 179, "lik OPUS_179_AT_3 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 3}' OPUS_179_AT_6 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 6}' -CWD = pathlib.Path("/c") -NOW = 1790000000 -# How a line said at NOW opens, with FakeEffects' local_time. -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") -def assistant(*parts): - return {"type": "assistant", "message": {"content": list(parts)}} - - -def kinds(*found): - return [entries.entry_from(entry) for entry in found] - - -def human(content): - return {"type": "user", "message": {"content": content}} - - -# The window the loops under test run in. -WINDOW = tmux.Window("loop-proj", "item-7", "%4") - - def a_loop(effects, **fields): """A loop in /r on effects, with fields in place of its defaults.""" home = pathlib.Path("/h") @@ -97,223 +73,12 @@ def a_loop(effects, **fields): return this_loop.Loop(**{**defaults, **fields}, effects=effects) -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=(), dm_failures=(), tmux_version="tmux 3.2", windows=None, owner="/r"): - self.calls = [] - # Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session. - self.tmux_calls = [] - self.tmux_version = tmux_version - self.windows = windows - # The checkout the session's @loop-root option names. - self.owner = owner - # Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent. - self.dms = [] - # The directory each DM named, in the order of self.dms; None where it named none. - self.dm_directories = [] - self.dm_failures = list(dm_failures) - 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) - self.terminal = on_terminal - self.worker_environments = [] - self.worker_folders = [] - self.terminal_environments = [] - self.terminal_folders = [] - # Each timer started, as its delay and action, which a test runs where the timer fires. - self.timers = [] - - def effects(self): - return Effects( - 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)), - dm=self.dm, - execv=self.execv, - git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)), - input=lambda prompt: self.answer("input", prompt), - local_time=lambda seconds: f"<{seconds}>", - memory=self.memory, - now=lambda: NOW, - on_terminal=lambda: self.terminal, - python=lambda args, cwd: self.answer("python", (args, cwd)), - sleep=lambda seconds: self.calls.append(("sleep", seconds)), - stream_claude=self.stream, - timer=self.timer, - tmux=self.tmux, - tmux_on_terminal=lambda args: self.tmux(args).returncode, - ) - - def timer(self, delay, action): - self.timers.append((delay, action)) - return lambda: self.calls.append(("stop_timer", delay)) - - def tmux(self, args): - self.tmux_calls.append(args) - if args[0] == "list-windows": - return subprocess.CompletedProcess(args, 1 if self.windows is None else 0, self.windows or "", "no server") - return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n", "show-options": self.owner + "\n"}.get(args[0], "@9\n"), "") - - def dm(self, text, directory): - self.dms.append(text) - self.dm_directories.append(directory) - return self.dm_failures.pop(0) if self.dm_failures else None - - def memory(self): - self.calls.append(("memory", None)) - return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16) - - def on_terminal_claude(self, args, cwd, env): - self.terminal_environments.append(env) - self.terminal_folders.append(cwd) - return self.answer("claude_on_terminal", args) - - def stream(self, args, cwd, env): - self.worker_environments.append(env) - self.worker_folders.append(cwd) - return self.answer("stream_claude", args) - - def answer(self, seam, what): - self.calls.append((seam, what)) - answer = self.scripts[seam].pop(0) - if isinstance(answer, BaseException): - raise answer - return answer(what) if callable(answer) else answer - - def execv(self, path, args): - self.calls.append(("execv", args)) - raise OSError(2, "No such file or directory") - - def made(self, seam): - return [what for called, what in self.calls if called == seam] - - -def ran(stdout="", code=0, stderr=""): - return subprocess.CompletedProcess([], code, stdout, stderr) - - JUDGE_RUN_LINE = re.compile(r"^Judge run: judge/[0-9a-f]{64}\.json\n", re.MULTILINE) -def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""): - reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed} - return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})})) - - -class Worker: - """A worker claude: writes a line to the session's transcript, then streams a result.""" - - def __init__(self, home, prompted=False, text="working", usage=None, sent=None): - self.home = home - # Whether it records its -p prompt in the transcript first, as claude does. - self.prompted = prompted - self.text = text - # The usage its message records, twice as Claude Code writes a message of two blocks; none where None. - self.usage = usage - # The time its message records, as utc() writes it; none where None. - self.sent = sent - - def __call__(self, args): - flag = "--session-id" if "--session-id" in args else "--resume" - path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with open(path, "a") as handle: - if flag == "--session-id": - handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid7())}) + "\n") - if self.prompted: - handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n") - said = assistant({"type": "text", "text": self.text}) - if self.usage is not None: - said["message"] |= {"id": "msg-1", "model": "claude-opus-5-5", "usage": self.usage} - if self.sent is not None: - said["timestamp"] = self.sent - handle.write((json.dumps(said) + "\n") * (1 if self.usage is None else 2)) - return Streamed(0) - - -class Streamed: - """A started claude. An event of None is an idle stretch of CHECK_EVERY seconds, which advances `clock` by that; `held` are the shells it has, and `stopped` collects the ones stopped.""" - - def __init__(self, code, *events, clock=None, held=()): - self.code = code - self.events = events or ({"type": "result"},) - self.clock = clock - self.held = list(held) - self.stopped = [] - - def lines(self, idle): - for event in self.events: - if event is None: - self.clock[0] += idle - yield None if event is None else json.dumps(event) + "\n" - - def shells(self): - return self.held - - def stop(self, shell): - self.stopped.append(shell) - - def wait(self): - return self.code - - -TYPED = states.TypedAnswer("Which one?", "Use B.") - - -class Transitions(unittest.TestCase): - def test_each_state_moves_on_its_events_and_only_on_them(self): - answered = states.Ruled(QuotedAnswer("e", "Which one?", "A.")) - legal = ( - (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), - (states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.WorkerRan("/t"), states.Judging("/t", 3)), - (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"))), - (states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"), 3)), - (states.Judging("/t"), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 1)), - (states.Judging("/t", 2), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 3)), - (states.Judging("/t", 3), answered, states.Interrupting("/t", QuotedAnswer("e", "Which one?", "A."), 3)), - (states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), - (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.HumanTalked(), states.Judging("/t")), - (states.Interrupting("/t", Interrupt("e", "q"), 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)), - (states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))), - (states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))), - ) - 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.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.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]: - with self.subTest(state=state, event=event), self.assertRaises(ValueError): - states.transition(state, event) - - def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self): - ran_on = Rung("claude-opus-5-5", "xhigh") - stepped = routing.StepUp(Route(ran_on), Route(Rung("claude-fable-5-2", "low"), escalated_at=3)) - interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴") - for state, event, after in ( - (states.Judging("/t"), states.Ruled(quoted, stepped), states.Working(quoted, 1, True)), - (states.Judging("/t", 3), states.Ruled(quoted, stepped), states.Interrupting("/t", quoted, 3, ran_on)), - (states.Judging("/t"), states.Ruled(interrupt, stepped), states.Interrupting("/t", interrupt, 0, ran_on)), - (states.Interrupting("/t", interrupt, 0, ran_on), states.HumanTyped(TYPED), states.Working(TYPED, 0, True)), - (states.Interrupting("/t", interrupt, 0, ran_on), states.HumanTalked(), states.Judging("/t")), - (states.Working(TYPED, 0, True), states.WorkerRan("/t"), states.Judging("/t")), - ): - with self.subTest(state=state, event=event): - self.assertEqual(states.transition(state, event), after) - - class QuestionFor(unittest.TestCase): def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self): - cycle = types.SimpleNamespace(prompts=prompts.WORKER) + cycle = types.SimpleNamespace(prompts=fresh_prompt.WORKER) self.assertEqual(run.question_for(cycle, Interrupt("e", "Which one?")), "Which one?") self.assertEqual(run.question_for(cycle, QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.") @@ -328,7 +93,7 @@ class Cycles(unittest.TestCase): self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): - return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge=Rung("judge-model"), premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", prompts=prompts.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan_of("")), unfinished_evidence=unfinished_evidence) + return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge=Rung("judge-model"), premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", prompts=fresh_prompt.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan_of("")), unfinished_evidence=unfinished_evidence) def archived_outcomes(self): """Each outcomes file's text without its `Judge run:` lines, which name a file by the hash of a prompt and its reply: the tests of the judge's runs check them.""" @@ -617,7 +382,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)) first, resumed = fake.made("stream_claude") self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) - self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.WORKER.rungs_held(concluded.route, OPUS_PROJECT)}")) + self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{fresh_prompt.WORKER.rungs_held(concluded.route, OPUS_PROJECT)}")) self.assertNotIn("went through", first[first.index("-p") + 1]) answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n" stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n" @@ -773,351 +538,6 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}")) -class Retried(unittest.TestCase): - def test_retries_a_minute_apart_and_stops_on_the_third_failure(self): - fake = FakeEffects() - results = [Failure("one"), "done"] - self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), "done") - self.assertEqual(fake.calls, [("sleep", 60)]) - fake = FakeEffects() - self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no")) - self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)]) - - def test_hands_each_failure_to_the_keeper_and_stops_where_it_stops(self): - kept = [] - def keep(failure): - kept.append(failure) - return Stop(1, "no room") if len(kept) == 2 else None - fake = FakeEffects() - self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects(), keep), Stop(1, "no room")) - self.assertEqual(kept, [Failure("no")] * 2) - self.assertEqual(fake.calls, [("sleep", 60)]) - - def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self): - fake = FakeEffects() - results = [Failure("one"), Failure("two"), Limited(NOW + 3600, "limit"), Failure("three"), Limited(None, "limit"), Limited(NOW - 600, "limit"), Failure("four"), Failure("five"), Failure("six")] - self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), Stop(1, "the worker failed three times running: six")) - self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60), ("sleep", 3720), ("sleep", 60), ("sleep", 600), ("sleep", 600), ("sleep", 60), ("sleep", 60)]) - - def test_says_what_claude_said_and_when_the_next_try_is_due(self): - results = [Limited(NOW + 3600, "You've hit your session limit"), "done"] - with contextlib.redirect_stderr(io.StringIO()) as said: - retry.retried("judge", lambda: results.pop(0), FakeEffects().effects()) - self.assertEqual(said.getvalue(), f"{STAMP} the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n") - - -class Limits(unittest.TestCase): - def test_the_worker_reports_the_latest_reset_its_stream_names(self): - rejected = [{"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}} for resets_at in (NOW + 60, NOW + 600)] - allowed = {"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": NOW + 9000}} - limited = {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"} - fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited)]) - self.assertEqual(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects()), Limited(NOW + 600, "You've hit your session limit")) - - def test_a_limit_outranks_the_exit_code_and_its_message_fits_one_line(self): - def limited(**said): - return {"type": "result", "api_error_status": 429, **said} - self.assertEqual(worker.worker_outcome(-9, limited(result="limit\n resets 7pm"), []), Limited(None, "limit resets 7pm")) - self.assertEqual(worker.worker_outcome(1, limited(result=" \n"), [NOW]), Limited(NOW, "claude gave no message")) - self.assertEqual(worker.worker_outcome(0, limited(), []), Limited(None, "claude gave no message")) - self.assertEqual(worker.worker_outcome(0, None, [NOW]), Failure("claude exited 0 without a result event")) - self.assertIsNone(worker.worker_outcome(0, {"type": "result"}, [NOW])) - - def test_the_judge_reports_a_limit_whatever_its_exit_code(self): - reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"}) - fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")]) - self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds("", "", ""), fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)")) - - def test_reads_only_a_rejecting_events_whole_seconds(self): - for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]: - with self.subTest(info=info): - self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want) - - -class LingeringWorkers(unittest.TestCase): - RESULT = {"type": "result"} - - def worker_with(self, *events, held=()): - """Runs a worker whose claude prints events and holds shells `held`; returns the claude, what loop-claude said and the record's text.""" - clock = [NOW] - streamed = Streamed(0, *events, clock=clock, held=held) - fake = FakeEffects(streams=[streamed]) - effects = dataclasses.replace(fake.effects(), now=lambda: clock[0]) - with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()) as said: - # The archive folder of a project's first stop doesn't exist yet. - archive = pathlib.Path(folder, "transcripts", "project") - worker.run_worker("/r", [], {}, archive, Rung("m"), effects) - record = archive / lingering_workers.RECORD - return streamed, said.getvalue(), record.read_text() if record.exists() else "" - - def shell(self, written=NOW - 1000, runs_busy_tool=False, holds_slot=False): - return Shell(pid=7, started=NOW - 1000, command="until false; do sleep 15; done", written=written, runs_busy_tool=runs_busy_tool, holds_slot=holds_slot) - - def test_a_worker_that_lingers_after_its_result_loses_its_quiet_shell_and_the_stop_is_said_and_recorded_in_utc(self): - shell = self.shell() - streamed, said, record = self.worker_with(self.RESULT, None, held=[shell]) - self.assertEqual(streamed.stopped, [shell]) - line = f"stopped shell 7, which held a worker after its final result; it had run 1300 s and written nothing for 1300 s: {shell.command}" - self.assertEqual(said, f"<{NOW + 300}> {line}\n") - self.assertEqual(record, f"- {utc(NOW + 300)} {line}\n") - - def test_a_worker_keeps_its_shells_where_it_printed_after_its_result_or_printed_none_or_no_check_came_due(self): - for events in ((self.RESULT, {"type": "assistant", "message": {"content": []}}, None), (self.RESULT,), (None,), ({"type": "assistant", "message": {"content": []}}, None)): - with self.subTest(events=events): - streamed, said, record = self.worker_with(*events, held=[self.shell()]) - self.assertEqual((streamed.stopped, said, record), ([], "", "")) - - def test_a_worker_keeps_every_shell_while_one_of_them_writes_output_runs_a_busy_tool_or_holds_a_heavy_slot(self): - for busy in (self.shell(written=NOW + 200), self.shell(runs_busy_tool=True), self.shell(holds_slot=True)): - with self.subTest(busy=busy): - streamed, _, _ = self.worker_with(self.RESULT, None, held=[self.shell(), busy]) - self.assertEqual(streamed.stopped, []) - - def test_a_worker_keeps_a_shell_that_wrote_within_the_quiet_time_and_stops_one_that_wrote_before_it(self): - # The check comes 300 s after the result, so a shell written at NOW + 300 - QUIET is the latest that is still kept. - kept = self.shell(written=NOW + 300 - lingering_workers.QUIET) - stopped = self.shell(written=NOW + 300 - lingering_workers.QUIET - 1) - self.assertEqual(self.worker_with(self.RESULT, None, held=[kept])[0].stopped, []) - self.assertEqual(self.worker_with(self.RESULT, None, held=[stopped])[0].stopped, [stopped]) - - def test_a_worker_reads_on_past_a_check_that_found_it_still_working(self): - clock = [NOW] - effects = dataclasses.replace(FakeEffects(streams=[Streamed(0, None, self.RESULT, clock=clock)]).effects(), now=lambda: clock[0]) - self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), effects)) - - def test_a_stop_that_cannot_be_recorded_is_said_on_stderr_and_every_shell_is_still_stopped(self): - clock = [NOW] - held = [self.shell(), self.shell()] - streamed = Streamed(0, self.RESULT, None, clock=clock, held=held) - effects = dataclasses.replace(FakeEffects(streams=[streamed]).effects(), now=lambda: clock[0]) - with tempfile.NamedTemporaryFile() as blocker, contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as failed: - worker.run_worker("/r", [], {}, pathlib.Path(blocker.name), Rung("m"), effects) - self.assertEqual(streamed.stopped, held) - self.assertIn("could not record the stop", failed.getvalue()) - - def test_every_stop_of_a_check_is_recorded_though_the_archive_folder_exists_after_the_first(self): - held = [self.shell(), self.shell()] - _, said, record = self.worker_with(self.RESULT, None, held=held) - self.assertEqual(record.count("stopped shell 7"), 2) - - -class MemoryWait(unittest.TestCase): - def test_a_worker_starts_only_once_a_quarter_of_memory_is_available(self): - fake = FakeEffects(free_memory=[memory.Memory(available=3, total=16), memory.Memory(available=3, total=16), memory.Memory(available=4, total=16)], streams=[Streamed(0)]) - with contextlib.redirect_stderr(io.StringIO()) as said: - self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects())) - self.assertEqual([seam for seam, _ in fake.calls], ["memory", "sleep", "memory", "sleep", "memory", "stream_claude"]) - self.assertEqual(fake.made("sleep"), [worker.MEMORY_POLL] * 2) - self.assertEqual(said.getvalue().count("waiting"), 1, said.getvalue()) - - def test_a_worker_starts_at_once_where_memory_cannot_be_read(self): - fake = FakeEffects(free_memory=[None], streams=[Streamed(0)]) - self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), Rung("m"), fake.effects())) - self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"]) - - -class Interrupts(unittest.TestCase): - def setUp(self): - self.home = pathlib.Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, self.home) - self.paths = paths.paths_from(self.home) - self.transcript = self.home / "t.jsonl" - self.transcript.write_text(json.dumps(human("a")) + "\n") - self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) - - def put(self, fake, answer_here=True, effects=None, question="Which one?"): - """interrupt's answer and what it said, without the bell it rang, which self.bells counts.""" - with contextlib.redirect_stderr(io.StringIO()) as said: - answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, prompts.DRIVER, effects or fake.effects()) - self.bells = said.getvalue().count(tmux.BELL) - return answer, said.getvalue().replace(tmux.BELL, "") - - def typed_there(self, args): - """The claude opened on the terminal: the human types a line in the worker's session, and it ends.""" - with open(self.transcript, "a") as handle: - handle.write(json.dumps(human("cut it")) + "\n") - return 0 - - def worked(self, minutes_ago, written_1h=5000, read=70000, written_5m=0): - """Appends the worker's last message, sent minutes_ago before NOW, whose usage wrote written_1h tokens to the hour-long cache, written_5m to the five-minute one, and read read tokens from the cache.""" - said = assistant({"type": "text", "text": "Which one?"}) - said["timestamp"] = utc(NOW - minutes_ago * 60) - said["message"] |= {"id": "msg-1", "model": "m", "usage": {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": written_5m, "ephemeral_1h_input_tokens": written_1h}, "cache_read_input_tokens": read, "output_tokens": 100}} - with open(self.transcript, "a") as handle: - handle.write(json.dumps(said) + "\n") - - def fired(self, fake, answer): - """An input that first fires every timer started, then returns answer as the line the human typed.""" - def typed(prompt): - for _, action in fake.timers: - action() - return answer - return typed - - def test_compacts_the_workers_session_ten_minutes_before_its_hour_long_prompt_cache_expires_and_keeps_waiting(self): - self.worked(minutes_ago=10) - fake = FakeEffects(streams=[Streamed(0)]) - fake.scripts["input"] = [self.fired(fake, "Use B.")] - answer, said = self.put(fake) - self.assertEqual(answer, "Use B.") - self.assertEqual([delay for delay, _ in fake.timers], [40 * 60]) - self.assertEqual([what for seam, what in fake.calls if seam == "stream_claude"], [["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "-p", "/compact", "--resume", str(self.session.id), "--output-format", "stream-json", "--verbose"]]) - self.assertEqual(fake.worker_environments, [self.session.env]) - self.assertEqual(fake.worker_folders, [self.session.root]) - self.assertIn(f"\n{STAMP} compacting the worker's claude session before its prompt cache expires; an answer typed meanwhile is read once that ends\n\n{STAMP} compacted the worker's claude session\n", said) - self.assertNotIn("still waiting", said) - - def test_compacts_on_the_rung_the_worker_ran_on_where_a_ruling_stepped_it_up_and_talk_opens_claude_on_the_new_rung(self): - self.worked(minutes_ago=10) - self.session = dataclasses.replace(self.session, rung=Rung("n", "medium")) - fake = FakeEffects(streams=[Streamed(0)], on_terminal_claude=[self.typed_there]) - fake.scripts["input"] = [self.fired(fake, "/talk")] - self.assertEqual(self.put(fake)[0], interrupt.Talked()) - (compaction,), (opened,) = fake.made("stream_claude"), fake.made("claude_on_terminal") - self.assertEqual(compaction[:4], ["--model", "m", "--effort", "high"]) - self.assertEqual(opened[:4], ["--model", "n", "--effort", "medium"]) - - def test_compacts_until_the_prompt_cache_expires_and_not_from_then_on(self): - for name, late, compactions in (("a second before", 50 * 60 - 1, 1), ("as it expires", 50 * 60, 0)): - with self.subTest(name): - self.transcript.write_text(json.dumps(human("a")) + "\n") - self.worked(minutes_ago=10) - fake = FakeEffects(streams=[Streamed(0)]) - clock = [NOW] - - def typed(prompt): - clock[0] = NOW + late - for _, action in fake.timers: - action() - return "Use B." - fake.scripts["input"] = [typed] - answer, said = self.put(fake, effects=dataclasses.replace(fake.effects(), now=lambda: clock[0])) - self.assertEqual(answer, "Use B.") - self.assertEqual(len(fake.made("stream_claude")), compactions) - self.assertEqual(said.count("compact"), 2 * compactions, said) - - def test_a_compaction_doesnt_wait_for_memory(self): - self.worked(minutes_ago=10) - fake = FakeEffects(streams=[Streamed(0)], free_memory=[memory.Memory(available=3, total=16)]) - fake.scripts["input"] = [self.fired(fake, "Use B.")] - said = self.put(fake)[1] - self.assertEqual([seam for seam, _ in fake.calls if seam in ("memory", "sleep", "stream_claude")], ["stream_claude"]) - self.assertNotIn("waiting to start the worker", said) - - def test_an_answer_before_the_timer_fires_stops_it_and_doesnt_compact_anything(self): - self.worked(minutes_ago=10) - fake = FakeEffects(inputs=["Use B."]) - self.assertEqual(self.put(fake)[0], "Use B.") - self.assertEqual([call for call in fake.calls if call[0] in ("stop_timer", "stream_claude")], [("stop_timer", 40 * 60)]) - - def test_stops_the_timer_before_talk_opens_the_workers_session(self): - self.worked(minutes_ago=10) - fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[self.typed_there]) - self.assertEqual(self.put(fake)[0], interrupt.Talked()) - self.assertEqual([call[0] for call in fake.calls if call[0] in ("stop_timer", "claude_on_terminal")], ["stop_timer", "claude_on_terminal"]) - - def test_starts_no_timer_under_60k_tokens_of_context_past_the_margin_on_a_five_minute_cache_or_where_claude_opens_at_once(self): - for name, minutes_ago, written_1h, written_5m, read, answer_here in (("small", 10, 5000, 0, 54997, True), ("margin begun", 50, 5000, 0, 70000, True), ("five minutes", 1, 0, 5000, 70000, True), ("nothing written", 1, 0, 0, 70000, True), ("opens at once", 10, 5000, 0, 70000, False)): - with self.subTest(name): - self.transcript.write_text(json.dumps(human("a")) + "\n") - self.worked(minutes_ago, written_1h, read, written_5m) - fake = FakeEffects(inputs=["Use B."], on_terminal_claude=[self.typed_there]) - self.put(fake, answer_here=answer_here) - self.assertEqual(fake.timers, []) - - def test_starts_the_timer_at_60k_tokens_of_context(self): - self.worked(minutes_ago=10, read=54998) - fake = FakeEffects(inputs=["Use B."]) - self.put(fake) - self.assertEqual([delay for delay, _ in fake.timers], [40 * 60]) - - def test_starts_no_timer_where_the_transcript_cannot_be_read_and_still_asks(self): - self.transcript.unlink() - fake = FakeEffects(inputs=["Use B."]) - self.assertEqual(self.put(fake)[0], "Use B.") - self.assertEqual(fake.timers, []) - - def test_a_compaction_that_hits_a_usage_limit_says_the_limits_message_and_keeps_waiting(self): - self.worked(minutes_ago=10) - fake = FakeEffects(streams=[Streamed(0, {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"})]) - fake.scripts["input"] = [self.fired(fake, "Use B.")] - answer, said = self.put(fake) - self.assertEqual(answer, "Use B.") - self.assertIn(f"\n{STAMP} could not compact the worker's claude session: You've hit your session limit\n", said) - - def test_a_compaction_that_fails_says_why_and_keeps_waiting(self): - self.worked(minutes_ago=10) - fake = FakeEffects(streams=[Streamed(1)]) - fake.scripts["input"] = [self.fired(fake, "Use B.")] - answer, said = self.put(fake) - self.assertEqual(answer, "Use B.") - self.assertIn(f"\n{STAMP} could not compact the worker's claude session: claude exited 1\n", said) - - def test_stops_off_a_terminal_before_asking(self): - fake = FakeEffects(on_terminal=False) - self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n")) - self.assertEqual(fake.calls, []) - - def test_dms_the_question_naming_the_project_on_a_terminal_or_off_one(self): - for on_terminal in (True, False): - with self.subTest(on_terminal=on_terminal): - fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal) - self.put(fake) - self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks, in the tmux window loop-proj:item-7:\n\nWhich one?"]) - - def test_marks_its_window_and_rings_the_bell_while_it_waits_and_clears_the_mark_once_answered(self): - fake = FakeEffects(inputs=["Use B."]) - answer, said = self.put(fake) - self.assertEqual(answer, "Use B.") - self.assertEqual(self.bells, 1) - self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"]]) - - def test_a_loop_that_stops_unanswered_leaves_its_window_marked(self): - fake = FakeEffects(on_terminal=False) - self.put(fake) - self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"]]) - - def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self): - fake = FakeEffects(inputs=["Use B."]) - seen = [] - effects = dataclasses.replace(fake.effects(), dm=lambda text, directory: seen.append(list(fake.calls))) - self.assertEqual(self.put(fake, effects=effects)[0], "Use B.") - self.assertEqual(seen, [[("discard_typed", None)]]) - - def test_says_why_a_dm_failed_and_still_takes_the_answer(self): - fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")]) - self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n")) - - def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self): - fake = FakeEffects(inputs=[" Use B. "]) - self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n")) - self.assertEqual(fake.calls, [("discard_typed", None), ("input", "Answer (/talk opens claude, Enter stops the loop): ")]) - - def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self): - for typed, answer_here in (([" /talk "], True), ([], False)): - with self.subTest(typed=typed): - fake = FakeEffects(inputs=typed, on_terminal_claude=[self.typed_there]) - self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talked()) - self.assertEqual(len(fake.made("input")), len(typed)) - self.assertEqual(fake.calls[0], ("discard_typed", None)) - - def test_stops_on_an_empty_answer_or_the_inputs_end(self): - for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")): - with self.subTest(why=why): - self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}")) - - def test_stops_when_nothing_was_typed_in_the_session(self): - fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0]) - stop, _ = self.put(fake) - 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 without anything typed")) - - def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self): - fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0]) - self.put(fake) - self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort", "CLAUDE_CODE_SANDBOXED": "1"}]) - - class RoutingCheck(unittest.TestCase): def setUp(self): self.home = pathlib.Path(tempfile.mkdtemp()) @@ -1239,25 +659,6 @@ class RoutingCheck(unittest.TestCase): 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) -class ModelPrompt(unittest.TestCase): - OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")] - - def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self): - self.assertEqual(model_choice.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5") - self.assertEqual(model_choice.model_picked("opus", self.OFFERED), "opus") - self.assertEqual(model_choice.model_picked("3", []), "3") - self.assertEqual(model_choice.model_picked("3", self.OFFERED), Failure("pick 1 to 2")) - self.assertIsNone(model_choice.model_picked(" ", self.OFFERED)) - - def test_asks_again_until_an_answer_picks_a_model(self): - with tempfile.TemporaryDirectory() as empty: - fake = FakeEffects(inputs=["", "my-model"]) - self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), prompts.DRIVER, fake.effects()), "my-model") - self.assertEqual(len(fake.made("input")), 2) - fake = FakeEffects(inputs=[EOFError()]) - self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), prompts.DRIVER, fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended")) - - # A plan read with no release cut yet. NO_CUT = LastCut(None, "", 0, []) def routed_item(todo, cut): @@ -1435,14 +836,14 @@ class Routing(unittest.TestCase): archived = Route(self.THREE_UP, 3, 4, 5) def never(): raise AssertionError("not asked") - self.assertEqual(chunk_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model"))) - self.assertEqual(chunk_start.routed(archived, OPUS_PROJECT, "claude-opus-5-5", never, never), archived) - self.assertEqual(chunk_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: archived, never), archived) - self.assertEqual(chunk_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: None, lambda: item), Route(self.TWO_UP, 3, 4, 5)) - self.assertEqual(chunk_start.routed(Route(self.SONNET), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) + self.assertEqual(cycle_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model"))) + self.assertEqual(cycle_start.routed(archived, OPUS_PROJECT, "claude-opus-5-5", never, never), archived) + self.assertEqual(cycle_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: archived, never), archived) + self.assertEqual(cycle_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: None, lambda: item), Route(self.TWO_UP, 3, 4, 5)) + self.assertEqual(cycle_start.routed(Route(self.SONNET), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) cheap = Route(self.SONNET, 4, 2, 3) - self.assertEqual(chunk_start.routed(cheap, OPUS_PROJECT, "claude-opus-5-5", never, never), cheap) - self.assertEqual(chunk_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) + self.assertEqual(cycle_start.routed(cheap, OPUS_PROJECT, "claude-opus-5-5", never, never), cheap) + self.assertEqual(cycle_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) class RouteSources(unittest.TestCase): @@ -1524,106 +925,30 @@ class RouteSources(unittest.TestCase): transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") route = Route(Rung("claude-fable-5-2", "low"), 3, 4, 5) with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) transcript.parent.mkdir(parents=True) transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") - self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW)) with contextlib.redirect_stderr(stderr): - self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), route) + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), route) self.assertEqual(stderr.getvalue(), "") with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1)) with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) self.assertEqual(stderr.getvalue(), f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route that can be read: {{"model": "claude-opus-5-5", "rung": 3}}\n') (chunk,) = archive.iterdir() chunk.chmod(0) try: with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) finally: chunk.chmod(0o700) self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue()) -class TmuxCommands(unittest.TestCase): - def test_refuses_a_tmux_older_than_needed_naming_both_versions(self): - for found, reason in (("tmux 3.2", None), ("tmux 3.8", None), ("tmux next-3.4", None), ("tmux 10.0", None), - ("tmux 3.1c", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), - ("tmux 2.9a", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 2.9a"), - ("", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux")): - with self.subTest(found=found): - fake = FakeEffects(tmux_version=found) - self.assertEqual(tmux.unusable(fake.tmux, prompts.DRIVER), reason) - self.assertEqual(fake.tmux_calls, [["-V"]]) - - def test_names_the_session_for_the_project(self): - self.assertEqual(tmux.session_name(tmux.LOOP, "claude-config"), "loop-claude-config") - # tmux reads `.` and `:` in a target as separators. - self.assertEqual(tmux.session_name(tmux.LOOP, "my.site:2 x"), "loop-my-site-2-x") - self.assertEqual(tmux.session_name(tmux.LOOP, "Acme/Billing"), "loop-Acme-Billing") - - def test_lists_the_windows_without_the_waiting_mark(self): - fake = FakeEffects(windows="item-372 ?\t0\t@1\nitem-380\t1\t@2\nno-item\t0\t@5\n") - self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False, asks=True), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)]) - self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) - self.assertEqual(tmux.listed("loop-proj", FakeEffects().tmux), []) - failed = lambda args: subprocess.CompletedProcess(args, 1, "item-1\t0\t@1\n", "no server") - self.assertEqual(tmux.listed("loop-proj", failed), []) - - def test_the_first_window_makes_the_session_and_each_later_one_joins_it(self): - fake = FakeEffects() - window = tmux.Window("loop-proj", "item-7", "") - self.assertIsNone(tmux.start_window(window, "/r", {"LOOP_CLAUDE_X": "1"}, ["/b/loop-claude", "--chunk", "item-7", "ship it;"], True, True, fake.tmux)) - self.assertIsNone(tmux.start_window(window, "/r", {}, ["/b/loop-claude"], False, True, fake.tmux)) - self.assertEqual(fake.tmux_calls, [ - ["new-session", "-d", "-s", "loop-proj", "-n", "item-7", "-c", "/r", "-e", "LOOP_CLAUDE_X=1", "-P", "-F", "#{window_id}", "--", "/b/loop-claude", "--chunk", "item-7", "ship it\;"], - ["set-option", "-t", "=loop-proj:", "@loop-root", "/r"], - ["set-option", "-w", "-t", "@9", "@chunk-root", "/r"], - ["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"], - ["new-window", "-d", "-t", "=loop-proj:", "-n", "item-7", "-c", "/r", "-P", "-F", "#{window_id}", "--", "/b/loop-claude"], - ["set-option", "-w", "-t", "@9", "@chunk-root", "/r"], - ["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"], - ]) - - def test_says_why_tmux_started_no_window(self): - failed = lambda args: subprocess.CompletedProcess(args, 1, "", "duplicate session: loop-proj\n") - silent = lambda args: subprocess.CompletedProcess(args, 2, "", "") - window = tmux.Window("loop-proj", "item-7", "") - self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, failed), Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj")) - self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, silent), Failure("tmux could not start the window loop-proj:item-7: it exited 2")) - - def test_fails_where_it_cannot_mark_a_session_it_made_as_the_checkouts_but_not_where_remain_on_exit_fails(self): - def answering(failing: str): - def run(args): - fails = args[:1] == ["set-option"] and failing in args - return subprocess.CompletedProcess(args, 1 if fails else 0, "" if fails else "@9\n", "no such session\n" if fails else "") - return run - window = tmux.Window("loop-proj", "item-7", "") - self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, True, answering(tmux.OWNER)), Failure("tmux started the session loop-proj but could not mark it as this checkout's: no such session")) - self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], True, True, answering("remain-on-exit"))) - self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], False, True, answering(tmux.OWNER))) - - def test_reads_the_checkout_the_session_names(self): - fake = FakeEffects(owner="/c/proj") - self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj") - self.assertEqual(fake.tmux_calls, [["show-options", "-qv", "-t", "=loop-proj:", "@loop-root"]]) - - def test_marks_a_waiting_window_by_its_pane_and_clears_the_mark(self): - fake = FakeEffects() - tmux.mark(WINDOW, True, fake.tmux) - tmux.mark(WINDOW, False, fake.tmux) - tmux.close(tmux.Listed("item-7", "@3", True), fake.tmux) - self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"], ["kill-window", "-t", "@3"]]) - self.assertEqual(WINDOW.target, "loop-proj:item-7") - - def test_shows_the_session_by_attaching_or_inside_tmux_by_switching(self): - self.assertEqual(tmux.show("loop-proj", False), ["attach-session", "-t", "=loop-proj"]) - self.assertEqual(tmux.show("loop-proj", True), ["switch-client", "-t", "=loop-proj"]) - - class ChunkWindows(unittest.TestCase): def plan(self, *touched): """A plan of items 1, 2 and on, each predicted to touch the path given for it.""" @@ -1860,24 +1185,24 @@ class Steps(unittest.TestCase): def test_a_finished_verdict_clears_the_route_and_the_evidence(self): run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS)) - self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence="")) - self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0) - self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(self.FABLE_MEDIUM, unfinished=1), unfinished_evidence="new", unfinished_run=1)) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence="")) + self.assertEqual(chunk_run.after_verdict(dataclasses.replace(run_with, unfinished_run=3), OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(self.FABLE_MEDIUM, unfinished=1), unfinished_evidence="new", unfinished_run=1)) def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self): run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4)) raised = Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=5) - self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1)) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1)) def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self): off_ladder = Route(Rung("worker-model")) run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="") - self.assertEqual(close.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder) + self.assertEqual(chunk_run.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder) def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self): run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.FABLE_LOW, 3, 3, 4, escalated_at=2)) - self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=9)) - self.assertEqual(close.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.FABLE_LOW, 3, 3, 4, unfinished=1, escalated_at=2)) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=9)) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.FABLE_LOW, 3, 3, 4, unfinished=1, escalated_at=2)) def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self): with tempfile.TemporaryDirectory() as home: @@ -1889,14 +1214,14 @@ class Steps(unittest.TestCase): before = Route(self.FABLE_LOW, 3, 3, 4) with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) - after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, prompts.DRIVER, a_loop(FakeEffects().effects(), session=opened)) - self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) + after = chunk_run.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) with contextlib.redirect_stderr(io.StringIO()): - close.closed_cycle(after, OPUS_PROJECT, run.Concluded(Finished("done"), after.route), archive, prompts.DRIVER, a_loop(FakeEffects().effects(), session=opened)) - self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) + chunk_run.closed_cycle(after, OPUS_PROJECT, run.Concluded(Finished("done"), after.route), archive, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) blocked = pathlib.Path(home, "blocked") blocked.write_text("") - stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, prompts.DRIVER, a_loop(FakeEffects().effects(), session=opened)) + stop = chunk_run.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self): @@ -1914,8 +1239,8 @@ class Steps(unittest.TestCase): before = Route(self.FABLE_LOW, 3, 3, 4) with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) - close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, prompts.DRIVER, a_loop(FakeEffects().effects(), session=opened)) - self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6)) + chunk_run.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6)) class ChunkFacts(unittest.TestCase): @@ -1939,8 +1264,8 @@ class ChunkFacts(unittest.TestCase): fake = FakeEffects(python=[ran("- A fact.\n")], windows="item-7\t0\t@1\nitem-5\t1\t@2\nitem-12 ?\t0\t@3\nitem-9\t0\t@4\n") said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project, running or stopped, hold items 5, 9, 12. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said) - self.assertEqual(prompts.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.") - self.assertTrue(prompts.held_by_others([4, 9]).startswith("\n\nOther chunks of this project, running or stopped, hold items 4, 9.")) + self.assertEqual(fresh_prompt.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.") + self.assertTrue(fresh_prompt.held_by_others([4, 9]).startswith("\n\nOther chunks of this project, running or stopped, hold items 4, 9.")) # A worker whose preflight failed is told them too. fake = FakeEffects(python=[ran(code=1, stderr="git could not start\n")], windows="item-9\t0\t@4\n") said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) @@ -1971,13 +1296,13 @@ class TypedAnswers(unittest.TestCase): def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self): route = Route(Rung("worker-model")) marked = "The human answered your question at loop-claude's terminal:\nB" - typed = worker_prompts.typed_answer(prompts.WORKER.typed("Which one?", "Use B.", route, None, False)) + typed = worker_prompts.typed_answer(fresh_prompt.WORKER.typed("Which one?", "Use B.", route, None, False)) self.assertEqual(typed.answer, "Use B.") self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task.")) - self.assertEqual(worker_prompts.typed_answer(prompts.WORKER.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.") - self.assertEqual(worker_prompts.typed_answer(prompts.WORKER.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), OPUS_PROJECT, True)).answer, "Use B.") - self.assertIsNone(worker_prompts.typed_answer(prompts.WORKER.answered("Which one?", marked, route, None, False))) - self.assertIsNone(worker_prompts.typed_answer(prompts.WORKER.resumed(marked, route, None))) + self.assertEqual(worker_prompts.typed_answer(fresh_prompt.WORKER.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.") + self.assertEqual(worker_prompts.typed_answer(fresh_prompt.WORKER.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), OPUS_PROJECT, True)).answer, "Use B.") + self.assertIsNone(worker_prompts.typed_answer(fresh_prompt.WORKER.answered("Which one?", marked, route, None, False))) + self.assertIsNone(worker_prompts.typed_answer(fresh_prompt.WORKER.resumed(marked, route, None))) class WorkerArgs(unittest.TestCase): @@ -1988,123 +1313,123 @@ class WorkerArgs(unittest.TestCase): FACTS = "- A preflight fact." def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): - routed = prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) - self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed) - unrouted = prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS) - self.assertIn(f"before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted) + routed = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) + self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed) + unrouted = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS) + self.assertIn(f"before creating a new one. {prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted) self.assertNotIn("loop-claude runs you on", unrouted) def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self): - routed = prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) + routed = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) self.assertIn("item 3's size again", routed) self.assertIn("escalation trigger 1", routed) self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed) - self.assertNotIn("size again", prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)) + self.assertNotIn("size again", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)) def test_gives_each_fresh_worker_the_reading_rule_once(self): rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context" for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))): with self.subTest(route=route): - self.assertEqual(prompts.WORKER.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1) + self.assertEqual(fresh_prompt.WORKER.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1) def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self): - self.assertIn("\n\n- A fact.", prompts.preflight_facts("- A fact.")) - failed = prompts.preflight_failed("git could not start") + self.assertIn("\n\n- A fact.", fresh_prompt.preflight_facts("- A fact.")) + failed = fresh_prompt.preflight_failed("git could not start") self.assertIn("yourself", failed) self.assertIn("git could not start", failed) def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self): - for facts in (prompts.preflight_facts("- A fact."), prompts.preflight_failed("git could not start")): + for facts in (fresh_prompt.preflight_facts("- A fact."), fresh_prompt.preflight_failed("git could not start")): with self.subTest(facts=facts): - self.assertEqual(prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1) + self.assertEqual(fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1) def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): opus = Rung("claude-opus-5-5", "medium") - below = prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT, self.FACTS) + below = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT, self.FACTS) self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 ` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below) - self.assertNotIn("Launch each", prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) + self.assertNotIn("Launch each", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self): opus = Rung("claude-opus-5-5", "medium") - level = prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 6), OPUS_PROJECT, self.FACTS) + level = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 6), OPUS_PROJECT, self.FACTS) self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", level) - below = prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), OPUS_PROJECT, self.FACTS) + below = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), OPUS_PROJECT, self.FACTS) self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below) - self.assertNotIn("Launch each reviewer", prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), OPUS_PROJECT)) + self.assertNotIn("Launch each reviewer", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), OPUS_PROJECT)) def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self): opus = Rung("claude-opus-5-5", "medium") taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8." - self.assertIn(f"item 3's L of 2.{taking_in} When an escalation trigger", prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) - self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.WORKER.resumed("", Route(opus, 3, 2, 6), OPUS_PROJECT)) - self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), OPUS_PROJECT)) - self.assertNotIn("Where an item you take into", prompts.WORKER.resumed("", Route(opus, 3, 2, 8), OPUS_PROJECT)) - self.assertNotIn("Where an item you take into", prompts.WORKER.resumed("", Route(Rung("m")), None)) + self.assertIn(f"item 3's L of 2.{taking_in} When an escalation trigger", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) + self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 6), OPUS_PROJECT)) + self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), OPUS_PROJECT)) + self.assertNotIn("Where an item you take into", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 8), OPUS_PROJECT)) + self.assertNotIn("Where an item you take into", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self): opus = Rung("claude-opus-5-5", "medium") - self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", prompts.WORKER.resumed("", Route(opus, 3, 2, 5, escape_and_impact_taken_in=7), OPUS_PROJECT)) - self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", prompts.WORKER.resumed("", Route(opus, escape_and_impact_taken_in=5), OPUS_PROJECT)) + self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 5, escape_and_impact_taken_in=7), OPUS_PROJECT)) + self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", fresh_prompt.WORKER.resumed("", Route(opus, escape_and_impact_taken_in=5), OPUS_PROJECT)) def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self): opus = Rung("claude-opus-5-5", "medium") - above = prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT, self.FACTS) - stepped_up = prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT) - self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up) - self.assertNotIn("the project's", prompts.WORKER.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT)) - self.assertNotIn("runs you on", prompts.WORKER.resumed("", Route(Rung("m")), None)) + above = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT, self.FACTS) + stepped_up = fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT) + self.assertIn(f"{prompts.ANSWERS_RECORDED}. {fresh_prompt.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up) + self.assertNotIn("the project's", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT)) + self.assertNotIn("runs you on", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) self.assertIn(f"item 3's L of 3.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", above) def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self): opus = Rung("claude-opus-5-5", "medium") - fresh = prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS) + fresh = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS) self.assertIn("item 3's L of 2. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh) - self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), OPUS_PROJECT)) - self.assertNotIn("escalation", prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT)) - self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours, only once the human agrees;", prompts.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT)) - self.assertIn("set to `model fable, effort max`, one rung above yours, only once the human agrees;", prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "high"), 3, 4, 5), OPUS_PROJECT), "one rung below the top still names the rung above") - self.assertNotIn("rerun", prompts.WORKER.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT), "a worker off the ladder is told no rerun rung") - self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours;", prompts.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), OPUS_PROJECT)) - self.assertNotIn("escalation", prompts.WORKER.resumed("", Route(Rung("m")), None)) - self.assertNotIn("escalation", prompts.WORKER.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.WORKER.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS)) + self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) + self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), OPUS_PROJECT)) + self.assertNotIn("escalation", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT)) + self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours, only once the human agrees;", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT)) + self.assertIn("set to `model fable, effort max`, one rung above yours, only once the human agrees;", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "high"), 3, 4, 5), OPUS_PROJECT), "one rung below the top still names the rung above") + self.assertNotIn("rerun", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT), "a worker off the ladder is told no rerun rung") + self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours;", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), OPUS_PROJECT)) + self.assertNotIn("escalation", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) + self.assertNotIn("escalation", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT)) + self.assertIn(f"{prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS)) def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): opus = Rung("claude-opus-5-5", "medium") offer = lambda cap: f" Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `{cap}`." - self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model fable, effort low')}", prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) - self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model opus, effort xhigh')}", prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertNotIn("Where the hard part", prompts.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT)) + self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model fable, effort low')}", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) + self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model opus, effort xhigh')}", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) + self.assertNotIn("Where the hard part", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT)) def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self): opus = Rung("claude-opus-5-5", "medium") markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium." - self.assertIn(markdown, prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 7), OPUS_PROJECT, self.FACTS)) - self.assertIn(markdown, prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertNotIn("only Markdown", prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) + self.assertIn(markdown, fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 7), OPUS_PROJECT, self.FACTS)) + self.assertIn(markdown, fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) + self.assertNotIn("only Markdown", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self): opus = Rung("claude-opus-5-5", "medium") both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`." - self.assertTrue(prompts.WORKER.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT).endswith(both)) - self.assertTrue(prompts.WORKER.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT).endswith(both)) - self.assertTrue(prompts.WORKER.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both)) - self.assertTrue(prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`.")) - self.assertTrue(prompts.WORKER.resumed("", Route(opus, 3, 2, 7), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`.")) - self.assertTrue(prompts.WORKER.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`.")) - self.assertNotIn("rerun", prompts.WORKER.resumed("", Route(Rung("m")), None)) - self.assertNotIn("rerun", prompts.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)) - self.assertIn(f"{both} After your first read", prompts.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) + self.assertTrue(fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT).endswith(both)) + self.assertTrue(fresh_prompt.WORKER.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT).endswith(both)) + self.assertTrue(fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both)) + self.assertTrue(fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`.")) + self.assertTrue(fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 7), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`.")) + self.assertTrue(fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`.")) + self.assertNotIn("rerun", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) + self.assertNotIn("rerun", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)) + self.assertIn(f"{both} After your first read", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) fable = Rung("claude-fable-5-2", "max") - self.assertNotIn("rerun", prompts.WORKER.resumed("", Route(fable), ProjectRung(LADDER, fable))) + self.assertNotIn("rerun", fresh_prompt.WORKER.resumed("", Route(fable), ProjectRung(LADDER, fable))) def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects")) - fresh = worker.worker_args(opened, Rung("m"), prompts.WORKER.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, self.FACTS), resume=False) + fresh = worker.worker_args(opened, Rung("m"), fresh_prompt.WORKER.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, self.FACTS), resume=False) self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id)) self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude") - resumed = worker.worker_args(opened, Rung("m"), prompts.WORKER.resumed("", Route(Rung("m")), None), resume=True) + resumed = worker.worker_args(opened, Rung("m"), fresh_prompt.WORKER.resumed("", Route(Rung("m")), None), resume=True) self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id)) self.assertNotIn("--session-id", resumed) self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once")) @@ -2117,84 +1442,10 @@ class WorkerArgs(unittest.TestCase): self.assertEqual(args[args.index("--disallowedTools") + 1], "ScheduleWakeup") -class Records(unittest.TestCase): - def test_heads_each_record_by_its_name_the_humans_rules_last(self): - with tempfile.TemporaryDirectory() as root: - claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") - config = configured(self, pathlib.Path(root), home=claude_md.parents[1]) / "config.toml" - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "") - claude_md.parent.mkdir(parents=True) - claude_md.write_text("# Global\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "From ~/.claude/CLAUDE.md:\n# Global") - pathlib.Path(root, "docs").mkdir() - pathlib.Path(root, "docs", "decisions.md").write_text("# Decisions\n") - pathlib.Path(root, "AGENTS.md").write_text("\n# Rules\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global") - pathlib.Path(claude_md.parent, "rules").mkdir() - pathlib.Path(claude_md.parent, "rules", "todo-items.md").write_text("# Todo\n") - pathlib.Path(claude_md.parent, "rules", "goals-and-audience.md").write_text("# Goals\n") - pathlib.Path(claude_md.parent, "rules", "notes.txt").write_text("not a rule\n") - pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True) - pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments")) - config.write_text(config.read_text().replace('"~/.claude/skills/larv-review/standards"', '"~/review-standards"')) - pathlib.Path(claude_md.parents[1], "review-standards").mkdir() - pathlib.Path(claude_md.parents[1], "review-standards", "quality.md").write_text("# Ours\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/review-standards/quality.md:\n# Ours"), "the config's standards folder replaces the default") - config.write_text(config.read_text().replace('"~/review-standards"', f'"{root}/standards"')) - pathlib.Path(root, "standards").mkdir() - pathlib.Path(root, "standards", "quality.md").write_text("# Elsewhere\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"), "a folder outside home is named in full") - - config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"').replace('"checkout:docs/decisions.md"', '"folder:log/decisions.md"')) - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"), "the checkout's AGENTS.md and docs/decisions.md are its owners'") - pathlib.Path(config.parent, "log").mkdir() - pathlib.Path(config.parent, "log", "decisions.md").write_text("# Ours\n") - pathlib.Path(config.parent, "AGENTS.md").write_text("# Our rules\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From AGENTS.md:\n# Our rules\n\nFrom docs/decisions.md:\n# Ours\n\nFrom ~/.claude/CLAUDE.md:\n# Global")) - config.unlink() - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"no config names the checkout {root}: write ~/.claude-projects//config.toml, as `project-config --help` shows - the judge cannot read the records.")) - - def test_puts_the_records_handed_in_first_and_reads_only_the_humans_rules_without_a_checkout(self): - with tempfile.TemporaryDirectory() as root: - claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") - configured(self, pathlib.Path(root), home=claude_md.parents[1]) - claude_md.parent.mkdir(parents=True) - claude_md.write_text("# Global\n") - pathlib.Path(claude_md.parent, "rules").mkdir() - pathlib.Path(claude_md.parent, "rules", "todo-items.md").write_text("# Todo\n") - pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True) - pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n") - pathlib.Path(root, "AGENTS.md").write_text("# Rules\n") - first = (("the epic ABC-1's description, ## Decisions", "Squash.\n"), ("the epic ABC-1's description, ## Scoring", " \n")) - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom AGENTS.md:\n# Rules\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments") - self.assertEqual(records.read_records(None, claude_md.parents[1], claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo") - - def test_stops_on_a_record_it_cannot_read(self): - with tempfile.TemporaryDirectory() as root: - claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") - configured(self, pathlib.Path(root), home=claude_md.parents[1]) - claude_md.mkdir(parents=True) - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records.")) - pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True) - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"cannot read {root}/docs/decisions.md: Is a directory - the judge cannot read the records.")) - pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records.")) - - - def test_stops_on_a_rule_it_cannot_read(self): - with tempfile.TemporaryDirectory() as root: - claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") - configured(self, pathlib.Path(root), home=claude_md.parents[1]) - rules = pathlib.Path(claude_md.parent, "rules") - rules.mkdir(parents=True) - pathlib.Path(rules, "todo-items.md").write_bytes(b"\xff\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records.")) - class JudgePrompt(unittest.TestCase): def test_shows_the_transcripts_tail_and_returns_what_it_showed(self): entries = [assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})] - prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 0, prompts.DRIVER)) + prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 0, fresh_prompt.DRIVER)) self.assertTrue(grounds.shown.endswith("\n\nnew")) self.assertNotIn("old", grounds.shown) self.assertIn(grounds.shown, prompt) @@ -2203,167 +1454,48 @@ class JudgePrompt(unittest.TestCase): self.assertEqual(grounds.quotable, "## Goals\n\n") def test_the_judge_prompt_and_schema_call_the_worker_the_worker(self): - prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(assistant({"type": "text", "text": "done"})), 1, prompts.DRIVER)) - self.assertNotRegex(prompt + json.dumps(judge.judge_schema(prompts.DRIVER)), r"\b[Aa]gent") + prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(assistant({"type": "text", "text": "done"})), 1, fresh_prompt.DRIVER)) + self.assertNotRegex(prompt + json.dumps(judge.judge_schema(fresh_prompt.DRIVER)), r"\b[Aa]gent") def test_the_judge_prompt_names_the_entry_points_answer_destinations_in_both_rules_on_a_recorded_answer(self): - prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, "the ledger", kinds(assistant({"type": "text", "text": "done"})), 0, prompts.DRIVER)) + prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, "the ledger", kinds(assistant({"type": "text", "text": "done"})), 0, fresh_prompt.DRIVER)) self.assertIn("is recorded in the ledger at the one place it governs", prompt) self.assertIn("the worker writing it into the ledger, but not into one of the human's rules", prompt) def test_the_typed_answers_prompt_names_the_entry_points_answer_destinations(self): - ledger = dataclasses.replace(prompts.WORKER, answer_destinations="the ledger") + ledger = dataclasses.replace(fresh_prompt.WORKER, answer_destinations="the ledger") self.assertIn("is recorded in the ledger at the one place it governs.", ledger.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)) def test_the_judge_prompt_names_every_rule_the_judge_reads_from_the_human(self): - self.assertEqual([name for name in records.HUMAN_RULE_NAMES if name not in judge.judge_rules(prompts.ANSWER_DESTINATIONS, prompts.DRIVER)], []) + self.assertEqual([name for name in records.HUMAN_RULE_NAMES if name not in judge.judge_rules(prompts.ANSWER_DESTINATIONS, fresh_prompt.DRIVER)], []) def test_shows_the_judge_where_the_worker_last_stepped_up_and_checks_an_escalation_only_after_it(self): entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"})] - prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, prompts.DRIVER)) + prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, fresh_prompt.DRIVER)) self.assertRegex(prompt, "round 2: 🔴\n\n\\[step\\] [^\n]+\n\nround 3: 🔴\n\n") self.assertEqual(grounds.after_mark, "round 3: 🔴") - prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 0, prompts.DRIVER)) + prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 0, fresh_prompt.DRIVER)) self.assertNotIn("stepped the worker up", prompt) self.assertEqual(grounds.shown, "round 2: 🔴\n\nround 3: 🔴") self.assertEqual(grounds.after_mark, "round 2: 🔴\n\nround 3: 🔴") def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self): entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})] - _, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, prompts.DRIVER)) + _, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, fresh_prompt.DRIVER)) self.assertEqual(judge.quotes_checked(Unfinished("e", "old x", entries_read=3), grounds), Unfinished("e", entries_read=3)) self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3)) def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self): - typed = prompts.WORKER.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False) + typed = fresh_prompt.WORKER.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False) entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})] - _, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, prompts.DRIVER)) + _, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, fresh_prompt.DRIVER)) self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown) -def turn(message_id, model, at, **usage): - return entries.AssistantTurn(message_id=message_id, model=model, timestamp=at, usage=usage) - - -class Spend(unittest.TestCase): - def test_reads_the_cache_writes_by_lifetime_and_counts_one_without_the_split_as_five_minutes(self): - self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5}), Tokens(1, 2, 3, 4, 5)) - self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9}), Tokens(1, 9, 0, 0, 0)) - self.assertEqual(tokens_of(None), Tokens()) - - def test_counts_a_messages_context_as_every_prompt_token_and_no_output(self): - self.assertEqual(Tokens(1, 2, 3, 4, 5).context(), 10) - - def test_counts_a_message_written_in_the_stamped_second_or_without_a_readable_time_as_before_since(self): - thread = [turn("m1", "a", "2026-11-01T10:00:01Z", output_tokens=7), turn("m2", "a", "not a time", output_tokens=3), turn("m3", "a", "2026-11-01T10:00:02Z", output_tokens=1)] - self.assertEqual(spend.spent("2026-11-01T10:00:01Z", thread, [], "j", Tokens()), {("worker", "a"): Tokens(output=1)}) - - def test_sums_two_subagents_of_one_name_on_one_model(self): - helpers = [spend.Subagent("Explore", [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]), spend.Subagent("Explore", [turn("s2", "b", "2026-11-01T10:00:00Z", input_tokens=4)])] - self.assertEqual(spend.spent("", [], helpers, "j", Tokens()), {("Explore", "b"): Tokens(input=7)}) - - def test_counts_each_message_once_by_its_id_and_only_after_since(self): - thread = [ - turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7), - turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2), - turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2), - turn("m3", "b", "2026-11-01T10:00:03Z", cache_read_input_tokens=5), - ] - self.assertEqual(spend.thread_spend(thread, "2026-11-01T10:00:01Z"), {"a": Tokens(1, 0, 0, 0, 2), "b": Tokens(0, 0, 0, 5, 0)}) - self.assertEqual(spend.thread_spend(thread, ""), {"a": Tokens(1, 0, 0, 0, 9), "b": Tokens(0, 0, 0, 5, 0)}) - - def test_names_each_spender_and_leaves_out_one_that_spent_nothing(self): - worker = [turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7)] - helper = spend.Subagent('Explore "Search"', [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]) - self.assertEqual(spend.spent("", worker, [helper], "j", Tokens()), {("worker", "a"): Tokens(output=7), ('Explore "Search"', "b"): Tokens(input=3)}) - self.assertEqual(spend.spent("", [], [], "j", Tokens(input=1)), {("judge", "j"): Tokens(input=1)}) - - def test_names_a_subagent_by_its_agent_type_and_description(self): - with tempfile.TemporaryDirectory() as root: - folder = pathlib.Path(root, "s", "subagents") - folder.mkdir(parents=True) - for name, meta in [("agent-a", {"agentType": "Explore", "description": "Search the hooks"}), ("agent-b", None), ("agent-c", ["Explore"]), ("agent-d", {"description": "Läs"}), ("agent-e", {"agentType": "Ex\nConfig: x"})]: - (folder / f"{name}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"id": name, "model": "m", "content": [], "usage": {"output_tokens": 1}}, "timestamp": "2026-11-01T10:00:00Z"}) + "\n") - if meta: - (folder / f"{name}.meta.json").write_text(json.dumps(meta)) - found = spend.subagents(str(pathlib.Path(root, "s.jsonl"))) - self.assertEqual([subagent.name for subagent in found], ['Explore "Search the hooks"', "subagent", "subagent", 'subagent "Läs"', "Ex Config: x"]) - self.assertEqual(spend.spent("", [], found[:2], "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)}) - self.assertEqual(spend.subagents(str(pathlib.Path(root, "none.jsonl"))), []) - - def test_renders_the_spend_then_the_list_prices_of_each_model_it_knows(self): - found = {("worker", "claude-opus-5-5"): Tokens(1, 2, 3, 4, 5), ("judge", "unpriced"): Tokens(input=6)} - self.assertEqual(outcomes.spent_block("2026-11-01T10:00:00Z", found), """Spent since 2026-11-01T10:00:00Z, in tokens of input, cache write 5m, cache write 1h, cache read, output: -- worker, claude-opus-5-5: 1, 2, 3, 4, 5 -- judge, unpriced: 6, 0, 0, 0, 0 - -List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output: -- claude-opus-5-5: 4, 5, 8, 0.2, 20""") - self.assertEqual(outcomes.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0") - self.assertEqual(outcomes.spent_block("", {}), "") - - def test_keeps_the_whole_typed_answer_that_holds_the_judges_quote_and_its_tokens(self): - shown = "[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name" - typed = ("Use A.", "No, keep the old name. Use X.") - for quoted, kept in [("No, keep the old name. Use X.", "No, keep the old name. Use X."), ("keep the old name", "No, keep the old name. Use X."), ("Use", "No, keep the old name. Use X."), ("keep the new name", ""), ("No, keep the name.", "")]: - with self.subTest(quoted=quoted): - answer = json.loads(judged("unfinished", reversed=quoted).stdout) - fake = FakeEffects(claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 2, "output_tokens": 3}}))]) - self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds(shown, shown, "", typed), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept))) - - -class SetupVersion(unittest.TestCase): - def test_names_the_release_and_the_commit_or_why_git_cannot_tell(self): - with tempfile.TemporaryDirectory() as root: - isolated = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root} - with unittest.mock.patch.dict(os.environ, isolated): - gone = main.setup_version(pathlib.Path(root), git) - self.assertRegex(gone, r"^unknown: [^\n]*not a git repository") - for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]): - self.assertIsInstance(git(*step, cwd=root), str) - head = git("rev-parse", "HEAD", cwd=root).strip() - self.assertEqual(main.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})") - git("tag", "v0.1.0", cwd=root) - self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})") - git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root) - head = git("rev-parse", "HEAD", cwd=root).strip() - self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})") - - def test_names_why_git_cannot_name_the_commit_on_one_line(self): - def fake_git(*args, cwd=None): - return Failure("fatal: bad HEAD\nhint: repair it") if args[0] == "rev-parse" else "v0.1.0\n" - - self.assertEqual(main.setup_version(pathlib.Path("/r"), fake_git), "unknown: fatal: bad HEAD hint: repair it") - - -class Grounded(unittest.TestCase): - def test_every_verdict_must_quote_the_transcript(self): - self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n")) - self.assertFalse(judge.grounded("invented", "the transcript")) - self.assertFalse(judge.grounded("", "the transcript")) - self.assertFalse(judge.grounded(" ", "the transcript")) - transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it." - self.assertTrue(judge.grounded("Your step:\n```\n./run.sh\n```\nRun it.", transcript)) - self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript)) - self.assertFalse(judge.grounded("**", transcript)) - - def test_an_elided_quote_holds_when_its_fragments_appear_in_order(self): - transcript = "**Decision for you:** security, or not.\n\nI recommend one more round of each.\n\nI recommend skipping it: it costs." - self.assertTrue(judge.grounded("**Decision for you:** security, … ... I recommend one more round of each ... I recommend skipping it: …", transcript)) - self.assertFalse(judge.grounded("I recommend skipping it ... Decision for you", transcript)) - self.assertFalse(judge.grounded("Decision for you ... invented", transcript)) - self.assertFalse(judge.grounded("... …", transcript)) - self.assertTrue(judge.grounded("a ... b ... c", "x a b a c")) - - # Item 297 scores the higher L, item 298 the higher E + I. SCORED = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 297 | 0.8.0 | | **Do it.** | 4 | 2 | 3 | 7 | 2 | 1 by 9 | 25 |\n| 298 | 0.8.0 | | **Do more.** | 3 | 3 | 4 | 8 | 2 | 1 by 9 | 20 |\n" -def said(*texts): - return entries.AssistantTurn(parts=tuple(entries.Text(text) for text in texts)) - - class ChunkItems(unittest.TestCase): def test_names_the_items_on_the_workers_latest_chunk_items_line(self): earlier = said("Chunk items: 297 (L 3, E + I 5)") @@ -2374,11 +1506,11 @@ class ChunkItems(unittest.TestCase): self.assertEqual(chunk_items.named([said("Chunk items: 297 and 298 (L 3, E + I 7)")]), (297, 298)) def test_reads_the_example_line_the_prompt_gives_the_worker(self): - example = re.search(r"`(Chunk items:[^`]*)`", prompts.NAME_THE_ITEMS)[1] + example = re.search(r"`(Chunk items:[^`]*)`", fresh_prompt.NAME_THE_ITEMS)[1] self.assertEqual(chunk_items.named([said(example)]), (297, 298)) def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self): - self.assertIn("on one line, as in `Chunk items: ", prompts.WORKER.resumed("", Route(Rung("m")), None)) + self.assertIn("on one line, as in `Chunk items: ", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self): prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)") @@ -2396,95 +1528,6 @@ class ChunkItems(unittest.TestCase): self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], plan_of("no items table")), TakenIn()) -class Verdict(unittest.TestCase): - def test_needs_every_field_the_schema_requires(self): - self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Finished("e")) - self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Unfinished("e")) - self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?")) - self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True)) - self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "reversed": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean")) - self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A.")) - self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?")) - self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge quoted an answer without a question")) - self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean")) - self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string")) - self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge interrupted without a question")) - self.assertEqual(verdict_from(None), Failure("the judge returned no reply")) - - def test_carries_the_earlier_answer_an_interrupt_names(self): - reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?", "reversed": ""} - self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", answered_before="Grant one more round.", left_open="one more")) - self.assertEqual(verdict_from({**reply, "interrupt": False, "finished": True}), Finished("e")) - - def test_takes_an_escalation_quote_on_an_unfinished_verdict(self): - reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False} - self.assertEqual(verdict_from(reply), Unfinished("e", "round 2: 🔴")) - self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e")) - self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string")) - - def test_takes_an_escalation_quote_on_an_interrupt(self): - reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False} - self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴")) - - def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self): - shown = "The agent: round 2: 🔴. Which one?" - self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q", "round 2: 🔴")) - self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: … 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q")) - self.assertEqual(judge.quotes_checked(Unfinished("e", "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e")) - - def test_turns_an_interrupt_that_re_asks_a_human_answer_into_that_answer_quoted_back(self): - answer = "Grant one more round; ask again if a 🔴 survives it." - shown = f"[loop] Asked.\n\n[human] {answer}\n\n[step] Round 2: a 🔴 survived." - grounds = judge.Grounds(shown, shown, "") - asking = "Grant a third round? Your answer left open: a 🔴 survives it" - kept = Interrupt("[step] Round 2", asking, answered_before=answer, left_open="a 🔴 survives it") - self.assertEqual(judge.quotes_checked(kept, grounds), kept) - re_asked = Interrupt("[step] Round 2", "Grant a third round?", "Round 2: a 🔴", answered_before=answer, left_open="a 🔴 survives it") - self.assertEqual(judge.quotes_checked(re_asked, grounds), Unfinished(answer, "Round 2: a 🔴")) - self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open=""), grounds), Unfinished(answer)) - self.assertEqual(judge.quotes_checked(dataclasses.replace(kept, left_open="a 🔴 survived"), grounds), Unfinished(answer)) - invented = dataclasses.replace(re_asked, answered_before="Grant two more rounds.") - self.assertEqual(judge.quotes_checked(invented, grounds), invented) - unnamed = Interrupt("[step] Round 2", "Grant a third round?") - self.assertEqual(judge.quotes_checked(unnamed, grounds), unnamed) - - def test_takes_an_escalation_quote_on_a_quoted_answer(self): - reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False} - self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴")) - - def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self): - shown = "The agent: round 2: 🔴. Which one?" - self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.", "round 2: 🔴")) - self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.")) - - def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self): - self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴"), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴")) - - def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self): - self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("s", "q")) - self.assertEqual(judge.quotes_checked(QuotedAnswer("s", "q", "the records"), judge.Grounds("shown", "shown", "From the records: the records")), QuotedAnswer("s", "q", "the records")) - - def test_drops_an_escalation_quote_found_only_in_the_transcript_entries_before_the_workers_last_step_up(self): - entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})] - def judged_on(mark, escalation): - return judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), mark, prompts.DRIVER), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects()) - self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", "round 2: 🔴", entries_read=3)) - self.assertEqual(judged_on(1, "round 2: 🔴"), Unfinished("working", entries_read=3)) - self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", "round 3: 🔴", entries_read=3)) - self.assertEqual(judged_on(1, "round 2: 🔴\n\nround 3: 🔴"), Unfinished("working", entries_read=3)) - self.assertEqual(judged_on(3, "round 3: 🔴"), Unfinished("working", entries_read=3)) - - def test_drops_an_escalation_quote_that_only_loop_claudes_prompts_or_the_humans_lines_repeat_after_the_step_up(self): - entries = [assistant({"type": "text", "text": "round 2: 🔴"}), {**human("as the work remaining: round 2: 🔴"), "promptSource": "sdk"}, human("round 2: 🔴 again"), assistant({"type": "text", "text": "working"})] - verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, prompts.DRIVER), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects()) - self.assertEqual(verdict, Unfinished("working", entries_read=4)) - - def test_takes_evidence_from_before_the_workers_last_step_up(self): - entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "working"})] - verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, prompts.DRIVER), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects()) - self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2)) - - class LoopRuns(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "", "unfinished_evidence": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1, "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "unfinished_evidence": ""})]): @@ -2731,8 +1774,8 @@ class HelpLimits(unittest.TestCase): self.assertIn(f"Once {state.CYCLES_PER_CHECK} cycles have closed across all projects", said) self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said) self.assertIn(f"{BASH_CEILING_CHARACTERS:,} characters", said) - self.assertIn(f"unfinished {close.UNFINISHED_LIMIT} cycles running", said) - self.assertIn(f"rerun to give it {close.UNFINISHED_LIMIT} more", said) + self.assertIn(f"unfinished {chunk_run.UNFINISHED_LIMIT} cycles running", said) + self.assertIn(f"rerun to give it {chunk_run.UNFINISHED_LIMIT} more", said) class OwnLadder(unittest.TestCase): @@ -2763,7 +1806,13 @@ class ExitContract(unittest.TestCase): ("agent_cycle/run.py", "close", "1", "annotation.reason", read), ("agent_cycle/run.py", "close", "1", "failure.reason", read), ("agent_cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"), - ("loop_claude/loop/close.py", "closed_cycle", "1", "failure.reason", read), + ("chunk_driver/chunk_run.py", "closed_cycle", "1", "failure.reason", read), + ("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_), + ("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"), ("loop_claude/loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"), @@ -2771,20 +1820,14 @@ class ExitContract(unittest.TestCase): ("loop_claude/loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"), ("loop_claude/loop/main.py", "next_cycle", "1", "premises.reason", premises_), ("loop_claude/loop/main.py", "next_cycle", "1", "records.reason", unreadable), - ("loop_claude/loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_), - ("loop_claude/loop/main.py", "next_cycle", "1", "ladder.reason", "the project's routing ladder cannot be read or holds a fault"), ("loop_claude/loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"), ("loop_claude/loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"), ("loop_claude/loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"), ("loop_claude/loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {loop.paths.config_clone}", "claude cannot start for an interrupt"), - ("loop_claude/project/checkout.py", "checkout_root", "1", "found.reason", git), - ("loop_claude/project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_), - ("loop_claude/project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_), - ("loop_claude/project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_), ] root = pathlib.Path(main.__file__).parents[2] found = [] - for path in sorted(path for package in ("agent_cycle", "loop_claude") for path in (root / package).rglob("*.py") if not path.name.startswith("test_")): + for path in sorted(path for package in ("agent_cycle", "chunk_driver", "loop_claude") for path in (root / package).rglob("*.py") if not path.name.startswith("test_")): functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)] stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))] found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)] diff --git a/bin/loop_effects/test_doubles.py b/bin/loop_effects/test_doubles.py new file mode 100644 index 00000000..7711cd55 --- /dev/null +++ b/bin/loop_effects/test_doubles.py @@ -0,0 +1,190 @@ +"""Test doubles for the suites that run cycles: FakeEffects stands in for loop_effects.effects.Effects, Worker and Streamed for a worker's claude, and judged for a judge's reply.""" +import json +import pathlib +import subprocess +import uuid + +from loop_effects.effects import Effects +from claude_code import entries +from machine_load import memory + + +CWD = pathlib.Path("/c") +NOW = 1790000000 +def assistant(*parts): + return {"type": "assistant", "message": {"content": list(parts)}} + + +def human(content): + return {"type": "user", "message": {"content": content}} + + +# The window the loops under test run in. +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=(), dm_failures=(), tmux_version="tmux 3.2", windows=None, owner="/r"): + self.calls = [] + # Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session. + self.tmux_calls = [] + self.tmux_version = tmux_version + self.windows = windows + # The checkout the session's @loop-root option names. + self.owner = owner + # Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent. + self.dms = [] + # The directory each DM named, in the order of self.dms; None where it named none. + self.dm_directories = [] + self.dm_failures = list(dm_failures) + 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) + self.terminal = on_terminal + self.worker_environments = [] + self.worker_folders = [] + self.terminal_environments = [] + self.terminal_folders = [] + # Each timer started, as its delay and action, which a test runs where the timer fires. + self.timers = [] + + def effects(self): + return Effects( + 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)), + dm=self.dm, + execv=self.execv, + git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)), + input=lambda prompt: self.answer("input", prompt), + local_time=lambda seconds: f"<{seconds}>", + memory=self.memory, + now=lambda: NOW, + on_terminal=lambda: self.terminal, + python=lambda args, cwd: self.answer("python", (args, cwd)), + sleep=lambda seconds: self.calls.append(("sleep", seconds)), + stream_claude=self.stream, + timer=self.timer, + tmux=self.tmux, + tmux_on_terminal=lambda args: self.tmux(args).returncode, + ) + + def timer(self, delay, action): + self.timers.append((delay, action)) + return lambda: self.calls.append(("stop_timer", delay)) + + def tmux(self, args): + self.tmux_calls.append(args) + if args[0] == "list-windows": + return subprocess.CompletedProcess(args, 1 if self.windows is None else 0, self.windows or "", "no server") + return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n", "show-options": self.owner + "\n"}.get(args[0], "@9\n"), "") + + def dm(self, text, directory): + self.dms.append(text) + self.dm_directories.append(directory) + return self.dm_failures.pop(0) if self.dm_failures else None + + def memory(self): + self.calls.append(("memory", None)) + return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16) + + def on_terminal_claude(self, args, cwd, env): + self.terminal_environments.append(env) + self.terminal_folders.append(cwd) + return self.answer("claude_on_terminal", args) + + def stream(self, args, cwd, env): + self.worker_environments.append(env) + self.worker_folders.append(cwd) + return self.answer("stream_claude", args) + + def answer(self, seam, what): + self.calls.append((seam, what)) + answer = self.scripts[seam].pop(0) + if isinstance(answer, BaseException): + raise answer + return answer(what) if callable(answer) else answer + + def execv(self, path, args): + self.calls.append(("execv", args)) + raise OSError(2, "No such file or directory") + + def made(self, seam): + return [what for called, what in self.calls if called == seam] + + +def ran(stdout="", code=0, stderr=""): + return subprocess.CompletedProcess([], code, stdout, stderr) + + +def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""): + reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed} + return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})})) + + +class Worker: + """A worker claude: writes a line to the session's transcript, then streams a result.""" + + def __init__(self, home, prompted=False, text="working", usage=None, sent=None): + self.home = home + # Whether it records its -p prompt in the transcript first, as claude does. + self.prompted = prompted + self.text = text + # The usage its message records, twice as Claude Code writes a message of two blocks; none where None. + self.usage = usage + # The time its message records, as utc() writes it; none where None. + self.sent = sent + + def __call__(self, args): + flag = "--session-id" if "--session-id" in args else "--resume" + path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl" + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "a") as handle: + if flag == "--session-id": + handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid7())}) + "\n") + if self.prompted: + handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n") + said = assistant({"type": "text", "text": self.text}) + if self.usage is not None: + said["message"] |= {"id": "msg-1", "model": "claude-opus-5-5", "usage": self.usage} + if self.sent is not None: + said["timestamp"] = self.sent + handle.write((json.dumps(said) + "\n") * (1 if self.usage is None else 2)) + return Streamed(0) + + +class Streamed: + """A started claude. An event of None is an idle stretch of CHECK_EVERY seconds, which advances `clock` by that; `held` are the shells it has, and `stopped` collects the ones stopped.""" + + def __init__(self, code, *events, clock=None, held=()): + self.code = code + self.events = events or ({"type": "result"},) + self.clock = clock + self.held = list(held) + self.stopped = [] + + def lines(self, idle): + for event in self.events: + if event is None: + self.clock[0] += idle + yield None if event is None else json.dumps(event) + "\n" + + def shells(self): + return self.held + + def stop(self, shell): + self.stopped.append(shell) + + def wait(self): + return self.code + + +# How a line said at NOW opens, with FakeEffects' local_time. +STAMP = f"<{NOW}>" + + +def kinds(*found): + return [entries.entry_from(entry) for entry in found] + + +def said(*texts): + return entries.AssistantTurn(parts=tuple(entries.Text(text) for text in texts)) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index 49da7a71..fd5d5032 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -5,7 +5,6 @@ An item is an open child issue. Its ID is the issue's number, so every child mus `add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, and its links to the epic's other open items. Of an issue a person filed it sets only the scores, with a comment that tells the team why.""" import dataclasses import pathlib -import re import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused @@ -13,6 +12,7 @@ from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE from plan_store.markdown_edits import bold_cell, plain, unfit_text from plan_store.plans import cells, no_item, Plan, Written +from atlassian.jira import entry_of, finishing_transition, ISSUE_KEY, Link, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from failure import Failure from plan.release import parsed, Release, tagged @@ -20,10 +20,6 @@ from plan import ranking # The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}. PROPERTY = "plan-item" -ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)") -PAGE = 100 -# The pages one read asks for at most, so an answer that never names a last page ends the read. -MAX_PAGES = 100 # The key in PROPERTY's value that marks an issue the loop filed, and its value. An edit of an issue without it, which a person filed, writes only PROPERTY and a comment. FILED_BY = ("Filed by", "loop") # The issue type of an issue the loop files, which Jira Software's project templates all have; a project without it refuses the issue, saying so. @@ -31,12 +27,6 @@ ISSUE_TYPE = "Task" # The name of the link type whose inward side reads "is blocked by", as Jira Cloud ships it. BLOCKS = "Blocks" SECURITY = "security" -# The key of the status category Jira Cloud gives every done status. -DONE = "done" -# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue. -PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {epic} before filing the item again" -# What a failed move ends with, for the same reason. -PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again" # What a failed edit ends with, for the same reason. PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at {key} before editing the item again" # The scores a caller sets, L, E, I and S; R is worked out from them. @@ -50,15 +40,6 @@ class ReadsScoring(typing.Protocol): """The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give.""" -@dataclasses.dataclass(frozen=True) -class Link: - """One "is blocked by" link of an issue.""" - # The key of the issue that blocks. - blocker: str - # The link's own id, which Jira deletes it by. - id: str - - @dataclasses.dataclass(frozen=True) class Issue: """A child issue as Jira answered it, checked to hold what an item is read from.""" @@ -142,10 +123,10 @@ class JiraPlan: before = placing(answered, filing.item, value, scoring) created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]}) if isinstance(created, Failure): - return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(epic=self.epic.key)}") + return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(under=self.epic.key)}") key = created.get("key") if isinstance(created, dict) else None if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key) or project_of(key) != project_of(self.epic.key): - return Failure(f"Jira answered the new issue without an issue key in {project_of(self.epic.key)}; {PERHAPS_FILED.format(epic=self.epic.key)}") + return Failure(f"Jira answered the new issue without an issue key in {project_of(self.epic.key)}; {PERHAPS_FILED.format(under=self.epic.key)}") return Written(number(key), self.linked_and_ranked(key, filing.blockers, before, authorization)) def linked_and_ranked(self, key: str, blockers: tuple[str, ...], before: str | None | Failure, authorization: str) -> tuple[str, ...]: @@ -395,54 +376,6 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment return Revision(body, release, tuple(dict.fromkeys(f"{project_of(issue.key)}-{blocker}" for blocker in checked.blocked_by)) if BLOCKED_BY in named else None) -def offer_of(raw: object) -> tuple[str, str, str, str] | None: - """One transition Jira offers, as its ID, its name, the name of the status it leads to and the key of that status's category; None where raw holds no such transition.""" - to = raw.get("to") if isinstance(raw, dict) else None - category = to.get("statusCategory") if isinstance(to, dict) else None - if not isinstance(raw, dict) or not isinstance(to, dict) or not isinstance(category, dict): - return None - id_, name, status, key = raw.get("id"), raw.get("name"), to.get("name"), category.get("key") - return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None - - -def finishing_transition(site: str, key: str, finish: Finish, authorization: str, http: Http) -> str | Failure: - """The ID of the transition finish names, as Jira offers it now for the issue named key, which is a plan item or an epic; or why none of those offered finishes it.""" - offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None) - if isinstance(offered, Failure): - return Failure(f"cannot read {key}'s transitions: {offered.reason}") - return transition_of(offered, key, finish) - - -def move_refusal(site: str, key: str, transition: str, finish: Finish, authorization: str, http: Http) -> str | None: - """Moves the issue named key by the transition with the ID transition, which finishing_transition answered for finish. Why Jira did not take the move; None where it did.""" - moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": transition}}) - return f"cannot move {key} by {finish.transition!r}: {moved.reason}" if isinstance(moved, Failure) else None - - -def transition_of(offered: object, key: str, finish: Finish) -> str | Failure: - """The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item.""" - raw = offered.get("transitions") if isinstance(offered, dict) else None - found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else [] - if not isinstance(raw, list) or len(found) != len(raw): - return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents") - named = [each for each in found if each[1] == finish.transition] - if not named: - others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found) - return Failure(f"{key} has no transition {finish.transition!r} from its status, " + (f"only {others}: move the issue in Jira to a status that has it, or name in `{JIRA_FINISH_TRANSITION}` one that leads to a done status" if found else "nor any other the account may make")) - id_, _, status, category = next((each for each in named if each[2] == finish.status), named[0]) - if status != finish.status: - return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, not to {finish.status!r}, which `{JIRA_FINISH_STATUS}` names") - # `children` reads an issue as finished by its status's category, so a move to any other category would leave the item in the plan. - if category != DONE: - return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status") - return id_ - - -def project_of(key: str) -> str: - """The key of the Jira project an issue key lies in.""" - return key.rpartition("-")[0] - - def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure: """The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan.""" # The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart. @@ -452,46 +385,16 @@ def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failu return searched(epic.site, f"{epic.key}'s children", f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC', {"fields": ["summary", "description", "fixVersions", "issuelinks"], "properties": [PROPERTY]}, authorization, http) -def rank_refusal(site: str, key: str, before: str, authorization: str, http: Http) -> str | None: - """Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors.""" - answer = http("PUT", f"{site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before}) - if isinstance(answer, Failure): - return answer.reason - entries = answer.get("entries") if isinstance(answer, dict) else None - refused = [entry for entry in entries if isinstance(entry, dict) and entry.get("status") != 200] if isinstance(entries, list) else [] - return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None - - -def searched(site: str, what: str, jql: str, asked: dict[str, object], authorization: str, http: Http) -> list[object] | Failure: - """Every issue a JQL search on site finds, page by page. The dict asked holds the request's `fields` and `properties` lists. The text what names the issues sought, in the Failure of a search that doesn't end.""" - body: dict[str, object] = {"jql": jql, "maxResults": PAGE} | asked - found: list[object] = [] - for _ in range(MAX_PAGES): - page = http("POST", f"{site}/rest/api/3/search/jql", authorization, body) - if isinstance(page, Failure): - return page - if not isinstance(page, dict) or not isinstance(page.get("issues"), list): - return Failure("the search answered something other than a page of issues") - found += page["issues"] - if not page.get("nextPageToken"): - return found - body = body | {"nextPageToken": page["nextPageToken"]} - return Failure(f"the search for {what} did not end within {MAX_PAGES} pages") - - def issue_of(raw: object) -> Issue | Failure: """The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how.""" - key = raw.get("key") if isinstance(raw, dict) else None - if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): - return Failure("the search answered an issue without an issue key") - # The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it. + entry = entry_of(raw, PROPERTY) + if isinstance(entry, Failure): + return entry + key, fields, links, held = entry.key, entry.fields, entry.links, entry.held try: - fields = raw["fields"] - links = blocked_by_links(fields) - held = raw.get("properties", {}).get(PROPERTY, {}) summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]) except (AttributeError, KeyError, TypeError) as failure: - return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") + return Failure(unshaped(key, failure)) if not isinstance(held, dict): return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") issue = Issue(key, summary, description, versions, links, held) @@ -500,11 +403,6 @@ def issue_of(raw: object) -> Issue | Failure: return issue -def blocked_by_links(fields: dict[str, typing.Any]) -> tuple[Link, ...]: - """The "is blocked by" links among an issue's `issuelinks` field. A field not in the shape Jira documents raises a KeyError or TypeError, which the caller turns into a Failure.""" - return tuple(Link(link["inwardIssue"]["key"], link["id"]) for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by") - - def keys_of(answered: list[object]) -> set[object]: """The key of each issue in the search's answer.""" return {raw.get("key") for raw in answered if isinstance(raw, dict)} diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 4b1425f4..821e37f9 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -171,7 +171,7 @@ class JiraPlan(unittest.TestCase): def test_a_search_that_never_names_a_last_page_fails_the_read(self): self.pages = [{"issues": [], "nextPageToken": "more"}] * 2 - with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 2): + with unittest.mock.patch("atlassian.jira.MAX_PAGES", 2): self.assertEqual(self.store().read(), Failure("the search for ABC-12's children did not end within 2 pages")) def test_an_issue_in_another_shape_fails_the_read_naming_it(self): @@ -224,7 +224,7 @@ class JiraPlan(unittest.TestCase): ISSUES = "https://acme.atlassian.net/rest/api/3/issue" LINKS = "https://acme.atlassian.net/rest/api/3/issueLink" VERSIONS = "https://acme.atlassian.net/rest/api/3/project/ABC/versions" -PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under ABC-12 before filing the item again" +PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under ABC-12 before filing it again" FIELDS = {"Release": "0.1.0", "Tagline": "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", "Moves": "1 by 9"} PROPERTY = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "", "Filed by": "loop"} RANK = "https://acme.atlassian.net/rest/agile/1.0/issue/rank" diff --git a/bin/repo_checks/test_citations.py b/bin/repo_checks/test_citations.py index 25334345..d6d0f143 100644 --- a/bin/repo_checks/test_citations.py +++ b/bin/repo_checks/test_citations.py @@ -6,7 +6,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from loop_claude.project.records import HUMAN_RULE_DIR +from chunk_driver.project.records import HUMAN_RULE_DIR from repo_checks import ROOT # The review standards this repo ships. A project's config may name another folder as `standards`. diff --git a/bin/repo_checks/test_package_cycles.py b/bin/repo_checks/test_package_cycles.py index 88636a3d..3f011f6b 100644 --- a/bin/repo_checks/test_package_cycles.py +++ b/bin/repo_checks/test_package_cycles.py @@ -24,6 +24,21 @@ def package_imports(bin_folder: pathlib.Path) -> dict[str, set[str]]: return imported +# The entry points that drive chunks. What two of them need lives in bin/chunk_driver/, so no other package imports one, its tests included. +DRIVERS = ("do_epic", "loop_claude") + + +def driver_imports(bin_folder: pathlib.Path, drivers: tuple[str, ...]) -> list[str]: + """Each module under bin_folder that imports a driver's package from outside it, tests included, as ` imports `.""" + found = [] + for module in sorted(bin_folder.rglob("*.py")): + package = module.relative_to(bin_folder).parts[0] + for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))): + names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [node.module or ""] if isinstance(node, ast.ImportFrom) and node.level == 0 else [] + found += [f"{module.relative_to(bin_folder)} imports {top}" for name in names if (top := name.split(".")[0]) in drivers and top != package] + return sorted(set(found)) + + def cycle(imported: dict[str, set[str]]) -> list[str]: """One cycle among the packages, as the packages along it; empty where there is none.""" try: @@ -37,6 +52,17 @@ class PackageCycles(unittest.TestCase): def test_no_package_under_bin_imports_one_that_imports_it_back(self): self.assertEqual(cycle(package_imports(ROOT / "bin")), [], "move what both packages need into a package that imports neither") + def test_no_package_imports_a_driver_of_chunks(self): + self.assertEqual(driver_imports(ROOT / "bin", DRIVERS), [], "move what the importer needs into bin/chunk_driver/, or a test double into the package whose code it stands in for") + + def test_a_driver_imported_from_another_package_is_found_in_tests_too(self): + with tempfile.TemporaryDirectory() as temp: + folder = pathlib.Path(temp) + for package, name, source in (("a", "mod.py", "import a.other\n"), ("b", "test_mod.py", "from a.mod import x\n"), ("b", "mod.py", "def f():\n\timport a\n"), ("c", "mod.py", "import b\n")): + (folder / package).mkdir(exist_ok=True) + (folder / package / name).write_text(source) + self.assertEqual(driver_imports(folder, ("a",)), ["b/mod.py imports a", "b/test_mod.py imports a"]) + def test_reads_an_import_deferred_into_a_function_and_leaves_out_tests(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) diff --git a/bin/rung_replay/command.py b/bin/rung_replay/command.py index 9d3425d4..241cbdae 100644 --- a/bin/rung_replay/command.py +++ b/bin/rung_replay/command.py @@ -7,7 +7,7 @@ from failure import Failure from model_routing.ladder import Ladder, Rung from claude_code.reply import Limited from loop_state.paths import paths_from -from loop_claude.project.model_choice import read_models_file +from chunk_driver.project.model_choice import read_models_file # What a tool reads from its arguments, such as the project's rung of the model they name. Parsed = typing.TypeVar("Parsed") diff --git a/docs/decisions.md b/docs/decisions.md index b9647373..06cc0ebb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -249,7 +249,7 @@ loop-claude hands each worker's claude `CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000` Why 200k. Item 231 asked for the best means to lower what a chunk spends on context, in dollars, then hours, with no loss of quality. Measured from loop-claude's archive, the 90 chunks with messages after the routing figures' reset of 2026-10-21 cost $1,215 at the list prices read on 2026-10-26 (Opus 5.5: $4 per million input tokens, $5 and $8 for 5-minute and 1-hour cache writes, $0.20 for cache reads, $20 for output; no model but Haiku 5.5 charges more above 200k). That is 0.86 of what the chunks' `cost-state` entries sum to, since some chunks' subagent transcripts are not in the archive. Worker main threads cost $375 (31%): 1-hour cache writes $149, cache reads $153, output $74. Subagents cost $840: 5-minute cache writes $379, output $274, cache reads $187, with the principles auditors at $274 over 342 runs, the stability reviewers $179 and general-purpose subagents $192. A worker starts at 41k tokens of context and peaks at a median 167k, one in ten past 358k, the largest at 848k. The worker's messages above 200k were 32% of its messages and 55% of its cost. -What reads cost, and whether a tool cuts them, measured at lilleman's ask after those figures: no tool cut a reviewer's reading without losing a finding, except a scout, which kept the stability reviewers' findings but lost the auditors' 🔴 and slowed every round; so none of them ships here. lilleman chose on 2026-10-27: workers trial a reading rule, reviewers get no scout, and the principles audit keeps reading the project whole. Every fresh worker prompt now holds that rule (`READING_RULE` in `bin/loop_claude/cycle/prompts.py`), and `todo.md` item 260 keeps or drops it. Two measures of reading: the characters a thread read, 93M in all, about 27M tokens; and the new input tokens of the messages that took results in, charged to those results, which also count what arrives beside a result, such as the agent's own previous reply. By the second measure tool results caused $620 of the $1,215, and reads (Read, Bash reads, Grep, Glob and git's diff, show and log) $537 of that: the worker's reads $140 (Bash reads $115, Read $12) of its $190 of results, the principles auditors' $133 (Read $109, Grep $22) of $139, the stability reviewers' $97 (Bash reads $79) of $106, general-purpose subagents' $84 of $97, the prose reviewers' $32, the architects' $30 and the product-owner reviewers' $21. By the first measure the worker's reads are about $45. Precision is low everywhere: of the characters a principles auditor read, 13% were in a file its report names; a stability reviewer 8%; a prose reviewer 18%; an architect 11%; the worker 4% in a file it later edited. Reading is mostly to find things and to learn what a project holds. The worker's `sed` ranges are small, median 25 lines, one in ten over 80. Of the worker's read characters, 49% were of a file it had read earlier in the thread: 36% within three messages, paging through it, and 13% later, with the file unchanged, about $6 of the $45; a reviewer's later reads of an unchanged file it had read are 1 to 2%. rule-hook's `repeat-read` now blocks a read of lines already in context. +What reads cost, and whether a tool cuts them, measured at lilleman's ask after those figures: no tool cut a reviewer's reading without losing a finding, except a scout, which kept the stability reviewers' findings but lost the auditors' 🔴 and slowed every round; so none of them ships here. lilleman chose on 2026-10-27: workers trial a reading rule, reviewers get no scout, and the principles audit keeps reading the project whole. Every fresh worker prompt now holds that rule (`READING_RULE` in `bin/chunk_driver/prompts.py`), and `todo.md` item 260 keeps or drops it. Two measures of reading: the characters a thread read, 93M in all, about 27M tokens; and the new input tokens of the messages that took results in, charged to those results, which also count what arrives beside a result, such as the agent's own previous reply. By the second measure tool results caused $620 of the $1,215, and reads (Read, Bash reads, Grep, Glob and git's diff, show and log) $537 of that: the worker's reads $140 (Bash reads $115, Read $12) of its $190 of results, the principles auditors' $133 (Read $109, Grep $22) of $139, the stability reviewers' $97 (Bash reads $79) of $106, general-purpose subagents' $84 of $97, the prose reviewers' $32, the architects' $30 and the product-owner reviewers' $21. By the first measure the worker's reads are about $45. Precision is low everywhere: of the characters a principles auditor read, 13% were in a file its report names; a stability reviewer 8%; a prose reviewer 18%; an architect 11%; the worker 4% in a file it later edited. Reading is mostly to find things and to learn what a project holds. The worker's `sed` ranges are small, median 25 lines, one in ten over 80. Of the worker's read characters, 49% were of a file it had read earlier in the thread: 36% within three messages, paging through it, and 13% later, with the file unchanged, about $6 of the $45; a reviewer's later reads of an unchanged file it had read are 1 to 2%. rule-hook's `repeat-read` now blocks a read of lines already in context. The trials: four stability rounds and five principles rounds archived on 2026-10-23, each holding 🔴 or 🟡 findings, replayed on the project's rung as `review-replay` replays them, with the reviewer's definition changed through `--agents`; and three worker-like tasks, a search, a rename and an explanation, run on fresh clones at the project's rung. The baseline, the reviewer as it is, found 4 of its own 6 archived findings in each pass, so a variant that finds 4 or 5 of 6 does what the same reviewer does twice. The options todo item 231 named, each simulated on the 90 chunks and, where lilleman asked, tried: @@ -435,7 +435,7 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the 2026-10-15, lilleman asked for it through todo item 144, implemented by claude. Serves goal 1.1: a cheap reviewer that finds the work below standard can have a more capable one check that ruling, and work below standard gets a more capable rung to fix it, unless the fix changes only prose. -The work is below standard where systems-architect returns BLOCK, a reviewer reports a finding against the review standards' `quality.md`, or `record-ruling` counts a comprehension seat's vote in a paired ruling as worse. That reviewer or seat may ask, and the worker then relaunches it on the rung loop-claude's prompt names, one above the rung it ran on. `bin/loop_claude/cycle/prompts.py`'s `reruns` names it: the seats run on the project's rung, and the reviewers on the highest of the worker's rung and the one their item's E + I picks. Off the ladder, or for a reviewer or seat already on the top rung, the prompt names none, and its report stands. +The work is below standard where systems-architect returns BLOCK, a reviewer reports a finding against the review standards' `quality.md`, or `record-ruling` counts a comprehension seat's vote in a paired ruling as worse. That reviewer or seat may ask, and the worker then relaunches it on the rung loop-claude's prompt names, one above the rung it ran on. `bin/chunk_driver/prompts.py`'s `reruns` names it: the seats run on the project's rung, and the reviewers on the highest of the worker's rung and the one their item's E + I picks. Off the ladder, or for a reviewer or seat already on the top rung, the prompt names none, and its report stands. A reviewer's relaunch gets the report that asked and confirms or dismisses each of its findings with a reason, so no finding goes unanswered; a seat's relaunch reads afresh, since a seat reports no findings. The relaunch's report stands in place of the one that asked, in the same round, so it adds no round, and a relaunch cannot ask again. So the round cap still bounds a pass, and one round launches a reviewer at most twice. The ruling that stands is the fourth escalation trigger in `CLAUDE.md`, except where the fix changes only prose: the worker fixes that on its own rung. lilleman ruled that on 2026-11-08 through todo item 276, after PR #432's two quality findings were false claims, one in a docstring and one in a sentence of this file. lilleman also ruled that no ruling raises the judge's rung, which `routing: on a model judge-replay covered` sets. @@ -638,7 +638,7 @@ Since 2026-10-16 the reviewers may run above the worker's rung, on the one the h ## routing: loop-claude reads the items a chunk takes from the worker's latest `Chunk items:` line and scores them by `todo.md` as the default branch held it when the cycle started; the judge reports the escalation and whether a release is ready to cut -2026-11-11, claude. Serves goal 1.4 and code health. The judge's reply held three facts beside its verdict: the items the worker took into the chunk, with their highest L and E + I; whether a release was ready to cut; and any escalation the worker asked for. Routing lifts the worker's and the reviewers' rungs by the items' levels. Code now reads the items: each chunk's first prompt, and each prompt resuming it, asks the worker for a line opening `Chunk items:`, `bin/loop_claude/cycle/chunk_items.py` reads the latest such line in the worker's own text, and `plan.todo_table` scores the items. So the judge's reply is smaller, and every L and E + I that routing reads comes from `todo.md`, through one module. +2026-11-11, claude. Serves goal 1.4 and code health. The judge's reply held three facts beside its verdict: the items the worker took into the chunk, with their highest L and E + I; whether a release was ready to cut; and any escalation the worker asked for. Routing lifts the worker's and the reviewers' rungs by the items' levels. Code now reads the items: each chunk's first prompt, and each prompt resuming it, asks the worker for a line opening `Chunk items:`, `bin/loop_claude/chunk/chunk_items.py` reads the latest such line in the worker's own text, and `plan.todo_table` scores the items. So the judge's reply is smaller, and every L and E + I that routing reads comes from `todo.md`, through one module. The judge field trials (`judge-field-trials/`) read each fact by code over the 709 archived cases. Code was wrong in each of the 39 cases where it and the judge disagreed on an escalation, and read a release ready to cut in 3 of the 31 interrupts that asked about a cut, so the judge keeps both. Workers stated an item with its L and E + I in 413 cases, but also stated items they filed, finished or only mentioned, so the worker writes the items on a line that holds only them, which code reads. Three fresh readers picked its label `Chunk items:`, 3 to 0, because it says the items are the chunk's. @@ -864,7 +864,7 @@ Valid while loop-claude starts a project's chunks side by side by this pick (`bi 2026-10-15, lilleman. Serves goal 1.1: a cheaper rung writes worse scores, and a wrong score routes a chunk onto the wrong rung, ranks the plan wrong and drops an item under the bar that should stay. Below the project's rung, a session or subagent may not score an item, move it between releases, split a milestone, delete an item under the bar, or rewrite a filed item. It drafts each new item, and each change to a filed item, such as a refresh a rule asks for. Before the next commit, one subagent on the project's rung or above applies and scores the drafts. One launch covers all of a chunk's drafts (goal 1.4). A security finding gets that subagent at once, since it is filed the moment it is found. Removing a finished item closes work and plans none, so any rung does it. Scoring a delegated task's L runs on any rung too: a launch on the project's rung to score each delegation would cost more than the cheaper task saves (goal 1.4). -Three places carry the rule. `rules/todo-items.md` states it; it loads with `todo.md`, and `CLAUDE.md` → "Topic rules" asks for it before an item is filed or changed. `CLAUDE.md`'s delegation rule launches the scoring subagent on the rung `bin/subagent-rung --plan` prints: the one the task's L picks, never below the project's, so a hard scoring task still climbs. `bin/loop_claude/cycle/prompts.py`'s `review_launches` names the same command to a worker below the project's rung, never a fixed rung, which would disagree with `--plan` on a scoring task of L 4. Valid while a worker or subagent may run below the project's rung. +Three places carry the rule. `rules/todo-items.md` states it; it loads with `todo.md`, and `CLAUDE.md` → "Topic rules" asks for it before an item is filed or changed. `CLAUDE.md`'s delegation rule launches the scoring subagent on the rung `bin/subagent-rung --plan` prints: the one the task's L picks, never below the project's, so a hard scoring task still climbs. `bin/chunk_driver/prompts.py`'s `review_launches` names the same command to a worker below the project's rung, never a fixed rung, which would disagree with `--plan` on a scoring task of L 4. Valid while a worker or subagent may run below the project's rung. ## todo.md: tools and agents read and change the plan as it stands only through `bin/plan_store` and `todo-item`; a tool that reads what a past commit held, ranks the file or checks its rank still parses `todo.md` diff --git a/todo.md b/todo.md index d4ebbf8f..bdf2917b 100644 --- a/todo.md +++ b/todo.md @@ -179,10 +179,11 @@ Touches: Touches: - `bin/agent_cycle/judge.py`: `Brief`, `judge_prompt`, `JUDGE_PROMPT_CHARS` -- `bin/loop_claude/project/records.py`: `read_records` +- `bin/chunk_driver/project/records.py`: `read_records` - `bin/judge_replay/main.py`: `rule` (small) - `bin/judge_replay/replay.py`: `case_from` (small) -- `bin/loop_claude/test_loop_claude.py`: `JudgePrompt`, `Records` +- `bin/loop_claude/test_loop_claude.py`: `JudgePrompt` +- `bin/chunk_driver/project/test_records.py`: `Records` - `bin/judge_replay/test_judge_replay.py` ### 395. Keep each block a save didn't change, with its localId, and the spacing paragraphs beside it as Jira or Confluence holds them. @@ -365,7 +366,7 @@ The maintainability senior and the inherited architect of PR #257's scoring run ### 443. Measure whether compacting a waiting worker's session cut the cost of 20 chunks with an interrupt, with quality holding. -The check lilleman set for item 310 on 2026-11-11, which project principle 1 asks for before a cost cut stands: compare the cost entries of 20 archived chunks with an interrupt from before the compaction shipped against 20 from after it. Measure the tokens written to the cache by each resume after an interrupt, and the tokens per finished chunk, and check that review rounds and unfinished verdicts per chunk hold. Where the saving doesn't show, or quality drops, file an item to remove the compaction or retune `COMPACT_FLOOR` and `CACHE_MARGIN` in `bin/loop_claude/cycle/interrupt.py`. Record the outcome as a decision. Start it once 20 chunks with an interrupt have run on 0.12.0 or later. +The check lilleman set for item 310 on 2026-11-11, which project principle 1 asks for before a cost cut stands: compare the cost entries of 20 archived chunks with an interrupt from before the compaction shipped against 20 from after it. Measure the tokens written to the cache by each resume after an interrupt, and the tokens per finished chunk, and check that review rounds and unfinished verdicts per chunk hold. Where the saving doesn't show, or quality drops, file an item to remove the compaction or retune `COMPACT_FLOOR` and `CACHE_MARGIN` in `bin/agent_cycle/interrupt.py`. Record the outcome as a decision. Start it once 20 chunks with an interrupt have run on 0.12.0 or later. ### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key. @@ -391,11 +392,11 @@ Project principle 4 asks that a rule a program can check is enforced by a progra ### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose. -Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend. +Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/chunk_driver/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend. ### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints. -"Functional core, imperative shell", in `principles/technical-principles.md`: `say` in `bin/loop_effects/effects.py` takes the effects but prints to stderr itself, and `retried` and the rest print through `say`. Two bare `print(file=sys.stderr)` calls remain outside them, in `bin/agent_cycle/interrupt.py` and `bin/loop_claude/project/model_choice.py`. The tests swap the global stream. +"Functional core, imperative shell", in `principles/technical-principles.md`: `say` in `bin/loop_effects/effects.py` takes the effects but prints to stderr itself, and `retried` and the rest print through `say`. Two bare `print(file=sys.stderr)` calls remain outside them, in `bin/agent_cycle/interrupt.py` and `bin/chunk_driver/project/model_choice.py`. The tests swap the global stream. ### 201. Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly. -- 2.52.0 From df210aaeca0c804348645c4a8539507db5e607e2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 11:29:32 +0100 Subject: [PATCH 04/14] =?UTF-8?q?Answer=20architecture=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20the=20cycle?= =?UTF-8?q?'s=20and=20the=20chunk=20run's=20suites=20sit=20beside=20their?= =?UTF-8?q?=20modules,=20and=20the=20claim=20rule=20and=20the=20model=20ov?= =?UTF-8?q?erride=20have=20one=20home=20each?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +- bin/agent_cycle/test_interrupt.py | 5 +- bin/agent_cycle/test_judge.py | 11 +- bin/agent_cycle/test_retry.py | 2 +- bin/agent_cycle/test_routing.py | 19 + bin/agent_cycle/test_run.py | 525 +++++++++++++++++ bin/agent_cycle/test_spend.py | 2 +- bin/agent_cycle/test_stuck_workers.py | 2 +- bin/agent_cycle/test_tmux.py | 5 +- bin/agent_cycle/test_worker.py | 2 +- bin/chunk_driver/claims.py | 12 + bin/chunk_driver/project/model_choice.py | 18 +- bin/chunk_driver/project/test_model_choice.py | 9 +- bin/chunk_driver/test_chunk_run.py | 92 +++ bin/chunk_pr/approval.py | 8 +- bin/do_epic/gates.py | 8 +- bin/do_epic/main.py | 4 +- bin/do_epic/scheduler.py | 7 +- bin/do_epic/test_findings.py | 2 +- bin/do_epic/test_finish.py | 2 +- bin/do_epic/test_human_tasks.py | 2 +- bin/do_epic/test_main.py | 3 +- bin/do_epic/test_planning.py | 2 +- bin/forge/reviews.py | 14 +- bin/loop_claude/loop/chunk_windows.py | 16 +- bin/loop_claude/loop/main.py | 6 +- bin/loop_claude/test_black_box.py | 2 +- bin/loop_claude/test_loop_claude.py | 550 +----------------- .../{test_doubles.py => doubles.py} | 76 +-- bin/repo_checks/test_package_cycles.py | 45 +- todo.md | 7 +- 31 files changed, 807 insertions(+), 657 deletions(-) create mode 100644 bin/agent_cycle/test_routing.py create mode 100644 bin/agent_cycle/test_run.py create mode 100644 bin/chunk_driver/test_chunk_run.py rename bin/loop_effects/{test_doubles.py => doubles.py} (66%) diff --git a/README.md b/README.md index 43e9870f..86457af9 100644 --- a/README.md +++ b/README.md @@ -219,13 +219,13 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a ### Packages under `bin/` -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. - `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. - `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the head of each entry it answers, an issue's links and the transition that finishes it, for `plan_store` and `do_epic`. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. -- `chunk_driver/` holds what `loop_claude` and `do_epic` share as they drive chunks through `agent_cycle`: how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither tool, and `repo_checks` fails any package that imports one of the two. +- `chunk_driver/` holds what `loop_claude` and `do_epic` share as they drive chunks through `agent_cycle`: how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither tool, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`. @@ -233,7 +233,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `loop_claude` runs `chunk-preflight` as a process of its own. -- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it. `test_doubles.py` holds the doubles their tests share, such as `FakeEffects`. +- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it. `doubles.py` holds the doubles their tests share, such as `FakeEffects`. - `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read. diff --git a/bin/agent_cycle/test_interrupt.py b/bin/agent_cycle/test_interrupt.py index 585c1203..d64d3c75 100644 --- a/bin/agent_cycle/test_interrupt.py +++ b/bin/agent_cycle/test_interrupt.py @@ -12,10 +12,9 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from loop_effects.test_doubles import assistant, FakeEffects, human, NOW, STAMP, Streamed +from loop_effects.doubles import assistant, FakeEffects, human, NOW, STAMP, Streamed from failure import Failure from agent_cycle import interrupt -from chunk_driver.drivers import LOOP_CLAUDE from machine_load import memory from loop_state import paths from model_routing.ladder import Rung @@ -37,7 +36,7 @@ class Interrupts(unittest.TestCase): def put(self, fake, answer_here=True, effects=None, question="Which one?"): """interrupt's answer and what it said, without the bell it rang, which self.bells counts.""" with contextlib.redirect_stderr(io.StringIO()) as said: - answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, LOOP_CLAUDE, effects or fake.effects()) + answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, "loop-claude", effects or fake.effects()) self.bells = said.getvalue().count(tmux.BELL) return answer, said.getvalue().replace(tmux.BELL, "") diff --git a/bin/agent_cycle/test_judge.py b/bin/agent_cycle/test_judge.py index fc97cb62..796a16ed 100644 --- a/bin/agent_cycle/test_judge.py +++ b/bin/agent_cycle/test_judge.py @@ -6,13 +6,10 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from loop_effects.test_doubles import assistant, FakeEffects, human, judged, kinds +from loop_effects.doubles import assistant, FakeEffects, human, judged, kinds from failure import Failure from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished from agent_cycle import judge -from chunk_driver.drivers import LOOP_CLAUDE -from chunk_driver import prompts -from chunk_driver.project import records from model_routing.ladder import Rung from agent_cycle.judge import verdict_from @@ -108,7 +105,7 @@ class Verdict(unittest.TestCase): def test_drops_an_escalation_quote_found_only_in_the_transcript_entries_before_the_workers_last_step_up(self): entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})] def judged_on(mark, escalation): - return judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), mark, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects()) + return judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), mark, "loop-claude"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects()) self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", "round 2: 🔴", entries_read=3)) self.assertEqual(judged_on(1, "round 2: 🔴"), Unfinished("working", entries_read=3)) self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", "round 3: 🔴", entries_read=3)) @@ -117,12 +114,12 @@ class Verdict(unittest.TestCase): def test_drops_an_escalation_quote_that_only_loop_claudes_prompts_or_the_humans_lines_repeat_after_the_step_up(self): entries = [assistant({"type": "text", "text": "round 2: 🔴"}), {**human("as the work remaining: round 2: 🔴"), "promptSource": "sdk"}, human("round 2: 🔴 again"), assistant({"type": "text", "text": "working"})] - verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects()) + verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 1, "loop-claude"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects()) self.assertEqual(verdict, Unfinished("working", entries_read=4)) def test_takes_evidence_from_before_the_workers_last_step_up(self): entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "working"})] - verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, LOOP_CLAUDE), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects()) + verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 1, "loop-claude"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects()) self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2)) diff --git a/bin/agent_cycle/test_retry.py b/bin/agent_cycle/test_retry.py index e0d0c98b..ed97ed74 100644 --- a/bin/agent_cycle/test_retry.py +++ b/bin/agent_cycle/test_retry.py @@ -8,7 +8,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -from loop_effects.test_doubles import FakeEffects, NOW, STAMP +from loop_effects.doubles import FakeEffects, NOW, STAMP from claude_code.reply import Limited from agent_cycle import retry from agent_cycle.stop import Stop diff --git a/bin/agent_cycle/test_routing.py b/bin/agent_cycle/test_routing.py new file mode 100644 index 00000000..6adf6a72 --- /dev/null +++ b/bin/agent_cycle/test_routing.py @@ -0,0 +1,19 @@ +import dataclasses +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from model_routing.route import Route +from agent_cycle import routing +from model_routing.ladder import Rung + + +class StepUp(unittest.TestCase): + OPUS = Rung("claude-opus-5-5", "medium") + + def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self): + route = Route(self.OPUS, 3, 3, 4) + self.assertIsNone(routing.step_up(route, dataclasses.replace(route, unfinished=1))) + self.assertEqual(routing.step_up(route, route.taking_in(6)), routing.StepUp(route, route.taking_in(6))) diff --git a/bin/agent_cycle/test_run.py b/bin/agent_cycle/test_run.py new file mode 100644 index 00000000..d4a9cd86 --- /dev/null +++ b/bin/agent_cycle/test_run.py @@ -0,0 +1,525 @@ +import contextlib +import dataclasses +import io +import json +import os +import pathlib +import re +import shutil +import stat +import sys +import tempfile +import types +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from test_env import assert_not_root +from failure import Failure +from loop_effects.doubles import FakeEffects, human, judged, NOW, ran, STAMP, Streamed, Worker +from agent_cycle.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished +from transcript_archive import outcomes, write +from loop_state import paths +from transcript_archive.location import project_archive +from model_routing.ladder import ProjectRung, Rung +from model_routing.ladder_file import read_ladder, SHIPPED +from model_routing.route import Route +from agent_cycle import routing +from agent_cycle import run, stuck_workers, worker_prompts +from claude_code import session +from loop_effects.child_shells import Shell +from agent_cycle.stop import Stop +from text_files.utc_stamp import utc +from agent_cycle.test_tmux import WINDOW +from agent_cycle.worker_prompts import WorkerPrompts + + +LADDER = read_ladder(SHIPPED) +OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium")) +# The ladder's rungs the cycles run on, and those one and three steps up from OPUS. +SONNET = Rung("claude-sonnet-5-5", "high") +OPUS = Rung("claude-opus-5-5", "medium") +ONE_UP = Rung("claude-fable-5-2", "low") +THREE_UP = Rung("claude-opus-5-5", "xhigh") +# How the archive records a worker that runs off the ladder. +OFF_LADDER = '{"model": "worker-model"}' +# The claude-config release and commit each cycle the tests run is under. +CONFIG = "v0.8.0 (abc123)" +# How it records routes by item 179's L of 2 and E + I of 5. +SONNET_179 = '{"model": "claude-sonnet-5-5", "effort": "high", "item": 179, "likelihood": 2, "escape_and_impact": 5}' +OPUS_179_AT_3 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 3}' +OPUS_179_AT_6 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 6}' +JUDGE_RUN_LINE = re.compile(r"^Judge run: judge/[0-9a-f]{64}\.json\n", re.MULTILINE) +# The prompts of an entry point that exists only here, so a cycle's tests read no real entry point's wording. +PROMPTS = WorkerPrompts( + driver="a-driver", + fresh=lambda task, premises, route, project, facts: f"Fresh: {task}\n\n{premises}\n\n{facts}", + resumed=lambda evidence, route, project: f"Resumed: {evidence}", + rungs_held=lambda route, project: f" You hold {route.rung}.", + quote_sources="the project's records", + answer_destinations="the plan or a comment", + records_named="the project's decisions", +) + + +class QuestionFor(unittest.TestCase): + def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self): + cycle = types.SimpleNamespace(prompts=PROMPTS) + self.assertEqual(run.question_for(cycle, Interrupt("e", "Which one?")), "Which one?") + self.assertEqual(run.question_for(cycle, QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe project's records says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.") + + +class Cycles(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.home = pathlib.Path(temp.name) + self.paths = paths.paths_from(self.home) + self.session = session.session_named("A proj a-driver", self.paths.claude_code_transcripts) + self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) + + def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): + return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge=Rung("judge-model"), premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", prompts=PROMPTS, taken_in=lambda entries: TakenIn(), unfinished_evidence=unfinished_evidence) + + def archived_outcomes(self): + """Each outcomes file's text without its `Judge run:` lines, which name a file by the hash of a prompt and its reply: the tests of the judge's runs check them.""" + return sorted(JUDGE_RUN_LINE.sub("", path.read_text()) for path in self.archive.glob("*/*.outcomes.md")) + + def test_a_finished_chunk_is_archived_and_its_session_deleted(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) + + def test_archives_the_cost_the_judges_reply_records_beside_its_verdict(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished", cost=0.25)]) + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working", judged=Judged(cost=0.25))) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nJudge cost: 0.2500\nWorker: {OFF_LADDER}\n"]) + self.assertIsNone(session.transcript_file(self.session)) + + def test_archives_what_the_worker_and_the_judge_spent_beside_the_verdict(self): + worker = Worker(self.paths.claude_code_transcripts.parent, usage={"input_tokens": 1, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5}) + answer = json.loads(judged("finished").stdout) + fake = FakeEffects(streams=[worker], claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 6, "output_tokens": 7}}))]) + run.run_cycle(self.cycle(fake)) + self.assertEqual(self.archived_outcomes(), [f"""Task: Do it. + +2026-09-21T14:13:20Z Verdict: finished + +Evidence: +> working + +Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output: +- worker, claude-opus-5-5: 1, 2, 3, 4, 5 +- judge, judge-model: 6, 0, 0, 0, 7 + +List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output: +- claude-opus-5-5: 4, 5, 8, 0.2, 20 + +Config: {CONFIG} +Judge: judge-model +Worker: {OFF_LADDER} +"""]) + + def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self): + worker = Worker(self.paths.claude_code_transcripts.parent) + fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) + self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Finished("working")) + fresh, resumed = (args[args.index("-p") + 1] for args in fake.made("stream_claude")) + self.assertIn("- A preflight fact.", fresh) + self.assertNotIn("- A preflight fact.", resumed) + + def test_a_worker_is_handed_the_projects_rung_its_own_its_reviews_e_plus_i_and_its_compaction_window_in_its_environment(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) + cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) + self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) + self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5", "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "200000", "BASH_MAX_OUTPUT_LENGTH": "6000"}]) + + def test_a_stuck_check_of_the_worker_runs_on_the_projects_rung_and_off_the_ladder_on_the_workers_own(self): + for project, model in ((OPUS_PROJECT, "claude-opus-5-5"), (None, "claude-haiku-5-5")): + with self.subTest(project=project): + clock = [NOW] + quiet = Shell(pid=7, started=NOW, command="bin/run-tests", written=NOW, runs_busy_tool=False) + events = ({"type": "assistant", "message": {"content": []}}, None, None, {"type": "result"}) + stream = lambda args: (Worker(self.paths.claude_code_transcripts.parent)(args), Streamed(0, *events, clock=clock, held=[quiet]))[1] + verdict = ran(json.dumps({"type": "result", "structured_output": {"verdict": "stuck", "process": 7, "why": "it waits"}})) + fake = FakeEffects(streams=[stream], claude=[verdict, judged("finished")]) + cycle = dataclasses.replace(self.cycle(fake), project=project, route=Route(Rung("claude-haiku-5-5", "max"))) + with contextlib.redirect_stdout(io.StringIO()): + run.run_cycle(dataclasses.replace(cycle, effects=dataclasses.replace(cycle.effects, now=lambda: clock[0]))) + [investigator, _] = [args for args, _ in fake.made("claude")] + self.assertEqual(investigator[investigator.index("--model") + 1], model) + self.assertEqual(fake.worker_folders, [str(self.home)]) + self.assertIn("judged the worker stuck", (self.archive / stuck_workers.RECORD).read_text()) + + def test_the_claude_an_interrupt_resumes_is_handed_the_same_rungs_as_the_worker(self): + def answer(args): + with open(session.transcript_file(self.session), "a") as handle: + handle.write(json.dumps(human("the second")) + "\n") + return 0 + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer]) + cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) + self.assertEqual(fake.terminal_environments, [{**environment, "CLAUDE_CODE_SANDBOXED": "1"} for environment in fake.worker_environments]) + self.assertEqual(fake.terminal_environments[0]["LOOP_CLAUDE_WORKER_RUNG"], "claude-haiku-5-5 at max effort") + + def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2) + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) + self.assertTrue(session.transcript_file(self.session)) + self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Unfinished("working", entries_read=4)) + workers = fake.made("stream_claude") + self.assertIn("--session-id", workers[0]) + self.assertIn("--resume", workers[1]) + self.assertEqual(workers[1][workers[1].index("-p") + 1], "Resumed: working") + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2) + + def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3) + self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()]) + self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, "")) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: {OFF_LADDER}\n"]) + + def test_each_judge_reply_the_loop_rejects_is_archived_with_why_beside_the_verdict_that_follows(self): + unfilled = ran(json.dumps({"structured_output": {"interrupt": False}})) + misquoted = judged("finished", evidence="never said") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[unfilled, misquoted, judged("finished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) + stamp = "2026-09-21T14:13:20Z" + self.assertEqual(self.archived_outcomes(), [ + "Task: Do it.\n\n" + f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n" + f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n" + f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) + + def test_archives_each_judge_runs_prompt_and_reply_beside_the_rejection_interrupt_and_verdict_it_gave(self): + rejected, interrupted, finished = ran(json.dumps({"structured_output": {"interrupt": False}})), judged("interrupt", cost=0.25), judged("finished") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[rejected, interrupted, finished], inputs=["Use B."]) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) + prompts = [stdin for args, stdin in fake.made("claude")[:3]] + [chunk] = self.archive.iterdir() + kept = "\n".join(path.read_text() for path in chunk.glob("*.outcomes.md")) + named = re.findall(r"^Judge run: (judge/[0-9a-f]{64}\.json)$", kept, re.MULTILINE) + self.assertEqual(len(named), 3, kept) + runs = [json.loads((chunk / name).read_text()) for name in named] + replies = [json.loads(reply.stdout) for reply in (rejected, interrupted, finished)] + self.assertEqual(sorted((found["prompt"], json.dumps(found["reply"])) for found in runs), sorted((prompt, json.dumps(reply)) for prompt, reply in zip(prompts, replies))) + self.assertEqual(sorted(path.name for path in (chunk / "judge").iterdir()), sorted(name.removeprefix("judge/") for name in named)) + + def test_stops_when_a_judge_run_cannot_be_archived(self): + self.archive.mkdir(parents=True) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) + def replace_file(path, data): + return Failure("disk full") if "/judge/" in str(path) else real_replace_file(path, data) + real_replace_file = write.replace_file + with unittest.mock.patch("transcript_archive.write.replace_file", replace_file): + stop = run.run_cycle(self.cycle(fake)) + self.assertEqual(stop.code, 1) + self.assertRegex(stop.reason, r"^could not archive the transcript: .*/judge/[0-9a-f]{64}\.json: disk full$") + + def test_archives_what_each_judge_run_cost_on_an_interrupt_a_quoted_answer_and_a_rejected_misquote(self): + for first, then, inputs in ( + (judged("interrupt", cost=0.25), judged("finished"), ["Use B."]), + (judged("quoted", answer="Use A.", cost=0.25), judged("finished"), []), + (judged("unfinished", cost=0.25), judged("finished"), []), + (judged("finished", evidence="never said", cost=0.25), judged("finished"), []), + ): + with self.subTest(first=first.stdout), tempfile.TemporaryDirectory() as archive: + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[first, then], inputs=inputs) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + run.run_cycle(dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project_archive=pathlib.Path(archive))) + kept = "".join(path.read_text() for path in pathlib.Path(archive).glob("*/*.outcomes.md")) + self.assertEqual(kept.count("Judge cost: 0.2500\n"), 1, kept) + self.assertIn("Judge cost: 0.2500\nJudge run: judge/", kept) + + def test_stops_with_exit_1_where_a_subagents_transcript_cannot_be_read_for_the_spend(self): + for verdict in ("interrupt", "finished"): + with self.subTest(verdict=verdict), tempfile.TemporaryDirectory() as archive: + unreadable = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" / "agent-x.jsonl" + unreadable.mkdir(parents=True) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged(verdict)], inputs=["Use B."]) + with contextlib.redirect_stderr(io.StringIO()): + stop = run.run_cycle(dataclasses.replace(self.cycle(fake), project_archive=pathlib.Path(archive))) + self.assertEqual((stop.code, stop.reason), (1, f"could not read the transcript {unreadable}: Is a directory")) + shutil.rmtree(unreadable.parent.parent) + (self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl").unlink() + + def test_counts_the_spend_since_the_last_outcome_that_recorded_one_and_archives_the_reversal(self): + transcript = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl" + transcript.parent.mkdir(parents=True) + old = {"type": "assistant", "timestamp": "2026-09-21T14:13:19Z", "message": {"id": "old", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 100}}} + new = {"type": "assistant", "timestamp": "2026-09-21T14:13:21Z", "message": {"id": "new", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 5}}} + transcript.write_text("\n".join(json.dumps(entry) for entry in [{"type": "queue-operation", "timestamp": "2026-09-21T14:00:00Z"}, old, human("No, keep the old name."), new]) + "\n") + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished", reversed="No, keep the old name.")]) + run.run_cycle(self.cycle(fake)) + latest = max(self.archived_outcomes(), key=len) + self.assertIn(f"""Reversed: +> No, keep the old name. + +Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache write 1h, cache read, output: +- worker, claude-opus-5-5: 0, 0, 0, 0, 5 +""", latest) + + def test_stops_with_exit_1_asking_nothing_where_an_interrupt_cannot_be_archived(self): + self.archive.parent.mkdir(parents=True) + self.archive.write_text("") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt")], inputs=["Use B."]) + with contextlib.redirect_stderr(io.StringIO()) as said: + stop = run.run_cycle(self.cycle(fake)) + self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) + self.assertNotIn("Which one?", said.getvalue()) + self.assertEqual(fake.made("claude_on_terminal"), []) + + def test_stops_when_a_rejected_reply_cannot_be_archived(self): + self.archive.parent.mkdir(parents=True) + self.archive.write_text("") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(json.dumps({"structured_output": {"interrupt": False}})), judged("finished")]) + stop = run.run_cycle(self.cycle(fake)) + self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$") + self.assertEqual(stop.code, 1) + self.assertEqual(len(fake.made("claude")), 1) + + def test_archives_the_judges_rejected_replies_though_it_fails_three_times_running(self): + unfilled = ran(json.dumps({"structured_output": {"interrupt": False}})) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[unfilled] * 3) + self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) + [archived] = self.archived_outcomes() + self.assertEqual(archived.count(f"Reply:\n> {unfilled.stdout}\n"), 3) + self.assertIn("Stopped: the judge failed three times running", archived) + + def test_archives_each_chunks_session_folder_replacing_a_copy_only_with_what_grew_from_it(self): + folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) + (folder / "subagents" / "workflows").mkdir(parents=True) + (folder / "subagents" / "agent-a.jsonl").write_text("a\n") + (folder / "subagents" / "workflows" / "journal.jsonl").write_text("j\n") + (folder / "custom-title.json").write_text("first") + (folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) + [chunk] = self.archive.iterdir() + kept = chunk / "session" / str(self.session.id) + self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n") + os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0)) + with open(folder / "subagents" / "agent-a.jsonl", "a") as handle: + handle.write("more\n") + (folder / "custom-title.json").write_text("second") + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) + self.assertFalse(folder.exists()) + self.assertEqual((kept / "subagents" / "agent-a.jsonl").read_text(), "a\nmore\n") + self.assertEqual((kept / "subagents" / "workflows" / "journal.jsonl").stat().st_mtime, 0) + self.assertEqual(sorted(path.read_text() for path in kept.glob("custom-title.json*")), ["first", "second"]) + self.assertEqual(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600) + folder.mkdir() + (folder / "custom-title.json").write_text("third") + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) + [next_chunk] = set(self.archive.iterdir()) - {chunk} + self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"]) + + def test_stops_on_a_session_folder_it_cannot_read_whole(self): + assert_not_root(self) + locked = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" + locked.mkdir(parents=True) + locked.chmod(0) + self.addCleanup(locked.chmod, 0o700) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished")]) + self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"could not archive the transcript: {locked}: Permission denied")) + + def test_an_interrupt_talked_over_in_claude_is_archived_answered_and_judged_again(self): + def answer(args): + with open(session.transcript_file(self.session), "a") as handle: + handle.write(json.dumps(human("the second")) + "\n") + return 0 + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer]) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4)) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) + self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) + judge_prompts = [stdin for args, stdin in fake.made("claude")] + self.assertEqual(len(judge_prompts), 2) + self.assertNotIn("the second", judge_prompts[0]) + self.assertIn("[human] the second", judge_prompts[1]) + self.assertIn("From the goals file, ## Goals", judge_prompts[0]) + self.assertIn("writing it into the plan or a comment,", judge_prompts[0]) + self.assertIn("The task the worker was given:\nDo it.", judge_prompts[0]) + + def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self): + answered = judged("quoted", answer="Use *A*.") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, inputs=[""]) + with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed: + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed")) + resumed = fake.made("stream_claude")[1] + self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nthe project's records answers it:\n\nUse *A*.\n\nContinue the task.") + self.assertEqual(len(fake.made("stream_claude")), 4) + self.assertEqual(printed.getvalue().count("=== the project's records answered: Which one? ===\nUse *A*."), 3) + self.assertIn("Which one?\n\nthe project's records says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue()) + quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nthe project's records says:\n> Use *A*.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n" + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nthe project's records says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3]) + + def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")]) + cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(SONNET, 179, 2, 5)) + with contextlib.redirect_stdout(io.StringIO()): + concluded = run.run_cycle(cycle) + self.assertEqual(concluded.route, Route(OPUS, 179, 2, 5, escalated_at=3)) + first, resumed = fake.made("stream_claude") + self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) + self.assertTrue(resumed[resumed.index("-p") + 1].endswith("Continue the task. Your request for a higher rung went through: a-driver runs you on claude-opus-5-5 at medium effort. The escalation triggers that fired before this step are spent. You hold claude-opus-5-5 at medium effort.")) + self.assertNotIn("went through", first[first.index("-p") + 1]) + answered = f"Verdict: quoted answer\n\nWhich one?\n\nthe project's records says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n" + stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n" + kept = "".join(self.archived_outcomes()) + self.assertIn(f"Z {answered}\n20", kept) + self.assertIn(f"Z {stepped}", kept) + + def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self): + steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")] + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""]) + cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(SONNET, 179, 2, 5)) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed")) + kept = "".join(self.archived_outcomes()) + self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n", kept) + self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept) + + def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self): + cycle = dataclasses.replace(self.cycle(FakeEffects()), project=OPUS_PROJECT, route=Route(ONE_UP, 3, 3, 4)) + for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)): + with self.subTest(ruling=ruling): + self.assertIsNone(run.ruling_step_up(cycle, ruling)) + self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(THREE_UP, 3, 3, 4, escalated_at=3))) + + def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self): + streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)] + rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")] + fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) + cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(SONNET, 179, 2, 5)) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + concluded = run.run_cycle(cycle) + self.assertEqual(concluded.route, Route(ONE_UP, 179, 2, 5, escalated_at=4)) + self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "low"]) + + def test_an_escalation_quoted_from_before_the_workers_last_step_up_steps_nothing_and_a_later_one_reaches_the_verdict(self): + for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", "working", entries_read=4))): + with self.subTest(escalation=escalation): + self.session = session.session_named(f"A proj {escalation} a-driver", self.paths.claude_code_transcripts) + streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)] + rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)] + fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) + cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(SONNET, 179, 2, 5)) + with contextlib.redirect_stderr(io.StringIO()): + concluded = run.run_cycle(cycle) + self.assertEqual(concluded, run.Concluded(verdict, Route(OPUS, 179, 2, 5, escalated_at=3))) + + def test_an_answer_typed_at_the_terminal_resumes_the_worker_headless_and_the_judge_reads_it_as_the_humans(self): + worker = Worker(self.paths.claude_code_transcripts.parent, prompted=True) + fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."]) + with contextlib.redirect_stderr(io.StringIO()) as said: + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6)) + self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue()) + self.assertEqual(fake.made("claude_on_terminal"), []) + resumed = fake.made("stream_claude")[1] + self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id)) + typed = resumed[resumed.index("-p") + 1] + self.assertEqual(worker_prompts.typed_answer(typed).answer, "Use B.") + self.assertIn("Which one?", typed) + self.assertIn("Continue the task. The chunk is finished only once every answer the human typed in it", typed) + judge_prompts = [stdin for args, stdin in fake.made("claude")] + self.assertRegex(judge_prompts[1], r"(?s)\[loop\] Your question was: Which one\?.*\n\n\[human\] Use B\.\n\nworking\n\nDecide whether") + self.assertNotIn("The human answered", judge_prompts[1]) + + def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."]) + cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(SONNET, 179, 2, 5)) + with contextlib.redirect_stderr(io.StringIO()): + concluded = run.run_cycle(cycle) + self.assertEqual(concluded.route, Route(OPUS, 179, 2, 5, escalated_at=3)) + first, resumed = fake.made("stream_claude") + self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) + typed = resumed[resumed.index("-p") + 1] + self.assertIn("Your request for a higher rung went through: a-driver runs you on claude-opus-5-5 at medium effort.", typed) + self.assertIn(" You hold claude-opus-5-5 at medium effort.", typed) + self.assertNotIn("went through", first[first.index("-p") + 1]) + + def test_an_interrupt_that_steps_the_worker_up_compacts_its_session_on_the_rung_it_ran_on(self): + usage = {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 5000}, "cache_read_input_tokens": 70000, "output_tokens": 100} + worker = Worker(self.paths.claude_code_transcripts.parent, usage=usage, sent=utc(NOW - 600)) + fake = FakeEffects(streams=[worker, Streamed(0), worker], claude=[judged("interrupt", escalation="working"), judged("finished")]) + + def typed(prompt): + for _, action in fake.timers: + action() + return "Use B." + fake.scripts["input"] = [typed] + cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(SONNET, 179, 2, 5)) + with contextlib.redirect_stderr(io.StringIO()): + run.run_cycle(cycle) + _, compaction, resumed = fake.made("stream_claude") + self.assertEqual(compaction[compaction.index("-p") + 1], "/compact") + self.assertEqual([(args[args.index("--model") + 1], args[args.index("--effort") + 1]) for args in (compaction, resumed)], [("claude-sonnet-5-5", "high"), ("claude-opus-5-5", "medium")]) + + def test_a_typed_answer_past_the_quoted_answers_cap_reaches_the_worker_with_its_own_question(self): + worker = Worker(self.paths.claude_code_transcripts.parent) + fake = FakeEffects(streams=[worker] * 5, claude=[judged("quoted", answer="Use A.")] * 4 + [judged("finished")], inputs=["Use B."]) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")).verdict, Finished("working")) + typed = fake.made("stream_claude")[4] + self.assertIn("Your question was: Which one?\n\nContinue the task.", typed[typed.index("-p") + 1]) + self.assertNotIn("Those files have answered", typed[typed.index("-p") + 1]) + + def test_a_release_ready_to_cut_opens_claudes_session_without_asking_for_an_answer(self): + def answer(args): + with open(session.transcript_file(self.session), "a") as handle: + handle.write(json.dumps(human("cut")) + "\n") + return 0 + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt", release_ready=True), judged("finished")], on_terminal_claude=[answer]) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) + self.assertEqual(fake.made("input"), []) + self.assertEqual(len(fake.made("claude_on_terminal")), 1) + + def test_stops_when_an_interrupt_cannot_be_archived(self): + self.archive.parent.mkdir(parents=True) + self.archive.write_text("") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt")], inputs=["Use B."]) + stop = run.run_cycle(self.cycle(fake)) + self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$") + self.assertEqual(fake.made("input"), []) + + def test_stops_when_a_quoted_answer_cannot_be_archived(self): + self.archive.parent.mkdir(parents=True) + self.archive.write_text("") + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use A.")]) + with contextlib.redirect_stdout(io.StringIO()): + stop = run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")) + self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$") + self.assertEqual(len(fake.made("stream_claude")), 1) + + def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], inputs=[""]) + with contextlib.redirect_stderr(io.StringIO()) as said: + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed")) + self.assertEqual(len(fake.made("stream_claude")), 1) + self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue()) + self.assertNotIn("Use ... A.", said.getvalue()) + + def test_stops_keeping_the_transcript_when_the_finished_chunks_session_cannot_be_deleted(self): + assert_not_root(self) + folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) + (folder / "subagents").mkdir(parents=True) + folder.chmod(0o500) + self.addCleanup(folder.chmod, 0o700) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) + stop = run.run_cycle(self.cycle(fake)) + self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then run it again; a run before that resumes the finished chunk's session")) + self.assertTrue(session.session_open(self.session)) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"]) + + def test_stops_when_the_worker_leaves_no_transcript(self): + fake = FakeEffects(streams=[Streamed(0)]) + self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}")) diff --git a/bin/agent_cycle/test_spend.py b/bin/agent_cycle/test_spend.py index 918e1813..3e6baf28 100644 --- a/bin/agent_cycle/test_spend.py +++ b/bin/agent_cycle/test_spend.py @@ -8,7 +8,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from claude_code import entries -from loop_effects.test_doubles import FakeEffects, judged, ran +from loop_effects.doubles import FakeEffects, judged, ran from agent_cycle import judge, spend from agent_cycle.verdicts import Judged, Unfinished from transcript_archive import outcomes diff --git a/bin/agent_cycle/test_stuck_workers.py b/bin/agent_cycle/test_stuck_workers.py index 14705797..ac943804 100644 --- a/bin/agent_cycle/test_stuck_workers.py +++ b/bin/agent_cycle/test_stuck_workers.py @@ -6,7 +6,7 @@ import pathlib import tempfile import unittest -from loop_effects.test_doubles import FakeEffects, NOW, ran, Streamed +from loop_effects.doubles import FakeEffects, NOW, ran, Streamed from model_routing.ladder import Rung from loop_effects.child_shells import Shell from agent_cycle import stuck_workers, worker diff --git a/bin/agent_cycle/test_tmux.py b/bin/agent_cycle/test_tmux.py index 0bfe4dff..fa431a9c 100644 --- a/bin/agent_cycle/test_tmux.py +++ b/bin/agent_cycle/test_tmux.py @@ -7,8 +7,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -from loop_effects.test_doubles import FakeEffects -from chunk_driver.drivers import LOOP_CLAUDE +from loop_effects.doubles import FakeEffects from agent_cycle import tmux @@ -23,7 +22,7 @@ class TmuxCommands(unittest.TestCase): ("", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux")): with self.subTest(found=found): fake = FakeEffects(tmux_version=found) - self.assertEqual(tmux.unusable(fake.tmux, LOOP_CLAUDE), reason) + self.assertEqual(tmux.unusable(fake.tmux, "loop-claude"), reason) self.assertEqual(fake.tmux_calls, [["-V"]]) def test_names_the_session_for_the_project(self): diff --git a/bin/agent_cycle/test_worker.py b/bin/agent_cycle/test_worker.py index 3ee38e72..6eba4ebe 100644 --- a/bin/agent_cycle/test_worker.py +++ b/bin/agent_cycle/test_worker.py @@ -12,7 +12,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from claude_code import entries from failure import Failure -from loop_effects.test_doubles import FakeEffects, NOW, ran, Streamed +from loop_effects.doubles import FakeEffects, NOW, ran, Streamed from agent_cycle import judge, lingering_workers, worker from claude_code.reply import Limited from machine_load import memory diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py index d1204f01..2ba31dd8 100644 --- a/bin/chunk_driver/claims.py +++ b/bin/chunk_driver/claims.py @@ -34,6 +34,18 @@ def project_lock(root: str, home: pathlib.Path) -> pathlib.Path: return home / CLAIMS / project_key(root, home) +def loop_session(root: str, home: pathlib.Path) -> str: + """The tmux session that holds the windows of loop-claude's chunks of the checkout root.""" + return tmux.session_name(tmux.LOOP, project_key(root, home)) + + +def loop_chunks(root: str, home: pathlib.Path, run: tmux.Tmux) -> list[tmux.Listed]: + """The windows of loop-claude's chunks that run in the checkout root. A session that runs another checkout's chunks under the same name doesn't hold any.""" + session = loop_session(root, home) + running = [window for window in tmux.listed(session, run) if not window.dead] + return running if running and tmux.owner(session, run) == root else [] + + def epic_chunks(root: str, run: tmux.Tmux) -> list[tmux.Placed]: """The windows of do-epic's sessions whose chunks run in the checkout root. A parked chunk doesn't run.""" return [placed for placed in tmux.everywhere(run) if placed.session.startswith(f"{tmux.EPIC}-") and placed.root == root and not placed.window.dead and not placed.window.parked] diff --git a/bin/chunk_driver/project/model_choice.py b/bin/chunk_driver/project/model_choice.py index 672f43cb..5153c7f9 100644 --- a/bin/chunk_driver/project/model_choice.py +++ b/bin/chunk_driver/project/model_choice.py @@ -18,14 +18,24 @@ class Models: worker: str +# The environment variables that name the judge's and the worker's model for one run, over the model saved or configured. +JUDGE_MODEL = "LOOP_CLAUDE_JUDGE_MODEL" +WORKER_MODEL = "LOOP_CLAUDE_WORKER_MODEL" + + +def overridden(env: typing.Mapping[str, str], default: str) -> Models: + """The models of a run: default, unless env names another for the judge or the worker.""" + return Models(env.get(JUDGE_MODEL) or default, env.get(WORKER_MODEL) or default) + + def get_or_ask_models(project_key: str, paths: Paths, env: typing.Mapping[str, str], driver: str, effects: Effects) -> Models | Stop: - judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") - if judge and worker: - return Models(judge, worker) + named = overridden(env, "") + if named.judge and named.worker: + return named chosen = get_or_ask_model(project_key, paths, driver, effects) if isinstance(chosen, Stop): return chosen - return Models(judge or chosen, worker or chosen) + return overridden(env, chosen) def get_or_ask_model(project_key: str, paths: Paths, driver: str, effects: Effects) -> str | Stop: diff --git a/bin/chunk_driver/project/test_model_choice.py b/bin/chunk_driver/project/test_model_choice.py index 837e59c4..356cb873 100644 --- a/bin/chunk_driver/project/test_model_choice.py +++ b/bin/chunk_driver/project/test_model_choice.py @@ -7,12 +7,19 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) from failure import Failure -from loop_effects.test_doubles import FakeEffects +from loop_effects.doubles import FakeEffects from chunk_driver.drivers import LOOP_CLAUDE from chunk_driver.project import model_choice from agent_cycle.stop import Stop +class Overridden(unittest.TestCase): + def test_the_environment_names_the_judges_or_the_workers_model_over_the_default(self): + self.assertEqual(model_choice.overridden({}, "saved"), model_choice.Models("saved", "saved")) + self.assertEqual(model_choice.overridden({"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": ""}, "saved"), model_choice.Models("j", "saved")) + self.assertEqual(model_choice.overridden({"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}, "saved"), model_choice.Models("j", "w")) + + class ModelPrompt(unittest.TestCase): OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")] diff --git a/bin/chunk_driver/test_chunk_run.py b/bin/chunk_driver/test_chunk_run.py new file mode 100644 index 00000000..3179a582 --- /dev/null +++ b/bin/chunk_driver/test_chunk_run.py @@ -0,0 +1,92 @@ +import contextlib +import dataclasses +import io +import json +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from chunk_driver import chunk_run, cycle_start, this_loop +from loop_effects.doubles import FakeEffects, NOW +from agent_cycle.verdicts import Finished, TakenIn, Unfinished +from transcript_archive import outcomes, write +from loop_state import paths +from model_routing.ladder import ProjectRung, Rung +from model_routing.ladder_file import read_ladder, SHIPPED +from model_routing.route import Route +from agent_cycle import run +from claude_code import session +from agent_cycle.test_tmux import WINDOW + +OPUS_PROJECT = ProjectRung(read_ladder(SHIPPED), Rung("claude-opus-5-5", "medium")) + + +def a_loop(effects, **fields): + """A loop in /r on effects, with fields in place of its defaults.""" + home = pathlib.Path("/h") + defaults = {"root": "/r", "session": session.session_named("A proj a-driver", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/a-driver"), "window": WINDOW} + return this_loop.Loop(**{**defaults, **fields}, effects=effects) + + +class Steps(unittest.TestCase): + OPUS = Rung("claude-opus-5-5", "medium") + # The rungs an L 3 and an L 4 pick from OPUS. + FABLE_LOW = Rung("claude-fable-5-2", "low") + FABLE_MEDIUM = Rung("claude-fable-5-2", "medium") + + def test_a_finished_verdict_clears_the_route_and_the_evidence(self): + run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="old", route=Route(self.OPUS)) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence="")) + self.assertEqual(chunk_run.after_verdict(dataclasses.replace(run_with, unfinished_run=3), OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(self.FABLE_MEDIUM, unfinished=1), unfinished_evidence="new", unfinished_run=1)) + + def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self): + run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4)) + raised = Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=5) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1)) + + def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self): + off_ladder = Route(Rung("worker-model")) + run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="") + self.assertEqual(chunk_run.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder) + + def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self): + run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="", route=Route(self.FABLE_LOW, 3, 3, 4, escalated_at=2)) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=9)) + self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.FABLE_LOW, 3, 3, 4, unfinished=1, escalated_at=2)) + + def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self): + with tempfile.TemporaryDirectory() as home: + opened = session.session_named("A proj a-driver", pathlib.Path(home, "projects")) + archive = pathlib.Path(home, "archive") + transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") + transcript.parent.mkdir(parents=True) + transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") + before = Route(self.FABLE_LOW, 3, 3, 4) + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) + after = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) + with contextlib.redirect_stderr(io.StringIO()): + chunk_run.closed_cycle(after, OPUS_PROJECT, run.Concluded(Finished("done"), after.route), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) + blocked = pathlib.Path(home, "blocked") + blocked.write_text("") + stop = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) + + def test_archives_a_higher_e_plus_i_taken_in_so_a_rerun_keeps_it(self): + with tempfile.TemporaryDirectory() as home: + opened = session.session_named("A proj a-driver", pathlib.Path(home, "projects")) + archive = pathlib.Path(home, "archive") + transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") + transcript.parent.mkdir(parents=True) + transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") + before = Route(self.FABLE_LOW, 3, 3, 4) + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) + chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6)) diff --git a/bin/chunk_pr/approval.py b/bin/chunk_pr/approval.py index bb343868..2e6fa2d8 100644 --- a/bin/chunk_pr/approval.py +++ b/bin/chunk_pr/approval.py @@ -2,9 +2,9 @@ import time import typing +from forge.reviews import APPROVED, CHANGES_REQUESTED, github_decision, REVIEW_REQUIRED, waiting_threads from failure import Failure from forge.commands import Forge, Run -from forge.reviews import github_decision, waiting_threads # A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed. POLL_SECONDS = 60 @@ -25,13 +25,13 @@ def approval(number: str, run: Run) -> bool | Failure: decision = github_decision(number, run) if isinstance(decision, Failure): return decision - if decision == "CHANGES_REQUESTED": + if decision == CHANGES_REQUESTED: return Failure(f"a reviewer requested changes on pull request {number}") if not decision: return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false") - if decision not in ("APPROVED", "REVIEW_REQUIRED"): + if decision not in (APPROVED, REVIEW_REQUIRED): return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision") - return decision == "APPROVED" + return decision == APPROVED def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None: diff --git a/bin/do_epic/gates.py b/bin/do_epic/gates.py index c73839e2..8bd1264b 100644 --- a/bin/do_epic/gates.py +++ b/bin/do_epic/gates.py @@ -4,7 +4,7 @@ A gate is something only time or a person passes: checks that still run, an appr import dataclasses import typing -from forge.reviews import ANSWERED, review_decision, waiting_threads +from forge.reviews import ANSWERED, APPROVED, CHANGES_REQUESTED, review_decision, REVIEW_REQUIRED, waiting_threads from forge.pulls import CheckFailed, checks_now, open_pull, Pending, required_checks from failure import Failure from forge.commands import forge_of, Run @@ -62,16 +62,16 @@ def gate(branch: str, checkout: str, at: typing.Callable[[str], Run]) -> Gate | return checks if isinstance(checks, Pending): return Gate(worktree, pull, CHECKS) - if decision == "CHANGES_REQUESTED": + if decision == CHANGES_REQUESTED: return Open(f"a reviewer requested changes on pull request #{pull}") waiting = waiting_threads(pull, run) if forge == "gh" else [] if isinstance(waiting, Failure): return waiting if waiting: return Open(f"a reviewer's comment on pull request #{pull} waits for an answer, in {', '.join(waiting)}") - if decision in (ANSWERED, "REVIEW_REQUIRED"): + if decision in (ANSWERED, REVIEW_REQUIRED): return Gate(worktree, pull, NEW_REVIEW if decision == ANSWERED else APPROVAL) - return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == "APPROVED" else "")) + return Open(f"pull request #{pull} passed its checks" + (" and is approved" if decision == APPROVED else "")) def worktree_of(branch: str, run: Run) -> str | None | Failure: diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 6c79cc70..adda3270 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -29,7 +29,7 @@ from do_epic.backend.jira import JiraEpic from claude_code.reply import Limited from do_epic.repos import locate from chunk_driver.this_loop import Loop -from chunk_driver.project.model_choice import Models +from chunk_driver.project.model_choice import Models, overridden from loop_state.paths import Paths from chunk_driver.project.premises import read_premises from forge.commands import Run, runner @@ -441,7 +441,7 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> def repoless_models(epic: EpicRun) -> Models: """The models of a chunk without a repo: `repoless-model`, unless the environment names another for the run, as it may for loop-claude.""" - return Models(epic.env.get("LOOP_CLAUDE_JUDGE_MODEL") or epic.config.repoless_model, epic.env.get("LOOP_CLAUDE_WORKER_MODEL") or epic.config.repoless_model) + return overridden(epic.env, epic.config.repoless_model) def records_read(root: str | None, epic: EpicRun) -> str | Failure: diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 59b5d126..8f7b7d90 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -6,14 +6,13 @@ import pathlib import typing from do_epic.epic_record import CAP -from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, LOCK, project_lock, starting +from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, LOCK, loop_chunks, project_lock, starting from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.repo_pick import HumanTask, recorded, Repo from project_config.settings import PARALLEL_CHUNKS from do_epic.parked import parked_chunks from chunk_pr.approval import PARKS -from transcript_archive.project_key import project_key from do_epic.split import SPLIT_LABEL from agent_cycle import tmux @@ -198,9 +197,7 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pathlib.Path, run: tmux.Tmux) -> RepoRoom: """The room in a repo's checkout under its limit. leaving is the session and name of the window that asks, which doesn't count: its chunk finished or is parked.""" theirs = [placed for placed in epic_chunks(checkout, run) if (placed.session, placed.window.name) != leaving] - loop_session = tmux.session_name(tmux.LOOP, project_key(checkout, home)) - loops = any(not window.dead for window in tmux.listed(loop_session, run)) and tmux.owner(loop_session, run) == checkout - return RepoRoom(limit, len(theirs), loops) + return RepoRoom(limit, len(theirs), bool(loop_chunks(checkout, home, run))) def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | None: diff --git a/bin/do_epic/test_findings.py b/bin/do_epic/test_findings.py index f140dc68..a9dab106 100644 --- a/bin/do_epic/test_findings.py +++ b/bin/do_epic/test_findings.py @@ -10,7 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic.test_main import DESCRIPTION, DoEpicTest from do_epic.epic_record import EpicRecord from failure import Failure -from loop_effects.test_doubles import FakeEffects +from loop_effects.doubles import FakeEffects from record_store.held import Held from do_epic import main from do_epic.backend.fake import MemoryEpic diff --git a/bin/do_epic/test_finish.py b/bin/do_epic/test_finish.py index 8365bd31..18f75bb5 100644 --- a/bin/do_epic/test_finish.py +++ b/bin/do_epic/test_finish.py @@ -9,7 +9,7 @@ from do_epic.test_main import Description, DESCRIPTION, DoEpicTest, MODELS, UNRE from do_epic.config import DoEpicConfig, load from do_epic.epic_record import EpicRecord from failure import Failure -from loop_effects.test_doubles import FakeEffects, judged, Worker +from loop_effects.doubles import FakeEffects, judged, Worker from do_epic import findings, finish, main, scheduler from project_config.settings import Finish from do_epic.test_scheduler import issue diff --git a/bin/do_epic/test_human_tasks.py b/bin/do_epic/test_human_tasks.py index 5fc9593b..9ac6e426 100644 --- a/bin/do_epic/test_human_tasks.py +++ b/bin/do_epic/test_human_tasks.py @@ -10,7 +10,7 @@ from project_config.test_project_config import configured from do_epic.test_main import DESCRIPTION, Description, DoEpicTest, MODELS, UNREAD from do_epic.epic_record import EpicRecord from failure import Failure -from loop_effects.test_doubles import FakeEffects +from loop_effects.doubles import FakeEffects from do_epic.scheduler import HUMAN_WAIT from do_epic.test_scheduler import issue from do_epic.backend.fake import MemoryEpic diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index d94de101..0c36fe7c 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -16,11 +16,10 @@ from chunk_driver.chunk_run import ChunkRun from project_config.test_project_config import configured from do_epic.config import DoEpicConfig from project_config.settings import Epic, Finish -from do_epic.backend.protocol import EpicIssue from do_epic.epic_record import EpicRecord from agent_cycle import escalation_mark, judge, tmux from failure import Failure -from loop_effects.test_doubles import FakeEffects, judged, Worker +from loop_effects.doubles import FakeEffects, judged, Worker from do_epic.test_gates import Forge from do_epic.test_scheduler import issue from chunk_driver.this_loop import Loop diff --git a/bin/do_epic/test_planning.py b/bin/do_epic/test_planning.py index 892f7730..627cd16e 100644 --- a/bin/do_epic/test_planning.py +++ b/bin/do_epic/test_planning.py @@ -14,7 +14,7 @@ from do_epic.test_main import Description, DoEpicTest, structured as says from do_epic.backend.protocol import EpicIssue from do_epic.epic_record import EpicRecord from failure import Failure -from loop_effects.test_doubles import FakeEffects +from loop_effects.doubles import FakeEffects from do_epic.test_scheduler import issue from claude_code.reply import Limited from do_epic.config import load diff --git a/bin/forge/reviews.py b/bin/forge/reviews.py index 69f26ba9..f5487011 100644 --- a/bin/forge/reviews.py +++ b/bin/forge/reviews.py @@ -5,7 +5,11 @@ import typing from failure import Failure from forge.commands import Forge, gitea, Run -# What `review_decision` returns in place of GitHub's `CHANGES_REQUESTED` once the worker answered those changes: GitHub keeps its decision until the reviewer reviews again. +# GitHub's review decisions on a pull request. CHANGES_REQUESTED is also the state of the review that asked for them. +APPROVED = "APPROVED" +REVIEW_REQUIRED = "REVIEW_REQUIRED" +CHANGES_REQUESTED = "CHANGES_REQUESTED" +# What `review_decision` returns in place of CHANGES_REQUESTED once the worker answered those changes: GitHub keeps its decision until the reviewer reviews again. ANSWERED = "CHANGES_ANSWERED" # What the title of a draft opens with on Gitea, in any case: Gitea's default `WORK_IN_PROGRESS_PREFIXES`. GITEA_DRAFT = ("WIP:", "[WIP]") @@ -22,7 +26,7 @@ def review_decision(forge: Forge, pull: str, head: str, run: Run) -> str | None def github_decision(pull: str, run: Run) -> str | Failure: - """GitHub's review decision on the pull request as it stands, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review.""" + """GitHub's review decision on the pull request as it stands, read once: APPROVED, REVIEW_REQUIRED, CHANGES_REQUESTED, or empty where its branch protection asks for no review.""" viewed = run(["gh", "pr", "view", pull, "--json", "reviewDecision"]) if isinstance(viewed, Failure): return viewed @@ -34,7 +38,7 @@ def github_decision(pull: str, run: Run) -> str | Failure: def answered_decision(pull: str, head: str, run: Run) -> str | None | Failure: - """GitHub's review decision on the pull request, whose head commit is head, read once: `APPROVED`, `REVIEW_REQUIRED`, `CHANGES_REQUESTED`, or empty where its branch protection asks for no review. ANSWERED in place of `CHANGES_REQUESTED` once the worker answered those changes. None where it is a draft.""" + """GitHub's review decision on the pull request, whose head commit is head, read once: APPROVED, REVIEW_REQUIRED, CHANGES_REQUESTED, or empty where its branch protection asks for no review. ANSWERED in place of CHANGES_REQUESTED once the worker answered those changes. None where it is a draft.""" viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"]) if isinstance(viewed, Failure): return viewed @@ -43,7 +47,7 @@ def answered_decision(pull: str, head: str, run: Run) -> str | None | Failure: if parsed["isDraft"]: return None decision = str(parsed["reviewDecision"] or "") - return ANSWERED if decision == "CHANGES_REQUESTED" and answered(parsed, head) else decision + return ANSWERED if decision == CHANGES_REQUESTED and answered(parsed, head) else decision except (ValueError, KeyError, TypeError): return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}") @@ -53,7 +57,7 @@ def answered(pull: dict[str, typing.Any], head: str) -> bool: The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed. """ - asked = max((review for review in pull["reviews"] if review["state"] == "CHANGES_REQUESTED"), key=lambda review: review["submittedAt"], default=None) + asked = max((review for review in pull["reviews"] if review["state"] == CHANGES_REQUESTED), key=lambda review: review["submittedAt"], default=None) if asked is None: return False author = pull["author"]["login"] diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index 792853de..61570bba 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -1,13 +1,12 @@ """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 fcntl import pathlib import re import typing from touch_predictions.beside import Beside, chunks_beside -from chunk_driver.claims import CHUNK_FLAG, CLAIMS, epic_chunks, HANDED, LOCK, project_lock, starting +from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, LOCK, loop_session, project_lock, starting from loop_claude.chunk import chunk_items from git_cli.git_repo import default_ref from loop_effects.effects import Effects, say @@ -115,7 +114,7 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map config = located(loop_run.root, paths.home) if isinstance(config, Failure): return config - session = tmux.session_name(tmux.LOOP, project_key(loop_run.root, paths.home)) + 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: @@ -159,13 +158,12 @@ def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]: """The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it.""" - key = project_key(root, paths.home) - wait_for_starts(paths.home, key) - others = [window.name for window in tmux.listed(tmux.session_name(tmux.LOOP, key), effects.tmux) if window.name != chunk] - return sorted(held_items(others, key, paths.claude_code_transcripts)) + wait_for_starts(root, paths.home) + others = [window.name for window in tmux.listed(loop_session(root, paths.home), effects.tmux) if window.name != chunk] + return sorted(held_items(others, project_key(root, paths.home), paths.claude_code_transcripts)) -def wait_for_starts(home: pathlib.Path, key: str) -> None: +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(home / CLAIMS / key): + with contextlib.suppress(OSError), starting(project_lock(root, home)): pass diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index fed28a68..69632c74 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -6,7 +6,7 @@ from chunk_driver.cycle_start import announced_route, cycle_of, project_routing from transcript_archive.location import archive_root, project_archive from loop_claude.loop.routing_check import check_routing from loop_claude.loop.checkout import checkout_root -from chunk_driver.claims import CHUNK_FLAG +from chunk_driver.claims import CHUNK_FLAG, loop_session 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 @@ -58,7 +58,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc return Stop(1, f"{CHUNK_FLAG} is how loop-claude starts itself in a tmux window; run loop-claude ") baseline = fingerprint(launcher) key = project_key(loop_run.root, paths.home) - window = tmux.Window(tmux.session_name(tmux.LOOP, key), loop_run.chunk, pane) + 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): @@ -86,7 +86,7 @@ def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Path started = start_chunks(loop_run, False, paths, env, launcher, effects) if isinstance(started, Failure): return Stop(1, started.reason) - session = tmux.session_name(tmux.LOOP, project_key(loop_run.root, paths.home)) + session = loop_session(loop_run.root, paths.home) say(f"started {', '.join(started)} in the tmux session {session}" if started else f"the tmux session {session} runs every chunk that may run now, so `{loop_run.task}` started in no new window", effects, stdout=True) if not effects.on_terminal(): say(f"not on a terminal; see the chunks with `tmux attach -t ={session}`", effects, stdout=True) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index c35875bd..5a3a2881 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -343,7 +343,7 @@ class Checkout: self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) stamped = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", " ", kept.read_text(), flags=re.MULTILINE) configured = re.sub(r"^Config: .*$", "Config: ", stamped, flags=re.MULTILINE) - # The judge's run is named by the hash of its prompt and reply, which test_loop_claude.py checks. + # The judge's run is named by the hash of its prompt and reply, which agent_cycle/test_run.py checks. outcomes[copy.read_text()] = re.sub(r"^Judge run: judge/[0-9a-f]{64}\.json\n", "", configured, flags=re.MULTILINE) return outcomes diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 52071b67..52d167e8 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -3,14 +3,11 @@ import contextlib import dataclasses import io import json -import os import pathlib import re import shutil -import stat import sys import tempfile -import types import unittest import unittest.mock @@ -18,7 +15,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive, state from test_env import assert_not_root -from loop_effects.test_doubles import assistant, CWD, FakeEffects, human, judged, kinds, NOW, ran, said, STAMP, Streamed, Worker +from loop_effects.doubles import assistant, CWD, FakeEffects, human, kinds, NOW, ran, said, STAMP from claude_code.output_limits import BASH_CEILING_CHARACTERS from routing_figures.calls import Call from loop_claude.chunk import chunk_items @@ -28,39 +25,29 @@ from project_config.test_project_config import configured from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES from claude_code import entries, reply, session from failure import Failure -from agent_cycle.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished +from agent_cycle.verdicts import Finished, Interrupt, TakenIn, Unfinished from loop_claude.chunk import fresh_prompt -from agent_cycle import judge, retry, run, states, stuck_workers, worker, worker_prompts +from agent_cycle import judge, retry, states, worker, worker_prompts import loop_claude.routed_item from loop_claude.loop import main, reload, routing_check, usage from release_plan import next_chunk from transcript_archive import outcomes, write from loop_state import paths from plan_store.todo_md import plan_of -from transcript_archive.location import project_archive from model_routing.ladder import ProjectRung, Rung from loop_effects.effects import PYTHON_TIMEOUT from model_routing.ladder_file import read_ladder, SHIPPED from chunk_driver.project import records from model_routing.route import Route, route_from, WorkerLine from agent_cycle import routing -from loop_effects.child_shells import Shell from agent_cycle.stop import Stop from agent_cycle import tmux from touch_predictions.test_touch_predictions import plan as touch_plan from text_files.utc_stamp import utc from agent_cycle.test_tmux import WINDOW -# How the archive records a worker that runs off the ladder. LADDER = read_ladder(SHIPPED) OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium")) -OFF_LADDER = '{"model": "worker-model"}' -# The claude-config release and commit each cycle the tests run is under. -CONFIG = "v0.8.0 (abc123)" -# How it records routes by item 179's L of 2 and E + I of 5, on Routing's rungs. -SONNET_179 = '{"model": "claude-sonnet-5-5", "effort": "high", "item": 179, "likelihood": 2, "escape_and_impact": 5}' -OPUS_179_AT_3 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 3}' -OPUS_179_AT_6 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 6}' # How git answers in a project's checkout it cannot read, such as one that is gone. UNREAD = Failure("not a git repository") @@ -73,471 +60,6 @@ def a_loop(effects, **fields): return this_loop.Loop(**{**defaults, **fields}, effects=effects) -JUDGE_RUN_LINE = re.compile(r"^Judge run: judge/[0-9a-f]{64}\.json\n", re.MULTILINE) - - -class QuestionFor(unittest.TestCase): - def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self): - cycle = types.SimpleNamespace(prompts=fresh_prompt.WORKER) - self.assertEqual(run.question_for(cycle, Interrupt("e", "Which one?")), "Which one?") - self.assertEqual(run.question_for(cycle, QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.") - - -class Cycles(unittest.TestCase): - def setUp(self): - temp = tempfile.TemporaryDirectory() - self.addCleanup(temp.cleanup) - self.home = pathlib.Path(temp.name) - self.paths = paths.paths_from(self.home) - self.session = session.session_named("A proj loop-claude", self.paths.claude_code_transcripts) - self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) - - def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."): - return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge=Rung("judge-model"), premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", prompts=fresh_prompt.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan_of("")), unfinished_evidence=unfinished_evidence) - - def archived_outcomes(self): - """Each outcomes file's text without its `Judge run:` lines, which name a file by the hash of a prompt and its reply: the tests of the judge's runs check them.""" - return sorted(JUDGE_RUN_LINE.sub("", path.read_text()) for path in self.archive.glob("*/*.outcomes.md")) - - def test_a_finished_chunk_is_archived_and_its_session_deleted(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) - - def test_archives_the_cost_the_judges_reply_records_beside_its_verdict(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished", cost=0.25)]) - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working", judged=Judged(cost=0.25))) - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nJudge cost: 0.2500\nWorker: {OFF_LADDER}\n"]) - self.assertIsNone(session.transcript_file(self.session)) - - def test_archives_what_the_worker_and_the_judge_spent_beside_the_verdict(self): - worker = Worker(self.paths.claude_code_transcripts.parent, usage={"input_tokens": 1, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5}) - answer = json.loads(judged("finished").stdout) - fake = FakeEffects(streams=[worker], claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 6, "output_tokens": 7}}))]) - run.run_cycle(self.cycle(fake)) - self.assertEqual(self.archived_outcomes(), [f"""Task: Do it. - -2026-09-21T14:13:20Z Verdict: finished - -Evidence: -> working - -Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output: -- worker, claude-opus-5-5: 1, 2, 3, 4, 5 -- judge, judge-model: 6, 0, 0, 0, 7 - -List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output: -- claude-opus-5-5: 4, 5, 8, 0.2, 20 - -Config: {CONFIG} -Judge: judge-model -Worker: {OFF_LADDER} -"""]) - - def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self): - worker = Worker(self.paths.claude_code_transcripts.parent) - fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")]) - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) - self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Finished("working")) - fresh, resumed = (args[args.index("-p") + 1] for args in fake.made("stream_claude")) - self.assertIn("- A preflight fact.", fresh) - self.assertNotIn("- A preflight fact.", resumed) - - def test_a_worker_is_handed_the_projects_rung_its_own_its_reviews_e_plus_i_and_its_compaction_window_in_its_environment(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) - cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) - self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) - self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5", "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "200000", "BASH_MAX_OUTPUT_LENGTH": "6000"}]) - - def test_a_stuck_check_of_the_worker_runs_on_the_projects_rung_and_off_the_ladder_on_the_workers_own(self): - for project, model in ((OPUS_PROJECT, "claude-opus-5-5"), (None, "claude-haiku-5-5")): - with self.subTest(project=project): - clock = [NOW] - quiet = Shell(pid=7, started=NOW, command="bin/run-tests", written=NOW, runs_busy_tool=False) - events = ({"type": "assistant", "message": {"content": []}}, None, None, {"type": "result"}) - stream = lambda args: (Worker(self.paths.claude_code_transcripts.parent)(args), Streamed(0, *events, clock=clock, held=[quiet]))[1] - verdict = ran(json.dumps({"type": "result", "structured_output": {"verdict": "stuck", "process": 7, "why": "it waits"}})) - fake = FakeEffects(streams=[stream], claude=[verdict, judged("finished")]) - cycle = dataclasses.replace(self.cycle(fake), project=project, route=Route(Rung("claude-haiku-5-5", "max"))) - with contextlib.redirect_stdout(io.StringIO()): - run.run_cycle(dataclasses.replace(cycle, effects=dataclasses.replace(cycle.effects, now=lambda: clock[0]))) - [investigator, _] = [args for args, _ in fake.made("claude")] - self.assertEqual(investigator[investigator.index("--model") + 1], model) - self.assertEqual(fake.worker_folders, [str(self.home)]) - self.assertIn("judged the worker stuck", (self.archive / stuck_workers.RECORD).read_text()) - - def test_the_claude_an_interrupt_resumes_is_handed_the_same_rungs_as_the_worker(self): - def answer(args): - with open(session.transcript_file(self.session), "a") as handle: - handle.write(json.dumps(human("the second")) + "\n") - return 0 - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer]) - cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) - with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) - self.assertEqual(fake.terminal_environments, [{**environment, "CLAUDE_CODE_SANDBOXED": "1"} for environment in fake.worker_environments]) - self.assertEqual(fake.terminal_environments[0]["LOOP_CLAUDE_WORKER_RUNG"], "claude-haiku-5-5 at max effort") - - def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2) - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) - self.assertTrue(session.transcript_file(self.session)) - self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Unfinished("working", entries_read=4)) - workers = fake.made("stream_claude") - self.assertIn("--session-id", workers[0]) - self.assertIn("--resume", workers[1]) - self.assertIn("as the work remaining:\n\n> working\n\nThe chunk is finished once", workers[1][workers[1].index("-p") + 1]) - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2) - - def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3) - self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()]) - self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, "")) - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: {OFF_LADDER}\n"]) - - def test_each_judge_reply_the_loop_rejects_is_archived_with_why_beside_the_verdict_that_follows(self): - unfilled = ran(json.dumps({"structured_output": {"interrupt": False}})) - misquoted = judged("finished", evidence="never said") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[unfilled, misquoted, judged("finished")]) - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) - stamp = "2026-09-21T14:13:20Z" - self.assertEqual(self.archived_outcomes(), [ - "Task: Do it.\n\n" - f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n" - f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n" - f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) - - def test_archives_each_judge_runs_prompt_and_reply_beside_the_rejection_interrupt_and_verdict_it_gave(self): - rejected, interrupted, finished = ran(json.dumps({"structured_output": {"interrupt": False}})), judged("interrupt", cost=0.25), judged("finished") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[rejected, interrupted, finished], inputs=["Use B."]) - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) - prompts = [stdin for args, stdin in fake.made("claude")[:3]] - [chunk] = self.archive.iterdir() - kept = "\n".join(path.read_text() for path in chunk.glob("*.outcomes.md")) - named = re.findall(r"^Judge run: (judge/[0-9a-f]{64}\.json)$", kept, re.MULTILINE) - self.assertEqual(len(named), 3, kept) - runs = [json.loads((chunk / name).read_text()) for name in named] - replies = [json.loads(reply.stdout) for reply in (rejected, interrupted, finished)] - self.assertEqual(sorted((found["prompt"], json.dumps(found["reply"])) for found in runs), sorted((prompt, json.dumps(reply)) for prompt, reply in zip(prompts, replies))) - self.assertEqual(sorted(path.name for path in (chunk / "judge").iterdir()), sorted(name.removeprefix("judge/") for name in named)) - - def test_stops_when_a_judge_run_cannot_be_archived(self): - self.archive.mkdir(parents=True) - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) - def replace_file(path, data): - return Failure("disk full") if "/judge/" in str(path) else real_replace_file(path, data) - real_replace_file = write.replace_file - with unittest.mock.patch("transcript_archive.write.replace_file", replace_file): - stop = run.run_cycle(self.cycle(fake)) - self.assertEqual(stop.code, 1) - self.assertRegex(stop.reason, r"^could not archive the transcript: .*/judge/[0-9a-f]{64}\.json: disk full$") - - def test_archives_what_each_judge_run_cost_on_an_interrupt_a_quoted_answer_and_a_rejected_misquote(self): - for first, then, inputs in ( - (judged("interrupt", cost=0.25), judged("finished"), ["Use B."]), - (judged("quoted", answer="Use A.", cost=0.25), judged("finished"), []), - (judged("unfinished", cost=0.25), judged("finished"), []), - (judged("finished", evidence="never said", cost=0.25), judged("finished"), []), - ): - with self.subTest(first=first.stdout), tempfile.TemporaryDirectory() as archive: - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[first, then], inputs=inputs) - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - run.run_cycle(dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project_archive=pathlib.Path(archive))) - kept = "".join(path.read_text() for path in pathlib.Path(archive).glob("*/*.outcomes.md")) - self.assertEqual(kept.count("Judge cost: 0.2500\n"), 1, kept) - self.assertIn("Judge cost: 0.2500\nJudge run: judge/", kept) - - def test_stops_with_exit_1_where_a_subagents_transcript_cannot_be_read_for_the_spend(self): - for verdict in ("interrupt", "finished"): - with self.subTest(verdict=verdict), tempfile.TemporaryDirectory() as archive: - unreadable = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" / "agent-x.jsonl" - unreadable.mkdir(parents=True) - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged(verdict)], inputs=["Use B."]) - with contextlib.redirect_stderr(io.StringIO()): - stop = run.run_cycle(dataclasses.replace(self.cycle(fake), project_archive=pathlib.Path(archive))) - self.assertEqual((stop.code, stop.reason), (1, f"could not read the transcript {unreadable}: Is a directory")) - shutil.rmtree(unreadable.parent.parent) - (self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl").unlink() - - def test_counts_the_spend_since_the_last_outcome_that_recorded_one_and_archives_the_reversal(self): - transcript = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl" - transcript.parent.mkdir(parents=True) - old = {"type": "assistant", "timestamp": "2026-09-21T14:13:19Z", "message": {"id": "old", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 100}}} - new = {"type": "assistant", "timestamp": "2026-09-21T14:13:21Z", "message": {"id": "new", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 5}}} - transcript.write_text("\n".join(json.dumps(entry) for entry in [{"type": "queue-operation", "timestamp": "2026-09-21T14:00:00Z"}, old, human("No, keep the old name."), new]) + "\n") - with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished", reversed="No, keep the old name.")]) - run.run_cycle(self.cycle(fake)) - latest = max(self.archived_outcomes(), key=len) - self.assertIn(f"""Reversed: -> No, keep the old name. - -Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache write 1h, cache read, output: -- worker, claude-opus-5-5: 0, 0, 0, 0, 5 -""", latest) - - def test_stops_with_exit_1_asking_nothing_where_an_interrupt_cannot_be_archived(self): - self.archive.parent.mkdir(parents=True) - self.archive.write_text("") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt")], inputs=["Use B."]) - with contextlib.redirect_stderr(io.StringIO()) as said: - stop = run.run_cycle(self.cycle(fake)) - self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) - self.assertNotIn("Which one?", said.getvalue()) - self.assertEqual(fake.made("claude_on_terminal"), []) - - def test_stops_when_a_rejected_reply_cannot_be_archived(self): - self.archive.parent.mkdir(parents=True) - self.archive.write_text("") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(json.dumps({"structured_output": {"interrupt": False}})), judged("finished")]) - stop = run.run_cycle(self.cycle(fake)) - self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$") - self.assertEqual(stop.code, 1) - self.assertEqual(len(fake.made("claude")), 1) - - def test_archives_the_judges_rejected_replies_though_it_fails_three_times_running(self): - unfilled = ran(json.dumps({"structured_output": {"interrupt": False}})) - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[unfilled] * 3) - self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) - [archived] = self.archived_outcomes() - self.assertEqual(archived.count(f"Reply:\n> {unfilled.stdout}\n"), 3) - self.assertIn("Stopped: the judge failed three times running", archived) - - def test_archives_each_chunks_session_folder_replacing_a_copy_only_with_what_grew_from_it(self): - folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) - (folder / "subagents" / "workflows").mkdir(parents=True) - (folder / "subagents" / "agent-a.jsonl").write_text("a\n") - (folder / "subagents" / "workflows" / "journal.jsonl").write_text("j\n") - (folder / "custom-title.json").write_text("first") - (folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")]) - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) - [chunk] = self.archive.iterdir() - kept = chunk / "session" / str(self.session.id) - self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n") - os.utime(kept / "subagents" / "workflows" / "journal.jsonl", (0, 0)) - with open(folder / "subagents" / "agent-a.jsonl", "a") as handle: - handle.write("more\n") - (folder / "custom-title.json").write_text("second") - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) - self.assertFalse(folder.exists()) - self.assertEqual((kept / "subagents" / "agent-a.jsonl").read_text(), "a\nmore\n") - self.assertEqual((kept / "subagents" / "workflows" / "journal.jsonl").stat().st_mtime, 0) - self.assertEqual(sorted(path.read_text() for path in kept.glob("custom-title.json*")), ["first", "second"]) - self.assertEqual(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600) - folder.mkdir() - (folder / "custom-title.json").write_text("third") - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3)) - [next_chunk] = set(self.archive.iterdir()) - {chunk} - self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"]) - - def test_stops_on_a_session_folder_it_cannot_read_whole(self): - assert_not_root(self) - locked = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" - locked.mkdir(parents=True) - locked.chmod(0) - self.addCleanup(locked.chmod, 0o700) - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished")]) - self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"could not archive the transcript: {locked}: Permission denied")) - - def test_an_interrupt_talked_over_in_claude_is_archived_answered_and_judged_again(self): - def answer(args): - with open(session.transcript_file(self.session), "a") as handle: - handle.write(json.dumps(human("the second")) + "\n") - return 0 - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer]) - with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4)) - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) - self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) - judge_prompts = [stdin for args, stdin in fake.made("claude")] - self.assertEqual(len(judge_prompts), 2) - self.assertNotIn("the second", judge_prompts[0]) - self.assertIn("[human] the second", judge_prompts[1]) - self.assertIn("From the goals file, ## Goals", judge_prompts[0]) - self.assertIn(f"writing it into {prompts.ANSWER_DESTINATIONS},", judge_prompts[0]) - self.assertIn("The task the worker was given:\nDo it.", judge_prompts[0]) - - def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self): - answered = judged("quoted", answer="Use *A*.") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, inputs=[""]) - with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed: - self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed")) - resumed = fake.made("stream_claude")[1] - self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards answers it:\n\nUse *A*.\n\nContinue the task.") - self.assertEqual(len(fake.made("stream_claude")), 4) - self.assertEqual(printed.getvalue().count("=== the goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards answered: Which one? ===\nUse *A*."), 3) - self.assertIn("Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue()) - quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\n> Use *A*.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n" - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3]) - - def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")]) - cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5)) - with contextlib.redirect_stdout(io.StringIO()): - concluded = run.run_cycle(cycle) - self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)) - first, resumed = fake.made("stream_claude") - self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) - self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{fresh_prompt.WORKER.rungs_held(concluded.route, OPUS_PROJECT)}")) - self.assertNotIn("went through", first[first.index("-p") + 1]) - answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n" - stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n" - kept = "".join(self.archived_outcomes()) - self.assertIn(f"Z {answered}\n20", kept) - self.assertIn(f"Z {stepped}", kept) - - def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self): - steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")] - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""]) - cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5)) - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed")) - kept = "".join(self.archived_outcomes()) - self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n", kept) - self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept) - - def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self): - cycle = dataclasses.replace(self.cycle(FakeEffects()), project=OPUS_PROJECT, route=Route(Routing.ONE_UP, 3, 3, 4)) - for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)): - with self.subTest(ruling=ruling): - self.assertIsNone(run.ruling_step_up(cycle, ruling)) - self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(Routing.THREE_UP, 3, 3, 4, escalated_at=3))) - - def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self): - streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)] - rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")] - fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) - cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5)) - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - concluded = run.run_cycle(cycle) - self.assertEqual(concluded.route, Route(Routing.ONE_UP, 179, 2, 5, escalated_at=4)) - self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "low"]) - - def test_an_escalation_quoted_from_before_the_workers_last_step_up_steps_nothing_and_a_later_one_reaches_the_verdict(self): - for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", "working", entries_read=4))): - with self.subTest(escalation=escalation): - self.session = session.session_named(f"A proj {escalation} loop-claude", self.paths.claude_code_transcripts) - streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)] - rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)] - fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."]) - cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5)) - with contextlib.redirect_stderr(io.StringIO()): - concluded = run.run_cycle(cycle) - self.assertEqual(concluded, run.Concluded(verdict, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))) - - def test_an_answer_typed_at_the_terminal_resumes_the_worker_headless_and_the_judge_reads_it_as_the_humans(self): - worker = Worker(self.paths.claude_code_transcripts.parent, prompted=True) - fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."]) - with contextlib.redirect_stderr(io.StringIO()) as said: - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6)) - self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue()) - self.assertEqual(fake.made("claude_on_terminal"), []) - resumed = fake.made("stream_claude")[1] - self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id)) - typed = resumed[resumed.index("-p") + 1] - self.assertEqual(worker_prompts.typed_answer(typed).answer, "Use B.") - self.assertIn("Which one?", typed) - self.assertIn("Continue the task. The chunk is finished only once every answer the human typed in it", typed) - judge_prompts = [stdin for args, stdin in fake.made("claude")] - self.assertRegex(judge_prompts[1], r"(?s)\[loop\] Your question was: Which one\?.*\n\n\[human\] Use B\.\n\nworking\n\nDecide whether") - self.assertNotIn("The human answered", judge_prompts[1]) - - def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."]) - cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5)) - with contextlib.redirect_stderr(io.StringIO()): - concluded = run.run_cycle(cycle) - self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)) - first, resumed = fake.made("stream_claude") - self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) - typed = resumed[resumed.index("-p") + 1] - self.assertIn("Your request for a higher rung went through: loop-claude runs you on claude-opus-5-5 at medium effort.", typed) - self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 179's E + I of 5 picks.", typed) - self.assertNotIn("went through", first[first.index("-p") + 1]) - - def test_an_interrupt_that_steps_the_worker_up_compacts_its_session_on_the_rung_it_ran_on(self): - usage = {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 5000}, "cache_read_input_tokens": 70000, "output_tokens": 100} - worker = Worker(self.paths.claude_code_transcripts.parent, usage=usage, sent=utc(NOW - 600)) - fake = FakeEffects(streams=[worker, Streamed(0), worker], claude=[judged("interrupt", escalation="working"), judged("finished")]) - - def typed(prompt): - for _, action in fake.timers: - action() - return "Use B." - fake.scripts["input"] = [typed] - cycle = dataclasses.replace(self.cycle(fake), project=OPUS_PROJECT, route=Route(Routing.SONNET, 179, 2, 5)) - with contextlib.redirect_stderr(io.StringIO()): - run.run_cycle(cycle) - _, compaction, resumed = fake.made("stream_claude") - self.assertEqual(compaction[compaction.index("-p") + 1], "/compact") - self.assertEqual([(args[args.index("--model") + 1], args[args.index("--effort") + 1]) for args in (compaction, resumed)], [("claude-sonnet-5-5", "high"), ("claude-opus-5-5", "medium")]) - - def test_a_typed_answer_past_the_quoted_answers_cap_reaches_the_worker_with_its_own_question(self): - worker = Worker(self.paths.claude_code_transcripts.parent) - fake = FakeEffects(streams=[worker] * 5, claude=[judged("quoted", answer="Use A.")] * 4 + [judged("finished")], inputs=["Use B."]) - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")).verdict, Finished("working")) - typed = fake.made("stream_claude")[4] - self.assertIn("Your question was: Which one?\n\nContinue the task.", typed[typed.index("-p") + 1]) - self.assertNotIn("Those files have answered", typed[typed.index("-p") + 1]) - - def test_a_release_ready_to_cut_opens_claudes_session_without_asking_for_an_answer(self): - def answer(args): - with open(session.transcript_file(self.session), "a") as handle: - handle.write(json.dumps(human("cut")) + "\n") - return 0 - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt", release_ready=True), judged("finished")], on_terminal_claude=[answer]) - with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) - self.assertEqual(fake.made("input"), []) - self.assertEqual(len(fake.made("claude_on_terminal")), 1) - - def test_stops_when_an_interrupt_cannot_be_archived(self): - self.archive.parent.mkdir(parents=True) - self.archive.write_text("") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt")], inputs=["Use B."]) - stop = run.run_cycle(self.cycle(fake)) - self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$") - self.assertEqual(fake.made("input"), []) - - def test_stops_when_a_quoted_answer_cannot_be_archived(self): - self.archive.parent.mkdir(parents=True) - self.archive.write_text("") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use A.")]) - with contextlib.redirect_stdout(io.StringIO()): - stop = run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")) - self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$") - self.assertEqual(len(fake.made("stream_claude")), 1) - - def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], inputs=[""]) - with contextlib.redirect_stderr(io.StringIO()) as said: - self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed")) - self.assertEqual(len(fake.made("stream_claude")), 1) - self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue()) - self.assertNotIn("Use ... A.", said.getvalue()) - - def test_stops_keeping_the_transcript_when_the_finished_chunks_session_cannot_be_deleted(self): - assert_not_root(self) - folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) - (folder / "subagents").mkdir(parents=True) - folder.chmod(0o500) - self.addCleanup(folder.chmod, 0o700) - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) - stop = run.run_cycle(self.cycle(fake)) - self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then run it again; a run before that resumes the finished chunk's session")) - self.assertTrue(session.session_open(self.session)) - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"]) - - def test_stops_when_the_worker_leaves_no_transcript(self): - fake = FakeEffects(streams=[Streamed(0)]) - self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}")) - - class RoutingCheck(unittest.TestCase): def setUp(self): self.home = pathlib.Path(tempfile.mkdtemp()) @@ -1177,72 +699,6 @@ class StartChunks(unittest.TestCase): self.assertEqual(chunk_windows.held_items(["item-7", "item-8", "no-item"], "proj", transcripts), {7, 8, 9}) -class Steps(unittest.TestCase): - OPUS = Rung("claude-opus-5-5", "medium") - # The rungs an L 3 and an L 4 pick from OPUS. - FABLE_LOW = Rung("claude-fable-5-2", "low") - FABLE_MEDIUM = Rung("claude-fable-5-2", "medium") - - def test_a_finished_verdict_clears_the_route_and_the_evidence(self): - run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS)) - self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence="")) - self.assertEqual(chunk_run.after_verdict(dataclasses.replace(run_with, unfinished_run=3), OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0) - self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(self.FABLE_MEDIUM, unfinished=1), unfinished_evidence="new", unfinished_run=1)) - - def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self): - run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4)) - raised = Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=5) - self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1)) - - def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self): - off_ladder = Route(Rung("worker-model")) - run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="") - self.assertEqual(chunk_run.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder) - - def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self): - run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.FABLE_LOW, 3, 3, 4, escalated_at=2)) - self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=9)) - self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.FABLE_LOW, 3, 3, 4, unfinished=1, escalated_at=2)) - - def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self): - with tempfile.TemporaryDirectory() as home: - opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects")) - archive = pathlib.Path(home, "archive") - transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") - transcript.parent.mkdir(parents=True) - transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") - before = Route(self.FABLE_LOW, 3, 3, 4) - with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) - after = chunk_run.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) - self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) - with contextlib.redirect_stderr(io.StringIO()): - chunk_run.closed_cycle(after, OPUS_PROJECT, run.Concluded(Finished("done"), after.route), archive, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) - self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) - blocked = pathlib.Path(home, "blocked") - blocked.write_text("") - stop = chunk_run.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) - self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) - - def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self): - route = Route(self.OPUS, 3, 3, 4) - self.assertIsNone(routing.step_up(route, dataclasses.replace(route, unfinished=1))) - self.assertEqual(routing.step_up(route, route.taking_in(6)), routing.StepUp(route, route.taking_in(6))) - - def test_archives_a_higher_e_plus_i_taken_in_so_a_rerun_keeps_it(self): - with tempfile.TemporaryDirectory() as home: - opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects")) - archive = pathlib.Path(home, "archive") - transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") - transcript.parent.mkdir(parents=True) - transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") - before = Route(self.FABLE_LOW, 3, 3, 4) - with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) - chunk_run.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, fresh_prompt.DRIVER, a_loop(FakeEffects().effects(), session=opened)) - self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6)) - - class ChunkFacts(unittest.TestCase): # The launcher beside which chunk_start finds /b/chunk-preflight. LAUNCHER = pathlib.Path("/b/loop-claude") diff --git a/bin/loop_effects/test_doubles.py b/bin/loop_effects/doubles.py similarity index 66% rename from bin/loop_effects/test_doubles.py rename to bin/loop_effects/doubles.py index 7711cd55..802abab9 100644 --- a/bin/loop_effects/test_doubles.py +++ b/bin/loop_effects/doubles.py @@ -2,20 +2,25 @@ import json import pathlib import subprocess +import typing import uuid from loop_effects.effects import Effects from claude_code import entries +from failure import Failure from machine_load import memory +from loop_effects.child_shells import Shell CWD = pathlib.Path("/c") NOW = 1790000000 -def assistant(*parts): + + +def assistant(*parts: typing.Any) -> dict[str, typing.Any]: return {"type": "assistant", "message": {"content": list(parts)}} -def human(content): +def human(content: typing.Any) -> dict[str, typing.Any]: return {"type": "user", "message": {"content": content}} @@ -23,31 +28,31 @@ 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=(), dm_failures=(), tmux_version="tmux 3.2", windows=None, owner="/r"): - self.calls = [] + def __init__(self, claude: typing.Iterable[typing.Any] = (), on_terminal_claude: typing.Iterable[typing.Any] = (), git: typing.Iterable[typing.Any] = (), inputs: typing.Iterable[typing.Any] = (), python: typing.Iterable[typing.Any] = (), streams: typing.Iterable[typing.Any] = (), on_terminal: bool = True, free_memory: typing.Iterable[memory.Memory | None] = (), dm_failures: typing.Iterable[Failure | None] = (), tmux_version: str = "tmux 3.2", windows: str | None = None, owner: str = "/r") -> None: + self.calls: list[tuple[str, typing.Any]] = [] # Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session. - self.tmux_calls = [] + self.tmux_calls: list[list[str]] = [] self.tmux_version = tmux_version self.windows = windows # The checkout the session's @loop-root option names. self.owner = owner # Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent. - self.dms = [] + self.dms: list[str] = [] # The directory each DM named, in the order of self.dms; None where it named none. - self.dm_directories = [] + self.dm_directories: list[str | None] = [] self.dm_failures = list(dm_failures) - 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)} + self.scripts: dict[str, list[typing.Any]] = {"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) self.terminal = on_terminal - self.worker_environments = [] - self.worker_folders = [] - self.terminal_environments = [] - self.terminal_folders = [] + self.worker_environments: list[dict[str, str]] = [] + self.worker_folders: list[str] = [] + self.terminal_environments: list[dict[str, str]] = [] + self.terminal_folders: list[str] = [] # Each timer started, as its delay and action, which a test runs where the timer fires. - self.timers = [] + self.timers: list[tuple[float, typing.Callable[[], None]]] = [] - def effects(self): + def effects(self) -> Effects: return Effects( claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)), claude_on_terminal=self.on_terminal_claude, @@ -68,55 +73,55 @@ class FakeEffects: tmux_on_terminal=lambda args: self.tmux(args).returncode, ) - def timer(self, delay, action): + def timer(self, delay: float, action: typing.Callable[[], None]) -> typing.Callable[[], None]: self.timers.append((delay, action)) return lambda: self.calls.append(("stop_timer", delay)) - def tmux(self, args): + def tmux(self, args: list[str]) -> subprocess.CompletedProcess[str]: self.tmux_calls.append(args) if args[0] == "list-windows": return subprocess.CompletedProcess(args, 1 if self.windows is None else 0, self.windows or "", "no server") return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n", "show-options": self.owner + "\n"}.get(args[0], "@9\n"), "") - def dm(self, text, directory): + def dm(self, text: str, directory: str | None) -> Failure | None: self.dms.append(text) self.dm_directories.append(directory) return self.dm_failures.pop(0) if self.dm_failures else None - def memory(self): + def memory(self) -> memory.Memory | None: self.calls.append(("memory", None)) return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16) - def on_terminal_claude(self, args, cwd, env): + def on_terminal_claude(self, args: list[str], cwd: str, env: dict[str, str]) -> typing.Any: self.terminal_environments.append(env) self.terminal_folders.append(cwd) return self.answer("claude_on_terminal", args) - def stream(self, args, cwd, env): + def stream(self, args: list[str], cwd: str, env: dict[str, str]) -> typing.Any: self.worker_environments.append(env) self.worker_folders.append(cwd) return self.answer("stream_claude", args) - def answer(self, seam, what): + def answer(self, seam: str, what: typing.Any) -> typing.Any: self.calls.append((seam, what)) answer = self.scripts[seam].pop(0) if isinstance(answer, BaseException): raise answer return answer(what) if callable(answer) else answer - def execv(self, path, args): + def execv(self, path: str, args: list[str]) -> None: self.calls.append(("execv", args)) raise OSError(2, "No such file or directory") - def made(self, seam): + def made(self, seam: str) -> list[typing.Any]: return [what for called, what in self.calls if called == seam] -def ran(stdout="", code=0, stderr=""): +def ran(stdout: str = "", code: int = 0, stderr: str = "") -> subprocess.CompletedProcess[str]: return subprocess.CompletedProcess([], code, stdout, stderr) -def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""): +def judged(verdict: str, evidence: str = "working", answer: str = "", escalation: str = "", release_ready: bool = False, cost: float | None = None, reversed: str = "") -> subprocess.CompletedProcess[str]: reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed} return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})})) @@ -124,7 +129,7 @@ def judged(verdict, evidence="working", answer="", escalation="", release_ready= class Worker: """A worker claude: writes a line to the session's transcript, then streams a result.""" - def __init__(self, home, prompted=False, text="working", usage=None, sent=None): + def __init__(self, home: pathlib.Path, prompted: bool = False, text: str = "working", usage: dict[str, typing.Any] | None = None, sent: str | None = None) -> None: self.home = home # Whether it records its -p prompt in the transcript first, as claude does. self.prompted = prompted @@ -134,7 +139,7 @@ class Worker: # The time its message records, as utc() writes it; none where None. self.sent = sent - def __call__(self, args): + def __call__(self, args: list[str]) -> "Streamed": flag = "--session-id" if "--session-id" in args else "--resume" path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl" path.parent.mkdir(parents=True, exist_ok=True) @@ -155,26 +160,27 @@ class Worker: class Streamed: """A started claude. An event of None is an idle stretch of CHECK_EVERY seconds, which advances `clock` by that; `held` are the shells it has, and `stopped` collects the ones stopped.""" - def __init__(self, code, *events, clock=None, held=()): + def __init__(self, code: int, *events: dict[str, typing.Any] | None, clock: list[float] | None = None, held: typing.Iterable[Shell] = ()) -> None: self.code = code self.events = events or ({"type": "result"},) self.clock = clock self.held = list(held) - self.stopped = [] + self.stopped: list[Shell] = [] - def lines(self, idle): + def lines(self, idle: float) -> typing.Iterator[str | None]: for event in self.events: if event is None: + assert self.clock is not None, "an idle stretch advances the clock the test passes" self.clock[0] += idle yield None if event is None else json.dumps(event) + "\n" - def shells(self): + def shells(self) -> list[Shell]: return self.held - def stop(self, shell): + def stop(self, shell: Shell) -> None: self.stopped.append(shell) - def wait(self): + def wait(self) -> int: return self.code @@ -182,9 +188,9 @@ class Streamed: STAMP = f"<{NOW}>" -def kinds(*found): +def kinds(*found: dict[str, typing.Any]) -> list[typing.Any]: return [entries.entry_from(entry) for entry in found] -def said(*texts): +def said(*texts: str) -> entries.AssistantTurn: return entries.AssistantTurn(parts=tuple(entries.Text(text) for text in texts)) diff --git a/bin/repo_checks/test_package_cycles.py b/bin/repo_checks/test_package_cycles.py index 3f011f6b..51135a47 100644 --- a/bin/repo_checks/test_package_cycles.py +++ b/bin/repo_checks/test_package_cycles.py @@ -10,17 +10,24 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from repo_checks import ROOT +def imported_by(module: pathlib.Path) -> set[str]: + """The top-level name of each module that the file module imports. A deferred import inside a function counts: it only hides a cycle.""" + found: set[str] = set() + for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))): + names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [node.module or ""] if isinstance(node, ast.ImportFrom) and node.level == 0 else [] + found.update(name.split(".")[0] for name in names) + return found + + def package_imports(bin_folder: pathlib.Path) -> dict[str, set[str]]: - """Each package under bin_folder, with the other packages its modules import, tests aside. A deferred import inside a function counts: it only hides a cycle.""" + """Each package under bin_folder, with the other packages its modules import, tests aside.""" packages = {init.parent.name for init in bin_folder.glob("*/__init__.py")} imported: dict[str, set[str]] = {package: set() for package in packages} for package in packages: for module in (bin_folder / package).rglob("*.py"): if module.name.startswith("test_"): continue - for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))): - names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [node.module or ""] if isinstance(node, ast.ImportFrom) and node.level == 0 else [] - imported[package].update(top for name in names if (top := name.split(".")[0]) in packages and top != package) + imported[package].update(top for top in imported_by(module) if top in packages and top != package) return imported @@ -33,10 +40,21 @@ def driver_imports(bin_folder: pathlib.Path, drivers: tuple[str, ...]) -> list[s found = [] for module in sorted(bin_folder.rglob("*.py")): package = module.relative_to(bin_folder).parts[0] - for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))): - names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [node.module or ""] if isinstance(node, ast.ImportFrom) and node.level == 0 else [] - found += [f"{module.relative_to(bin_folder)} imports {top}" for name in names if (top := name.split(".")[0]) in drivers and top != package] - return sorted(set(found)) + found += [f"{module.relative_to(bin_folder)} imports {top}" for top in imported_by(module) if top in drivers and top != package] + return sorted(found) + + +# The packages a package may not import, its tests included, since they are the layer above it: chunk_driver drives chunks through agent_cycle. +ABOVE = {"agent_cycle": ("chunk_driver",)} + + +def upward_imports(bin_folder: pathlib.Path, above: dict[str, tuple[str, ...]]) -> list[str]: + """Each module under bin_folder that imports a package above names as above its own, tests included, as ` imports `.""" + found = [] + for package, banned in above.items(): + for module in sorted((bin_folder / package).rglob("*.py")): + found += [f"{module.relative_to(bin_folder)} imports {top}" for top in imported_by(module) if top in banned] + return sorted(found) def cycle(imported: dict[str, set[str]]) -> list[str]: @@ -55,6 +73,17 @@ class PackageCycles(unittest.TestCase): def test_no_package_imports_a_driver_of_chunks(self): self.assertEqual(driver_imports(ROOT / "bin", DRIVERS), [], "move what the importer needs into bin/chunk_driver/, or a test double into the package whose code it stands in for") + def test_no_package_imports_the_layer_above_it(self): + self.assertEqual(upward_imports(ROOT / "bin", ABOVE), [], "pass the value in from the layer above, or in a test write it as a literal") + + def test_an_import_of_the_layer_above_is_found_in_tests_too(self): + with tempfile.TemporaryDirectory() as temp: + folder = pathlib.Path(temp) + for package, name, source in (("low", "mod.py", "import other\n"), ("low", "test_mod.py", "from high.mod import x\n"), ("low", "run.py", "def f():\n\timport high\n"), ("high", "mod.py", "import low\n")): + (folder / package).mkdir(exist_ok=True) + (folder / package / name).write_text(source) + self.assertEqual(upward_imports(folder, {"low": ("high",)}), ["low/run.py imports high", "low/test_mod.py imports high"]) + def test_a_driver_imported_from_another_package_is_found_in_tests_too(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) diff --git a/todo.md b/todo.md index bdf2917b..87438e68 100644 --- a/todo.md +++ b/todo.md @@ -171,7 +171,8 @@ The replay: `review-replay claude-opus-5-5 --read-limit` already replays Touches: - `bin/agent_cycle/run.py`: `worker_environment` (small) - `bin/loop_claude/loop/usage.py`: `HELP` (small) -- `bin/loop_claude/test_loop_claude.py`: `Cycles` (small), `HelpLimits` (small) +- `bin/agent_cycle/test_run.py`: `Cycles` (small) +- `bin/loop_claude/test_loop_claude.py`: `HelpLimits` (small) ### 298. Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind. @@ -432,7 +433,7 @@ The archive holds 277 chunk folders under `home/lilleman/.claude`, from 2026-09- ### 181. Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`. -`bin/loop_claude/test_loop_claude.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308. +`bin/agent_cycle/test_run.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308. ### 193. Narrow `numbered`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy. @@ -440,7 +441,7 @@ Found by review of PR #317. `bin/plan/goals_file.py`'s `numbered` writes `typing ### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run. -Found by review of PR #317. The black-box test, `bin/loop_claude/test_black_box.py:609`, not the unit test of the same name in `test_loop_claude.py`, which runs on a fake clock, sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it. +Found by review of PR #317. The black-box test, `bin/loop_claude/test_black_box.py:609`, not the unit test of the same name in `bin/agent_cycle/test_retry.py`, which runs on a fake clock, sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it. ### 265. Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work. -- 2.52.0 From 9bc2887ee816c47a69917a7de964baf64aef194a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 11:43:38 +0100 Subject: [PATCH 05/14] =?UTF-8?q?Answer=20architecture=20round=203:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20every=20sui?= =?UTF-8?q?te=20sits=20beside=20the=20module=20it=20tests,=20and=20test=5F?= =?UTF-8?q?loop=5Fclaude.py=20holds=20only=20loop-claude's=20own?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- bin/agent_cycle/doubles.py | 15 + bin/agent_cycle/test_interrupt.py | 2 +- bin/agent_cycle/test_judge.py | 50 ++++ bin/agent_cycle/test_routing.py | 98 +++++- bin/agent_cycle/test_run.py | 13 +- bin/agent_cycle/test_tmux.py | 4 +- bin/agent_cycle/test_worker.py | 21 +- bin/agent_cycle/test_worker_prompts.py | 33 +++ bin/chunk_driver/doubles.py | 16 + bin/chunk_driver/project/test_records.py | 6 + bin/chunk_driver/test_chunk_run.py | 12 +- bin/chunk_driver/test_cycle_start.py | 62 ++++ bin/chunk_driver/test_prompts.py | 120 ++++++++ bin/loop_claude/test_loop_claude.py | 360 +---------------------- bin/model_routing/test_route.py | 65 ++++ todo.md | 2 +- 17 files changed, 503 insertions(+), 380 deletions(-) create mode 100644 bin/agent_cycle/doubles.py create mode 100644 bin/agent_cycle/test_worker_prompts.py create mode 100644 bin/chunk_driver/doubles.py create mode 100644 bin/chunk_driver/test_prompts.py create mode 100644 bin/model_routing/test_route.py diff --git a/README.md b/README.md index 86457af9..3847b9c0 100644 --- a/README.md +++ b/README.md @@ -222,10 +222,10 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a `bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. -- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. +- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. `doubles.py` holds the doubles its tests share with `chunk_driver`'s. - `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the head of each entry it answers, an issue's links and the transition that finishes it, for `plan_store` and `do_epic`. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. -- `chunk_driver/` holds what `loop_claude` and `do_epic` share as they drive chunks through `agent_cycle`: how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither tool, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included. +- `chunk_driver/` holds what `loop_claude` and `do_epic` share as they drive chunks through `agent_cycle`: how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). `doubles.py` holds the loop its tests share with `loop_claude`'s. It imports neither tool, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`. diff --git a/bin/agent_cycle/doubles.py b/bin/agent_cycle/doubles.py new file mode 100644 index 00000000..32ca2013 --- /dev/null +++ b/bin/agent_cycle/doubles.py @@ -0,0 +1,15 @@ +"""Test doubles for the suites that run a cycle: the tmux window it runs in, and the prompts of an entry point that exists only in tests.""" +from agent_cycle import tmux +from agent_cycle.worker_prompts import WorkerPrompts + +WINDOW = tmux.Window("loop-proj", "item-7", "%4") +# The prompts of an entry point that exists only in tests, so a cycle's tests read no real entry point's wording. +PROMPTS = WorkerPrompts( + driver="a-driver", + fresh=lambda task, premises, route, project, facts: f"Fresh: {task}\n\n{premises}\n\n{facts}", + resumed=lambda evidence, route, project: f"Resumed: {evidence}", + rungs_held=lambda route, project: f" You hold {route.rung}.", + quote_sources="the project's records", + answer_destinations="the plan or a comment", + records_named="the project's decisions", +) diff --git a/bin/agent_cycle/test_interrupt.py b/bin/agent_cycle/test_interrupt.py index d64d3c75..17d917de 100644 --- a/bin/agent_cycle/test_interrupt.py +++ b/bin/agent_cycle/test_interrupt.py @@ -21,7 +21,7 @@ from model_routing.ladder import Rung from agent_cycle.stop import Stop from agent_cycle import tmux from text_files.utc_stamp import utc -from agent_cycle.test_tmux import WINDOW +from agent_cycle.doubles import WINDOW class Interrupts(unittest.TestCase): diff --git a/bin/agent_cycle/test_judge.py b/bin/agent_cycle/test_judge.py index 796a16ed..71ec6090 100644 --- a/bin/agent_cycle/test_judge.py +++ b/bin/agent_cycle/test_judge.py @@ -1,4 +1,5 @@ import dataclasses +import json import pathlib import sys import unittest @@ -10,6 +11,8 @@ from loop_effects.doubles import assistant, FakeEffects, human, judged, kinds from failure import Failure from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished from agent_cycle import judge +from agent_cycle.doubles import PROMPTS +from model_routing.route import Route from model_routing.ladder import Rung from agent_cycle.judge import verdict_from @@ -123,5 +126,52 @@ class Verdict(unittest.TestCase): self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2)) +class JudgePrompt(unittest.TestCase): + def brief(self, entries, escalated_at, answer_destinations="the plan or a comment"): + """What the judge of a-driver reads of a transcript holding entries.""" + return judge.Brief("Do it.", "## Goals", "", "the project's decisions", answer_destinations, kinds(*entries), escalated_at, "a-driver") + + def test_shows_the_transcripts_tail_and_returns_what_it_showed(self): + entries = [assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})] + prompt, grounds = judge.judge_prompt(self.brief(entries, 0)) + self.assertTrue(grounds.shown.endswith("\n\nnew")) + self.assertNotIn("old", grounds.shown) + self.assertIn(grounds.shown, prompt) + self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS) + self.assertEqual(grounds.after_mark, "old " + "x" * judge.JUDGE_PROMPT_CHARS + "\n\nnew") + self.assertEqual(grounds.quotable, "## Goals\n\n") + + def test_the_judge_prompt_and_schema_call_the_worker_the_worker(self): + prompt, _ = judge.judge_prompt(self.brief([assistant({"type": "text", "text": "done"})], 1)) + self.assertNotRegex(prompt + json.dumps(judge.judge_schema("a-driver")), r"\b[Aa]gent") + + def test_the_judge_prompt_names_the_entry_points_answer_destinations_in_both_rules_on_a_recorded_answer(self): + prompt, _ = judge.judge_prompt(self.brief([assistant({"type": "text", "text": "done"})], 0, "the ledger")) + self.assertIn("is recorded in the ledger at the one place it governs", prompt) + self.assertIn("the worker writing it into the ledger, but not into one of the human's rules", prompt) + + def test_shows_the_judge_where_the_worker_last_stepped_up_and_checks_an_escalation_only_after_it(self): + entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"})] + prompt, grounds = judge.judge_prompt(self.brief(entries, 1)) + self.assertRegex(prompt, "round 2: 🔴\n\n\\[step\\] [^\n]+\n\nround 3: 🔴\n\n") + self.assertEqual(grounds.after_mark, "round 3: 🔴") + prompt, grounds = judge.judge_prompt(self.brief(entries, 0)) + self.assertNotIn("stepped the worker up", prompt) + self.assertEqual(grounds.shown, "round 2: 🔴\n\nround 3: 🔴") + self.assertEqual(grounds.after_mark, "round 2: 🔴\n\nround 3: 🔴") + + def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self): + entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})] + _, grounds = judge.judge_prompt(self.brief(entries, 1)) + self.assertEqual(judge.quotes_checked(Unfinished("e", "old x", entries_read=3), grounds), Unfinished("e", entries_read=3)) + self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3)) + + def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self): + typed = PROMPTS.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False) + entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})] + _, grounds = judge.judge_prompt(self.brief(entries, 1)) + self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown) + + if __name__ == "__main__": unittest.main() diff --git a/bin/agent_cycle/test_routing.py b/bin/agent_cycle/test_routing.py index 6adf6a72..50f53ef3 100644 --- a/bin/agent_cycle/test_routing.py +++ b/bin/agent_cycle/test_routing.py @@ -1,19 +1,109 @@ import dataclasses import pathlib import sys +import types import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from agent_cycle.verdicts import Interrupt, TakenIn, Unfinished +from model_routing.ladder import ProjectRung, Rung +from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.route import Route from agent_cycle import routing -from model_routing.ladder import Rung + +LADDER = read_ladder(SHIPPED) +OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium")) +# The ladder's rungs around the project's: the one below it, its own, and those one to four steps up. +SONNET = Rung("claude-sonnet-5-5", "high") +OPUS = Rung("claude-opus-5-5", "medium") +ONE_UP = Rung("claude-fable-5-2", "low") +TWO_UP = Rung("claude-fable-5-2", "medium") +THREE_UP = Rung("claude-opus-5-5", "xhigh") +FOUR_UP = Rung("claude-fable-5-2", "high") + + +def scored(likelihood, escape_and_impact): + """Item 3 with that L and E + I, as routing.Scored reads an item.""" + return types.SimpleNamespace(id=3, likelihood=likelihood, escape_and_impact=escape_and_impact) + + +def unfinished(likelihood=0, escalated_at=None): + """An unfinished verdict: the worker took in an item of that L, 0 for none, and the judge found an escalation after reading escalated_at transcript entries, None for none.""" + return Unfinished("e", escalation="round 2: 🔴" if escalated_at is not None else "", taken_in=TakenIn(highest_likelihood=likelihood), entries_read=escalated_at) + + +def interrupted(likelihood=0, escalated_at=None): + """An interrupt, its arguments as unfinished's.""" + return Interrupt("e", "q", escalation="round 2: 🔴" if escalated_at is not None else "", taken_in=TakenIn(highest_likelihood=likelihood), entries_read=escalated_at) + + +class FirstRoute(unittest.TestCase): + def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self): + self.assertEqual(routing.first_route(OPUS_PROJECT, scored(4, 5)), Route(TWO_UP, 3, 4, 5)) + self.assertEqual(routing.first_route(OPUS_PROJECT, scored(1, 5)), Route(SONNET, 3, 1, 5)) + self.assertEqual(routing.first_route(OPUS_PROJECT, None), Route(OPUS)) + + +class NextRoute(unittest.TestCase): + def test_steps_up_a_rung_after_every_second_unfinished_verdict(self): + once = routing.next_route(OPUS_PROJECT, Route(ONE_UP, 3, 3, 4), unfinished()) + self.assertEqual(once, Route(ONE_UP, 3, 3, 4, unfinished=1)) + self.assertEqual(routing.next_route(OPUS_PROJECT, once, unfinished()), Route(TWO_UP, 3, 3, 4)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(LADDER.rungs[-1], unfinished=1), unfinished()).rung, LADDER.rungs[-1]) + + def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self): + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(OPUS), unfinished(4)).rung, TWO_UP) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(THREE_UP), unfinished(4)).rung, THREE_UP) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(OPUS, unfinished=1), unfinished(4)).rung, THREE_UP) + + def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self): + low = Route(SONNET, 3, 1, 3, unfinished=1) + self.assertEqual(routing.next_route(OPUS_PROJECT, low, unfinished()).rung, OPUS) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(low.rung, 3, 1, 3), unfinished(3)).rung, ONE_UP) + + def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self): + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(TWO_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(THREE_UP, 3, 4, 5, escalated_at=7)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(THREE_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(FOUR_UP, 3, 4, 5, escalated_at=9)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(FOUR_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(TWO_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(THREE_UP, 3, 4, 5, escalated_at=7)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(TWO_UP), unfinished(escalated_at=7)), Route(TWO_UP, unfinished=1)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(TWO_UP, 3, 2, 4, unfinished=1)) + + def test_keeps_the_mark_through_a_step_no_escalation_took(self): + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(ONE_UP, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(TWO_UP, 3, 3, 4, escalated_at=5)) + + def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self): + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(TWO_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(THREE_UP, 3, 4, 5, escalated_at=7)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(THREE_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(FOUR_UP, 3, 4, 5, escalated_at=9)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(OPUS, 3, 2, 4, escalated_at=7)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(TWO_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(TWO_UP, 3, 4, 5, unfinished=1, escalated_at=2)) + + def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self): + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(TWO_UP, 3, 1, 3, escalated_at=2)) + + def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self): + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(ONE_UP, 3, 3, 4), interrupted(4, escalated_at=7)), Route(THREE_UP, 3, 3, 4, escalated_at=7)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(THREE_UP, 3, 4, 5, escalated_at=7)) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(FOUR_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(FOUR_UP, 3, 4, 5, unfinished=1)) + + def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self): + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, OPUS) + self.assertEqual(routing.next_route(OPUS_PROJECT, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, OPUS) class StepUp(unittest.TestCase): - OPUS = Rung("claude-opus-5-5", "medium") - def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self): - route = Route(self.OPUS, 3, 3, 4) + route = Route(OPUS, 3, 3, 4) self.assertIsNone(routing.step_up(route, dataclasses.replace(route, unfinished=1))) self.assertEqual(routing.step_up(route, route.taking_in(6)), routing.StepUp(route, route.taking_in(6))) + + +class JudgeRung(unittest.TestCase): + def test_runs_the_judge_of_a_replayed_model_on_its_models_highest_rung(self): + self.assertEqual(routing.judge_rung(LADDER, "claude-opus-5-5"), THREE_UP) + # A model off the ladder, or not replayed, gets no effort flag. + self.assertEqual(routing.judge_rung(LADDER, "judge-model"), Rung("judge-model")) + self.assertEqual(routing.judge_rung(LADDER, "claude-sonnet-5-5"), Rung("claude-sonnet-5-5")) diff --git a/bin/agent_cycle/test_run.py b/bin/agent_cycle/test_run.py index d4a9cd86..8a31f5ee 100644 --- a/bin/agent_cycle/test_run.py +++ b/bin/agent_cycle/test_run.py @@ -23,6 +23,7 @@ from transcript_archive import outcomes, write from loop_state import paths from transcript_archive.location import project_archive from model_routing.ladder import ProjectRung, Rung +from agent_cycle.doubles import PROMPTS, WINDOW from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.route import Route from agent_cycle import routing @@ -31,8 +32,6 @@ from claude_code import session from loop_effects.child_shells import Shell from agent_cycle.stop import Stop from text_files.utc_stamp import utc -from agent_cycle.test_tmux import WINDOW -from agent_cycle.worker_prompts import WorkerPrompts LADDER = read_ladder(SHIPPED) @@ -51,16 +50,6 @@ SONNET_179 = '{"model": "claude-sonnet-5-5", "effort": "high", "item": 179, "lik OPUS_179_AT_3 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 3}' OPUS_179_AT_6 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 6}' JUDGE_RUN_LINE = re.compile(r"^Judge run: judge/[0-9a-f]{64}\.json\n", re.MULTILINE) -# The prompts of an entry point that exists only here, so a cycle's tests read no real entry point's wording. -PROMPTS = WorkerPrompts( - driver="a-driver", - fresh=lambda task, premises, route, project, facts: f"Fresh: {task}\n\n{premises}\n\n{facts}", - resumed=lambda evidence, route, project: f"Resumed: {evidence}", - rungs_held=lambda route, project: f" You hold {route.rung}.", - quote_sources="the project's records", - answer_destinations="the plan or a comment", - records_named="the project's decisions", -) class QuestionFor(unittest.TestCase): diff --git a/bin/agent_cycle/test_tmux.py b/bin/agent_cycle/test_tmux.py index fa431a9c..8577cecd 100644 --- a/bin/agent_cycle/test_tmux.py +++ b/bin/agent_cycle/test_tmux.py @@ -9,9 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure from loop_effects.doubles import FakeEffects from agent_cycle import tmux - - -WINDOW = tmux.Window("loop-proj", "item-7", "%4") +from agent_cycle.doubles import WINDOW class TmuxCommands(unittest.TestCase): diff --git a/bin/agent_cycle/test_worker.py b/bin/agent_cycle/test_worker.py index 6eba4ebe..fae69230 100644 --- a/bin/agent_cycle/test_worker.py +++ b/bin/agent_cycle/test_worker.py @@ -10,7 +10,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from claude_code import entries +from claude_code import entries, session from failure import Failure from loop_effects.doubles import FakeEffects, NOW, ran, Streamed from agent_cycle import judge, lingering_workers, worker @@ -131,5 +131,24 @@ class MemoryWait(unittest.TestCase): self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"]) +class WorkerArgs(unittest.TestCase): + OPENED = session.session_named("A proj a-driver", pathlib.Path("/h/.claude/projects")) + + def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): + fresh = worker.worker_args(self.OPENED, Rung("m"), "Do it.", resume=False) + self.assertEqual(fresh[fresh.index("--session-id") + 1], str(self.OPENED.id)) + self.assertEqual(fresh[fresh.index("--name") + 1], "A proj a-driver") + resumed = worker.worker_args(self.OPENED, Rung("m"), "Continue the task.", resume=True) + self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.OPENED.id)) + self.assertNotIn("--session-id", resumed) + self.assertEqual(resumed[resumed.index("-p") + 1], "Continue the task.") + + def test_disallows_a_wakeup_so_a_worker_that_ends_its_turn_exits(self): + for resume in (False, True): + with self.subTest(resume=resume): + args = worker.worker_args(self.OPENED, Rung("m"), "Do it.", resume=resume) + self.assertEqual(args[args.index("--disallowedTools") + 1], "ScheduleWakeup") + + if __name__ == "__main__": unittest.main() diff --git a/bin/agent_cycle/test_worker_prompts.py b/bin/agent_cycle/test_worker_prompts.py new file mode 100644 index 00000000..7a6f04e9 --- /dev/null +++ b/bin/agent_cycle/test_worker_prompts.py @@ -0,0 +1,33 @@ +import dataclasses +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from agent_cycle.doubles import PROMPTS +from model_routing.route import Route +from model_routing.ladder import Rung +from agent_cycle import worker_prompts + + +class TypedAnswers(unittest.TestCase): + def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self): + route = Route(Rung("worker-model")) + marked = "The human answered your question at a-driver's terminal:\nB" + typed = worker_prompts.typed_answer(PROMPTS.typed("Which one?", "Use B.", route, None, False)) + self.assertEqual(typed.answer, "Use B.") + self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task.")) + self.assertEqual(worker_prompts.typed_answer(PROMPTS.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.") + # A ruling that stepped the worker up adds the sentences naming its new rung. + self.assertEqual(worker_prompts.typed_answer(PROMPTS.typed("Which one?", "Use B.", Route(Rung("claude-sonnet-5-5", "high"), 179, 2, 5), None, True)).answer, "Use B.") + self.assertIsNone(worker_prompts.typed_answer(PROMPTS.answered("Which one?", marked, route, None, False))) + self.assertIsNone(worker_prompts.typed_answer(PROMPTS.resumed(marked, route, None))) + + def test_the_typed_answers_prompt_names_the_entry_points_answer_destinations(self): + ledger = dataclasses.replace(PROMPTS, answer_destinations="the ledger") + self.assertIn("is recorded in the ledger at the one place it governs.", ledger.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/chunk_driver/doubles.py b/bin/chunk_driver/doubles.py new file mode 100644 index 00000000..239478e0 --- /dev/null +++ b/bin/chunk_driver/doubles.py @@ -0,0 +1,16 @@ +"""Test doubles for the suites that drive a chunk: the loop of an entry point that exists only in tests.""" +import pathlib +import typing + +from loop_effects.effects import Effects +from chunk_driver.this_loop import Loop +from loop_state import paths +from claude_code import session +from agent_cycle.doubles import WINDOW + + +def a_loop(effects: Effects, **fields: typing.Any) -> Loop: + """A loop in /r on effects, with fields in place of its defaults.""" + home = pathlib.Path("/h") + defaults = {"root": "/r", "session": session.session_named("A proj a-driver", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/a-driver"), "window": WINDOW} + return Loop(**{**defaults, **fields}, effects=effects) diff --git a/bin/chunk_driver/project/test_records.py b/bin/chunk_driver/project/test_records.py index 1d0d225f..3ef42e98 100644 --- a/bin/chunk_driver/project/test_records.py +++ b/bin/chunk_driver/project/test_records.py @@ -8,6 +8,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) from project_config.test_project_config import configured from failure import Failure +from agent_cycle import judge from chunk_driver.project import records @@ -86,5 +87,10 @@ class Records(unittest.TestCase): self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records.")) +class JudgeRules(unittest.TestCase): + def test_the_judge_prompt_names_every_rule_the_judge_reads_from_the_human(self): + self.assertEqual([name for name in records.HUMAN_RULE_NAMES if name not in judge.judge_rules("the ledger", "a-driver")], []) + + if __name__ == "__main__": unittest.main() diff --git a/bin/chunk_driver/test_chunk_run.py b/bin/chunk_driver/test_chunk_run.py index 3179a582..1122a68e 100644 --- a/bin/chunk_driver/test_chunk_run.py +++ b/bin/chunk_driver/test_chunk_run.py @@ -9,28 +9,20 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from chunk_driver import chunk_run, cycle_start, this_loop +from chunk_driver.doubles import a_loop +from chunk_driver import chunk_run, cycle_start from loop_effects.doubles import FakeEffects, NOW from agent_cycle.verdicts import Finished, TakenIn, Unfinished from transcript_archive import outcomes, write -from loop_state import paths from model_routing.ladder import ProjectRung, Rung from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.route import Route from agent_cycle import run from claude_code import session -from agent_cycle.test_tmux import WINDOW OPUS_PROJECT = ProjectRung(read_ladder(SHIPPED), Rung("claude-opus-5-5", "medium")) -def a_loop(effects, **fields): - """A loop in /r on effects, with fields in place of its defaults.""" - home = pathlib.Path("/h") - defaults = {"root": "/r", "session": session.session_named("A proj a-driver", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/a-driver"), "window": WINDOW} - return this_loop.Loop(**{**defaults, **fields}, effects=effects) - - class Steps(unittest.TestCase): OPUS = Rung("claude-opus-5-5", "medium") # The rungs an L 3 and an L 4 pick from OPUS. diff --git a/bin/chunk_driver/test_cycle_start.py b/bin/chunk_driver/test_cycle_start.py index 7a6bb8a5..3a4ad967 100644 --- a/bin/chunk_driver/test_cycle_start.py +++ b/bin/chunk_driver/test_cycle_start.py @@ -1,15 +1,28 @@ +import contextlib +import io +import json import os import pathlib import sys import tempfile +import types import unittest import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from chunk_driver.doubles import a_loop from chunk_driver import cycle_start from failure import Failure +from loop_effects.doubles import FakeEffects, NOW, STAMP from git_cli.git_repo import git +from transcript_archive import outcomes, write +from model_routing.ladder import ProjectRung, Rung +from model_routing.ladder_file import read_ladder, SHIPPED +from model_routing.route import Route, WorkerLine +from claude_code import session + +OPUS_PROJECT = ProjectRung(read_ladder(SHIPPED), Rung("claude-opus-5-5", "medium")) class SetupVersion(unittest.TestCase): @@ -36,5 +49,54 @@ class SetupVersion(unittest.TestCase): self.assertEqual(cycle_start.setup_version(pathlib.Path("/r"), fake_git), "unknown: fatal: bad HEAD hint: repair it") +class Routes(unittest.TestCase): + OPUS = Rung("claude-opus-5-5", "medium") + SONNET = Rung("claude-sonnet-5-5", "high") + + def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self): + item = types.SimpleNamespace(id=3, likelihood=4, escape_and_impact=5) + archived = Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5) + def never(): + raise AssertionError("not asked") + self.assertEqual(cycle_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model"))) + self.assertEqual(cycle_start.routed(archived, OPUS_PROJECT, "claude-opus-5-5", never, never), archived) + self.assertEqual(cycle_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: archived, never), archived) + self.assertEqual(cycle_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: None, lambda: item), Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5)) + self.assertEqual(cycle_start.routed(Route(self.SONNET), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) + cheap = Route(self.SONNET, 4, 2, 3) + self.assertEqual(cycle_start.routed(cheap, OPUS_PROJECT, "claude-opus-5-5", never, never), cheap) + self.assertEqual(cycle_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) + + def test_resumes_on_the_archived_route_and_says_why_it_routes_afresh(self): + with tempfile.TemporaryDirectory() as home: + opened = session.session_named("A proj a-driver", pathlib.Path(home, "projects")) + archive = pathlib.Path(home, "archive") + transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") + route = Route(Rung("claude-fable-5-2", "low"), 3, 4, 5) + with contextlib.redirect_stderr(io.StringIO()) as stderr: + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + transcript.parent.mkdir(parents=True) + transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW)) + with contextlib.redirect_stderr(stderr): + self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), route) + self.assertEqual(stderr.getvalue(), "") + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1)) + with contextlib.redirect_stderr(io.StringIO()) as stderr: + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + self.assertEqual(stderr.getvalue(), f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route that can be read: {{"model": "claude-opus-5-5", "rung": 3}}\n') + (chunk,) = archive.iterdir() + chunk.chmod(0) + try: + with contextlib.redirect_stderr(io.StringIO()) as stderr: + self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) + finally: + chunk.chmod(0o700) + self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue()) + + if __name__ == "__main__": unittest.main() diff --git a/bin/chunk_driver/test_prompts.py b/bin/chunk_driver/test_prompts.py new file mode 100644 index 00000000..ca031f12 --- /dev/null +++ b/bin/chunk_driver/test_prompts.py @@ -0,0 +1,120 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from model_routing.ladder import ProjectRung, Rung +from chunk_driver import prompts +from model_routing.ladder_file import read_ladder, SHIPPED +from model_routing.route import Route + +LADDER = read_ladder(SHIPPED) +# The ladder's rungs around the project's: the one below it, its own, and those one to three steps up. +SONNET = Rung("claude-sonnet-5-5", "high") +OPUS = Rung("claude-opus-5-5", "medium") +FABLE_LOW = Rung("claude-fable-5-2", "low") +FABLE_MEDIUM = Rung("claude-fable-5-2", "medium") +OPUS_XHIGH = Rung("claude-opus-5-5", "xhigh") +OPUS_PROJECT = ProjectRung(LADDER, OPUS) +# The sentence with which an entry point that exists only here asks its worker to name the chunk's items. +NAMING = "Name the items." +SCAN = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." +SEATS = " Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung." +MARKDOWN = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium." + + +def held(route, project=OPUS_PROJECT): + """The rung sentences a-driver's worker reads on route, each after a space.""" + return prompts.rungs_held("a-driver", route, project) + + +def resumed(route, project=OPUS_PROJECT): + """The prompt that resumes a-driver's worker on route, with no evidence of work remaining.""" + return prompts.resumed("a-driver", NAMING, "", route, project) + + +class Resumed(unittest.TestCase): + def test_resumes_the_worker_saying_when_the_chunk_is_finished(self): + self.assertTrue(resumed(Route(Rung("m")), None).startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once")) + + +class ReviewLaunches(unittest.TestCase): + def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): + below = held(Route(SONNET, 3, 2, 4)) + self.assertTrue(below.startswith(f" Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 ` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger"), below) + self.assertNotIn("Launch each", held(Route(OPUS, 3, 2, 4))) + + def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self): + level = held(Route(OPUS, 3, 2, 6)) + self.assertTrue(level.startswith(f" Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{MARKDOWN} When an escalation trigger"), level) + below = held(Route(SONNET, 3, 2, 5)) + self.assertTrue(below.startswith(f" Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{SEATS}{SCAN} Your rung is below the project's:"), below) + self.assertNotIn("Launch each reviewer", held(Route(FABLE_MEDIUM, 3, 4, 6))) + + def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self): + taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8." + self.assertTrue(held(Route(OPUS, 3, 2, 4)).startswith(f"{taking_in} When an escalation trigger")) + self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", held(Route(OPUS, 3, 2, 6))) + self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", held(Route(FABLE_MEDIUM, 3, 4, 4))) + self.assertNotIn("Where an item you take into", held(Route(OPUS, 3, 2, 8))) + self.assertNotIn("Where an item you take into", held(Route(Rung("m")), None)) + + def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self): + self.assertIn(f"a-driver runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{MARKDOWN} When an escalation trigger", resumed(Route(OPUS, 3, 2, 5, escape_and_impact_taken_in=7))) + self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", held(Route(OPUS, escape_and_impact_taken_in=5))) + + def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self): + above = Route(FABLE_LOW, 3, 3, 4) + sentences = f"{SEATS}{SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{MARKDOWN} When an escalation trigger" + self.assertIn(f"{prompts.ANSWERS_RECORDED}. {NAMING} a-driver runs you on claude-fable-5-2 at low effort.{sentences}", resumed(above)) + self.assertNotIn("the project's", resumed(Route(OPUS, 3, 2, 4))) + self.assertNotIn("runs you on", resumed(Route(Rung("m")), None)) + self.assertTrue(held(above).startswith(sentences), held(above)) + + def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self): + self.assertIn(MARKDOWN, held(Route(OPUS, 3, 2, 7))) + self.assertIn(MARKDOWN, held(Route(FABLE_LOW, 3, 3, 4))) + self.assertNotIn("only Markdown", held(Route(OPUS, 3, 2, 4))) + + +class Escalation(unittest.TestCase): + def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self): + routed = held(Route(OPUS, 3, 2, 4)) + self.assertTrue(routed.startswith(" Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number."), routed) + self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", held(Route(FABLE_LOW, 3, 3, 4))) + self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", held(Route(FABLE_MEDIUM, 3, 3, 4))) + self.assertNotIn("escalation", held(Route(Rung("claude-fable-5-2", "max"), 3, 4, 8))) + self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours, only once the human agrees; a-driver will not resume you higher for a trigger either, so ask the human for that yes.", held(Route(OPUS_XHIGH, 3, 3, 4))) + self.assertIn("set to `model fable, effort max`, one rung above yours, only once the human agrees;", held(Route(Rung("claude-fable-5-2", "high"), 3, 4, 5)), "one rung below the top still names the rung above") + self.assertNotIn("rerun", held(Route(Rung("claude-opus-5-5", "low"), 3, 3, 4)), "a worker off the ladder is told no rerun rung") + self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours;", held(Route(OPUS_XHIGH, 3, 4, 5))) + self.assertNotIn("escalation", held(Route(Rung("m")), None)) + self.assertNotIn("escalation", held(Route(Rung("claude-opus-5-5", "low"), 3, 3, 4))) + unrouted = held(Route(OPUS)) + self.assertTrue(unrouted.startswith(" Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking a-driver for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer"), unrouted) + + def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): + offer = lambda cap: f" Where the hard part is the rest of the chunk, end your run instead, asking a-driver for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `{cap}`." + self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model fable, effort low')}", held(Route(OPUS, 3, 2, 4))) + self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model opus, effort xhigh')}", held(Route(FABLE_LOW, 3, 3, 4))) + self.assertNotIn("Where the hard part", held(Route(OPUS_XHIGH, 3, 3, 4))) + + +class Reruns(unittest.TestCase): + def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self): + both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`." + self.assertTrue(resumed(Route(OPUS, 3, 2, 4)).endswith(both)) + self.assertTrue(resumed(Route(SONNET, 3, 2, 4)).endswith(both)) + self.assertTrue(held(Route(OPUS)).endswith(both)) + self.assertTrue(resumed(Route(FABLE_LOW, 3, 3, 4)).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`.")) + self.assertTrue(resumed(Route(OPUS, 3, 2, 7)).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`.")) + self.assertTrue(resumed(Route(Rung("claude-fable-5-2", "max"), 3, 4, 8)).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`.")) + self.assertNotIn("rerun", resumed(Route(Rung("m")), None)) + self.assertNotIn("rerun", held(Route(Rung("m", "high"), 3, 4, 5), None)) + fable = Rung("claude-fable-5-2", "max") + self.assertNotIn("rerun", resumed(Route(fable), ProjectRung(LADDER, fable))) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 52d167e8..ace9f16d 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -13,38 +13,37 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from chunk_driver.doubles import a_loop from routing_figures import archive, state from test_env import assert_not_root -from loop_effects.doubles import assistant, CWD, FakeEffects, human, kinds, NOW, ran, said, STAMP +from loop_effects.doubles import assistant, CWD, FakeEffects, NOW, ran, said, STAMP from claude_code.output_limits import BASH_CEILING_CHARACTERS from routing_figures.calls import Call from loop_claude.chunk import chunk_items -from chunk_driver import chunk_run, cycle_start, prompts, this_loop +from chunk_driver import chunk_run, prompts, this_loop from loop_claude.loop import chunk_start, chunk_windows from project_config.test_project_config import configured from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES from claude_code import entries, reply, session from failure import Failure -from agent_cycle.verdicts import Finished, Interrupt, TakenIn, Unfinished +from agent_cycle.verdicts import Finished, TakenIn, Unfinished from loop_claude.chunk import fresh_prompt -from agent_cycle import judge, retry, states, worker, worker_prompts +from agent_cycle import judge, retry, states, worker import loop_claude.routed_item from loop_claude.loop import main, reload, routing_check, usage from release_plan import next_chunk -from transcript_archive import outcomes, write +from transcript_archive import outcomes from loop_state import paths from plan_store.todo_md import plan_of from model_routing.ladder import ProjectRung, Rung from loop_effects.effects import PYTHON_TIMEOUT from model_routing.ladder_file import read_ladder, SHIPPED from chunk_driver.project import records -from model_routing.route import Route, route_from, WorkerLine -from agent_cycle import routing +from model_routing.route import Route from agent_cycle.stop import Stop from agent_cycle import tmux from touch_predictions.test_touch_predictions import plan as touch_plan from text_files.utc_stamp import utc -from agent_cycle.test_tmux import WINDOW LADDER = read_ladder(SHIPPED) OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium")) @@ -53,13 +52,6 @@ OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium")) UNREAD = Failure("not a git repository") -def a_loop(effects, **fields): - """A loop in /r on effects, with fields in place of its defaults.""" - home = pathlib.Path("/h") - defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude"), "window": WINDOW} - return this_loop.Loop(**{**defaults, **fields}, effects=effects) - - class RoutingCheck(unittest.TestCase): def setUp(self): self.home = pathlib.Path(tempfile.mkdtemp()) @@ -200,24 +192,7 @@ TODO = """# todo """ -def unfinished(likelihood=0, escalated_at=None): - """An unfinished verdict: the worker took in an item of that L, 0 for none, and the judge found an escalation after reading escalated_at transcript entries, None for none.""" - return Unfinished("e", escalation="round 2: 🔴" if escalated_at is not None else "", taken_in=TakenIn(highest_likelihood=likelihood), entries_read=escalated_at) - - -def interrupted(likelihood=0, escalated_at=None): - """An interrupt, its arguments as unfinished's.""" - return Interrupt("e", "q", escalation="round 2: 🔴" if escalated_at is not None else "", taken_in=TakenIn(highest_likelihood=likelihood), entries_read=escalated_at) - - -class Routing(unittest.TestCase): - OPUS = Rung("claude-opus-5-5", "medium") - ONE_UP = Rung("claude-fable-5-2", "low") - TWO_UP = Rung("claude-fable-5-2", "medium") - THREE_UP = Rung("claude-opus-5-5", "xhigh") - FOUR_UP = Rung("claude-fable-5-2", "high") - SONNET = Rung("claude-sonnet-5-5", "high") - +class RoutedItem(unittest.TestCase): def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self): self.assertEqual(routed_item(TODO, NO_CUT).id, 3) self.assertIsNone(routed_item(TODO.replace("| | **Do", "| question | **Do"), NO_CUT)) @@ -244,129 +219,10 @@ class Routing(unittest.TestCase): first = "| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n" self.assertEqual(routed_item(todo.replace(first, "") + first, NO_CUT).id, 3) - def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self): - self.assertEqual(routing.first_route(OPUS_PROJECT, routed_item(TODO, NO_CUT)), Route(self.TWO_UP, 3, 4, 5)) - cheap = routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT) - self.assertEqual(routing.first_route(OPUS_PROJECT, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5)) - self.assertEqual(routing.first_route(OPUS_PROJECT, None), Route(self.OPUS)) - - def test_steps_up_a_rung_after_every_second_unfinished_verdict(self): - once = routing.next_route(OPUS_PROJECT, Route(self.ONE_UP, 3, 3, 4), unfinished()) - self.assertEqual(once, Route(self.ONE_UP, 3, 3, 4, unfinished=1)) - self.assertEqual(routing.next_route(OPUS_PROJECT, once, unfinished()), Route(self.TWO_UP, 3, 3, 4)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(LADDER.rungs[-1], unfinished=1), unfinished()).rung, LADDER.rungs[-1]) - - def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self): - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.OPUS), unfinished(4)).rung, self.TWO_UP) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.THREE_UP), unfinished(4)).rung, self.THREE_UP) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.THREE_UP) - - def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self): - low = Route(self.SONNET, 3, 1, 3, unfinished=1) - self.assertEqual(routing.next_route(OPUS_PROJECT, low, unfinished()).rung, self.OPUS) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.ONE_UP) - - def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self): - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.THREE_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.FOUR_UP, 3, 4, 5, escalated_at=9)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.FOUR_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.TWO_UP, 3, 2, 4, unfinished=1)) - - def test_keeps_the_mark_through_a_step_no_escalation_took(self): - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.ONE_UP, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.TWO_UP, 3, 3, 4, escalated_at=5)) - - def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self): - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.THREE_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.FOUR_UP, 3, 4, 5, escalated_at=9)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.FOUR_UP, 3, 4, 5, unfinished=1, escalated_at=9)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.TWO_UP, 3, 4, 5, unfinished=1, escalated_at=2)) - - def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self): - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 1, 3, escalated_at=2)) - - def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self): - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.ONE_UP, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 3, 4, escalated_at=7)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7)) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(self.FOUR_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.FOUR_UP, 3, 4, 5, unfinished=1)) - - def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self): - taken = Route(self.OPUS, 3, 3, 4).taking_in(6) - self.assertEqual(taken, Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)) - self.assertEqual(taken.taking_in(7), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=7)) - self.assertEqual(taken.taking_in(5), taken) - self.assertEqual(taken.taking_in(6), taken) - self.assertEqual(Route(self.OPUS, 3, 3, 4).taking_in(4), Route(self.OPUS, 3, 3, 4)) - self.assertEqual(Route(self.OPUS, 3, 2, 2).taking_in(4), Route(self.OPUS, 3, 2, 2)) - self.assertEqual(Route(self.OPUS).taking_in(5), Route(self.OPUS, escape_and_impact_taken_in=5)) - self.assertEqual(Route(self.OPUS).taking_in(3), Route(self.OPUS)) - self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS)) - - def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self): - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS) - self.assertEqual(routing.next_route(OPUS_PROJECT, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS) - - def test_runs_the_judge_of_a_replayed_model_on_its_models_highest_rung(self): - self.assertEqual(routing.judge_rung(LADDER, "claude-opus-5-5"), self.THREE_UP) - # A model off the ladder, or not replayed, gets no effort flag. - self.assertEqual(routing.judge_rung(LADDER, "judge-model"), Rung("judge-model")) - self.assertEqual(routing.judge_rung(LADDER, "claude-sonnet-5-5"), Rung("claude-sonnet-5-5")) - - def test_refuses_a_route_whose_item_has_levels_off_their_scales_or_levels_without_an_item(self): - for item, likelihood, escape_and_impact in ((3, 0, 5), (3, 5, 5), (3, 4, 1), (3, 4, 9), (0, 4, 5), (0, 4, 0), (0, 0, 5)): - with self.subTest(item=item, likelihood=likelihood, escape_and_impact=escape_and_impact): - with self.assertRaises(ValueError): - Route(self.ONE_UP, item, likelihood, escape_and_impact) - - def test_refuses_a_route_taking_in_an_e_plus_i_off_its_scale_or_not_above_its_items(self): - for taken_in in (1, 9, -1, 5, 4): - with self.subTest(taken_in=taken_in): - with self.assertRaises(ValueError): - Route(self.ONE_UP, 3, 4, 5, escape_and_impact_taken_in=taken_in) - - def test_takes_a_route_whose_item_holds_each_levels_lowest_value(self): - self.assertEqual(Route(self.ONE_UP, 3, 1, 2).escape_and_impact, 2) - def test_routes_nothing_on_an_item_without_e_or_i(self): without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |") self.assertIsNone(routed_item(without_i, NO_CUT)) - def test_archives_the_route_as_a_json_worker_line_it_reads_back_field_by_field(self): - route = Route(self.ONE_UP, 3, 4, 5) - self.assertEqual(route.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5}') - self.assertEqual(route_from(route.worker_line()), route) - self.assertEqual(Route(Rung("worker-model")).worker_line(), '{"model": "worker-model"}') - self.assertEqual(route_from('{"model": "worker-model"}'), Route(Rung("worker-model"))) - marked = Route(self.ONE_UP, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12) - self.assertEqual(marked.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}') - self.assertEqual(route_from(marked.worker_line()), marked) - self.assertEqual(route_from(Route(self.ONE_UP, escalated_at=3).worker_line()), Route(self.ONE_UP, escalated_at=3)) - - def test_leaves_the_count_of_unfinished_verdicts_out_of_the_worker_line_so_a_rerun_restarts_it(self): - self.assertEqual(route_from(Route(self.ONE_UP, 3, 4, 5, unfinished=1).worker_line()), Route(self.ONE_UP, 3, 4, 5)) - - def test_reads_no_route_from_a_worker_line_that_route_worker_line_could_not_have_written(self): - for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": ', "worker-model", "claude-fable-5-2 at low effort, routed by item 3's L of 4 and E + I of 5"): - with self.subTest(line=line): - self.assertIsNone(route_from(line)) - - def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self): - item = routed_item(TODO, NO_CUT) - archived = Route(self.THREE_UP, 3, 4, 5) - def never(): - raise AssertionError("not asked") - self.assertEqual(cycle_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model"))) - self.assertEqual(cycle_start.routed(archived, OPUS_PROJECT, "claude-opus-5-5", never, never), archived) - self.assertEqual(cycle_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: archived, never), archived) - self.assertEqual(cycle_start.routed(None, OPUS_PROJECT, "claude-opus-5-5", lambda: None, lambda: item), Route(self.TWO_UP, 3, 4, 5)) - self.assertEqual(cycle_start.routed(Route(self.SONNET), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) - cheap = Route(self.SONNET, 4, 2, 3) - self.assertEqual(cycle_start.routed(cheap, OPUS_PROJECT, "claude-opus-5-5", never, never), cheap) - self.assertEqual(cycle_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), OPUS_PROJECT, "claude-opus-5-5", never, lambda: None), Route(self.OPUS)) - class RouteSources(unittest.TestCase): def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): @@ -440,36 +296,6 @@ class RouteSources(unittest.TestCase): self.assertIn("the items the worker names lift no rung: no config names the checkout", stderr.getvalue()) self.assertIn("no config names the checkout", chunk_start.fetched_plan(loop).reason) - def test_resumes_on_the_archived_route_and_says_why_it_routes_afresh(self): - with tempfile.TemporaryDirectory() as home: - opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects")) - archive = pathlib.Path(home, "archive") - transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") - route = Route(Rung("claude-fable-5-2", "low"), 3, 4, 5) - with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) - transcript.parent.mkdir(parents=True) - transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") - self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) - with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW)) - with contextlib.redirect_stderr(stderr): - self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), route) - self.assertEqual(stderr.getvalue(), "") - with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1)) - with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) - self.assertEqual(stderr.getvalue(), f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route that can be read: {{"model": "claude-opus-5-5", "rung": 3}}\n') - (chunk,) = archive.iterdir() - chunk.chmod(0) - try: - with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) - finally: - chunk.chmod(0o700) - self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue()) - class ChunkWindows(unittest.TestCase): def plan(self, *touched): @@ -748,23 +574,8 @@ class ChunkFacts(unittest.TestCase): self.assertEqual((resumed.made("python"), facts), ([], "")) -class TypedAnswers(unittest.TestCase): - def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self): - route = Route(Rung("worker-model")) - marked = "The human answered your question at loop-claude's terminal:\nB" - typed = worker_prompts.typed_answer(fresh_prompt.WORKER.typed("Which one?", "Use B.", route, None, False)) - self.assertEqual(typed.answer, "Use B.") - self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task.")) - self.assertEqual(worker_prompts.typed_answer(fresh_prompt.WORKER.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.") - self.assertEqual(worker_prompts.typed_answer(fresh_prompt.WORKER.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), OPUS_PROJECT, True)).answer, "Use B.") - self.assertIsNone(worker_prompts.typed_answer(fresh_prompt.WORKER.answered("Which one?", marked, route, None, False))) - self.assertIsNone(worker_prompts.typed_answer(fresh_prompt.WORKER.resumed(marked, route, None))) - - -class WorkerArgs(unittest.TestCase): - SCAN = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." - SEATS = " Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung." - MARKDOWN = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium." +class FreshPrompt(unittest.TestCase): + """loop-claude's first prompt of a chunk.""" # What the preflight found, as the fresh prompt quotes it. FACTS = "- A preflight fact." @@ -799,153 +610,10 @@ class WorkerArgs(unittest.TestCase): with self.subTest(facts=facts): self.assertEqual(fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1) - def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self): - opus = Rung("claude-opus-5-5", "medium") - below = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT, self.FACTS) - self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 ` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below) - self.assertNotIn("Launch each", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) - - def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self): - opus = Rung("claude-opus-5-5", "medium") - level = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 6), OPUS_PROJECT, self.FACTS) - self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", level) - below = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), OPUS_PROJECT, self.FACTS) - self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below) - self.assertNotIn("Launch each reviewer", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), OPUS_PROJECT)) - - def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self): - opus = Rung("claude-opus-5-5", "medium") - taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8." - self.assertIn(f"item 3's L of 2.{taking_in} When an escalation trigger", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) - self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 6), OPUS_PROJECT)) - self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), OPUS_PROJECT)) - self.assertNotIn("Where an item you take into", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 8), OPUS_PROJECT)) - self.assertNotIn("Where an item you take into", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) - - def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self): - opus = Rung("claude-opus-5-5", "medium") - self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 5, escape_and_impact_taken_in=7), OPUS_PROJECT)) - self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", fresh_prompt.WORKER.resumed("", Route(opus, escape_and_impact_taken_in=5), OPUS_PROJECT)) - - def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self): - opus = Rung("claude-opus-5-5", "medium") - above = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT, self.FACTS) - stepped_up = fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT) - self.assertIn(f"{prompts.ANSWERS_RECORDED}. {fresh_prompt.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up) - self.assertNotIn("the project's", fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT)) - self.assertNotIn("runs you on", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) - self.assertIn(f"item 3's L of 3.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", above) - - def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self): - opus = Rung("claude-opus-5-5", "medium") - fresh = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS) - self.assertIn("item 3's L of 2. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh) - self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number.", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), OPUS_PROJECT)) - self.assertNotIn("escalation", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT)) - self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours, only once the human agrees;", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT)) - self.assertIn("set to `model fable, effort max`, one rung above yours, only once the human agrees;", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "high"), 3, 4, 5), OPUS_PROJECT), "one rung below the top still names the rung above") - self.assertNotIn("rerun", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT), "a worker off the ladder is told no rerun rung") - self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort high`, one rung above yours;", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), OPUS_PROJECT)) - self.assertNotIn("escalation", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) - self.assertNotIn("escalation", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertIn(f"{prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger :`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS)) - - def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self): - opus = Rung("claude-opus-5-5", "medium") - offer = lambda cap: f" Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `{cap}`." - self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model fable, effort low')}", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) - self.assertIn(f"`Escalation trigger :`, n the trigger's number.{offer('model opus, effort xhigh')}", fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertNotIn("Where the hard part", fresh_prompt.WORKER.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), OPUS_PROJECT)) - - def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self): - opus = Rung("claude-opus-5-5", "medium") - markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium." - self.assertIn(markdown, fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 7), OPUS_PROJECT, self.FACTS)) - self.assertIn(markdown, fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT)) - self.assertNotIn("only Markdown", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) - - def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self): - opus = Rung("claude-opus-5-5", "medium") - both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`." - self.assertTrue(fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 4), OPUS_PROJECT).endswith(both)) - self.assertTrue(fresh_prompt.WORKER.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), OPUS_PROJECT).endswith(both)) - self.assertTrue(fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus), OPUS_PROJECT, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both)) - self.assertTrue(fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`.")) - self.assertTrue(fresh_prompt.WORKER.resumed("", Route(opus, 3, 2, 7), OPUS_PROJECT).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`.")) - self.assertTrue(fresh_prompt.WORKER.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), OPUS_PROJECT).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`.")) - self.assertNotIn("rerun", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) - self.assertNotIn("rerun", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)) - self.assertIn(f"{both} After your first read", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(opus, 3, 2, 4), OPUS_PROJECT, self.FACTS)) - fable = Rung("claude-fable-5-2", "max") - self.assertNotIn("rerun", fresh_prompt.WORKER.resumed("", Route(fable), ProjectRung(LADDER, fable))) - - def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self): - opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects")) - fresh = worker.worker_args(opened, Rung("m"), fresh_prompt.WORKER.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, self.FACTS), resume=False) - self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id)) - self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude") - resumed = worker.worker_args(opened, Rung("m"), fresh_prompt.WORKER.resumed("", Route(Rung("m")), None), resume=True) - self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id)) - self.assertNotIn("--session-id", resumed) - self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once")) - - def test_disallows_a_wakeup_so_a_worker_that_ends_its_turn_exits(self): - opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects")) - for resume in (False, True): - with self.subTest(resume=resume): - args = worker.worker_args(opened, Rung("m"), "Do it.", resume=resume) - self.assertEqual(args[args.index("--disallowedTools") + 1], "ScheduleWakeup") - - -class JudgePrompt(unittest.TestCase): - def test_shows_the_transcripts_tail_and_returns_what_it_showed(self): - entries = [assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})] - prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 0, fresh_prompt.DRIVER)) - self.assertTrue(grounds.shown.endswith("\n\nnew")) - self.assertNotIn("old", grounds.shown) - self.assertIn(grounds.shown, prompt) - self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS) - self.assertEqual(grounds.after_mark, "old " + "x" * judge.JUDGE_PROMPT_CHARS + "\n\nnew") - self.assertEqual(grounds.quotable, "## Goals\n\n") - - def test_the_judge_prompt_and_schema_call_the_worker_the_worker(self): - prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(assistant({"type": "text", "text": "done"})), 1, fresh_prompt.DRIVER)) - self.assertNotRegex(prompt + json.dumps(judge.judge_schema(fresh_prompt.DRIVER)), r"\b[Aa]gent") - - def test_the_judge_prompt_names_the_entry_points_answer_destinations_in_both_rules_on_a_recorded_answer(self): - prompt, _ = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, "the ledger", kinds(assistant({"type": "text", "text": "done"})), 0, fresh_prompt.DRIVER)) - self.assertIn("is recorded in the ledger at the one place it governs", prompt) - self.assertIn("the worker writing it into the ledger, but not into one of the human's rules", prompt) - - def test_the_typed_answers_prompt_names_the_entry_points_answer_destinations(self): - ledger = dataclasses.replace(fresh_prompt.WORKER, answer_destinations="the ledger") - self.assertIn("is recorded in the ledger at the one place it governs.", ledger.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)) - - def test_the_judge_prompt_names_every_rule_the_judge_reads_from_the_human(self): - self.assertEqual([name for name in records.HUMAN_RULE_NAMES if name not in judge.judge_rules(prompts.ANSWER_DESTINATIONS, fresh_prompt.DRIVER)], []) - - def test_shows_the_judge_where_the_worker_last_stepped_up_and_checks_an_escalation_only_after_it(self): - entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"})] - prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, fresh_prompt.DRIVER)) - self.assertRegex(prompt, "round 2: 🔴\n\n\\[step\\] [^\n]+\n\nround 3: 🔴\n\n") - self.assertEqual(grounds.after_mark, "round 3: 🔴") - prompt, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 0, fresh_prompt.DRIVER)) - self.assertNotIn("stepped the worker up", prompt) - self.assertEqual(grounds.shown, "round 2: 🔴\n\nround 3: 🔴") - self.assertEqual(grounds.after_mark, "round 2: 🔴\n\nround 3: 🔴") - - def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self): - entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})] - _, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, fresh_prompt.DRIVER)) - self.assertEqual(judge.quotes_checked(Unfinished("e", "old x", entries_read=3), grounds), Unfinished("e", entries_read=3)) - self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3)) - - def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self): - typed = fresh_prompt.WORKER.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False) - entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})] - _, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", records.RECORDS_NAMED, prompts.ANSWER_DESTINATIONS, kinds(*entries), 1, fresh_prompt.DRIVER)) - self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown) + def test_puts_the_rung_sentences_after_the_route_or_else_before_the_facts(self): + routed, unrouted = Route(OPUS_PROJECT.rung, 3, 2, 4), Route(OPUS_PROJECT.rung) + self.assertIn(f"routed by item 3's L of 2.{prompts.rungs_held(fresh_prompt.DRIVER, routed, OPUS_PROJECT)} After your first read", fresh_prompt.WORKER.fresh("Do it.", "## Goals", routed, OPUS_PROJECT, self.FACTS)) + self.assertIn(f"{fresh_prompt.NAME_THE_ITEMS}\n\n{prompts.rungs_held(fresh_prompt.DRIVER, unrouted, OPUS_PROJECT).lstrip()}\n\n{self.FACTS}", fresh_prompt.WORKER.fresh("Do it.", "## Goals", unrouted, OPUS_PROJECT, self.FACTS)) # Item 297 scores the higher L, item 298 the higher E + I. diff --git a/bin/model_routing/test_route.py b/bin/model_routing/test_route.py new file mode 100644 index 00000000..302c1476 --- /dev/null +++ b/bin/model_routing/test_route.py @@ -0,0 +1,65 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from model_routing.route import Route, route_from +from model_routing.ladder import Rung + +OPUS = Rung("claude-opus-5-5", "medium") +FABLE = Rung("claude-fable-5-2", "low") + + +class Levels(unittest.TestCase): + def test_refuses_a_route_whose_item_has_levels_off_their_scales_or_levels_without_an_item(self): + for item, likelihood, escape_and_impact in ((3, 0, 5), (3, 5, 5), (3, 4, 1), (3, 4, 9), (0, 4, 5), (0, 4, 0), (0, 0, 5)): + with self.subTest(item=item, likelihood=likelihood, escape_and_impact=escape_and_impact): + with self.assertRaises(ValueError): + Route(FABLE, item, likelihood, escape_and_impact) + + def test_refuses_a_route_taking_in_an_e_plus_i_off_its_scale_or_not_above_its_items(self): + for taken_in in (1, 9, -1, 5, 4): + with self.subTest(taken_in=taken_in): + with self.assertRaises(ValueError): + Route(FABLE, 3, 4, 5, escape_and_impact_taken_in=taken_in) + + def test_takes_a_route_whose_item_holds_each_levels_lowest_value(self): + self.assertEqual(Route(FABLE, 3, 1, 2).escape_and_impact, 2) + + def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self): + taken = Route(OPUS, 3, 3, 4).taking_in(6) + self.assertEqual(taken, Route(OPUS, 3, 3, 4, escape_and_impact_taken_in=6)) + self.assertEqual(taken.taking_in(7), Route(OPUS, 3, 3, 4, escape_and_impact_taken_in=7)) + self.assertEqual(taken.taking_in(5), taken) + self.assertEqual(taken.taking_in(6), taken) + self.assertEqual(Route(OPUS, 3, 3, 4).taking_in(4), Route(OPUS, 3, 3, 4)) + self.assertEqual(Route(OPUS, 3, 2, 2).taking_in(4), Route(OPUS, 3, 2, 2)) + self.assertEqual(Route(OPUS).taking_in(5), Route(OPUS, escape_and_impact_taken_in=5)) + self.assertEqual(Route(OPUS).taking_in(3), Route(OPUS)) + self.assertEqual(Route(OPUS).taking_in(0), Route(OPUS)) + + +class WorkerLines(unittest.TestCase): + def test_archives_the_route_as_a_json_worker_line_it_reads_back_field_by_field(self): + route = Route(FABLE, 3, 4, 5) + self.assertEqual(route.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5}') + self.assertEqual(route_from(route.worker_line()), route) + self.assertEqual(Route(Rung("worker-model")).worker_line(), '{"model": "worker-model"}') + self.assertEqual(route_from('{"model": "worker-model"}'), Route(Rung("worker-model"))) + marked = Route(FABLE, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12) + self.assertEqual(marked.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}') + self.assertEqual(route_from(marked.worker_line()), marked) + self.assertEqual(route_from(Route(FABLE, escalated_at=3).worker_line()), Route(FABLE, escalated_at=3)) + + def test_leaves_the_count_of_unfinished_verdicts_out_of_the_worker_line_so_a_rerun_restarts_it(self): + self.assertEqual(route_from(Route(FABLE, 3, 4, 5, unfinished=1).worker_line()), Route(FABLE, 3, 4, 5)) + + def test_reads_no_route_from_a_worker_line_that_route_worker_line_could_not_have_written(self): + for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": ', "worker-model", "claude-fable-5-2 at low effort, routed by item 3's L of 4 and E + I of 5"): + with self.subTest(line=line): + self.assertIsNone(route_from(line)) + + +if __name__ == "__main__": + unittest.main() diff --git a/todo.md b/todo.md index 87438e68..0ac0f7eb 100644 --- a/todo.md +++ b/todo.md @@ -183,7 +183,7 @@ Touches: - `bin/chunk_driver/project/records.py`: `read_records` - `bin/judge_replay/main.py`: `rule` (small) - `bin/judge_replay/replay.py`: `case_from` (small) -- `bin/loop_claude/test_loop_claude.py`: `JudgePrompt` +- `bin/agent_cycle/test_judge.py`: `JudgePrompt` - `bin/chunk_driver/project/test_records.py`: `Records` - `bin/judge_replay/test_judge_replay.py` -- 2.52.0 From 8ca612b7a4a21f1608105364a92dea04a710aeff Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 11:54:34 +0100 Subject: [PATCH 06/14] =?UTF-8?q?Answer=20architecture=20round=204:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20loop-claude?= =?UTF-8?q?'s=20suites=20sit=20beside=20their=20modules,=20and=20what=20te?= =?UTF-8?q?sts=20share=20across=20packages=20lives=20in=20each=20package's?= =?UTF-8?q?=20doubles.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/atlassian/test_client.py | 2 +- bin/branch_chunks/test_branch_chunks.py | 2 +- bin/chunk_driver/project/test_records.py | 2 +- bin/chunk_preflight/test_chunk_preflight.py | 3 +- bin/do_epic/test_human_tasks.py | 2 +- bin/do_epic/test_main.py | 2 +- bin/do_epic/test_planning.py | 2 +- bin/do_epic/test_repos.py | 2 +- bin/judge_replay/test_judge_replay.py | 2 +- bin/larv_review/test_larv_review.py | 2 +- bin/larv_review/test_scoring_setup.py | 2 +- bin/loop_claude/chunk/test_chunk_items.py | 56 + bin/loop_claude/chunk/test_fresh_prompt.py | 57 + bin/loop_claude/doubles.py | 22 + bin/loop_claude/loop/test_chunk_start.py | 149 +++ bin/loop_claude/loop/test_chunk_windows.py | 252 +++++ bin/loop_claude/loop/test_main.py | 267 +++++ bin/loop_claude/loop/test_routing_check.py | 154 +++ bin/loop_claude/loop/test_usage.py | 123 +++ bin/loop_claude/test_black_box.py | 3 +- bin/loop_claude/test_loop_claude.py | 998 ------------------ bin/loop_claude/test_routed_item.py | 53 + bin/metric_bench/test_metric_bench.py | 2 +- bin/model_routing/test_ladder_file.py | 2 +- bin/notifier/test_notifier.py | 2 +- bin/plan/doubles.py | 87 ++ bin/plan/test_blockers.py | 2 +- bin/plan/test_formula.py | 2 +- bin/plan/test_ranking.py | 90 +- bin/plan_store/test_stores.py | 2 +- bin/project_config/doubles.py | 46 + bin/project_config/test_project_config.py | 38 +- bin/project_record/test_project_record.py | 2 +- bin/reading_cost/test_reading_cost.py | 2 +- bin/repo_checks/test_package_cycles.py | 33 + bin/rest_client/doubles.py | 50 + bin/rest_client/test_json_request.py | 49 +- bin/review_replay/test_review_replay.py | 2 +- bin/routing_figures/test_routing_figures.py | 2 +- bin/rule_hook/test_rule_hook.py | 4 +- bin/score_outcomes/test_score_outcomes.py | 2 +- bin/subagent_rung/test_subagent_rung.py | 2 +- bin/test_rank_todo.py | 6 +- bin/todo_item/doubles.py | 13 + bin/todo_item/test_todo_item.py | 15 +- bin/touch_predictions/doubles.py | 12 + .../test_touch_predictions.py | 13 +- todo.md | 4 +- 49 files changed, 1415 insertions(+), 1228 deletions(-) create mode 100644 bin/loop_claude/chunk/test_chunk_items.py create mode 100644 bin/loop_claude/chunk/test_fresh_prompt.py create mode 100644 bin/loop_claude/doubles.py create mode 100644 bin/loop_claude/loop/test_chunk_start.py create mode 100644 bin/loop_claude/loop/test_chunk_windows.py create mode 100644 bin/loop_claude/loop/test_main.py create mode 100644 bin/loop_claude/loop/test_routing_check.py create mode 100644 bin/loop_claude/loop/test_usage.py delete mode 100644 bin/loop_claude/test_loop_claude.py create mode 100644 bin/loop_claude/test_routed_item.py create mode 100644 bin/plan/doubles.py create mode 100644 bin/project_config/doubles.py create mode 100644 bin/rest_client/doubles.py create mode 100644 bin/todo_item/doubles.py create mode 100644 bin/touch_predictions/doubles.py diff --git a/README.md b/README.md index 3847b9c0..4e1e67c6 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a ### Packages under `bin/` -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. - `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. `doubles.py` holds the doubles its tests share with `chunk_driver`'s. diff --git a/bin/atlassian/test_client.py b/bin/atlassian/test_client.py index fbf91612..dd070c4b 100644 --- a/bin/atlassian/test_client.py +++ b/bin/atlassian/test_client.py @@ -10,7 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from atlassian import client from rest_client.json_request import ErrorAnswer from failure import Failure -from rest_client.test_json_request import Served +from rest_client.doubles import Served AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode() diff --git a/bin/branch_chunks/test_branch_chunks.py b/bin/branch_chunks/test_branch_chunks.py index 429900d3..e790d5ef 100644 --- a/bin/branch_chunks/test_branch_chunks.py +++ b/bin/branch_chunks/test_branch_chunks.py @@ -13,7 +13,7 @@ from project_config.templates import BARE, Titles from branch_chunks.fixes import blamed, fixing_changes, removed, removed_work, Traced, with_fixes from branch_chunks.cut import Branch, chunk_log, Commit, cut_branch, landing, NOT_WORK, shipped, Span from branch_chunks.read import branch_chunks, traced_to, unsupported -from project_config.test_project_config import configured +from project_config.doubles import configured from failure import Failure from git_cli.git_repo import git from test_env import isolated_env diff --git a/bin/chunk_driver/project/test_records.py b/bin/chunk_driver/project/test_records.py index 3ef42e98..bafe0a2d 100644 --- a/bin/chunk_driver/project/test_records.py +++ b/bin/chunk_driver/project/test_records.py @@ -6,7 +6,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) -from project_config.test_project_config import configured +from project_config.doubles import configured from failure import Failure from agent_cycle import judge from chunk_driver.project import records diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index f94dfb76..137aa08f 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -11,7 +11,6 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.templates import BRANCH from release_plan.next_chunk import CarriedOver, NoItem -from chunk_preflight import choices from failure import Failure from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree from test_env import isolated_env @@ -21,7 +20,7 @@ from release_plan import next_chunk from chunk_preflight.facts import open_pulls, render from plan_store.todo_md import plan_of from chunk_preflight.choices import worktree_add -from project_config.test_project_config import write_config +from project_config.doubles import write_config BIN = pathlib.Path(__file__).resolve().parents[1] README = "# Project\n\n## Goals\n\n**Void:** code health, since the plan's scores weigh goal 1 alone.\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n" diff --git a/bin/do_epic/test_human_tasks.py b/bin/do_epic/test_human_tasks.py index 9ac6e426..631a3851 100644 --- a/bin/do_epic/test_human_tasks.py +++ b/bin/do_epic/test_human_tasks.py @@ -6,7 +6,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.test_project_config import configured +from project_config.doubles import configured from do_epic.test_main import DESCRIPTION, Description, DoEpicTest, MODELS, UNREAD from do_epic.epic_record import EpicRecord from failure import Failure diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 0c36fe7c..a983c4b0 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -13,7 +13,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic import chunk_prompt, main from chunk_driver.chunk_run import ChunkRun -from project_config.test_project_config import configured +from project_config.doubles import configured from do_epic.config import DoEpicConfig from project_config.settings import Epic, Finish from do_epic.epic_record import EpicRecord diff --git a/bin/do_epic/test_planning.py b/bin/do_epic/test_planning.py index 627cd16e..2f8e9ef9 100644 --- a/bin/do_epic/test_planning.py +++ b/bin/do_epic/test_planning.py @@ -9,7 +9,7 @@ import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.test_project_config import configured +from project_config.doubles import configured from do_epic.test_main import Description, DoEpicTest, structured as says from do_epic.backend.protocol import EpicIssue from do_epic.epic_record import EpicRecord diff --git a/bin/do_epic/test_repos.py b/bin/do_epic/test_repos.py index 1e504ab8..fdd8d66e 100644 --- a/bin/do_epic/test_repos.py +++ b/bin/do_epic/test_repos.py @@ -10,7 +10,7 @@ from do_epic.config import DoEpicConfig from failure import Failure from do_epic.repos import locate, Located, Unsure from project_config.settings import ProjectConfig -from project_config.test_project_config import write_config +from project_config.doubles import write_config class FakeGit: diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index b39308f0..314a0637 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -14,7 +14,7 @@ from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINIS from claude_code.entries import AssistantTurn, HumanTurn, LoopPrompt, Text from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind from text_files import compressed -from project_config.test_project_config import configured +from project_config.doubles import configured from loop_effects.effects import Effects from failure import Failure from agent_cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index c0126123..88782485 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -18,7 +18,7 @@ from review_rules.comprehension_history import appended, entries, HistoryChange, from larv_review.history_commands import appended_to from larv_review.plan import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due from review_rules import comprehension_history -from project_config.test_project_config import configured +from project_config.doubles import configured from larv_review.ruling import counted, ruling, split, surplus, votes from larv_review.history_commands import decided, rerank from project_config.settings import DEFAULT_FLOOR diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py index 38602a6e..59f97a15 100644 --- a/bin/larv_review/test_scoring_setup.py +++ b/bin/larv_review/test_scoring_setup.py @@ -12,7 +12,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from larv_review.scoring_setup import bullets, file_globs, prepare_scoring, project_values, removed_setup, score_bullets from failure import Failure from test_env import isolated_env -from project_config.test_project_config import write_config +from project_config.doubles import write_config TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review" SKILL = pathlib.Path(__file__).resolve().parents[2] / "skills" / "comprehension-panel" / "SKILL.md" diff --git a/bin/loop_claude/chunk/test_chunk_items.py b/bin/loop_claude/chunk/test_chunk_items.py new file mode 100644 index 00000000..a5619e2d --- /dev/null +++ b/bin/loop_claude/chunk/test_chunk_items.py @@ -0,0 +1,56 @@ +import pathlib +import re +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from loop_claude.chunk import chunk_items +from claude_code import entries +from failure import Failure +from loop_claude.chunk import fresh_prompt +from plan_store.todo_md import plan_of +from model_routing.route import Route +from model_routing.ladder import Rung +from loop_effects.doubles import said +from agent_cycle.verdicts import TakenIn + + +# Item 297 scores the higher L, item 298 the higher E + I. +SCORED = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 297 | 0.8.0 | | **Do it.** | 4 | 2 | 3 | 7 | 2 | 1 by 9 | 25 |\n| 298 | 0.8.0 | | **Do more.** | 3 | 3 | 4 | 8 | 2 | 1 by 9 | 20 |\n" + + +class ChunkItems(unittest.TestCase): + def test_names_the_items_on_the_workers_latest_chunk_items_line(self): + earlier = said("Chunk items: 297 (L 3, E + I 5)") + latest = said("Starting.\n**Chunk items:** 297 (L 4, E + I 5), item 298 (L 3, E + I 7), #12, 298\nOn to the tests.") + self.assertEqual(chunk_items.named([earlier, latest]), (297, 298, 12)) + self.assertEqual(chunk_items.named([latest, earlier]), (297,)) + self.assertEqual(chunk_items.named([earlier, said("Chunk items: none")]), ()) + self.assertEqual(chunk_items.named([said("Chunk items: 297 and 298 (L 3, E + I 7)")]), (297, 298)) + + def test_reads_the_example_line_the_prompt_gives_the_worker(self): + example = re.search(r"`(Chunk items:[^`]*)`", fresh_prompt.NAME_THE_ITEMS)[1] + self.assertEqual(chunk_items.named([said(example)]), (297, 298)) + + def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self): + self.assertIn("on one line, as in `Chunk items: ", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) + + def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self): + prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)") + written = entries.AssistantTurn(parts=(entries.ToolCall("t", "Write", {"content": "Chunk items: 9"}),)) + mentioned = said("Once I know them, I write `Chunk items: 5`.") + self.assertEqual(chunk_items.named([prompt, written, mentioned]), ()) + + def test_takes_the_highest_l_and_e_plus_i_todo_md_scores_among_the_named_items(self): + self.assertEqual(chunk_items.taken_in([said("Chunk items: 297 (L 1, E + I 2), 298, 400")], plan_of(SCORED)), TakenIn(4, 7)) + self.assertEqual(chunk_items.taken_in([said("Chunk items: 400")], plan_of(SCORED)), TakenIn()) + self.assertEqual(chunk_items.taken_in([], plan_of(SCORED)), TakenIn()) + + def test_names_the_items_at_no_level_where_todo_md_cannot_be_read(self): + self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], Failure("no todo.md")), TakenIn()) + self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], plan_of("no items table")), TakenIn()) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/chunk/test_fresh_prompt.py b/bin/loop_claude/chunk/test_fresh_prompt.py new file mode 100644 index 00000000..0f6df9bc --- /dev/null +++ b/bin/loop_claude/chunk/test_fresh_prompt.py @@ -0,0 +1,57 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from loop_claude.chunk import fresh_prompt +from loop_claude.doubles import OPUS_PROJECT +from chunk_driver import prompts +from model_routing.route import Route +from model_routing.ladder import Rung + + +class FreshPrompt(unittest.TestCase): + """loop-claude's first prompt of a chunk.""" + # What the preflight found, as the fresh prompt quotes it. + FACTS = "- A preflight fact." + + def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): + routed = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) + self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed) + unrouted = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS) + self.assertIn(f"before creating a new one. {prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted) + self.assertNotIn("loop-claude runs you on", unrouted) + + def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self): + routed = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) + self.assertIn("item 3's size again", routed) + self.assertIn("escalation trigger 1", routed) + self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed) + self.assertNotIn("size again", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)) + + def test_gives_each_fresh_worker_the_reading_rule_once(self): + rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context" + for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))): + with self.subTest(route=route): + self.assertEqual(fresh_prompt.WORKER.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1) + + def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self): + self.assertIn("\n\n- A fact.", fresh_prompt.preflight_facts("- A fact.")) + failed = fresh_prompt.preflight_failed("git could not start") + self.assertIn("yourself", failed) + self.assertIn("git could not start", failed) + + def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self): + for facts in (fresh_prompt.preflight_facts("- A fact."), fresh_prompt.preflight_failed("git could not start")): + with self.subTest(facts=facts): + self.assertEqual(fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1) + + def test_puts_the_rung_sentences_after_the_route_or_else_before_the_facts(self): + routed, unrouted = Route(OPUS_PROJECT.rung, 3, 2, 4), Route(OPUS_PROJECT.rung) + self.assertIn(f"routed by item 3's L of 2.{prompts.rungs_held(fresh_prompt.DRIVER, routed, OPUS_PROJECT)} After your first read", fresh_prompt.WORKER.fresh("Do it.", "## Goals", routed, OPUS_PROJECT, self.FACTS)) + self.assertIn(f"{fresh_prompt.NAME_THE_ITEMS}\n\n{prompts.rungs_held(fresh_prompt.DRIVER, unrouted, OPUS_PROJECT).lstrip()}\n\n{self.FACTS}", fresh_prompt.WORKER.fresh("Do it.", "## Goals", unrouted, OPUS_PROJECT, self.FACTS)) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/doubles.py b/bin/loop_claude/doubles.py new file mode 100644 index 00000000..74f6651a --- /dev/null +++ b/bin/loop_claude/doubles.py @@ -0,0 +1,22 @@ +"""Test doubles for loop-claude's suites: the shipped ladder's opus project, a plan and its release standing.""" +from model_routing.ladder import Ladder, ProjectRung, Rung +from release_plan.release_standing import LastCut +from model_routing.ladder_file import read_ladder, SHIPPED + +LADDER = read_ladder(SHIPPED) +assert isinstance(LADDER, Ladder), LADDER +OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium")) + +# A plan read with no release cut yet. +NO_CUT = LastCut(None, "", 0, []) + +TODO = """# todo + +## Items + +| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score | +|---|---|---|---|---|---|---|---|---|---|---| +| 7 | 0.2.0 | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 | +| 3 | 0.2.0 | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 | +| 1 | 0.3.0 | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 | +""" diff --git a/bin/loop_claude/loop/test_chunk_start.py b/bin/loop_claude/loop/test_chunk_start.py new file mode 100644 index 00000000..15e9fc6e --- /dev/null +++ b/bin/loop_claude/loop/test_chunk_start.py @@ -0,0 +1,149 @@ +import contextlib +import dataclasses +import io +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from chunk_driver.doubles import a_loop +from loop_claude.loop import chunk_start +from project_config.doubles import configured +from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES +from failure import Failure +from loop_effects.doubles import FakeEffects, ran, STAMP +from loop_claude.chunk import fresh_prompt +from loop_claude.doubles import NO_CUT, TODO +from loop_state import paths +from plan_store.todo_md import plan_of +from claude_code import session +from agent_cycle import tmux + + +class RouteSources(unittest.TestCase): + def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): + self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), None, FakeEffects().effects())) + self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), None, FakeEffects().effects()).id, 3) + self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), None, FakeEffects().effects())) + + def test_routes_a_window_named_for_an_item_on_that_item_whatever_the_plan_takes_next(self): + plan = DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])) + later = next(item.id for item in plan.plan.items if item.id != 3) + self.assertEqual(chunk_start.plan_item(plan, later, FakeEffects().effects()).id, later) + # 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)) + # 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) + 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): + with contextlib.redirect_stderr(io.StringIO()) as stderr: + self.assertIsNone(chunk_start.plan_item(plan, None, FakeEffects().effects())) + self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue()) + + def test_says_why_the_items_the_worker_names_lift_no_rung(self): + unscored = plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")) + for default, said in ((DefaultPlan(unscored, NO_CUT), "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("no git"), "the items the worker names lift no rung: no git\n"), (DefaultPlan(plan_of(TODO), NO_CUT), "")): + with self.subTest(said=said): + with contextlib.redirect_stderr(io.StringIO()) as stderr: + scored = chunk_start.scored_plan(default, FakeEffects().effects()) + self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "") + self.assertEqual(scored, default.plan if isinstance(default, DefaultPlan) else default) + + def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self): + def git(*args, **options): + answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "show": f"what {args[-1]} holds\n"} + return answers.get(args[0], "1\n") + + with tempfile.TemporaryDirectory() as root: + folder = configured(self, pathlib.Path(root)) + effects = dataclasses.replace(FakeEffects().effects(), git=git) + held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[1]))) + self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n") + + def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): + with tempfile.TemporaryDirectory() as root: + folder = configured(self, pathlib.Path(root)) + loop = a_loop(FakeEffects(git=["origin\n", "origin/main\n"] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + config = folder / "config.toml" + tracked = a_loop(FakeEffects(git=["origin\n", "origin/main\n", *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + with contextlib.redirect_stderr(io.StringIO()) as stderr: + chunk_start.fetched_plan(tracked) + self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release") + config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) + (folder / "todo.md").write_text(TODO) + unread = Failure("no git") + standing = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + with contextlib.redirect_stderr(io.StringIO()) as stderr: + held = chunk_start.fetched_plan(standing) + self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers") + self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review loop-claude cannot call due is never skipped silently") + quiet = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + with contextlib.redirect_stderr(io.StringIO()) as stderr: + chunk_start.fetched_plan(quiet, announce=False) + self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts") + config.unlink() + with contextlib.redirect_stderr(io.StringIO()) as stderr: + self.assertIn("no config names the checkout", chunk_start.scored_plan(chunk_start.fetched_plan(loop), loop.effects).reason) + self.assertIn("the items the worker names lift no rung: no config names the checkout", stderr.getvalue()) + self.assertIn("no config names the checkout", chunk_start.fetched_plan(loop).reason) + + +class ChunkFacts(unittest.TestCase): + # The launcher beside which chunk_start finds /b/chunk-preflight. + LAUNCHER = pathlib.Path("/b/loop-claude") + + def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self): + fake = FakeEffects(python=[ran("- A fact.\n")]) + said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) + self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")]) + self.assertTrue(said.endswith("\n\n- A fact."), said) + self.assertNotIn("yourself", said) + + def test_a_chunk_without_an_item_runs_the_preflight_without_naming_one(self): + fake = FakeEffects(python=[ran("- A fact.\n")]) + chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER, window=tmux.Window("loop-proj", "no-item", "%4"))) + self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")]) + + def test_the_facts_end_with_the_items_the_projects_other_running_chunks_hold(self): + # The loop's own window, a stopped one and two that run, one of them waiting for the human. + fake = FakeEffects(python=[ran("- A fact.\n")], windows="item-7\t0\t@1\nitem-5\t1\t@2\nitem-12 ?\t0\t@3\nitem-9\t0\t@4\n") + said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) + self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project, running or stopped, hold items 5, 9, 12. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said) + self.assertEqual(fresh_prompt.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.") + self.assertTrue(fresh_prompt.held_by_others([4, 9]).startswith("\n\nOther chunks of this project, running or stopped, hold items 4, 9.")) + # A worker whose preflight failed is told them too. + fake = FakeEffects(python=[ran(code=1, stderr="git could not start\n")], windows="item-9\t0\t@4\n") + said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) + self.assertTrue(said.endswith("Other chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said) + + def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self): + for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")): + with self.subTest(why=why): + said = chunk_start.chunk_facts(a_loop(FakeEffects(python=[failed]).effects(), launcher=self.LAUNCHER)) + self.assertIn("yourself", said) + self.assertIn(why, said) + + def test_runs_the_preflight_only_where_the_session_is_not_open(self): + with tempfile.TemporaryDirectory() as home: + opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects")) + fresh = FakeEffects(python=[ran("- A fact.\n")]) + facts, _ = chunk_start.chunk_start(a_loop(fresh.effects(), session=opened, launcher=self.LAUNCHER)) + self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")], True)) + transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") + transcript.parent.mkdir(parents=True) + transcript.write_text("") + resumed = FakeEffects() + facts, _ = chunk_start.chunk_start(a_loop(resumed.effects(), session=opened, launcher=self.LAUNCHER)) + self.assertEqual((resumed.made("python"), facts), ([], "")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/loop/test_chunk_windows.py b/bin/loop_claude/loop/test_chunk_windows.py new file mode 100644 index 00000000..9376890f --- /dev/null +++ b/bin/loop_claude/loop/test_chunk_windows.py @@ -0,0 +1,252 @@ +import contextlib +import io +import json +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +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 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 + + +class ChunkWindows(unittest.TestCase): + def plan(self, *touched): + """A plan of items 1, 2 and on, each predicted to touch the path given for it.""" + items = touch_plan(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1))) + return next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="") + + def test_starts_the_next_item_and_those_picked_beside_it_up_to_the_limit(self): + # Item 2 overlaps item 1, so it waits for it; items 3 and 4 run beside it. + plan = self.plan("a.py", "a.py", "c.py", "d.py") + self.assertEqual(chunk_windows.may_start(plan, [], set(), 1), ["item-1"]) + self.assertEqual(chunk_windows.may_start(plan, [], set(), 2), ["item-1", "item-3"]) + self.assertEqual(chunk_windows.may_start(plan, [], set(), 9), ["item-1", "item-3", "item-4"]) + + def test_leaves_the_items_running_chunks_hold_and_starts_only_as_many_as_the_room_left(self): + plan = self.plan("a.py", "a.py", "c.py", "d.py") + self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 1), ["item-4"]) + self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 2), ["item-3", "item-4"]) + self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 0), []) + + def test_counts_the_running_chunks_against_the_limit_and_restarts_stopped_ones_first(self): + windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True), tmux.Listed("item-4", "", True)] + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 3), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 0)) + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3"], 0)) + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 5), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 2)) + + def test_a_loop_whose_chunk_finished_leaves_its_room_and_restarts_no_stopped_chunk(self): + windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True)] + self.assertEqual(chunk_windows.room_of(windows, "item-1", True, 2), chunk_windows.Room([], ["item-3"], [], 2)) + + def test_leaves_no_room_where_more_chunks_run_than_the_limit(self): + windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)] + self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0) + + def test_starts_no_item_that_overlaps_a_running_chunks_items(self): + # Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py. + items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`")) + plan = next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="") + self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 2), ["item-4"]) + # A running chunk's item without a prediction leaves no other item free to start beside it. + unpredicted = touch_plan((2, "1.0.0", "", "- `a.py`"), (3, "1.0.0", "", None)) + self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 2), []) + # A held item that left the plan, as once it merged, overlaps nothing. + self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 2), ["item-2", "item-4"]) + + def test_a_plan_without_an_item_starts_one_chunk_and_only_alone(self): + none = next_chunk.NoItem("release 1.0.0 has no items") + self.assertEqual(chunk_windows.may_start(none, [], set(), 3), ["no-item"]) + self.assertEqual(chunk_windows.may_start(none, ["item-1"], {1}, 3), []) + + def test_names_a_window_for_its_item_and_reads_the_item_back(self): + self.assertEqual(chunk_windows.window_name(372), "item-372") + self.assertEqual([chunk_windows.item_of(chunk) for chunk in ("item-372", "no-item", "item-", "item-3x", "xitem-3")], [372, None, None, None, None]) + # Only ASCII digits name an item, as window_name writes them. + 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"]) + + def test_a_chunk_whose_transcript_cannot_be_read_holds_the_item_it_started_from(self): + with tempfile.TemporaryDirectory() as temp: + transcripts = pathlib.Path(temp) + folder = transcripts / "-r" + folder.mkdir() + # A folder in place of the transcript file, so reading it fails. + (folder / f"{chunk_windows.chunk_session('proj', 'item-7', transcripts).id}.jsonl").mkdir() + self.assertEqual(chunk_windows.held_items(["item-7"], "proj", transcripts), {7}) + + def test_tells_a_chunk_the_items_the_projects_other_live_chunks_hold(self): + with tempfile.TemporaryDirectory() as temp: + home = pathlib.Path(temp) + held = paths.paths_from(home) + folder = held.claude_code_transcripts / "-r" + folder.mkdir(parents=True) + lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})] + (folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines)) + # Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item. + fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n") + self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11]) + self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) + + +class StartChunks(unittest.TestCase): + """start_chunks: the windows a loop opens for the chunks that may start now.""" + LAUNCHER = pathlib.Path("/b/loop-claude") + + def setUp(self): + made = tempfile.TemporaryDirectory() + self.addCleanup(made.cleanup) + self.root = pathlib.Path(made.name, "r") + 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") + + def limit(self, chunks): + config = self.home / ".claude-projects" / self.root.name / "config.toml" + config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n") + + def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None): + """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() + 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) + return started + + 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")] + + def test_opens_a_window_for_each_chunk_that_may_start_the_first_making_the_session(self): + self.limit(2) + fake = FakeEffects() + self.assertEqual(self.start(fake, env={"LOOP_CLAUDE_WORKER_MODEL": "m", "PATH": "/bin"}), ["item-1", "item-3"]) + self.assertEqual(self.starts(fake), [("new-session", "item-1", [str(self.LAUNCHER), "--chunk", "item-1", "ship it"]), ("new-window", "item-3", [str(self.LAUNCHER), "--chunk", "item-3", "ship it"])]) + first = next(call for call in fake.tmux_calls if call[0] == "new-session") + self.assertEqual((first[first.index("-s") + 1], first[first.index("-c") + 1]), (self.session, str(self.root))) + # Only loop-claude's own variables are handed on, since a window gets the tmux server's environment. + self.assertEqual([word for word in first if "=" in word], ["LOOP_CLAUDE_WORKER_MODEL=m"]) + self.assertEqual(fake.tmux_calls[0], ["list-windows", "-t", f"={self.session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]) + # The session names the checkout whose chunks it runs. + self.assertIn(["set-option", "-t", f"={self.session}:", "@loop-root", str(self.root)], fake.tmux_calls) + + def test_refuses_a_session_that_runs_another_checkouts_chunks(self): + for owner, named in (("/c/acme.api", "/c/acme.api"), ("", "another checkout")): + with self.subTest(owner=owner): + fake = FakeEffects(windows="item-5\t0\t@1\n") + self.assertEqual(self.start(fake, owner=owner), Failure(f"the tmux session {self.session} runs the chunks of {named}, whose key maps to the same session name; rename one of the two checkouts' folders")) + self.assertEqual(self.starts(fake), []) + self.assertIn(["show-options", "-qv", "-t", f"={self.session}:", "@loop-root"], fake.tmux_calls) + + def test_refuses_a_checkout_do_epic_runs_chunks_in(self): + fake = FakeEffects(windows=f"epic-ABC-12\tABC-34 ?\t0\t@4\t{self.root}\nepic-ABC-12\tABC-35\t0\t@5\t/c/other\nepic-ABC-12\tABC-36\t1\t@6\t{self.root}\nloop-x\titem-1\t0\t@7\t{self.root}\n") + self.assertEqual(self.start(fake), Failure(f"do-epic runs chunks in {self.root}: ABC-34 of epic-ABC-12; loop-claude doesn't start a chunk there until those chunks finish")) + self.assertEqual(self.starts(fake), []) + + def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self): + self.limit(2) + transcripts = paths.paths_from(self.home).claude_code_transcripts + folder = transcripts / "-r" + folder.mkdir(parents=True) + opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts) + (folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n") + self.assertEqual(self.start(FakeEffects(windows="item-5\t0\t@1\n")), ["item-3"]) + + def test_starts_one_chunk_without_parallel_chunks(self): + fake = FakeEffects() + self.assertEqual(self.start(fake), ["item-1"]) + + def test_starts_none_and_reads_no_plan_while_the_running_chunks_fill_the_limit(self): + self.limit(2) + fake = FakeEffects(windows="item-5\t0\t@1\nitem-6 ?\t0\t@2\n") + self.assertEqual((self.start(fake), self.planned, self.starts(fake)), ([], 0, [])) + # More chunks run than the limit allows, as after it was lowered; a stopped chunk still waits. + fake = FakeEffects(windows="item-5\t0\t@1\nitem-6\t0\t@2\nitem-7\t0\t@3\nitem-8\t1\t@4\nitem-9\t1\t@5\n") + self.assertEqual((self.start(fake), self.planned), ([], 0)) + + def test_a_finishing_chunks_own_window_counts_as_no_longer_running(self): + fake = FakeEffects(windows="item-5\t0\t@1\n") + self.assertEqual(self.start(fake, chunk="item-5"), []) + fake = FakeEffects(windows="item-5\t0\t@1\n") + self.assertEqual(self.start(fake, chunk="item-5", leaving=True), ["item-1"]) + # The session exists, since the finishing loop's window is still in it. + self.assertEqual(self.starts(fake)[0][0], "new-window") + + def test_the_humans_loop_claude_starts_a_stopped_chunk_again_first_closing_its_dead_window(self): + fake = FakeEffects(windows="item-5\t1\t@3\n") + self.assertEqual((self.start(fake), self.planned), (["item-5"], 0)) + self.assertIn(["kill-window", "-t", "@3"], fake.tmux_calls) + # Its dead window was the session's last, so the session is made again. + self.assertEqual(self.starts(fake)[0][0], "new-session") + self.limit(2) + fake = FakeEffects(windows="item-5\t1\t@3\n") + self.assertEqual(self.start(fake), ["item-5", "item-1"]) + + 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"]) + + def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self): + self.limit(2) + transcripts = paths.paths_from(self.home).claude_code_transcripts + folder = transcripts / "-r" + folder.mkdir(parents=True) + opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts) + (folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n") + fake = FakeEffects(windows="item-7\t0\t@1\nitem-5\t1\t@3\n") + # Item 1 is the stopped chunk's, so item 3 starts; the stopped one doesn't count against parallel-chunks. + 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")), []) + + def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self): + fake = FakeEffects() + self.assertEqual(self.start(fake, plan=Failure("no origin/main")), ["no-item"]) + 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")) + + def test_says_why_it_cannot_take_the_lock_on_starting_windows(self): + (self.home / ".local" / "state").mkdir(parents=True) + (self.home / ".local" / "state" / "loop-claude").write_text("") + started = self.start(FakeEffects()) + self.assertIsInstance(started, Failure) + self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/loop-claude/"), started.reason) + + 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) + opened = chunk_windows.chunk_session("proj", "item-7", transcripts) + self.assertEqual(opened.name, "A proj loop-claude item-7") + folder = transcripts / "-r" + folder.mkdir() + lines = [assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2)"}), assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2), 9 (L 2, E + I 3)"})] + (folder / f"{opened.id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines)) + self.assertEqual(chunk_windows.held_items(["item-7", "item-8", "no-item"], "proj", transcripts), {7, 8, 9}) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/loop/test_main.py b/bin/loop_claude/loop/test_main.py new file mode 100644 index 00000000..0f37bee2 --- /dev/null +++ b/bin/loop_claude/loop/test_main.py @@ -0,0 +1,267 @@ +import contextlib +import dataclasses +import io +import json +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from chunk_driver.doubles import a_loop +from loop_effects.doubles import CWD, FakeEffects, ran, STAMP +from failure import Failure +from agent_cycle.verdicts import Finished, Unfinished +from loop_claude.loop import main, reload, usage +from loop_claude.doubles import OPUS_PROJECT +from loop_state import paths +from model_routing.route import Route +from model_routing.ladder import Rung +from claude_code import session +from agent_cycle.stop import Stop +from chunk_driver import this_loop +from agent_cycle import tmux + + +class LoopRuns(unittest.TestCase): + def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): + for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "", "unfinished_evidence": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1, "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "unfinished_evidence": ""})]): + with self.subTest(handed=handed): + self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: {' '.join(handed)}")) + + def test_decodes_every_field_of_the_state_and_its_route(self): + state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2) + self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state) + self.assertEqual(set(reload.LOOP_RUN_FIELDS), {field.name for field in dataclasses.fields(main.LoopRun)}) + + def test_rejects_a_field_of_another_type_or_an_unknown_field(self): + state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2)) + for path, wrong in ((("unfinished_run",), "2"), (("unfinished_run",), True), (("route", "unfinished"), 1.0), (("route", "escalated_at"), "9"), (("route", "item"), True), (("route", "rung"), "claude-opus-5-5"), (("route", "rung", "model"), None), (("route",), "r"), (("route", "extra"), 1), (("route", "model"), "claude-opus-5-5"), (("route", "effort"), "high")): + with self.subTest(path=path, wrong=wrong): + handed = json.loads(json.dumps(state)) + target = handed + for key in path[:-1]: + target = target[key] + target[path[-1]] = wrong + self.assertIsNone(reload.decode_handed(json.dumps(handed))) + + def test_rejects_a_state_or_rung_missing_a_required_field(self): + state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low")))) + for path in (("cycle_number",), ("root",), ("task",), ("unfinished_evidence",), ("route", "rung"), ("route", "rung", "model")): + with self.subTest(path=path): + handed = json.loads(json.dumps(state)) + target = handed + for key in path[:-1]: + target = target[key] + del target[path[-1]] + self.assertIsNone(reload.decode_handed(json.dumps(handed))) + + def test_decodes_a_rung_without_an_effort(self): + state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("some-model"))) + self.assertEqual(reload.decode_handed(json.dumps({**dataclasses.asdict(state), "route": {"rung": {"model": "some-model"}}})), state) + + def test_rejects_text_that_is_not_json(self): + self.assertIsNone(reload.decode_handed("not json")) + + def test_decodes_a_route_inside_the_state_or_none(self): + state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1)) + self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state) + unrouted = dataclasses.replace(state, route=None) + self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(unrouted))), unrouted) + handed = dataclasses.asdict(state) + handed["route"]["rung"]["effort"] = 1 + self.assertIsNone(reload.decode_handed(json.dumps(handed))) + del handed["route"]["rung"] + self.assertIsNone(reload.decode_handed(json.dumps(handed))) + off_scale = dataclasses.asdict(state) + off_scale["route"]["likelihood"] = 9 + self.assertIsNone(reload.decode_handed(json.dumps(off_scale))) + older = dataclasses.asdict(state) + del older["route"]["escape_and_impact_taken_in"] + self.assertEqual(reload.decode_handed(json.dumps(older)), state) + taken = dataclasses.replace(state, route=dataclasses.replace(state.route, escape_and_impact_taken_in=7)) + self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(taken))), taken) + for taken_in in (9, 5): + with self.subTest(taken_in=taken_in): + handed = dataclasses.asdict(state) + handed["route"]["escape_and_impact_taken_in"] = taken_in + self.assertIsNone(reload.decode_handed(json.dumps(handed))) + + def test_decodes_a_state_from_before_a_field_with_a_default_joined_it(self): + self.assertEqual(reload.decode_handed(json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "unfinished_evidence": ""})), main.LoopRun(3, "/r", "do it", "")) + + def test_drops_the_items_taken_in_that_a_loop_started_before_0_11_0_hands_on(self): + state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="") + self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"items_taken_in": [12, 14]})), state) + + def test_drops_the_slot_that_a_loop_started_before_chunks_ran_in_windows_hands_on(self): + state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="") + self.assertEqual(reload.decode_handed(json.dumps({key: value for key, value in dataclasses.asdict(state).items() if key != "chunk"} | {"slot": 1})), state) + + def test_stops_when_the_reload_cannot_start_python(self): + with tempfile.TemporaryDirectory() as root: + launcher = pathlib.Path(root, "loop-claude") + launcher.write_text("") + fake = FakeEffects(python=[ran()]) + 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 ")) + + +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] + return stop, said.getvalue() + + def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self): + fake = FakeEffects(git=["/r\n"], tmux_version="tmux 3.1c") + self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), "")) + self.assertEqual((fake.tmux_calls, self.asked), ([["-V"]], [])) + + def test_prints_the_help_without_tmux(self): + fake = FakeEffects(tmux_version="") + self.assertEqual(self.run_loop(["--help"], fake)[0], Stop(0, usage.HELP)) + self.assertEqual(fake.tmux_calls, []) + + def test_starts_the_chunks_then_attaches_to_the_session_or_inside_tmux_switches_to_it(self): + for env, shown in (({}, ["attach-session", "-t", "=loop-r"]), ({"TMUX": "/tmp/tmux-1000/default,1,0"}, ["switch-client", "-t", "=loop-r"])): + with self.subTest(shown=shown): + fake = FakeEffects(git=["/r\n"]) + stop, said = self.run_loop(["do", "it"], fake, env) + self.assertEqual((stop, said), (Stop(0, ""), f"{STAMP} started item-3, item-4 in the tmux session loop-r\n")) + self.assertEqual(fake.tmux_calls, [["-V"], shown]) + self.assertEqual(self.asked, [(main.LoopRun(0, "/r", "do it", ""), False)]) + + 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)) + + 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"]) + effects, env = fake.effects(), {"TMUX_PANE": "%4"} + launcher = pathlib.Path("/b/loop-claude") + cycle = unittest.mock.Mock(project=OPUS_PROJECT) + 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) + 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) + + 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)) + + def test_a_window_loop_outside_a_checkout_stops(self): + self.assertIsInstance(main.loop_run_from(["--chunk", "item-3", "do it"], CWD, FakeEffects(git=[Failure("git cannot start")]).effects()), Stop) + + def test_says_that_nothing_started_where_the_session_already_runs_every_chunk_that_may(self): + self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=())[1], f"{STAMP} the tmux session loop-r runs every chunk that may run now, so `do it` started in no new window\n") + + def test_off_a_terminal_it_prints_how_to_attach(self): + fake = FakeEffects(git=["/r\n"], on_terminal=False) + stop, said = self.run_loop(["do it"], fake) + self.assertEqual(stop, Stop(0, "")) + self.assertTrue(said.endswith(f"{STAMP} not on a terminal; see the chunks with `tmux attach -t =loop-r`\n"), said) + self.assertEqual(fake.tmux_calls, [["-V"]]) + + def test_stops_where_no_chunk_could_start(self): + self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=Failure("no plan"))[0], Stop(1, "no plan")) + + 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) + 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): + fake = FakeEffects(git=["/r\n"]) + self.assertEqual(self.run_loop(["--chunk", "item-3", "do it"], fake)[0], Stop(1, "--chunk is how loop-claude starts itself in a tmux window; run loop-claude ")) + self.assertEqual(self.asked, []) + + def test_reads_the_chunk_a_window_loop_is_started_with(self): + self.assertEqual(main.loop_run_from(["--chunk", "item-3", "do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "", chunk="item-3")) + self.assertEqual(main.loop_run_from(["do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "")) + + def test_a_finished_chunk_starts_each_chunk_that_may_start_and_stops_without_a_reason(self): + 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) + 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)) + + +class StopDms(unittest.TestCase): + def run_main(self, argv, fake): + with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()): + code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "loop-claude"), CWD, fake.effects()) + return code, said.getvalue() + + 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(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(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(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) + 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): + fake = FakeEffects() + code, said = self.run_main([main.RELOAD_FLAG, "3"], fake) + self.assertEqual(code, 1) + self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: 3"]) + + def test_says_why_the_dm_of_a_stop_failed_after_the_reason(self): + fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")]) + self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n")) + + def test_skips_the_dm_where_it_prints_its_help(self): + for argv, code in (([], 1), (["--help"], 0)): + with self.subTest(argv=argv): + fake = FakeEffects() + self.assertEqual(self.run_main(argv, fake)[0], code) + self.assertEqual(fake.dms, []) + + +class OwnLadder(unittest.TestCase): + def test_a_cycle_on_a_projects_own_ladder_names_its_file_and_says_where_the_workers_model_is_off_it(self): + file = pathlib.Path("/h/.claude-projects/acme/routing-ladder.json") + self.assertEqual(main.own_ladder(file, "claude-fable-5-2", False), f"routing on the project's own ladder, {file}.") + self.assertEqual(main.own_ladder(file, "claude-opus-5-5", True), f"routing on the project's own ladder, {file}. claude-opus-5-5 is not on it, so the worker runs on claude-opus-5-5 unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run.") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/loop/test_routing_check.py b/bin/loop_claude/loop/test_routing_check.py new file mode 100644 index 00000000..4c510b97 --- /dev/null +++ b/bin/loop_claude/loop/test_routing_check.py @@ -0,0 +1,154 @@ +import contextlib +import io +import json +import pathlib +import shutil +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from chunk_driver.doubles import a_loop +from routing_figures import archive, state +from test_env import assert_not_root +from routing_figures.calls import Call +from failure import Failure +from loop_effects.doubles import FakeEffects, NOW +from transcript_archive import outcomes +from loop_state import paths +from loop_claude.loop import routing_check +from model_routing.ladder import Rung +from claude_code import session +from agent_cycle.stop import Stop +from text_files.utc_stamp import utc + + +# How git answers in a project's checkout it cannot read, such as one that is gone. +UNREAD = Failure("not a git repository") + + +class RoutingCheck(unittest.TestCase): + def setUp(self): + self.home = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.home) + self.root = self.home / "archive" + self.paths = paths.paths_from(self.home) + self.session = session.session_named("A log loop-claude", self.paths.claude_code_transcripts) + + def loop(self, fake): + """The loop in /code/log.""" + return a_loop(fake.effects(), root="/code/log", session=self.session, paths=self.paths) + + def chunks(self, count, verdicts, project="log"): + """count finished chunks, each closed by verdicts verdicts, each with one Explore subagent whose report outgrew its searches.""" + for number in range(count): + folder = self.root / project / f"c{number}" + subagents = folder / "session" / "s" / "subagents" + subagents.mkdir(parents=True) + kept = "".join(f"2026-10-14T10:0{verdict}:00Z {outcomes.unfinished('w', 'e', 'j', '')}\n" for verdict in range(verdicts - 1)) + (folder / "copy.outcomes.md").write_text(f"Task: t\n\n{kept}2026-10-14T11:00:00Z {outcomes.finished('w', 'm', 'j')}\n") + launch = {"type": "assistant", "timestamp": "2026-10-14T09:00:00Z", "message": {"id": "m", "content": [{"type": "tool_use", "id": "a", "name": "Agent", "input": {"subagent_type": "Explore"}}]}} + report = {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "a", "content": "long report"}]}} + (folder / "copy.jsonl").write_text(json.dumps(launch) + "\n" + json.dumps(report) + "\n") + (subagents / "agent-a.jsonl").write_text("") + (subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"})) + + def check(self, fake): + """What check_routing returns and says for a loop in /code/log.""" + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: + stop = routing_check.check_routing(self.root, Rung("m", "high"), self.loop(fake)) + return stop, said.getvalue() + + def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self): + self.chunks(5, 3) + self.assertEqual(self.check(FakeEffects()), (None, "")) + self.assertFalse((self.root / "routing-figures.md").exists()) + self.chunks(6, 1, "other") + self.assertEqual(self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 6))[0], None) + self.assertIn("at cycle 21 across", (self.root / "routing-figures.md").read_text()) + + def test_reads_each_projects_history_through_the_loops_git_and_names_each_it_cannot_read(self): + self.chunks(5, 4) + fake = FakeEffects(on_terminal=False, git=[UNREAD] * 3) + self.check(fake) + located = ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"] + self.assertEqual(fake.made("git"), [located, located, ["remote"]], "the config is located for its title templates, then for where it keeps the plan") + self.assertIn("## Default branches unread\n\n- log: not a git repository\n", (self.root / "routing-figures.md").read_text()) + + def test_hands_the_terminal_over_once_for_each_new_call(self): + self.chunks(5, 4) + fake = FakeEffects(on_terminal_claude=[0], git=[UNREAD] * 3) + stop, said = self.check(fake) + self.assertIsNone(stop) + call = "Explore subagents' reports took more of the worker's context than their searches would have." + self.assertIn(f"- {call}", said) + self.assertIn(f"- {call}", (self.root / "routing-figures.md").read_text()) + ((args),) = fake.made("claude_on_terminal") + self.assertEqual(args[:6], ["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions"]) + self.assertIn(f"don't change anything until they answer:\n- {call}", args[6]) + self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}]) + self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release") + self.assertIn("Record what they decide in this checkout, the development clone", args[6]) + self.assertIsNone(state.mark_measured(self.root, 0)) + self.assertEqual(self.check(FakeEffects(git=[UNREAD] * 3))[0], None) + self.assertNotIn(call, self.check(FakeEffects())[1]) + + def test_stamps_the_figures_and_the_calls_raised_when_it_measures(self): + self.chunks(5, 4) + (self.root / "routing-calls-raised.md").write_text("# Routing calls raised\n\n- 2026-10-14T10:02:00Z Reset\n") + self.check(FakeEffects(on_terminal_claude=[0], git=[UNREAD] * 3)) + figures = (self.root / "routing-figures.md").read_text() + self.assertIn(f"Measured {utc(NOW)}, at cycle 20 across", figures) + self.assertIn("that finished after the reset of 2026-10-14T10:02:00Z", figures) + self.assertIn(f"- {utc(NOW)} Explore subagents'", (self.root / "routing-calls-raised.md").read_text()) + + def test_says_a_figure_it_cannot_read(self): + self.chunks(5, 4) + (self.root / "routing-state.json").mkdir() + self.assertIn("routing figures: could not read", self.check(FakeEffects())[1]) + + def test_goes_on_off_a_terminal_and_raises_the_call_again_next_time(self): + self.chunks(5, 4) + stop, said = self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 3)) + self.assertIsNone(stop) + self.assertIn("Not on a terminal: the calls are raised again at the next measurement.", said) + self.assertIsNone(state.mark_measured(self.root, 0)) + self.assertIn("Not on a terminal", self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 3))[1]) + + def test_leaves_the_measuring_to_a_loop_holding_the_lock(self): + self.chunks(5, 4) + with archive.locked(self.root): + self.assertEqual(self.check(FakeEffects()), (None, "")) + + def test_stops_when_claude_cannot_start_for_the_calls(self): + self.chunks(5, 4) + stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD] * 3)) + self.assertEqual(stop, Stop(1, f"could not start claude for the routing calls in {self.home / 'code' / 'claude-config'}, the setup's development clone: No such file or directory")) + + def test_says_a_figure_it_cannot_write_and_goes_on(self): + assert_not_root(self) + self.chunks(5, 4) + (self.root / "routing-figures.lock").touch() + self.root.chmod(0o555) + self.addCleanup(self.root.chmod, 0o755) + stop, said = self.check(FakeEffects(git=[UNREAD] * 3)) + self.assertIsNone(stop) + self.assertIn("routing figures: could not write", said) + + 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.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()) + [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) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/loop/test_usage.py b/bin/loop_claude/loop/test_usage.py new file mode 100644 index 00000000..a6da1337 --- /dev/null +++ b/bin/loop_claude/loop/test_usage.py @@ -0,0 +1,123 @@ +import ast +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) + +from claude_code.output_limits import BASH_CEILING_CHARACTERS +from chunk_driver import chunk_run +from agent_cycle import judge, retry, states, worker +from loop_claude.loop import main, usage +from loop_effects.effects import PYTHON_TIMEOUT +from chunk_driver.project import records +from claude_code import reply +from routing_figures import state + + +class HelpLimits(unittest.TestCase): + def test_help_wraps_at_100_columns(self): + self.assertEqual([line for line in usage.HELP.splitlines() if len(line) > 100], []) + + def test_help_states_the_limits_the_code_holds(self): + said = " ".join(usage.HELP.split()) + self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", said) + # The retry messages say these limits in words too. + self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60)) + self.assertIn("fails three times running, retried a minute apart", said) + self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said) + self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said) + self.assertIn(f"Once {state.CYCLES_PER_CHECK} cycles have closed across all projects", said) + self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said) + self.assertIn(f"{BASH_CEILING_CHARACTERS:,} characters", said) + self.assertIn(f"unfinished {chunk_run.UNFINISHED_LIMIT} cycles running", said) + self.assertIn(f"rerun to give it {chunk_run.UNFINISHED_LIMIT} more", said) + + +class ExitContract(unittest.TestCase): + def test_every_exit_1_stop_has_its_clause_in_help(self): + read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "no config names the checkout, its config cannot be read, or the goals file holds no premises" + models_ = "the models file cannot be read or written" + names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], f"{records.HUMAN_RULE_NAMES[1]}*.md", records.HUMAN_RULE_NAMES[2]) + unreadable = f"the goals file, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8" + # Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause. + clauses = [ + ("agent_cycle/interrupt.py", "claude_open", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), + ("agent_cycle/interrupt.py", "human_typed", "1", "entries.reason", read), + ("agent_cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read), + ("agent_cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"), + ("agent_cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read), + ("agent_cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), + ("agent_cycle/run.py", "rule", "1", "entries.reason", read), + ("agent_cycle/run.py", "rule", "1", "annotation.reason", read), + ("agent_cycle/run.py", "rule", "1", "failure.reason", read), + ("agent_cycle/run.py", "keep_rejection", "1", "unkept.reason", read), + ("agent_cycle/run.py", "close", "1", "annotation.reason", read), + ("agent_cycle/run.py", "close", "1", "failure.reason", read), + ("agent_cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"), + ("chunk_driver/chunk_run.py", "closed_cycle", "1", "failure.reason", read), + ("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_), + ("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"), + ("loop_claude/loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"), + ("loop_claude/loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"), + ("loop_claude/loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"), + ("loop_claude/loop/main.py", "next_cycle", "1", "premises.reason", premises_), + ("loop_claude/loop/main.py", "next_cycle", "1", "records.reason", unreadable), + ("loop_claude/loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"), + ("loop_claude/loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"), + ("loop_claude/loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"), + ("loop_claude/loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {loop.paths.config_clone}", "claude cannot start for an interrupt"), + ] + root = pathlib.Path(main.__file__).parents[2] + found = [] + for path in sorted(path for package in ("agent_cycle", "chunk_driver", "loop_claude") for path in (root / package).rglob("*.py") if not path.name.startswith("test_")): + functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)] + stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))] + found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)] + self.assertEqual(len(found), len(clauses), found) + for (path, function, code, reason), (want_path, want_function, want_code, reason_start, _) in zip(found, clauses): + with self.subTest(path=path, function=function): + self.assertEqual((path, function, code), (want_path, want_function, want_code)) + self.assertTrue(reason.startswith(reason_start), reason) + help_exit_1 = " ".join(usage.HELP[usage.HELP.index("Exit 1"):usage.HELP.index("Exit 2")].split()) + self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], []) + + +class JudgeFailures(unittest.TestCase): + def test_every_failed_judge_run_has_its_clause_in_help(self): + started, exited, unparsed = "claude cannot start", "exits non-zero", "prints no json reply" + field, unasked = "its reply misses or mistypes a field", "interrupts or quotes an answer without a question" + # Every Failure the judge's run returns, in source order of judge.py, then of the claude run it calls: function, start of reason, its --help clause. + clauses = [ + ("verdict_from", "'the judge returned no reply'", field), + ("verdict_from", 'f"the judge\'s reply has no {name}', field), + ("verdict_from", "'the judge interrupted without a question'", unasked), + ("verdict_from", "'the judge quoted an answer without a question'", unasked), + ("run_judge", "verdict.reason", field), + ("run_judge", "checked.reason", "quotes a passage the transcript does not hold"), + ("misquoted_evidence", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"), + ("claude_reply", "f'could not start claude:", started), + ("claude_reply", "proc.stderr.strip() or f'{who} exited", exited), + ("claude_reply", 'f"{who} printed no json reply', unparsed), + ] + found = [] + for module in (judge, reply): + functions = [node for node in ast.walk(ast.parse(pathlib.Path(module.__file__).read_text())) if isinstance(node, ast.FunctionDef)] + found += sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) in ("Failure", "Rejected")) + self.assertEqual(len(found), len(clauses), found) + for (_, function, reason), (want_function, reason_start, _) in zip(found, clauses): + with self.subTest(function=function): + self.assertEqual(function, want_function) + self.assertTrue(reason.startswith(reason_start), reason) + judge_clause = " ".join(usage.HELP[usage.HELP.index("a judge when"):usage.HELP.index("A usage limit")].split()) + self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 5a3a2881..020098ed 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -1,6 +1,5 @@ import dataclasses import datetime -import fcntl import hashlib import json import os @@ -19,7 +18,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from test_env import assert_not_root, isolated_env -from project_config.test_project_config import write_config +from project_config.doubles import write_config BIN = pathlib.Path(__file__).resolve().parents[1] TASK = "Do the next chunk." diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py deleted file mode 100644 index ace9f16d..00000000 --- a/bin/loop_claude/test_loop_claude.py +++ /dev/null @@ -1,998 +0,0 @@ -import ast -import contextlib -import dataclasses -import io -import json -import pathlib -import re -import shutil -import sys -import tempfile -import unittest -import unittest.mock - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) - -from chunk_driver.doubles import a_loop -from routing_figures import archive, state -from test_env import assert_not_root -from loop_effects.doubles import assistant, CWD, FakeEffects, NOW, ran, said, STAMP -from claude_code.output_limits import BASH_CEILING_CHARACTERS -from routing_figures.calls import Call -from loop_claude.chunk import chunk_items -from chunk_driver import chunk_run, prompts, this_loop -from loop_claude.loop import chunk_start, chunk_windows -from project_config.test_project_config import configured -from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES -from claude_code import entries, reply, session -from failure import Failure -from agent_cycle.verdicts import Finished, TakenIn, Unfinished -from loop_claude.chunk import fresh_prompt -from agent_cycle import judge, retry, states, worker -import loop_claude.routed_item -from loop_claude.loop import main, reload, routing_check, usage -from release_plan import next_chunk -from transcript_archive import outcomes -from loop_state import paths -from plan_store.todo_md import plan_of -from model_routing.ladder import ProjectRung, Rung -from loop_effects.effects import PYTHON_TIMEOUT -from model_routing.ladder_file import read_ladder, SHIPPED -from chunk_driver.project import records -from model_routing.route import Route -from agent_cycle.stop import Stop -from agent_cycle import tmux -from touch_predictions.test_touch_predictions import plan as touch_plan -from text_files.utc_stamp import utc - -LADDER = read_ladder(SHIPPED) -OPUS_PROJECT = ProjectRung(LADDER, Rung("claude-opus-5-5", "medium")) - -# How git answers in a project's checkout it cannot read, such as one that is gone. -UNREAD = Failure("not a git repository") - - -class RoutingCheck(unittest.TestCase): - def setUp(self): - self.home = pathlib.Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, self.home) - self.root = self.home / "archive" - self.paths = paths.paths_from(self.home) - self.session = session.session_named("A log loop-claude", self.paths.claude_code_transcripts) - - def loop(self, fake): - """The loop in /code/log.""" - return a_loop(fake.effects(), root="/code/log", session=self.session, paths=self.paths) - - def chunks(self, count, verdicts, project="log"): - """count finished chunks, each closed by verdicts verdicts, each with one Explore subagent whose report outgrew its searches.""" - for number in range(count): - folder = self.root / project / f"c{number}" - subagents = folder / "session" / "s" / "subagents" - subagents.mkdir(parents=True) - kept = "".join(f"2026-10-14T10:0{verdict}:00Z {outcomes.unfinished('w', 'e', 'j', '')}\n" for verdict in range(verdicts - 1)) - (folder / "copy.outcomes.md").write_text(f"Task: t\n\n{kept}2026-10-14T11:00:00Z {outcomes.finished('w', 'm', 'j')}\n") - launch = {"type": "assistant", "timestamp": "2026-10-14T09:00:00Z", "message": {"id": "m", "content": [{"type": "tool_use", "id": "a", "name": "Agent", "input": {"subagent_type": "Explore"}}]}} - report = {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "a", "content": "long report"}]}} - (folder / "copy.jsonl").write_text(json.dumps(launch) + "\n" + json.dumps(report) + "\n") - (subagents / "agent-a.jsonl").write_text("") - (subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"})) - - def check(self, fake): - """What check_routing returns and says for a loop in /code/log.""" - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: - stop = routing_check.check_routing(self.root, Rung("m", "high"), self.loop(fake)) - return stop, said.getvalue() - - def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self): - self.chunks(5, 3) - self.assertEqual(self.check(FakeEffects()), (None, "")) - self.assertFalse((self.root / "routing-figures.md").exists()) - self.chunks(6, 1, "other") - self.assertEqual(self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 6))[0], None) - self.assertIn("at cycle 21 across", (self.root / "routing-figures.md").read_text()) - - def test_reads_each_projects_history_through_the_loops_git_and_names_each_it_cannot_read(self): - self.chunks(5, 4) - fake = FakeEffects(on_terminal=False, git=[UNREAD] * 3) - self.check(fake) - located = ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"] - self.assertEqual(fake.made("git"), [located, located, ["remote"]], "the config is located for its title templates, then for where it keeps the plan") - self.assertIn("## Default branches unread\n\n- log: not a git repository\n", (self.root / "routing-figures.md").read_text()) - - def test_hands_the_terminal_over_once_for_each_new_call(self): - self.chunks(5, 4) - fake = FakeEffects(on_terminal_claude=[0], git=[UNREAD] * 3) - stop, said = self.check(fake) - self.assertIsNone(stop) - call = "Explore subagents' reports took more of the worker's context than their searches would have." - self.assertIn(f"- {call}", said) - self.assertIn(f"- {call}", (self.root / "routing-figures.md").read_text()) - ((args),) = fake.made("claude_on_terminal") - self.assertEqual(args[:6], ["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions"]) - self.assertIn(f"don't change anything until they answer:\n- {call}", args[6]) - self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}]) - self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release") - self.assertIn("Record what they decide in this checkout, the development clone", args[6]) - self.assertIsNone(state.mark_measured(self.root, 0)) - self.assertEqual(self.check(FakeEffects(git=[UNREAD] * 3))[0], None) - self.assertNotIn(call, self.check(FakeEffects())[1]) - - def test_stamps_the_figures_and_the_calls_raised_when_it_measures(self): - self.chunks(5, 4) - (self.root / "routing-calls-raised.md").write_text("# Routing calls raised\n\n- 2026-10-14T10:02:00Z Reset\n") - self.check(FakeEffects(on_terminal_claude=[0], git=[UNREAD] * 3)) - figures = (self.root / "routing-figures.md").read_text() - self.assertIn(f"Measured {utc(NOW)}, at cycle 20 across", figures) - self.assertIn("that finished after the reset of 2026-10-14T10:02:00Z", figures) - self.assertIn(f"- {utc(NOW)} Explore subagents'", (self.root / "routing-calls-raised.md").read_text()) - - def test_says_a_figure_it_cannot_read(self): - self.chunks(5, 4) - (self.root / "routing-state.json").mkdir() - self.assertIn("routing figures: could not read", self.check(FakeEffects())[1]) - - def test_goes_on_off_a_terminal_and_raises_the_call_again_next_time(self): - self.chunks(5, 4) - stop, said = self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 3)) - self.assertIsNone(stop) - self.assertIn("Not on a terminal: the calls are raised again at the next measurement.", said) - self.assertIsNone(state.mark_measured(self.root, 0)) - self.assertIn("Not on a terminal", self.check(FakeEffects(on_terminal=False, git=[UNREAD] * 3))[1]) - - def test_leaves_the_measuring_to_a_loop_holding_the_lock(self): - self.chunks(5, 4) - with archive.locked(self.root): - self.assertEqual(self.check(FakeEffects()), (None, "")) - - def test_stops_when_claude_cannot_start_for_the_calls(self): - self.chunks(5, 4) - stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD] * 3)) - self.assertEqual(stop, Stop(1, f"could not start claude for the routing calls in {self.home / 'code' / 'claude-config'}, the setup's development clone: No such file or directory")) - - def test_says_a_figure_it_cannot_write_and_goes_on(self): - assert_not_root(self) - self.chunks(5, 4) - (self.root / "routing-figures.lock").touch() - self.root.chmod(0o555) - self.addCleanup(self.root.chmod, 0o755) - stop, said = self.check(FakeEffects(git=[UNREAD] * 3)) - self.assertIsNone(stop) - self.assertIn("routing figures: could not write", said) - - 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.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()) - [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) - - -# A plan read with no release cut yet. -NO_CUT = LastCut(None, "", 0, []) -def routed_item(todo, cut): - """loop_claude.routed_item.routed_item for the plan a todo.md's text holds.""" - return loop_claude.routed_item.routed_item(plan_of(todo), cut) - - -TODO = """# todo - -## Items - -| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score | -|---|---|---|---|---|---|---|---|---|---|---| -| 7 | 0.2.0 | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 | -| 3 | 0.2.0 | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 | -| 1 | 0.3.0 | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 | -""" - - -class RoutedItem(unittest.TestCase): - def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self): - self.assertEqual(routed_item(TODO, NO_CUT).id, 3) - self.assertIsNone(routed_item(TODO.replace("| | **Do", "| question | **Do"), NO_CUT)) - self.assertIsNone(routed_item("# todo\n", NO_CUT)) - self.assertIsNone(routed_item(TODO[:TODO.index("| 7 |")], NO_CUT)) - old_shape = "## Items\n\n| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 3 | 0.2.0 | | **Do the next thing.** | 5 | 3 | 6 | 8 | 9 | 1 | 25 |\n" - self.assertIsNone(routed_item(old_shape, NO_CUT)) - self.assertEqual(routed_item(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), Failure("item 3's L 'x' is not a whole number from 1 to 4")) - - def test_routes_on_no_item_where_the_release_after_the_last_cut_has_none(self): - self.assertEqual(routed_item(TODO, LastCut("v0.1.0", "", 3, [TODO])).id, 3) - # Someone cut 0.2.0 while it held items: they count as 0.3.0's, the next release, and where no later release is known, no item routes. - self.assertEqual(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])).id, 3) - self.assertIsNone(routed_item(re.sub(r"(?m)^\| \d+ \| 0\.3\.0 \|.*\n", "", TODO), LastCut("v0.2.0", "", 3, []))) - later_only = TODO[:TODO.index("| 7 |")] + TODO[TODO.index("| 1 | 0.3.0 |"):] - self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 3, [TODO]))) - self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 0, [TODO]))) - self.assertEqual(routed_item(later_only, LastCut("v0.2.0", "", 3, [later_only])).id, 1) - - def test_routes_past_an_item_a_waiting_item_blocks(self): - todo = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n| 8 | 0.2.0 | 7 | | **Use the answer.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 9 | 0.2.0 | 8 | | **Build on it.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 |\n" - self.assertEqual(routed_item(todo, NO_CUT).id, 3) - self.assertEqual(routed_item(todo.replace("| question |", "| |"), NO_CUT).id, 7) - first = "| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n" - self.assertEqual(routed_item(todo.replace(first, "") + first, NO_CUT).id, 3) - - def test_routes_nothing_on_an_item_without_e_or_i(self): - without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |") - self.assertIsNone(routed_item(without_i, NO_CUT)) - - -class RouteSources(unittest.TestCase): - def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): - self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), None, FakeEffects().effects())) - self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), None, FakeEffects().effects()).id, 3) - self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), None, FakeEffects().effects())) - - def test_routes_a_window_named_for_an_item_on_that_item_whatever_the_plan_takes_next(self): - plan = DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])) - later = next(item.id for item in plan.plan.items if item.id != 3) - self.assertEqual(chunk_start.plan_item(plan, later, FakeEffects().effects()).id, later) - # 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)) - # 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) - 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): - with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(chunk_start.plan_item(plan, None, FakeEffects().effects())) - self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue()) - - def test_says_why_the_items_the_worker_names_lift_no_rung(self): - unscored = plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")) - for default, said in ((DefaultPlan(unscored, NO_CUT), "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("no git"), "the items the worker names lift no rung: no git\n"), (DefaultPlan(plan_of(TODO), NO_CUT), "")): - with self.subTest(said=said): - with contextlib.redirect_stderr(io.StringIO()) as stderr: - scored = chunk_start.scored_plan(default, FakeEffects().effects()) - self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "") - self.assertEqual(scored, default.plan if isinstance(default, DefaultPlan) else default) - - def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self): - def git(*args, **options): - answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "show": f"what {args[-1]} holds\n"} - return answers.get(args[0], "1\n") - - with tempfile.TemporaryDirectory() as root: - folder = configured(self, pathlib.Path(root)) - effects = dataclasses.replace(FakeEffects().effects(), git=git) - held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[1]))) - self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n") - - def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): - with tempfile.TemporaryDirectory() as root: - folder = configured(self, pathlib.Path(root)) - loop = a_loop(FakeEffects(git=["origin\n", "origin/main\n"] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1])) - config = folder / "config.toml" - tracked = a_loop(FakeEffects(git=["origin\n", "origin/main\n", *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) - with contextlib.redirect_stderr(io.StringIO()) as stderr: - chunk_start.fetched_plan(tracked) - self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release") - config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) - (folder / "todo.md").write_text(TODO) - unread = Failure("no git") - standing = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) - with contextlib.redirect_stderr(io.StringIO()) as stderr: - held = chunk_start.fetched_plan(standing) - self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers") - self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review loop-claude cannot call due is never skipped silently") - quiet = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) - with contextlib.redirect_stderr(io.StringIO()) as stderr: - chunk_start.fetched_plan(quiet, announce=False) - self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts") - config.unlink() - with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIn("no config names the checkout", chunk_start.scored_plan(chunk_start.fetched_plan(loop), loop.effects).reason) - self.assertIn("the items the worker names lift no rung: no config names the checkout", stderr.getvalue()) - self.assertIn("no config names the checkout", chunk_start.fetched_plan(loop).reason) - - -class ChunkWindows(unittest.TestCase): - def plan(self, *touched): - """A plan of items 1, 2 and on, each predicted to touch the path given for it.""" - items = touch_plan(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1))) - return next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="") - - def test_starts_the_next_item_and_those_picked_beside_it_up_to_the_limit(self): - # Item 2 overlaps item 1, so it waits for it; items 3 and 4 run beside it. - plan = self.plan("a.py", "a.py", "c.py", "d.py") - self.assertEqual(chunk_windows.may_start(plan, [], set(), 1), ["item-1"]) - self.assertEqual(chunk_windows.may_start(plan, [], set(), 2), ["item-1", "item-3"]) - self.assertEqual(chunk_windows.may_start(plan, [], set(), 9), ["item-1", "item-3", "item-4"]) - - def test_leaves_the_items_running_chunks_hold_and_starts_only_as_many_as_the_room_left(self): - plan = self.plan("a.py", "a.py", "c.py", "d.py") - self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 1), ["item-4"]) - self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 2), ["item-3", "item-4"]) - self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 0), []) - - def test_counts_the_running_chunks_against_the_limit_and_restarts_stopped_ones_first(self): - windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True), tmux.Listed("item-4", "", True)] - self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 3), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 0)) - self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3"], 0)) - self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 5), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 2)) - - def test_a_loop_whose_chunk_finished_leaves_its_room_and_restarts_no_stopped_chunk(self): - windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True)] - self.assertEqual(chunk_windows.room_of(windows, "item-1", True, 2), chunk_windows.Room([], ["item-3"], [], 2)) - - def test_leaves_no_room_where_more_chunks_run_than_the_limit(self): - windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)] - self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0) - - def test_starts_no_item_that_overlaps_a_running_chunks_items(self): - # Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py. - items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`")) - plan = next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="") - self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 2), ["item-4"]) - # A running chunk's item without a prediction leaves no other item free to start beside it. - unpredicted = touch_plan((2, "1.0.0", "", "- `a.py`"), (3, "1.0.0", "", None)) - self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 2), []) - # A held item that left the plan, as once it merged, overlaps nothing. - self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 2), ["item-2", "item-4"]) - - def test_a_plan_without_an_item_starts_one_chunk_and_only_alone(self): - none = next_chunk.NoItem("release 1.0.0 has no items") - self.assertEqual(chunk_windows.may_start(none, [], set(), 3), ["no-item"]) - self.assertEqual(chunk_windows.may_start(none, ["item-1"], {1}, 3), []) - - def test_names_a_window_for_its_item_and_reads_the_item_back(self): - self.assertEqual(chunk_windows.window_name(372), "item-372") - self.assertEqual([chunk_windows.item_of(chunk) for chunk in ("item-372", "no-item", "item-", "item-3x", "xitem-3")], [372, None, None, None, None]) - # Only ASCII digits name an item, as window_name writes them. - 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"]) - - def test_a_chunk_whose_transcript_cannot_be_read_holds_the_item_it_started_from(self): - with tempfile.TemporaryDirectory() as temp: - transcripts = pathlib.Path(temp) - folder = transcripts / "-r" - folder.mkdir() - # A folder in place of the transcript file, so reading it fails. - (folder / f"{chunk_windows.chunk_session('proj', 'item-7', transcripts).id}.jsonl").mkdir() - self.assertEqual(chunk_windows.held_items(["item-7"], "proj", transcripts), {7}) - - def test_tells_a_chunk_the_items_the_projects_other_live_chunks_hold(self): - with tempfile.TemporaryDirectory() as temp: - home = pathlib.Path(temp) - held = paths.paths_from(home) - folder = held.claude_code_transcripts / "-r" - folder.mkdir(parents=True) - lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})] - (folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines)) - # Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item. - fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n") - self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11]) - self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) - - -class StartChunks(unittest.TestCase): - """start_chunks: the windows a loop opens for the chunks that may start now.""" - LAUNCHER = pathlib.Path("/b/loop-claude") - - def setUp(self): - made = tempfile.TemporaryDirectory() - self.addCleanup(made.cleanup) - self.root = pathlib.Path(made.name, "r") - 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") - - def limit(self, chunks): - config = self.home / ".claude-projects" / self.root.name / "config.toml" - config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n") - - def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None): - """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() - 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) - return started - - 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")] - - def test_opens_a_window_for_each_chunk_that_may_start_the_first_making_the_session(self): - self.limit(2) - fake = FakeEffects() - self.assertEqual(self.start(fake, env={"LOOP_CLAUDE_WORKER_MODEL": "m", "PATH": "/bin"}), ["item-1", "item-3"]) - self.assertEqual(self.starts(fake), [("new-session", "item-1", [str(self.LAUNCHER), "--chunk", "item-1", "ship it"]), ("new-window", "item-3", [str(self.LAUNCHER), "--chunk", "item-3", "ship it"])]) - first = next(call for call in fake.tmux_calls if call[0] == "new-session") - self.assertEqual((first[first.index("-s") + 1], first[first.index("-c") + 1]), (self.session, str(self.root))) - # Only loop-claude's own variables are handed on, since a window gets the tmux server's environment. - self.assertEqual([word for word in first if "=" in word], ["LOOP_CLAUDE_WORKER_MODEL=m"]) - self.assertEqual(fake.tmux_calls[0], ["list-windows", "-t", f"={self.session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]) - # The session names the checkout whose chunks it runs. - self.assertIn(["set-option", "-t", f"={self.session}:", "@loop-root", str(self.root)], fake.tmux_calls) - - def test_refuses_a_session_that_runs_another_checkouts_chunks(self): - for owner, named in (("/c/acme.api", "/c/acme.api"), ("", "another checkout")): - with self.subTest(owner=owner): - fake = FakeEffects(windows="item-5\t0\t@1\n") - self.assertEqual(self.start(fake, owner=owner), Failure(f"the tmux session {self.session} runs the chunks of {named}, whose key maps to the same session name; rename one of the two checkouts' folders")) - self.assertEqual(self.starts(fake), []) - self.assertIn(["show-options", "-qv", "-t", f"={self.session}:", "@loop-root"], fake.tmux_calls) - - def test_refuses_a_checkout_do_epic_runs_chunks_in(self): - fake = FakeEffects(windows=f"epic-ABC-12\tABC-34 ?\t0\t@4\t{self.root}\nepic-ABC-12\tABC-35\t0\t@5\t/c/other\nepic-ABC-12\tABC-36\t1\t@6\t{self.root}\nloop-x\titem-1\t0\t@7\t{self.root}\n") - self.assertEqual(self.start(fake), Failure(f"do-epic runs chunks in {self.root}: ABC-34 of epic-ABC-12; loop-claude doesn't start a chunk there until those chunks finish")) - self.assertEqual(self.starts(fake), []) - - def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self): - self.limit(2) - transcripts = paths.paths_from(self.home).claude_code_transcripts - folder = transcripts / "-r" - folder.mkdir(parents=True) - opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts) - (folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n") - self.assertEqual(self.start(FakeEffects(windows="item-5\t0\t@1\n")), ["item-3"]) - - def test_starts_one_chunk_without_parallel_chunks(self): - fake = FakeEffects() - self.assertEqual(self.start(fake), ["item-1"]) - - def test_starts_none_and_reads_no_plan_while_the_running_chunks_fill_the_limit(self): - self.limit(2) - fake = FakeEffects(windows="item-5\t0\t@1\nitem-6 ?\t0\t@2\n") - self.assertEqual((self.start(fake), self.planned, self.starts(fake)), ([], 0, [])) - # More chunks run than the limit allows, as after it was lowered; a stopped chunk still waits. - fake = FakeEffects(windows="item-5\t0\t@1\nitem-6\t0\t@2\nitem-7\t0\t@3\nitem-8\t1\t@4\nitem-9\t1\t@5\n") - self.assertEqual((self.start(fake), self.planned), ([], 0)) - - def test_a_finishing_chunks_own_window_counts_as_no_longer_running(self): - fake = FakeEffects(windows="item-5\t0\t@1\n") - self.assertEqual(self.start(fake, chunk="item-5"), []) - fake = FakeEffects(windows="item-5\t0\t@1\n") - self.assertEqual(self.start(fake, chunk="item-5", leaving=True), ["item-1"]) - # The session exists, since the finishing loop's window is still in it. - self.assertEqual(self.starts(fake)[0][0], "new-window") - - def test_the_humans_loop_claude_starts_a_stopped_chunk_again_first_closing_its_dead_window(self): - fake = FakeEffects(windows="item-5\t1\t@3\n") - self.assertEqual((self.start(fake), self.planned), (["item-5"], 0)) - self.assertIn(["kill-window", "-t", "@3"], fake.tmux_calls) - # Its dead window was the session's last, so the session is made again. - self.assertEqual(self.starts(fake)[0][0], "new-session") - self.limit(2) - fake = FakeEffects(windows="item-5\t1\t@3\n") - self.assertEqual(self.start(fake), ["item-5", "item-1"]) - - 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"]) - - def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self): - self.limit(2) - transcripts = paths.paths_from(self.home).claude_code_transcripts - folder = transcripts / "-r" - folder.mkdir(parents=True) - opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts) - (folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n") - fake = FakeEffects(windows="item-7\t0\t@1\nitem-5\t1\t@3\n") - # Item 1 is the stopped chunk's, so item 3 starts; the stopped one doesn't count against parallel-chunks. - 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")), []) - - def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self): - fake = FakeEffects() - self.assertEqual(self.start(fake, plan=Failure("no origin/main")), ["no-item"]) - 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")) - - def test_says_why_it_cannot_take_the_lock_on_starting_windows(self): - (self.home / ".local" / "state").mkdir(parents=True) - (self.home / ".local" / "state" / "loop-claude").write_text("") - started = self.start(FakeEffects()) - self.assertIsInstance(started, Failure) - self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/loop-claude/"), started.reason) - - 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) - opened = chunk_windows.chunk_session("proj", "item-7", transcripts) - self.assertEqual(opened.name, "A proj loop-claude item-7") - folder = transcripts / "-r" - folder.mkdir() - lines = [assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2)"}), assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2), 9 (L 2, E + I 3)"})] - (folder / f"{opened.id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines)) - self.assertEqual(chunk_windows.held_items(["item-7", "item-8", "no-item"], "proj", transcripts), {7, 8, 9}) - - -class ChunkFacts(unittest.TestCase): - # The launcher beside which chunk_start finds /b/chunk-preflight. - LAUNCHER = pathlib.Path("/b/loop-claude") - - def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self): - fake = FakeEffects(python=[ran("- A fact.\n")]) - said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) - self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")]) - self.assertTrue(said.endswith("\n\n- A fact."), said) - self.assertNotIn("yourself", said) - - def test_a_chunk_without_an_item_runs_the_preflight_without_naming_one(self): - fake = FakeEffects(python=[ran("- A fact.\n")]) - chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER, window=tmux.Window("loop-proj", "no-item", "%4"))) - self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")]) - - def test_the_facts_end_with_the_items_the_projects_other_running_chunks_hold(self): - # The loop's own window, a stopped one and two that run, one of them waiting for the human. - fake = FakeEffects(python=[ran("- A fact.\n")], windows="item-7\t0\t@1\nitem-5\t1\t@2\nitem-12 ?\t0\t@3\nitem-9\t0\t@4\n") - said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) - self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project, running or stopped, hold items 5, 9, 12. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said) - self.assertEqual(fresh_prompt.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.") - self.assertTrue(fresh_prompt.held_by_others([4, 9]).startswith("\n\nOther chunks of this project, running or stopped, hold items 4, 9.")) - # A worker whose preflight failed is told them too. - fake = FakeEffects(python=[ran(code=1, stderr="git could not start\n")], windows="item-9\t0\t@4\n") - said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) - self.assertTrue(said.endswith("Other chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said) - - def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self): - for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")): - with self.subTest(why=why): - said = chunk_start.chunk_facts(a_loop(FakeEffects(python=[failed]).effects(), launcher=self.LAUNCHER)) - self.assertIn("yourself", said) - self.assertIn(why, said) - - def test_runs_the_preflight_only_where_the_session_is_not_open(self): - with tempfile.TemporaryDirectory() as home: - opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects")) - fresh = FakeEffects(python=[ran("- A fact.\n")]) - facts, _ = chunk_start.chunk_start(a_loop(fresh.effects(), session=opened, launcher=self.LAUNCHER)) - self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")], True)) - transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") - transcript.parent.mkdir(parents=True) - transcript.write_text("") - resumed = FakeEffects() - facts, _ = chunk_start.chunk_start(a_loop(resumed.effects(), session=opened, launcher=self.LAUNCHER)) - self.assertEqual((resumed.made("python"), facts), ([], "")) - - -class FreshPrompt(unittest.TestCase): - """loop-claude's first prompt of a chunk.""" - # What the preflight found, as the fresh prompt quotes it. - FACTS = "- A preflight fact." - - def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self): - routed = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) - self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed) - unrouted = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS) - self.assertIn(f"before creating a new one. {prompts.READING_RULE} {fresh_prompt.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted) - self.assertNotIn("loop-claude runs you on", unrouted) - - def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self): - routed = fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS) - self.assertIn("item 3's size again", routed) - self.assertIn("escalation trigger 1", routed) - self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed) - self.assertNotIn("size again", fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)) - - def test_gives_each_fresh_worker_the_reading_rule_once(self): - rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context" - for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))): - with self.subTest(route=route): - self.assertEqual(fresh_prompt.WORKER.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1) - - def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self): - self.assertIn("\n\n- A fact.", fresh_prompt.preflight_facts("- A fact.")) - failed = fresh_prompt.preflight_failed("git could not start") - self.assertIn("yourself", failed) - self.assertIn("git could not start", failed) - - def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self): - for facts in (fresh_prompt.preflight_facts("- A fact."), fresh_prompt.preflight_failed("git could not start")): - with self.subTest(facts=facts): - self.assertEqual(fresh_prompt.WORKER.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1) - - def test_puts_the_rung_sentences_after_the_route_or_else_before_the_facts(self): - routed, unrouted = Route(OPUS_PROJECT.rung, 3, 2, 4), Route(OPUS_PROJECT.rung) - self.assertIn(f"routed by item 3's L of 2.{prompts.rungs_held(fresh_prompt.DRIVER, routed, OPUS_PROJECT)} After your first read", fresh_prompt.WORKER.fresh("Do it.", "## Goals", routed, OPUS_PROJECT, self.FACTS)) - self.assertIn(f"{fresh_prompt.NAME_THE_ITEMS}\n\n{prompts.rungs_held(fresh_prompt.DRIVER, unrouted, OPUS_PROJECT).lstrip()}\n\n{self.FACTS}", fresh_prompt.WORKER.fresh("Do it.", "## Goals", unrouted, OPUS_PROJECT, self.FACTS)) - - -# Item 297 scores the higher L, item 298 the higher E + I. -SCORED = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 297 | 0.8.0 | | **Do it.** | 4 | 2 | 3 | 7 | 2 | 1 by 9 | 25 |\n| 298 | 0.8.0 | | **Do more.** | 3 | 3 | 4 | 8 | 2 | 1 by 9 | 20 |\n" - - -class ChunkItems(unittest.TestCase): - def test_names_the_items_on_the_workers_latest_chunk_items_line(self): - earlier = said("Chunk items: 297 (L 3, E + I 5)") - latest = said("Starting.\n**Chunk items:** 297 (L 4, E + I 5), item 298 (L 3, E + I 7), #12, 298\nOn to the tests.") - self.assertEqual(chunk_items.named([earlier, latest]), (297, 298, 12)) - self.assertEqual(chunk_items.named([latest, earlier]), (297,)) - self.assertEqual(chunk_items.named([earlier, said("Chunk items: none")]), ()) - self.assertEqual(chunk_items.named([said("Chunk items: 297 and 298 (L 3, E + I 7)")]), (297, 298)) - - def test_reads_the_example_line_the_prompt_gives_the_worker(self): - example = re.search(r"`(Chunk items:[^`]*)`", fresh_prompt.NAME_THE_ITEMS)[1] - self.assertEqual(chunk_items.named([said(example)]), (297, 298)) - - def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self): - self.assertIn("on one line, as in `Chunk items: ", fresh_prompt.WORKER.resumed("", Route(Rung("m")), None)) - - def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self): - prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)") - written = entries.AssistantTurn(parts=(entries.ToolCall("t", "Write", {"content": "Chunk items: 9"}),)) - mentioned = said("Once I know them, I write `Chunk items: 5`.") - self.assertEqual(chunk_items.named([prompt, written, mentioned]), ()) - - def test_takes_the_highest_l_and_e_plus_i_todo_md_scores_among_the_named_items(self): - self.assertEqual(chunk_items.taken_in([said("Chunk items: 297 (L 1, E + I 2), 298, 400")], plan_of(SCORED)), TakenIn(4, 7)) - self.assertEqual(chunk_items.taken_in([said("Chunk items: 400")], plan_of(SCORED)), TakenIn()) - self.assertEqual(chunk_items.taken_in([], plan_of(SCORED)), TakenIn()) - - def test_names_the_items_at_no_level_where_todo_md_cannot_be_read(self): - self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], Failure("no todo.md")), TakenIn()) - self.assertEqual(chunk_items.taken_in([said("Chunk items: 297")], plan_of("no items table")), TakenIn()) - - -class LoopRuns(unittest.TestCase): - def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): - for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "", "unfinished_evidence": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1, "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "unfinished_evidence": ""})]): - with self.subTest(handed=handed): - self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: {' '.join(handed)}")) - - def test_decodes_every_field_of_the_state_and_its_route(self): - state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2) - self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state) - self.assertEqual(set(reload.LOOP_RUN_FIELDS), {field.name for field in dataclasses.fields(main.LoopRun)}) - - def test_rejects_a_field_of_another_type_or_an_unknown_field(self): - state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2)) - for path, wrong in ((("unfinished_run",), "2"), (("unfinished_run",), True), (("route", "unfinished"), 1.0), (("route", "escalated_at"), "9"), (("route", "item"), True), (("route", "rung"), "claude-opus-5-5"), (("route", "rung", "model"), None), (("route",), "r"), (("route", "extra"), 1), (("route", "model"), "claude-opus-5-5"), (("route", "effort"), "high")): - with self.subTest(path=path, wrong=wrong): - handed = json.loads(json.dumps(state)) - target = handed - for key in path[:-1]: - target = target[key] - target[path[-1]] = wrong - self.assertIsNone(reload.decode_handed(json.dumps(handed))) - - def test_rejects_a_state_or_rung_missing_a_required_field(self): - state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low")))) - for path in (("cycle_number",), ("root",), ("task",), ("unfinished_evidence",), ("route", "rung"), ("route", "rung", "model")): - with self.subTest(path=path): - handed = json.loads(json.dumps(state)) - target = handed - for key in path[:-1]: - target = target[key] - del target[path[-1]] - self.assertIsNone(reload.decode_handed(json.dumps(handed))) - - def test_decodes_a_rung_without_an_effort(self): - state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("some-model"))) - self.assertEqual(reload.decode_handed(json.dumps({**dataclasses.asdict(state), "route": {"rung": {"model": "some-model"}}})), state) - - def test_rejects_text_that_is_not_json(self): - self.assertIsNone(reload.decode_handed("not json")) - - def test_decodes_a_route_inside_the_state_or_none(self): - state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1)) - self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state) - unrouted = dataclasses.replace(state, route=None) - self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(unrouted))), unrouted) - handed = dataclasses.asdict(state) - handed["route"]["rung"]["effort"] = 1 - self.assertIsNone(reload.decode_handed(json.dumps(handed))) - del handed["route"]["rung"] - self.assertIsNone(reload.decode_handed(json.dumps(handed))) - off_scale = dataclasses.asdict(state) - off_scale["route"]["likelihood"] = 9 - self.assertIsNone(reload.decode_handed(json.dumps(off_scale))) - older = dataclasses.asdict(state) - del older["route"]["escape_and_impact_taken_in"] - self.assertEqual(reload.decode_handed(json.dumps(older)), state) - taken = dataclasses.replace(state, route=dataclasses.replace(state.route, escape_and_impact_taken_in=7)) - self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(taken))), taken) - for taken_in in (9, 5): - with self.subTest(taken_in=taken_in): - handed = dataclasses.asdict(state) - handed["route"]["escape_and_impact_taken_in"] = taken_in - self.assertIsNone(reload.decode_handed(json.dumps(handed))) - - def test_decodes_a_state_from_before_a_field_with_a_default_joined_it(self): - self.assertEqual(reload.decode_handed(json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "unfinished_evidence": ""})), main.LoopRun(3, "/r", "do it", "")) - - def test_drops_the_items_taken_in_that_a_loop_started_before_0_11_0_hands_on(self): - state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="") - self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"items_taken_in": [12, 14]})), state) - - def test_drops_the_slot_that_a_loop_started_before_chunks_ran_in_windows_hands_on(self): - state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="") - self.assertEqual(reload.decode_handed(json.dumps({key: value for key, value in dataclasses.asdict(state).items() if key != "chunk"} | {"slot": 1})), state) - - def test_stops_when_the_reload_cannot_start_python(self): - with tempfile.TemporaryDirectory() as root: - launcher = pathlib.Path(root, "loop-claude") - launcher.write_text("") - fake = FakeEffects(python=[ran()]) - 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 ")) - - -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] - return stop, said.getvalue() - - def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self): - fake = FakeEffects(git=["/r\n"], tmux_version="tmux 3.1c") - self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), "")) - self.assertEqual((fake.tmux_calls, self.asked), ([["-V"]], [])) - - def test_prints_the_help_without_tmux(self): - fake = FakeEffects(tmux_version="") - self.assertEqual(self.run_loop(["--help"], fake)[0], Stop(0, usage.HELP)) - self.assertEqual(fake.tmux_calls, []) - - def test_starts_the_chunks_then_attaches_to_the_session_or_inside_tmux_switches_to_it(self): - for env, shown in (({}, ["attach-session", "-t", "=loop-r"]), ({"TMUX": "/tmp/tmux-1000/default,1,0"}, ["switch-client", "-t", "=loop-r"])): - with self.subTest(shown=shown): - fake = FakeEffects(git=["/r\n"]) - stop, said = self.run_loop(["do", "it"], fake, env) - self.assertEqual((stop, said), (Stop(0, ""), f"{STAMP} started item-3, item-4 in the tmux session loop-r\n")) - self.assertEqual(fake.tmux_calls, [["-V"], shown]) - self.assertEqual(self.asked, [(main.LoopRun(0, "/r", "do it", ""), False)]) - - 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)) - - 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"]) - effects, env = fake.effects(), {"TMUX_PANE": "%4"} - launcher = pathlib.Path("/b/loop-claude") - cycle = unittest.mock.Mock(project=OPUS_PROJECT) - 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) - 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) - - 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)) - - def test_a_window_loop_outside_a_checkout_stops(self): - self.assertIsInstance(main.loop_run_from(["--chunk", "item-3", "do it"], CWD, FakeEffects(git=[Failure("git cannot start")]).effects()), Stop) - - def test_says_that_nothing_started_where_the_session_already_runs_every_chunk_that_may(self): - self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=())[1], f"{STAMP} the tmux session loop-r runs every chunk that may run now, so `do it` started in no new window\n") - - def test_off_a_terminal_it_prints_how_to_attach(self): - fake = FakeEffects(git=["/r\n"], on_terminal=False) - stop, said = self.run_loop(["do it"], fake) - self.assertEqual(stop, Stop(0, "")) - self.assertTrue(said.endswith(f"{STAMP} not on a terminal; see the chunks with `tmux attach -t =loop-r`\n"), said) - self.assertEqual(fake.tmux_calls, [["-V"]]) - - def test_stops_where_no_chunk_could_start(self): - self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=Failure("no plan"))[0], Stop(1, "no plan")) - - 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) - 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): - fake = FakeEffects(git=["/r\n"]) - self.assertEqual(self.run_loop(["--chunk", "item-3", "do it"], fake)[0], Stop(1, "--chunk is how loop-claude starts itself in a tmux window; run loop-claude ")) - self.assertEqual(self.asked, []) - - def test_reads_the_chunk_a_window_loop_is_started_with(self): - self.assertEqual(main.loop_run_from(["--chunk", "item-3", "do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "", chunk="item-3")) - self.assertEqual(main.loop_run_from(["do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "")) - - def test_a_finished_chunk_starts_each_chunk_that_may_start_and_stops_without_a_reason(self): - 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) - 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)) - - -class StopDms(unittest.TestCase): - def run_main(self, argv, fake): - with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()): - code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "loop-claude"), CWD, fake.effects()) - return code, said.getvalue() - - 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(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(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(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) - 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): - fake = FakeEffects() - code, said = self.run_main([main.RELOAD_FLAG, "3"], fake) - self.assertEqual(code, 1) - self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: 3"]) - - def test_says_why_the_dm_of_a_stop_failed_after_the_reason(self): - fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")]) - self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n")) - - def test_skips_the_dm_where_it_prints_its_help(self): - for argv, code in (([], 1), (["--help"], 0)): - with self.subTest(argv=argv): - fake = FakeEffects() - self.assertEqual(self.run_main(argv, fake)[0], code) - self.assertEqual(fake.dms, []) - - -class HelpLimits(unittest.TestCase): - def test_help_wraps_at_100_columns(self): - self.assertEqual([line for line in usage.HELP.splitlines() if len(line) > 100], []) - - def test_help_states_the_limits_the_code_holds(self): - said = " ".join(usage.HELP.split()) - self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", said) - # The retry messages say these limits in words too. - self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60)) - self.assertIn("fails three times running, retried a minute apart", said) - self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said) - self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said) - self.assertIn(f"Once {state.CYCLES_PER_CHECK} cycles have closed across all projects", said) - self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said) - self.assertIn(f"{BASH_CEILING_CHARACTERS:,} characters", said) - self.assertIn(f"unfinished {chunk_run.UNFINISHED_LIMIT} cycles running", said) - self.assertIn(f"rerun to give it {chunk_run.UNFINISHED_LIMIT} more", said) - - -class OwnLadder(unittest.TestCase): - def test_a_cycle_on_a_projects_own_ladder_names_its_file_and_says_where_the_workers_model_is_off_it(self): - file = pathlib.Path("/h/.claude-projects/acme/routing-ladder.json") - self.assertEqual(main.own_ladder(file, "claude-fable-5-2", False), f"routing on the project's own ladder, {file}.") - self.assertEqual(main.own_ladder(file, "claude-opus-5-5", True), f"routing on the project's own ladder, {file}. claude-opus-5-5 is not on it, so the worker runs on claude-opus-5-5 unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run.") - - -class ExitContract(unittest.TestCase): - def test_every_exit_1_stop_has_its_clause_in_help(self): - read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "no config names the checkout, its config cannot be read, or the goals file holds no premises" - models_ = "the models file cannot be read or written" - names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], f"{records.HUMAN_RULE_NAMES[1]}*.md", records.HUMAN_RULE_NAMES[2]) - unreadable = f"the goals file, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8" - # Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause. - clauses = [ - ("agent_cycle/interrupt.py", "claude_open", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), - ("agent_cycle/interrupt.py", "human_typed", "1", "entries.reason", read), - ("agent_cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read), - ("agent_cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"), - ("agent_cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read), - ("agent_cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), - ("agent_cycle/run.py", "rule", "1", "entries.reason", read), - ("agent_cycle/run.py", "rule", "1", "annotation.reason", read), - ("agent_cycle/run.py", "rule", "1", "failure.reason", read), - ("agent_cycle/run.py", "keep_rejection", "1", "unkept.reason", read), - ("agent_cycle/run.py", "close", "1", "annotation.reason", read), - ("agent_cycle/run.py", "close", "1", "failure.reason", read), - ("agent_cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"), - ("chunk_driver/chunk_run.py", "closed_cycle", "1", "failure.reason", read), - ("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_), - ("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"), - ("loop_claude/loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"), - ("loop_claude/loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"), - ("loop_claude/loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"), - ("loop_claude/loop/main.py", "next_cycle", "1", "premises.reason", premises_), - ("loop_claude/loop/main.py", "next_cycle", "1", "records.reason", unreadable), - ("loop_claude/loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"), - ("loop_claude/loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"), - ("loop_claude/loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"), - ("loop_claude/loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {loop.paths.config_clone}", "claude cannot start for an interrupt"), - ] - root = pathlib.Path(main.__file__).parents[2] - found = [] - for path in sorted(path for package in ("agent_cycle", "chunk_driver", "loop_claude") for path in (root / package).rglob("*.py") if not path.name.startswith("test_")): - functions = [node for node in ast.walk(ast.parse(path.read_text())) if isinstance(node, ast.FunctionDef)] - stops = [(call.lineno, function.name, ast.unparse(call.args[0]), ast.unparse(call.args[1])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))] - found += [(str(path.relative_to(root)), function, code, reason) for _, function, code, reason in sorted(stops)] - self.assertEqual(len(found), len(clauses), found) - for (path, function, code, reason), (want_path, want_function, want_code, reason_start, _) in zip(found, clauses): - with self.subTest(path=path, function=function): - self.assertEqual((path, function, code), (want_path, want_function, want_code)) - self.assertTrue(reason.startswith(reason_start), reason) - help_exit_1 = " ".join(usage.HELP[usage.HELP.index("Exit 1"):usage.HELP.index("Exit 2")].split()) - self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], []) - - -class JudgeFailures(unittest.TestCase): - def test_every_failed_judge_run_has_its_clause_in_help(self): - started, exited, unparsed = "claude cannot start", "exits non-zero", "prints no json reply" - field, unasked = "its reply misses or mistypes a field", "interrupts or quotes an answer without a question" - # Every Failure the judge's run returns, in source order of judge.py, then of the claude run it calls: function, start of reason, its --help clause. - clauses = [ - ("verdict_from", "'the judge returned no reply'", field), - ("verdict_from", 'f"the judge\'s reply has no {name}', field), - ("verdict_from", "'the judge interrupted without a question'", unasked), - ("verdict_from", "'the judge quoted an answer without a question'", unasked), - ("run_judge", "verdict.reason", field), - ("run_judge", "checked.reason", "quotes a passage the transcript does not hold"), - ("misquoted_evidence", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"), - ("claude_reply", "f'could not start claude:", started), - ("claude_reply", "proc.stderr.strip() or f'{who} exited", exited), - ("claude_reply", 'f"{who} printed no json reply', unparsed), - ] - found = [] - for module in (judge, reply): - functions = [node for node in ast.walk(ast.parse(pathlib.Path(module.__file__).read_text())) if isinstance(node, ast.FunctionDef)] - found += sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) in ("Failure", "Rejected")) - self.assertEqual(len(found), len(clauses), found) - for (_, function, reason), (want_function, reason_start, _) in zip(found, clauses): - with self.subTest(function=function): - self.assertEqual(function, want_function) - self.assertTrue(reason.startswith(reason_start), reason) - judge_clause = " ".join(usage.HELP[usage.HELP.index("a judge when"):usage.HELP.index("A usage limit")].split()) - self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], []) - - -if __name__ == "__main__": - unittest.main() diff --git a/bin/loop_claude/test_routed_item.py b/bin/loop_claude/test_routed_item.py new file mode 100644 index 00000000..25458df4 --- /dev/null +++ b/bin/loop_claude/test_routed_item.py @@ -0,0 +1,53 @@ +import pathlib +import re +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from release_plan.release_standing import LastCut +import loop_claude.routed_item +from loop_claude.doubles import NO_CUT, TODO +from plan_store.todo_md import plan_of + + +def routed_item(todo, cut): + """loop_claude.routed_item.routed_item for the plan a todo.md's text holds.""" + return loop_claude.routed_item.routed_item(plan_of(todo), cut) + + +class RoutedItem(unittest.TestCase): + def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self): + self.assertEqual(routed_item(TODO, NO_CUT).id, 3) + self.assertIsNone(routed_item(TODO.replace("| | **Do", "| question | **Do"), NO_CUT)) + self.assertIsNone(routed_item("# todo\n", NO_CUT)) + self.assertIsNone(routed_item(TODO[:TODO.index("| 7 |")], NO_CUT)) + old_shape = "## Items\n\n| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 3 | 0.2.0 | | **Do the next thing.** | 5 | 3 | 6 | 8 | 9 | 1 | 25 |\n" + self.assertIsNone(routed_item(old_shape, NO_CUT)) + self.assertEqual(routed_item(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), Failure("item 3's L 'x' is not a whole number from 1 to 4")) + + def test_routes_on_no_item_where_the_release_after_the_last_cut_has_none(self): + self.assertEqual(routed_item(TODO, LastCut("v0.1.0", "", 3, [TODO])).id, 3) + # Someone cut 0.2.0 while it held items: they count as 0.3.0's, the next release, and where no later release is known, no item routes. + self.assertEqual(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])).id, 3) + self.assertIsNone(routed_item(re.sub(r"(?m)^\| \d+ \| 0\.3\.0 \|.*\n", "", TODO), LastCut("v0.2.0", "", 3, []))) + later_only = TODO[:TODO.index("| 7 |")] + TODO[TODO.index("| 1 | 0.3.0 |"):] + self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 3, [TODO]))) + self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 0, [TODO]))) + self.assertEqual(routed_item(later_only, LastCut("v0.2.0", "", 3, [later_only])).id, 1) + + def test_routes_past_an_item_a_waiting_item_blocks(self): + todo = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n| 8 | 0.2.0 | 7 | | **Use the answer.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 9 | 0.2.0 | 8 | | **Build on it.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 30 |\n| 3 | 0.2.0 | | | **Do the next thing.** | 4 | 2 | 3 | 7 | 3 | 1 by 9 | 25 |\n" + self.assertEqual(routed_item(todo, NO_CUT).id, 3) + self.assertEqual(routed_item(todo.replace("| question |", "| |"), NO_CUT).id, 7) + first = "| 7 | 0.2.0 | | question | **Ask first.** | 4 | 3 | 5 | 10 | 1 | 1 by 9 | 30 |\n" + self.assertEqual(routed_item(todo.replace(first, "") + first, NO_CUT).id, 3) + + def test_routes_nothing_on_an_item_without_e_or_i(self): + without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |") + self.assertIsNone(routed_item(without_i, NO_CUT)) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/metric_bench/test_metric_bench.py b/bin/metric_bench/test_metric_bench.py index eef60c2f..381585d0 100644 --- a/bin/metric_bench/test_metric_bench.py +++ b/bin/metric_bench/test_metric_bench.py @@ -15,7 +15,7 @@ from review_rules.comprehension_history import entries, Place from failure import Failure from test_env import isolated_env from metric_bench.main import scored_runs -from project_config.test_project_config import write_config +from project_config.doubles import write_config TOOL = pathlib.Path(__file__).resolve().parents[1] / "metric-bench" diff --git a/bin/model_routing/test_ladder_file.py b/bin/model_routing/test_ladder_file.py index a4693b40..73ffef27 100644 --- a/bin/model_routing/test_ladder_file.py +++ b/bin/model_routing/test_ladder_file.py @@ -10,7 +10,7 @@ from failure import Failure from test_env import isolated_env from model_routing.ladder import Ladder, Rung from model_routing.ladder_file import NAME, project_ladder, project_ladder_file, read_ladder, SHIPPED -from project_config.test_project_config import write_config +from project_config.doubles import write_config FABLE_ONLY = '[\n\t{"model": "claude-fable-5-2", "effort": "low"},\n\t{"model": "claude-fable-5-2", "effort": "max"}\n]\n' FABLE_LADDER = Ladder((Rung("claude-fable-5-2", "low"), Rung("claude-fable-5-2", "max"))) diff --git a/bin/notifier/test_notifier.py b/bin/notifier/test_notifier.py index ee563e57..1961e536 100644 --- a/bin/notifier/test_notifier.py +++ b/bin/notifier/test_notifier.py @@ -10,7 +10,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.test_project_config import configured +from project_config.doubles import configured from failure import Failure from rest_client.json_request import Http from test_env import isolated_env diff --git a/bin/plan/doubles.py b/bin/plan/doubles.py new file mode 100644 index 00000000..962f0b62 --- /dev/null +++ b/bin/plan/doubles.py @@ -0,0 +1,87 @@ +"""Test doubles for the tools that read a plan: a goals file, a decision log and plans in todo.md's shapes.""" + +# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it. +VOID = "**Void:** code health, since a test project has no code to read.\n\n" + +README = "# P\n\n## Goals\n\n" + VOID + "1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n" + +DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n" + +TODO = """# todo + +## Scoring + +`Score = 100 * V / 2**S` + +`Bar = 2` + +`Next ID = 6` + +## Items + +| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | +|---|---|---|---|---|---|---|---|---|---|---|---| +| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 0 | +| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 | +| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 0 | +| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 | +| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 | + +## Details + +### 1. stale heading + +Later detail. + +### 3. Make it fast. + +Fast detail. + +## Notes + +Kept as written. +""" + +OLD_SHAPE = """# todo + +## Scoring + +`Score = -R - S/4 + 2*A + 2*G*W` + +`Bar = 9` + +`Next ID = 6` + +| Goal | W | +|---|---| +| 1 | 1.00 | +| 2 | 0.67 | +| 2.1 | 0.33 | + +## Items + +| ID | Release | Blocked by | Exempt | Item | R | S | C | A | G | Goals | Score | +|---|---|---|---|---|---|---|---|---|---|---|---| +| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 0 | +| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 | +| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 0 | +| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | 0 | +| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 | + +## Details + +### 1. stale heading + +Later detail. + +### 3. Make it fast. + +Fast detail. + +## Notes + +Kept as written. +""" + +# A scoring run of the project whose overall mean is {overall}. +SCORED = "# Comprehension history\n\n## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mid A | 6 |\n| Mean | {overall} |\n" diff --git a/bin/plan/test_blockers.py b/bin/plan/test_blockers.py index 587c9746..fb9a33ae 100644 --- a/bin/plan/test_blockers.py +++ b/bin/plan/test_blockers.py @@ -5,7 +5,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from plan.test_ranking import DECISIONS, README, TODO +from plan.doubles import DECISIONS, README, TODO from project_config.settings import DEFAULT_FLOOR from failure import Failure from plan import ranking, todo_table diff --git a/bin/plan/test_formula.py b/bin/plan/test_formula.py index 52d0f8e8..b130ecf5 100644 --- a/bin/plan/test_formula.py +++ b/bin/plan/test_formula.py @@ -4,7 +4,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from plan.test_ranking import DECISIONS, README, TODO +from plan.doubles import DECISIONS, README, TODO from project_config.settings import DEFAULT_FLOOR from failure import Failure from plan import ranking diff --git a/bin/plan/test_ranking.py b/bin/plan/test_ranking.py index 83ba4dae..d73f707b 100644 --- a/bin/plan/test_ranking.py +++ b/bin/plan/test_ranking.py @@ -9,7 +9,8 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.test_project_config import configured +from project_config.doubles import configured +from plan.doubles import DECISIONS, OLD_SHAPE, README, SCORED, TODO, VOID from project_config.settings import DEFAULT_FLOOR from failure import Failure from plan_store.stores import file_plan @@ -18,89 +19,6 @@ from project_config.main import located from repo_checks import ROOT from plan import todo_table -# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it. -VOID = "**Void:** code health, since a test project has no code to read.\n\n" - -README = "# P\n\n## Goals\n\n" + VOID + "1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n" - -DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n" - -TODO = """# todo - -## Scoring - -`Score = 100 * V / 2**S` - -`Bar = 2` - -`Next ID = 6` - -## Items - -| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | -|---|---|---|---|---|---|---|---|---|---|---|---| -| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 0 | -| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 | -| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 0 | -| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 | -| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 | - -## Details - -### 1. stale heading - -Later detail. - -### 3. Make it fast. - -Fast detail. - -## Notes - -Kept as written. -""" - -OLD_SHAPE = """# todo - -## Scoring - -`Score = -R - S/4 + 2*A + 2*G*W` - -`Bar = 9` - -`Next ID = 6` - -| Goal | W | -|---|---| -| 1 | 1.00 | -| 2 | 0.67 | -| 2.1 | 0.33 | - -## Items - -| ID | Release | Blocked by | Exempt | Item | R | S | C | A | G | Goals | Score | -|---|---|---|---|---|---|---|---|---|---|---|---| -| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 0 | -| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 | -| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 0 | -| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | 0 | -| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 | - -## Details - -### 1. stale heading - -Later detail. - -### 3. Make it fast. - -Fast detail. - -## Notes - -Kept as written. -""" - def numbered_goals(goals_text): """The goals ranked_goals numbers in a goals file, before it adds code health.""" @@ -256,10 +174,6 @@ class Rank(unittest.TestCase): self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure) -# A scoring run of the project whose overall mean is {overall}. -SCORED = "# Comprehension history\n\n## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mid A | 6 |\n| Mean | {overall} |\n" - - class CodeHealth(unittest.TestCase): readme = "## Goals\n\n1. **Achieve:** A.\n" todo = TODO.split("| 1 | 0.2.0", 1)[0].replace("`Bar = 2`", "`Bar = 0.1`") + "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 0 |\n| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n" diff --git a/bin/plan_store/test_stores.py b/bin/plan_store/test_stores.py index af711edb..f75c7327 100644 --- a/bin/plan_store/test_stores.py +++ b/bin/plan_store/test_stores.py @@ -17,7 +17,7 @@ from plan_store.fakes import MemoryPlan from record_store.fakes import MemoryStore from plan.todo_table import NoItemsTable from plan_store import plans, scoring, stores, todo_md -from plan.test_ranking import README, SCORED, VOID +from plan.doubles import README, SCORED, VOID from plan.release import release_of EMPTY = "# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = 2`\n\n`Next ID = 1`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" diff --git a/bin/project_config/doubles.py b/bin/project_config/doubles.py new file mode 100644 index 00000000..d38ab31e --- /dev/null +++ b/bin/project_config/doubles.py @@ -0,0 +1,46 @@ +"""Test doubles for the tools that read a project's config: a client's config text, and a checkout that a config names.""" +import os +import pathlib +import subprocess +import tempfile +import unittest +import unittest.mock + +from test_env import isolated_env + +CLIENT = """checkout = "~/code/acme-billing" +plan = "folder:todo.md" +working-rules = "folder:AGENTS.md" +decisions = "folder:docs/decisions.md" +score-anchors = "folder:docs/score-anchors.md" +comprehension-history = "folder:docs/comprehension-history.md" +reading-cost = "folder:docs/reading-cost.md" +changelog = "checkout:CHANGELOG.md" +goals-and-audience = "folder:goals.md" +principles = "~/.claude/principles" +standards = "~/.claude/skills/larv-review/standards" +""" + +JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12" +JIRA_SCORING = 'jira-score-formula = "100 * V / (2**S + 8)"\njira-score-bar = 1\n' + + +def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path: + """A config under home that names checkout, every setting inside it but goals-and-audience; for the tests of each tool that reads the config.""" + folder = home / ".claude-projects" / checkout.name + folder.mkdir(parents=True, exist_ok=True) + (folder / "config.toml").write_text(CLIENT.replace('"~/code/acme-billing"', f'"{checkout}"').replace('"folder:', '"checkout:').replace('"checkout:goals.md"', f'"{goals}"'), encoding="utf-8") + return folder + + +def configured(test: unittest.TestCase, checkout: pathlib.Path, goals: str = "checkout:README.md", home: pathlib.Path | None = None) -> pathlib.Path: + """Makes checkout a git checkout that a config names, under home, else a HOME of its own, for the rest of the test; the config's folder.""" + subprocess.run(["git", "init", "--quiet", str(checkout)], check=True, env=isolated_env()) + if home is None: + made = tempfile.TemporaryDirectory() + test.addCleanup(made.cleanup) + home = pathlib.Path(made.name) + patched = unittest.mock.patch.dict(os.environ, {"HOME": str(home)}) + patched.start() + test.addCleanup(patched.stop) + return write_config(home, checkout, goals) diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index 6bec16d9..00739d8e 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -1,5 +1,4 @@ import decimal -import os import pathlib import subprocess import sys @@ -10,6 +9,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.settings import by_name, env_files, Epic, Finish, held, JiraScoring, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed +from project_config.doubles import CLIENT, JIRA_PLAN, JIRA_SCORING from failure import Failure from test_env import isolated_env from project_config.main import located, title_templates @@ -17,46 +17,10 @@ from project_config.templates import Titles TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-config" -CLIENT = """checkout = "~/code/acme-billing" -plan = "folder:todo.md" -working-rules = "folder:AGENTS.md" -decisions = "folder:docs/decisions.md" -score-anchors = "folder:docs/score-anchors.md" -comprehension-history = "folder:docs/comprehension-history.md" -reading-cost = "folder:docs/reading-cost.md" -changelog = "checkout:CHANGELOG.md" -goals-and-audience = "folder:goals.md" -principles = "~/.claude/principles" -standards = "~/.claude/skills/larv-review/standards" -""" - -JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12" -JIRA_SCORING = 'jira-score-formula = "100 * V / (2**S + 8)"\njira-score-bar = 1\n' JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n' + JIRA_SCORING DECISIONS_PAGE = "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761/Decisions" -def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path: - """A config under home that names checkout, every setting inside it but goals-and-audience; for the tests of each tool that reads the config.""" - folder = home / ".claude-projects" / checkout.name - folder.mkdir(parents=True, exist_ok=True) - (folder / "config.toml").write_text(CLIENT.replace('"~/code/acme-billing"', f'"{checkout}"').replace('"folder:', '"checkout:').replace('"checkout:goals.md"', f'"{goals}"'), encoding="utf-8") - return folder - - -def configured(test: unittest.TestCase, checkout: pathlib.Path, goals: str = "checkout:README.md", home: pathlib.Path | None = None) -> pathlib.Path: - """Makes checkout a git checkout that a config names, under home, else a HOME of its own, for the rest of the test; the config's folder.""" - subprocess.run(["git", "init", "--quiet", str(checkout)], check=True, env=isolated_env()) - if home is None: - made = tempfile.TemporaryDirectory() - test.addCleanup(made.cleanup) - home = pathlib.Path(made.name) - patched = unittest.mock.patch.dict(os.environ, {"HOME": str(home)}) - patched.start() - test.addCleanup(patched.stop) - return write_config(home, checkout, goals) - - class ConfigCase(unittest.TestCase): def setUp(self) -> None: made = tempfile.TemporaryDirectory() diff --git a/bin/project_record/test_project_record.py b/bin/project_record/test_project_record.py index 5a83f5fb..2f7a872f 100644 --- a/bin/project_record/test_project_record.py +++ b/bin/project_record/test_project_record.py @@ -7,7 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.test_project_config import configured +from project_config.doubles import configured from record_store.confluence_page import ConfluencePage from failure import Failure from project_record import main diff --git a/bin/reading_cost/test_reading_cost.py b/bin/reading_cost/test_reading_cost.py index adab0ba5..101ab675 100644 --- a/bin/reading_cost/test_reading_cost.py +++ b/bin/reading_cost/test_reading_cost.py @@ -26,7 +26,7 @@ from record_store.fakes import MemoryStore from transcript_archive import outcomes from transcript_archive.location import project_archive from reading_cost.shell_reads import Reads, shell_reads -from project_config.test_project_config import write_config +from project_config.doubles import write_config TOOL = pathlib.Path(__file__).resolve().parents[1] / "reading-cost" diff --git a/bin/repo_checks/test_package_cycles.py b/bin/repo_checks/test_package_cycles.py index 51135a47..6b261ce8 100644 --- a/bin/repo_checks/test_package_cycles.py +++ b/bin/repo_checks/test_package_cycles.py @@ -57,6 +57,21 @@ def upward_imports(bin_folder: pathlib.Path, above: dict[str, tuple[str, ...]]) return sorted(found) +def imports_of_test_modules(bin_folder: pathlib.Path) -> list[str]: + """Each module under bin_folder that imports a test module of another package, as ` imports `. A module at bin_folder's root, such as test_env.py, belongs to no package.""" + found = [] + for module in sorted(bin_folder.rglob("*.py")): + package = module.relative_to(bin_folder).parts[0] + for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))): + names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [f"{node.module}.{alias.name}" for alias in node.names] if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module else [] + for name in names: + top, *below = name.split(".") + tests = [part for part in below if part.startswith("test_")] + if tests and top != package: + found.append(f"{module.relative_to(bin_folder)} imports {name[:name.index(tests[0]) + len(tests[0])]}") + return sorted(set(found)) + + def cycle(imported: dict[str, set[str]]) -> list[str]: """One cycle among the packages, as the packages along it; empty where there is none.""" try: @@ -92,6 +107,24 @@ class PackageCycles(unittest.TestCase): (folder / package / name).write_text(source) self.assertEqual(driver_imports(folder, ("a",)), ["b/mod.py imports a", "b/test_mod.py imports a"]) + def test_no_module_imports_a_test_module_of_another_package(self): + self.assertEqual(imports_of_test_modules(ROOT / "bin"), [], "move what the importer needs into the doubles.py of the package that owns it") + + def test_a_test_module_imported_from_another_package_is_found_however_it_is_spelled(self): + with tempfile.TemporaryDirectory() as temp: + folder = pathlib.Path(temp) + sources = ( + ("a", "test_mod.py", "from a.test_other import x\nfrom test_env import y\nfrom a.doubles import z\n"), + ("b", "test_mod.py", "from a.test_mod import x\n"), + ("b", "mod.py", "def f():\n\timport a.deep.test_far\n"), + ("c", "test_mod.py", "from a import test_mod\nfrom a.test_mod import x, y\n"), + ) + for package, name, source in sources: + (folder / package).mkdir(exist_ok=True) + (folder / package / name).write_text(source) + (folder / "test_root.py").write_text("from a.test_mod import x\n") + self.assertEqual(imports_of_test_modules(folder), ["b/mod.py imports a.deep.test_far", "b/test_mod.py imports a.test_mod", "c/test_mod.py imports a.test_mod", "test_root.py imports a.test_mod"]) + def test_reads_an_import_deferred_into_a_function_and_leaves_out_tests(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) diff --git a/bin/rest_client/doubles.py b/bin/rest_client/doubles.py new file mode 100644 index 00000000..00a7500d --- /dev/null +++ b/bin/rest_client/doubles.py @@ -0,0 +1,50 @@ +"""Test doubles for the suites that send HTTP requests: a local server that answers by a script.""" +import http.server +import threading +import unittest + + +class Recorded(http.server.BaseHTTPRequestHandler): + """Answers each request with the server's next scripted status and body, recording what it got.""" + + def do_GET(self) -> None: + self.answer() + + def do_POST(self) -> None: + self.answer() + + def do_PUT(self) -> None: + self.answer() + + def answer(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined] + status, body = self.server.script.pop(0) # type: ignore[attr-defined] + if status is None: + # Raw bytes, as a server that breaks HTTP sends them. + self.wfile.write(body) + self.close_connection = True + return + self.send_response(status) + if 300 <= status < 400: + self.send_header("Location", "/elsewhere") + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + +class Served(unittest.TestCase): + """A test case with a local server that answers by a script; it holds no test itself, so a test elsewhere may build on it.""" + + def serve(self, *script: tuple[int, bytes]) -> str: + server = http.server.HTTPServer(("127.0.0.1", 0), Recorded) + server.script = list(script) # type: ignore[attr-defined] + server.got = [] # type: ignore[attr-defined] + threading.Thread(target=server.serve_forever, daemon=True).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + self.server = server + return f"http://127.0.0.1:{server.server_port}" diff --git a/bin/rest_client/test_json_request.py b/bin/rest_client/test_json_request.py index 3e030eb9..52f4e917 100644 --- a/bin/rest_client/test_json_request.py +++ b/bin/rest_client/test_json_request.py @@ -1,9 +1,7 @@ -import http.server import json import pathlib import socket import sys -import threading import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -11,6 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from rest_client.json_request import ErrorAnswer from failure import Failure from rest_client import json_request +from rest_client.doubles import Served def message(answer: object) -> str: @@ -21,52 +20,6 @@ def send(method: str, url: str, token: str, body: object, seconds: float = 5) -> return json_request.http_json(method, url, f"Bearer {token}", body, seconds, message) # type: ignore[arg-type] -class Recorded(http.server.BaseHTTPRequestHandler): - """Answers each request with the server's next scripted status and body, recording what it got.""" - - def do_GET(self) -> None: - self.answer() - - def do_POST(self) -> None: - self.answer() - - def do_PUT(self) -> None: - self.answer() - - def answer(self) -> None: - length = int(self.headers.get("Content-Length") or 0) - self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined] - status, body = self.server.script.pop(0) # type: ignore[attr-defined] - if status is None: - # Raw bytes, as a server that breaks HTTP sends them. - self.wfile.write(body) - self.close_connection = True - return - self.send_response(status) - if 300 <= status < 400: - self.send_header("Location", "/elsewhere") - self.send_header("Content-Type", "application/json") - self.end_headers() - self.wfile.write(body) - - def log_message(self, format: str, *args: object) -> None: - pass - - -class Served(unittest.TestCase): - """A test case with a local server that answers by a script; it holds no test itself, so a test elsewhere may build on it.""" - - def serve(self, *script: tuple[int, bytes]) -> str: - server = http.server.HTTPServer(("127.0.0.1", 0), Recorded) - server.script = list(script) # type: ignore[attr-defined] - server.got = [] # type: ignore[attr-defined] - threading.Thread(target=server.serve_forever, daemon=True).start() - self.addCleanup(server.server_close) - self.addCleanup(server.shutdown) - self.server = server - return f"http://127.0.0.1:{server.server_port}" - - class HttpJson(Served): def test_sends_the_authorization_and_the_body_as_json_and_reads_the_json_answer(self): base = self.serve((201, b'{"id": "post-id"}')) diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index 4ea2d19d..cd6004c6 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -17,7 +17,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from review_replay.rounds import authored_by, lost_inputs, recorded_findings, reviewed_path, Round, round_from, sample, stamp_seconds from review_replay import changes, main, recall, replay from text_files import compressed -from project_config.test_project_config import configured, write_config +from project_config.doubles import configured, write_config from loop_effects.effects import Effects, system_effects from claude_code.entries import entry_from from failure import Failure diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index 61803e64..c7b9e68a 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -21,7 +21,7 @@ from branch_chunks.cut import BranchChunk from routing_figures.calls import Call, calls, totals from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Reports, Subagent from text_files import compressed -from project_config.test_project_config import configured, write_config +from project_config.doubles import configured, write_config from routing_figures.state import due from claude_code.entries import entry_from from failure import Failure diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 38d8c1da..7e969d38 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -19,8 +19,8 @@ from rule_hook.rules import blocks, Breach, check, command_breaches, file_breach from rule_hook.main import breaches_of from rule_hook.call import Call, parsed_call from git_cli.git_command import commit_message, CommitCall, commits -from project_config.test_project_config import configured, write_config -from plan.test_ranking import DECISIONS, README, TODO +from project_config.doubles import configured, write_config +from plan.doubles import DECISIONS, README, TODO from rule_hook.git import guarded_git from test_env import isolated_env from rule_hook.override_log import LogLine, parsed_entry, this_chunks diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index a2ac7adc..fe9c8bfe 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -10,7 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from score_outcomes.anchors import anchor_lines, parse_anchors from branch_chunks.cut import BranchChunk, Landing -from project_config.test_project_config import configured, write_config +from project_config.doubles import configured, write_config from failure import Failure from score_outcomes.results import file_lines, NamedCode, nearest, rank_correlation, render, report, Result, results_of from review_rules.round_titles import Findings diff --git a/bin/subagent_rung/test_subagent_rung.py b/bin/subagent_rung/test_subagent_rung.py index 705ae10a..b7755473 100644 --- a/bin/subagent_rung/test_subagent_rung.py +++ b/bin/subagent_rung/test_subagent_rung.py @@ -9,7 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from test_env import isolated_env from subagent_rung import main from model_routing.ladder_file import read_ladder, SHIPPED -from project_config.test_project_config import write_config +from project_config.doubles import write_config LADDER = read_ladder(SHIPPED) TOOL = pathlib.Path(__file__).resolve().parents[1] / "subagent-rung" diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index a6460dda..ba56c8d8 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -7,12 +7,12 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from project_config.test_project_config import configured -from plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO +from project_config.doubles import configured +from plan.doubles import DECISIONS, OLD_SHAPE, README, TODO from project_config.settings import DEFAULT_FLOOR from plan import goals_file, ranking import rank_todo -from todo_item.test_todo_item import READABLE_TOUCHES, UNREADABLE_BULLETS +from todo_item.doubles import READABLE_TOUCHES, UNREADABLE_BULLETS class Main(unittest.TestCase): diff --git a/bin/todo_item/doubles.py b/bin/todo_item/doubles.py new file mode 100644 index 00000000..0131e48d --- /dev/null +++ b/bin/todo_item/doubles.py @@ -0,0 +1,13 @@ +"""Test doubles for the suites that read an item's detail: Touches bullets that touch-predictions can and cannot read.""" + +# The bullets six items held on 2026-11-18, which touch-predictions cannot read: `(small)` after a bare path, and a part not in backticks. +UNREADABLE_BULLETS = ( + "- `bin/judge_replay/main.py` (small)", + "- `bin/do_epic/main.py` (small)", + "- `principles/technical-principles.md`: the tests bullet group, `A valuable test checks behaviour` (small)", + "- `README.md`: loop-claude's section (small)", + "- `bin/rule_hook/rules.py`: the rule table (small)", + "- `settings.json`: the PreToolUse matcher (small)", +) + +READABLE_TOUCHES = "Why.\n\nTouches:\n\n- `bin/a.py`: `main`, `Plan.branch` (small)\n- `bin/run.sh`: lines 10-20\n- `docs/new.md`\n" diff --git a/bin/todo_item/test_todo_item.py b/bin/todo_item/test_todo_item.py index 0b9d2cd2..c95157ff 100644 --- a/bin/todo_item/test_todo_item.py +++ b/bin/todo_item/test_todo_item.py @@ -8,8 +8,8 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) -from project_config.test_project_config import configured, JIRA_PLAN, JIRA_SCORING -from plan.test_ranking import DECISIONS, README, TODO +from project_config.doubles import configured, JIRA_PLAN, JIRA_SCORING +from plan.doubles import DECISIONS, README, TODO from project_config.settings import DEFAULT_FLOOR from todo_item import edits, main from failure import Failure @@ -18,6 +18,7 @@ from project_config.main import located from plan_store.fakes import MemoryPlan from plan_store.todo_md import plan_of from plan import ranking +from todo_item.doubles import READABLE_TOUCHES, UNREADABLE_BULLETS from todo_item.table import table ADD = ["add", "--release", "0.1.0", "--l", "1", "--e", "1", "--i", "1", "--s", "1", "--moves", "1 by 9", "Count the `a | b` runs."] @@ -25,16 +26,6 @@ CHANGELOG = "# Changelog\n\n## Unreleased\n\n- Older news.\n\n## 0.1.0\n\n- Firs # ## Details of the ranked fixture, without the trailing ## Notes. HEADER = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves |\n|---|---|---|---|---|---|---|---|---|---|---|\n" DETAILS = "## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n" -# The bullets six items held on 2026-11-18, which touch-predictions cannot read: `(small)` after a bare path, and a part not in backticks. -UNREADABLE_BULLETS = ( - "- `bin/judge_replay/main.py` (small)", - "- `bin/do_epic/main.py` (small)", - "- `principles/technical-principles.md`: the tests bullet group, `A valuable test checks behaviour` (small)", - "- `README.md`: loop-claude's section (small)", - "- `bin/rule_hook/rules.py`: the rule table (small)", - "- `settings.json`: the PreToolUse matcher (small)", -) -READABLE_TOUCHES = "Why.\n\nTouches:\n\n- `bin/a.py`: `main`, `Plan.branch` (small)\n- `bin/run.sh`: lines 10-20\n- `docs/new.md`\n" class Terminal(io.StringIO): diff --git a/bin/touch_predictions/doubles.py b/bin/touch_predictions/doubles.py new file mode 100644 index 00000000..22189131 --- /dev/null +++ b/bin/touch_predictions/doubles.py @@ -0,0 +1,12 @@ +"""Test doubles for the suites that read touch predictions: a plan whose items hold them.""" +from failure import Failure +from plan_store.todo_md import plan_of + + +def plan(*items: tuple[int, str, str, str]) -> list: + """A plan's items, each given as its ID, release, the IDs that block it and the bullets of its prediction, none for an item without one.""" + rows = "".join(f"| {id_} | {release} | {blocked} | | **Do {id_}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" for id_, release, blocked, _ in items) + details = "".join(f"### {id_}. Do {id_}.\n\nTouches:\n\n{bullets}\n\n" for id_, _, _, bullets in items if bullets) + found = plan_of(f"# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 99`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n{rows}\n## Details\n\n{details}") + assert not isinstance(found, Failure), found + return found.items diff --git a/bin/touch_predictions/test_touch_predictions.py b/bin/touch_predictions/test_touch_predictions.py index e960c9a6..1d2e1659 100644 --- a/bin/touch_predictions/test_touch_predictions.py +++ b/bin/touch_predictions/test_touch_predictions.py @@ -15,9 +15,9 @@ from test_env import isolated_env from project_config.main import located from record_store.fakes import MemoryStore from plan.touches import Part -from plan_store.todo_md import plan_of +from touch_predictions.doubles import plan from project_config.settings import ProjectConfig -from project_config.test_project_config import write_config +from project_config.doubles import write_config PYTHON = """\"\"\"Docstring.\"\"\" import os @@ -132,15 +132,6 @@ class FilePartsTest(unittest.TestCase): self.assertIsNone(self.names("run.sh", "echo\n", 1)) -def plan(*items: tuple[int, str, str, str]) -> list: - """A plan's items, each given as its ID, release, the IDs that block it and the bullets of its prediction, none for an item without one.""" - rows = "".join(f"| {id_} | {release} | {blocked} | | **Do {id_}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" for id_, release, blocked, _ in items) - details = "".join(f"### {id_}. Do {id_}.\n\nTouches:\n\n{bullets}\n\n" for id_, _, _, bullets in items if bullets) - found = plan_of(f"# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 99`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n{rows}\n## Details\n\n{details}") - assert not isinstance(found, Failure), found - return found.items - - class ChunksBesideTest(unittest.TestCase): def test_picks_in_the_plans_order_each_item_that_overlaps_none_before_it(self) -> None: items = plan((1, "0.2.0", "", "- `a.py`: `f`"), (2, "0.2.0", "", "- `a.py`: `g`\n- `b.py`"), (3, "0.2.0", "", "- `b.py`: `h`"), (4, "0.2.0", "", "- `a.py`: `f`"), (5, "0.2.0", "", "- `c.py`")) diff --git a/todo.md b/todo.md index 0ac0f7eb..c9701e5f 100644 --- a/todo.md +++ b/todo.md @@ -172,7 +172,7 @@ Touches: - `bin/agent_cycle/run.py`: `worker_environment` (small) - `bin/loop_claude/loop/usage.py`: `HELP` (small) - `bin/agent_cycle/test_run.py`: `Cycles` (small) -- `bin/loop_claude/test_loop_claude.py`: `HelpLimits` (small) +- `bin/loop_claude/loop/test_usage.py`: `HelpLimits` (small) ### 298. Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind. @@ -329,7 +329,7 @@ A release's capacity is a sum of its items' cost, as the formula counts it. Each ### 165. Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant. -A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: many tests in `bin/loop_claude/test_loop_claude.py` pin whole sentences of the question, archive, prompt or help text, up to about 750 characters. `test_every_exit_1_stop_has_its_clause_in_help` and `test_every_failed_judge_run_has_its_clause_in_help` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py` asserts `len(LADDER) == 6`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills. +A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: many tests under `bin/loop_claude/` pin whole sentences of the question, archive, prompt or help text, up to about 750 characters. `test_every_exit_1_stop_has_its_clause_in_help` and `test_every_failed_judge_run_has_its_clause_in_help` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py` asserts `len(LADDER) == 6`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills. ### 392. Group bin/'s packages by concern into seven folders (plan, records, integrations, loop, review, forge and host), so a newcomer finds a tool's neighbours in one place. -- 2.52.0 From cb3135bc8cdfa4cdd3963c42ec0856d2ceb98dbb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 12:42:03 +0100 Subject: [PATCH 07/14] =?UTF-8?q?Answer=20principles=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=207=20=F0=9F=9F=A1=20(0=20misread);=20every=20eff?= =?UTF-8?q?ect=20is=20handed=20in=20as=20an=20argument,=20no=20test=20patc?= =?UTF-8?q?hes=20a=20global,=20and=20the=20traces=20principle=20scopes=20t?= =?UTF-8?q?ools=20that=20run=20on=20their=20user's=20machine?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/adf_codec/convert.py | 30 ++++-- bin/adf_codec/test_adf_codec.py | 27 +++-- bin/agent_cycle/run.py | 2 +- bin/agent_cycle/test_interrupt.py | 1 - bin/agent_cycle/test_judge.py | 1 - bin/agent_cycle/test_retry.py | 1 - bin/agent_cycle/test_run.py | 11 +- bin/agent_cycle/test_spend.py | 1 - bin/agent_cycle/test_states.py | 1 - bin/agent_cycle/test_tmux.py | 1 - bin/agent_cycle/test_worker.py | 1 - bin/atlassian/jira.py | 53 ++++++--- bin/atlassian/test_jira.py | 57 ++++++++++ bin/branch_chunks/test_branch_chunks.py | 4 +- bin/chunk_driver/claims.py | 31 ++++-- bin/chunk_driver/project/model_choice.py | 29 +++-- bin/chunk_driver/project/test_model_choice.py | 68 +++++++++++- bin/chunk_driver/project/test_records.py | 1 - bin/chunk_driver/test_chunk_run.py | 5 +- bin/chunk_driver/test_claims.py | 41 +++++++ bin/chunk_driver/test_cycle_start.py | 34 +++--- bin/chunk_pr/approval.py | 3 +- bin/chunk_pr/main.py | 4 +- bin/chunk_pr/test_chunk_pr.py | 36 +++---- bin/compress-archives | 8 +- bin/compress_archives/main.py | 9 +- .../test_compress_archives.py | 13 ++- bin/deploy_release/cut.py | 9 +- bin/deploy_release/main.py | 3 +- bin/do-epic | 2 +- bin/do-epic-e2e | 4 +- bin/do_epic/backend/jira.py | 6 +- bin/do_epic/backend/test_jira.py | 17 ++- bin/do_epic/e2e/main.py | 10 +- bin/do_epic/e2e/test_main.py | 15 +-- bin/do_epic/main.py | 36 +++++-- bin/do_epic/scheduler.py | 100 ++++++++--------- bin/do_epic/test_finish.py | 8 ++ bin/do_epic/test_main.py | 15 +++ bin/do_epic/test_repos.py | 17 +-- bin/do_epic/test_scheduler.py | 16 +++ bin/forge/pulls.py | 3 +- bin/forge/reviews.py | 100 +++++++++++++---- bin/forge/test_reviews.py | 102 ++++++++++++++++++ bin/git_cli/git_repo.py | 11 +- bin/judge-replay | 2 +- bin/judge_replay/main.py | 10 +- bin/judge_replay/test_judge_replay.py | 8 +- bin/larv_review/test_larv_review.py | 27 +++-- bin/larv_review/test_scoring_setup.py | 7 +- bin/loop-claude | 2 +- bin/loop_claude/loop/chunk_windows.py | 31 +++--- bin/loop_claude/loop/main.py | 57 +++++++--- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/loop/test_chunk_start.py | 21 +++- bin/loop_claude/loop/test_chunk_windows.py | 63 ++++++++--- bin/loop_claude/loop/test_main.py | 72 ++++++++----- bin/loop_claude/loop/test_routing_check.py | 7 +- bin/loop_claude/loop/test_usage.py | 3 +- bin/loop_effects/child_shells.py | 9 +- bin/loop_effects/doubles.py | 4 + bin/loop_effects/effects.py | 26 +++-- bin/loop_effects/test_effects.py | 49 ++++----- bin/machine_load/slots.py | 17 +-- bin/machine_load/test_machine_load.py | 23 ++-- bin/mutate-changes | 3 +- bin/mutate_changes/in_diff_tools.py | 16 +-- bin/mutate_changes/main.py | 34 +++--- bin/mutate_changes/mutmut_tool.py | 30 +++--- bin/mutate_changes/test_mutate_changes.py | 14 +-- .../test_mutate_changes_runs.py | 14 ++- bin/mutate_changes/tool_process.py | 21 ++-- bin/notifier/mattermost.py | 8 +- bin/notifier/slack.py | 8 +- bin/notifier/test_mattermost.py | 7 +- bin/notifier/test_notifier.py | 5 +- bin/notifier/test_slack.py | 7 +- bin/plan/test_ranking.py | 6 +- bin/plan_store/jira_epic.py | 16 +-- bin/plan_store/test_jira_epic.py | 4 +- bin/project_config/doubles.py | 7 +- bin/project_config/test_project_config.py | 1 - bin/project_record/test_project_record.py | 8 +- bin/rank_todo.py | 6 +- bin/reading_cost/test_reading_cost.py | 7 +- bin/repo_checks/test_no_patched_globals.py | 36 +++++++ bin/repo_checks/test_package_cycles.py | 42 ++++---- bin/review-replay | 2 +- bin/review_replay/change_comparison.py | 9 +- bin/review_replay/main.py | 25 ++--- bin/review_replay/recall.py | 20 ++-- bin/review_replay/replay.py | 18 ++-- bin/review_replay/test_recall.py | 16 ++- bin/review_replay/test_review_replay.py | 22 ++-- bin/routing_figures/state.py | 9 +- bin/routing_figures/test_routing_figures.py | 43 ++++---- bin/rule_hook/test_rule_hook.py | 39 ++++--- bin/rule_hook/todo_check.py | 16 +-- bin/run-tests | 2 +- bin/run_heavy/main.py | 12 ++- bin/run_tests/main.py | 3 +- bin/run_tests/test_run_tests.py | 12 +-- bin/rung_replay/archive.py | 17 +-- bin/rung_replay/command.py | 13 +++ bin/rung_replay/search.py | 21 ++-- bin/rung_replay/test_rung_replay.py | 22 ++-- bin/score-outcomes | 2 +- bin/score_outcomes/main.py | 24 ++--- bin/score_outcomes/test_score_outcomes.py | 4 +- bin/test_rank_todo.py | 24 +++-- bin/text_files/compressed.py | 16 +-- bin/text_files/doubles.py | 10 ++ bin/text_files/test_compressed.py | 22 ++-- bin/todo-item | 2 +- bin/todo_item/main.py | 8 +- bin/todo_item/test_todo_item.py | 20 ++-- bin/touch_predictions/doubles.py | 11 +- bin/touch_predictions/main.py | 4 +- .../test_touch_predictions.py | 2 +- .../test_transcript_archive.py | 33 +++--- bin/transcript_archive/write.py | 29 ++--- docs/decisions.md | 8 +- principles/technical-principles.md | 1 + 124 files changed, 1437 insertions(+), 793 deletions(-) create mode 100644 bin/atlassian/test_jira.py create mode 100644 bin/chunk_driver/test_claims.py create mode 100644 bin/forge/test_reviews.py create mode 100644 bin/repo_checks/test_no_patched_globals.py create mode 100644 bin/text_files/doubles.py diff --git a/README.md b/README.md index 4e1e67c6..3550176a 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a ### Packages under `bin/` -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No test swaps a global with `mock.patch`: the code under test takes each effect as an argument, and the test hands it a double, which `repo_checks/test_no_patched_globals.py` checks. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. - `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. `doubles.py` holds the doubles its tests share with `chunk_driver`'s. diff --git a/bin/adf_codec/convert.py b/bin/adf_codec/convert.py index 4e9ed444..fe3f4720 100644 --- a/bin/adf_codec/convert.py +++ b/bin/adf_codec/convert.py @@ -8,16 +8,18 @@ adf-codec has two pairs of calls, and each function here names the one it runs: """ import contextlib import dataclasses +import fcntl import hashlib import json import os import pathlib import subprocess import sys +import time import typing from failure import Failure -from machine_load.slots import HELD, slot_count, slot_folder, usable_cpus, waited_slot +from machine_load.slots import HELD, Lock, slot_count, slot_folder, usable_cpus, waited_slot SHIM = pathlib.Path(__file__).resolve().parent / "node_shim" SHIM_FILES = ("Dockerfile", "package.json", "package-lock.json", "shim.mjs") @@ -62,7 +64,13 @@ def docker_args(image: str, mode: str) -> list[str]: return ["docker", "run", "--rm", "-i", "--memory", MEMORY, "--memory-swap", MEMORY, "--network", "none", "--read-only", image, mode] -def docker(args: list[str], text: str, seconds: int, call: typing.Callable[..., typing.Any] = subprocess.run) -> Ran | Failure: +def docker(args: list[str], text: str, seconds: int) -> Ran | Failure: + """Runs a docker command line as a process of this one: the shim's shell, as git_repo.git is git's.""" + return docker_ran(args, text, seconds, subprocess.run) + + +def docker_ran(args: list[str], text: str, seconds: int, call: typing.Callable[..., typing.Any]) -> Ran | Failure: + """What call, which runs a command line as subprocess.run does, made of a docker command line on text.""" try: done = call(args, input=text, capture_output=True, text=True, encoding="utf-8", timeout=seconds) except FileNotFoundError: @@ -73,16 +81,22 @@ def docker(args: list[str], text: str, seconds: int, call: typing.Callable[..., @contextlib.contextmanager -def heavy_slot(env: typing.Mapping[str, str] = os.environ, slots: int | None = None) -> typing.Iterator[Failure | None]: - """Holds one of the machine's heavy slots, which run-heavy shares, for the with block. Under run-heavy the process already holds one, so it doesn't wait.""" +def machine_slot() -> typing.Iterator[Failure | None]: + """heavy_slot on this process's environment, home, processors, stderr and clock: the shim's shell, as docker is.""" + with heavy_slot(os.environ, pathlib.Path.home(), slot_count(usable_cpus()), lambda text: print(text, file=sys.stderr, flush=True), time.sleep, fcntl.flock) as refused: + yield refused + + +@contextlib.contextmanager +def heavy_slot(env: typing.Mapping[str, str], home: pathlib.Path, slots: int, say: typing.Callable[[str], None], sleep: typing.Callable[[float], None], lock: Lock) -> typing.Iterator[Failure | None]: + """Holds one of the machine's heavy slots, which run-heavy shares, for the with block, telling say where it waits for one. Under run-heavy the process already holds one, so it doesn't wait.""" if HELD in env: yield None return - folder = slot_folder(env, pathlib.Path.home()) - count = slot_count(usable_cpus()) if slots is None else slots + folder = slot_folder(env, home) try: folder.mkdir(parents=True, exist_ok=True) - _, fd = waited_slot(folder, count, lambda: print(f"adf-codec: waiting for a heavy slot, of {count} on this machine, in {folder}, to build the shim's image; `fuser {folder}/slot-*` names the processes that hold them", file=sys.stderr, flush=True)) + _, fd = waited_slot(folder, slots, lambda: say(f"adf-codec: waiting for a heavy slot, of {slots} on this machine, in {folder}, to build the shim's image; `fuser {folder}/slot-*` names the processes that hold them"), sleep, lock) except OSError as failure: yield Failure(f"cannot take a heavy slot in {folder}: {failure.strerror}") return @@ -92,7 +106,7 @@ def heavy_slot(env: typing.Mapping[str, str] = os.environ, slots: int | None = N os.close(fd) -def ensure_image(shim: pathlib.Path, run_docker: Docker = docker, slot: Slot = heavy_slot) -> str | Failure: +def ensure_image(shim: pathlib.Path, run_docker: Docker = docker, slot: Slot = machine_slot) -> str | Failure: """The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag. The build waits for a heavy slot. Once this process holds the slot, it inspects again, as another process may have built the image meanwhile.""" diff --git a/bin/adf_codec/test_adf_codec.py b/bin/adf_codec/test_adf_codec.py index c1f79f42..464ec4e7 100644 --- a/bin/adf_codec/test_adf_codec.py +++ b/bin/adf_codec/test_adf_codec.py @@ -1,4 +1,5 @@ import contextlib +import fcntl import json import os import subprocess @@ -161,7 +162,7 @@ def test_docker_passes_the_text_on_stdin_and_returns_the_output(): seen.update(kwargs, args=args) return subprocess.CompletedProcess(args, 3, "out", "err") - assert convert.docker(["docker", "x"], "text", 7, call) == convert.Ran(3, "out", "err") + assert convert.docker_ran(["docker", "x"], "text", 7, call) == convert.Ran(3, "out", "err") assert seen == {"args": ["docker", "x"], "input": "text", "capture_output": True, "text": True, "encoding": "utf-8", "timeout": 7} @@ -169,7 +170,7 @@ def test_docker_missing_becomes_a_failure(): def call(args, **kwargs): raise FileNotFoundError - failure = convert.docker(["docker", "x"], "", 7, call) + failure = convert.docker_ran(["docker", "x"], "", 7, call) assert failure == Failure("docker is not installed, and the adf-codec shim runs in a container") @@ -177,7 +178,7 @@ def test_docker_that_takes_too_long_becomes_a_failure(): def call(args, **kwargs): raise subprocess.TimeoutExpired(args, 7) - assert convert.docker(["docker", "build", "x"], "", 7, call) == Failure("`docker build` took more than 7 seconds") + assert convert.docker_ran(["docker", "build", "x"], "", 7, call) == Failure("`docker build` took more than 7 seconds") def shim_dir(tmp_path): @@ -260,19 +261,27 @@ def test_a_failure_to_start_docker_passes_through_inspect_and_build(tmp_path, an assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == DOWN +def not_said(text): + raise AssertionError(f"said {text}") + + +def not_slept(seconds): + raise AssertionError(f"slept {seconds} seconds") + + def test_a_heavy_slot_is_held_until_the_block_ends(tmp_path): - with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, 1) as held: + with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, tmp_path, 1, not_said, not_slept, fcntl.flock) as held: assert held is None - assert slots.taken_slot(tmp_path / "run-heavy", 1) is None - slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1) + assert slots.taken_slot(tmp_path / "run-heavy", 1, fcntl.flock) is None + slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1, fcntl.flock) os.close(fd) def test_a_process_under_run_heavy_takes_no_second_slot(tmp_path): (tmp_path / "run-heavy").mkdir() - slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1) + slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1, fcntl.flock) try: - with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path), slots.HELD: "0"}, 1) as held: + with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path), slots.HELD: "0"}, tmp_path, 1, not_said, not_slept, fcntl.flock) as held: assert held is None finally: os.close(fd) @@ -280,7 +289,7 @@ def test_a_process_under_run_heavy_takes_no_second_slot(tmp_path): def test_a_heavy_slot_folder_that_cannot_be_made_yields_a_failure(tmp_path): (tmp_path / "run-heavy").write_text("a file where the folder goes") - with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, 1) as held: + with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, tmp_path, 1, not_said, not_slept, fcntl.flock) as held: assert isinstance(held, Failure) and held.reason.startswith(f"cannot take a heavy slot in {tmp_path / 'run-heavy'}: ") diff --git a/bin/agent_cycle/run.py b/bin/agent_cycle/run.py index 70702d4d..065cdef2 100644 --- a/bin/agent_cycle/run.py +++ b/bin/agent_cycle/run.py @@ -101,7 +101,7 @@ def archived_stop(project_archive: pathlib.Path, session: Session, task: str, ro def archived(project_archive: pathlib.Path, transcript_path: str, task: str, outcome: str, effects: Effects, judge_run: JudgeRun | None = None) -> Failure | None: """transcript_archive.write.archive, stamped now and saying its notes through effects. A cycle and close.py, which has no Cycle, both archive through it.""" - return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects), judge_run) + return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects), judge_run, replace=effects.replace_file) def step(cycle: Cycle, state: Active) -> Event | Stop: diff --git a/bin/agent_cycle/test_interrupt.py b/bin/agent_cycle/test_interrupt.py index 17d917de..ebc42344 100644 --- a/bin/agent_cycle/test_interrupt.py +++ b/bin/agent_cycle/test_interrupt.py @@ -7,7 +7,6 @@ import shutil import sys import tempfile import unittest -import unittest.mock import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/agent_cycle/test_judge.py b/bin/agent_cycle/test_judge.py index 71ec6090..c4b5ed67 100644 --- a/bin/agent_cycle/test_judge.py +++ b/bin/agent_cycle/test_judge.py @@ -3,7 +3,6 @@ import json import pathlib import sys import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/agent_cycle/test_retry.py b/bin/agent_cycle/test_retry.py index ed97ed74..eafc7630 100644 --- a/bin/agent_cycle/test_retry.py +++ b/bin/agent_cycle/test_retry.py @@ -3,7 +3,6 @@ import io import pathlib import sys import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/agent_cycle/test_run.py b/bin/agent_cycle/test_run.py index 8a31f5ee..64440dc0 100644 --- a/bin/agent_cycle/test_run.py +++ b/bin/agent_cycle/test_run.py @@ -11,7 +11,6 @@ import sys import tempfile import types import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -25,6 +24,7 @@ from transcript_archive.location import project_archive from model_routing.ladder import ProjectRung, Rung from agent_cycle.doubles import PROMPTS, WINDOW from model_routing.ladder_file import read_ladder, SHIPPED +from text_files.file_writes import replace_file from model_routing.route import Route from agent_cycle import routing from agent_cycle import run, stuck_workers, worker_prompts @@ -202,11 +202,8 @@ Worker: {OFF_LADDER} def test_stops_when_a_judge_run_cannot_be_archived(self): self.archive.mkdir(parents=True) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) - def replace_file(path, data): - return Failure("disk full") if "/judge/" in str(path) else real_replace_file(path, data) - real_replace_file = write.replace_file - with unittest.mock.patch("transcript_archive.write.replace_file", replace_file): - stop = run.run_cycle(self.cycle(fake)) + fake.replace_file = lambda path, data: Failure("disk full") if "/judge/" in str(path) else replace_file(path, data) + stop = run.run_cycle(self.cycle(fake)) self.assertEqual(stop.code, 1) self.assertRegex(stop.reason, r"^could not archive the transcript: .*/judge/[0-9a-f]{64}\.json: disk full$") @@ -244,7 +241,7 @@ Worker: {OFF_LADDER} new = {"type": "assistant", "timestamp": "2026-09-21T14:13:21Z", "message": {"id": "new", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 5}}} transcript.write_text("\n".join(json.dumps(entry) for entry in [{"type": "queue-operation", "timestamp": "2026-09-21T14:00:00Z"}, old, human("No, keep the old name."), new]) + "\n") with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) + self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW, replace=replace_file)) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished", reversed="No, keep the old name.")]) run.run_cycle(self.cycle(fake)) latest = max(self.archived_outcomes(), key=len) diff --git a/bin/agent_cycle/test_spend.py b/bin/agent_cycle/test_spend.py index 3e6baf28..a2b5f267 100644 --- a/bin/agent_cycle/test_spend.py +++ b/bin/agent_cycle/test_spend.py @@ -3,7 +3,6 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/agent_cycle/test_states.py b/bin/agent_cycle/test_states.py index bb2efccb..328c01b3 100644 --- a/bin/agent_cycle/test_states.py +++ b/bin/agent_cycle/test_states.py @@ -1,7 +1,6 @@ import pathlib import sys import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/agent_cycle/test_tmux.py b/bin/agent_cycle/test_tmux.py index 8577cecd..23fea0ef 100644 --- a/bin/agent_cycle/test_tmux.py +++ b/bin/agent_cycle/test_tmux.py @@ -2,7 +2,6 @@ import pathlib import subprocess import sys import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/agent_cycle/test_worker.py b/bin/agent_cycle/test_worker.py index fae69230..c5d3cbc9 100644 --- a/bin/agent_cycle/test_worker.py +++ b/bin/agent_cycle/test_worker.py @@ -6,7 +6,6 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py index fca56fc5..db5ed9e6 100644 --- a/bin/atlassian/jira.py +++ b/bin/atlassian/jira.py @@ -16,7 +16,8 @@ DONE = "done" # What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue. PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {under} before filing it again" # What a failed move ends with, for the same reason. -PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again" +SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents" +PERHAPS_MOVED ="unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again" @dataclasses.dataclass(frozen=True) @@ -44,17 +45,21 @@ def entry_of(raw: object, property_: str) -> Entry | Failure: key = raw.get("key") if isinstance(raw, dict) else None if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): return Failure("the search answered an issue without an issue key") - # The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it. - try: - fields = raw["fields"] - return Entry(key, fields, blocked_by_links(fields), raw.get("properties", {}).get(property_, {})) - except (AttributeError, KeyError, TypeError) as failure: - return Failure(unshaped(key, failure)) + # Each nested field is checked as Jira documents it; one missing or of another type ends the read here, as a Failure, so no later step meets it. + fields, properties = raw.get("fields"), raw.get("properties", {}) + if not isinstance(fields, dict): + return Failure(f"{key} {SHAPE}: its fields are no object") + if not isinstance(properties, dict): + return Failure(f"{key} {SHAPE}: its properties are no object") + links = blocked_by_links(fields) + if isinstance(links, Failure): + return Failure(f"{key} {SHAPE}: {links.reason}") + return Entry(key, fields, links, properties.get(property_, {})) def unshaped(key: str, failure: Exception) -> str: """Why the issue named key cannot be read, for a field that is missing or of another type than Jira documents.""" - return f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}" + return f"{key} {SHAPE}: {failure!r}" def offer_of(raw: object) -> tuple[str, str, str, str] | None: @@ -115,11 +120,11 @@ def rank_refusal(site: str, key: str, before: str, authorization: str, http: Htt return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None -def searched(site: str, what: str, jql: str, asked: dict[str, object], authorization: str, http: Http) -> list[object] | Failure: - """Every issue a JQL search on site finds, page by page. The dict asked holds the request's `fields` and `properties` lists. The text what names the issues sought, in the Failure of a search that doesn't end.""" +def searched(site: str, what: str, jql: str, asked: dict[str, object], authorization: str, http: Http, max_pages: int = MAX_PAGES) -> list[object] | Failure: + """Every issue a JQL search on site finds, page by page, up to max_pages pages. The dict asked holds the request's `fields` and `properties` lists. The text what names the issues sought, in the Failure of a search that doesn't end.""" body: dict[str, object] = {"jql": jql, "maxResults": PAGE} | asked found: list[object] = [] - for _ in range(MAX_PAGES): + for _ in range(max_pages): page = http("POST", f"{site}/rest/api/3/search/jql", authorization, body) if isinstance(page, Failure): return page @@ -129,9 +134,27 @@ def searched(site: str, what: str, jql: str, asked: dict[str, object], authoriza if not page.get("nextPageToken"): return found body = body | {"nextPageToken": page["nextPageToken"]} - return Failure(f"the search for {what} did not end within {MAX_PAGES} pages") + return Failure(f"the search for {what} did not end within {max_pages} pages") -def blocked_by_links(fields: dict[str, typing.Any]) -> tuple[Link, ...]: - """The "is blocked by" links among an issue's `issuelinks` field. A field not in the shape Jira documents raises a KeyError or TypeError, which the caller turns into a Failure.""" - return tuple(Link(link["inwardIssue"]["key"], link["id"]) for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by") +def blocked_by_links(fields: dict[str, typing.Any]) -> tuple[Link, ...] | Failure: + """The "is blocked by" links among an issue's `issuelinks` field, or how that field is not in the shape Jira documents.""" + listed = fields.get("issuelinks") + if not isinstance(listed, list): + return Failure("its issuelinks are no list") + found = [] + for link in listed: + if not isinstance(link, dict): + return Failure("its issuelinks hold a link that is no object") + if "inwardIssue" not in link: + continue + kind = link.get("type") + if not isinstance(kind, dict) or not isinstance(kind.get("inward"), str): + return Failure("its issuelinks hold a link whose type names no inward text") + if kind["inward"] != "is blocked by": + continue + blocker, id_ = link["inwardIssue"], link.get("id") + if not isinstance(blocker, dict) or not isinstance(blocker.get("key"), str) or not isinstance(id_, str): + return Failure("its issuelinks hold a link whose id or whose linked issue's key is no text") + found.append(Link(blocker["key"], id_)) + return tuple(found) diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py new file mode 100644 index 00000000..f2fcea04 --- /dev/null +++ b/bin/atlassian/test_jira.py @@ -0,0 +1,57 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from atlassian.jira import Entry, entry_of, Link +from failure import Failure +from atlassian import jira + +BLOCKED = {"id": "9", "type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-2"}} +SHAPE = "ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: " + + +def raw(*links: object, **more: object) -> dict[str, object]: + return {"key": "ABC-1", "fields": {"issuelinks": list(links)}} | more + + +class TheHeadOfAnEntry(unittest.TestCase): + def test_holds_the_key_the_fields_the_blocked_by_links_and_the_property_asked_for(self): + outward = {"id": "3", "type": {"inward": "is blocked by"}, "outwardIssue": {"key": "ABC-3"}} + relates = {"id": "4", "type": {"inward": "relates to"}, "inwardIssue": {"key": "ABC-4"}} + found = entry_of(raw(BLOCKED, outward, relates, properties={"plan": {"L": 2}}), "plan") + self.assertEqual(found, Entry("ABC-1", {"issuelinks": [BLOCKED, outward, relates]}, (Link("ABC-2", "9"),), {"L": 2})) + self.assertEqual(entry_of(raw(), "plan"), Entry("ABC-1", {"issuelinks": []}, (), {})) + + def test_an_entry_without_an_issue_key_is_a_failure(self): + for wrong in ([], {}, {"key": 7}, {"key": "abc"}): + with self.subTest(wrong=wrong): + self.assertEqual(entry_of(wrong, "plan"), Failure("the search answered an issue without an issue key")) + + def test_an_entry_in_another_shape_is_a_failure_naming_the_issue_and_the_field(self): + cases = { + "its fields are no object": {"key": "ABC-1"}, + "its properties are no object": raw(properties=[]), + "its issuelinks are no list": {"key": "ABC-1", "fields": {}}, + "its issuelinks hold a link that is no object": raw("link"), + "its issuelinks hold a link whose type names no inward text": raw(BLOCKED | {"type": None}), + "its issuelinks hold a link whose id or whose linked issue's key is no text": raw(BLOCKED | {"inwardIssue": {"key": 7}}), + } + for how, wrong in cases.items(): + with self.subTest(how=how): + self.assertEqual(entry_of(wrong, "plan"), Failure(SHAPE + how)) + self.assertEqual(entry_of(raw(BLOCKED | {"id": 9}), "plan"), Failure(SHAPE + "its issuelinks hold a link whose id or whose linked issue's key is no text")) + self.assertEqual(entry_of(raw(BLOCKED | {"inwardIssue": None}), "plan"), Failure(SHAPE + "its issuelinks hold a link whose id or whose linked issue's key is no text")) + + def test_a_fault_in_reading_the_links_is_not_reported_as_jiras(self): + class Faulty(dict): + def get(self, key, default=None): + raise TypeError("ours") + + with self.assertRaisesRegex(TypeError, "ours"): + entry_of({"key": "ABC-1", "fields": Faulty()}, "plan") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/branch_chunks/test_branch_chunks.py b/bin/branch_chunks/test_branch_chunks.py index e790d5ef..16aa0877 100644 --- a/bin/branch_chunks/test_branch_chunks.py +++ b/bin/branch_chunks/test_branch_chunks.py @@ -5,7 +5,6 @@ import subprocess import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -258,8 +257,7 @@ class BranchChunks(unittest.TestCase): def read(self, run=None, titles=BARE): """branch_chunks over main, run by git_repo's git, or else by run.""" - with unittest.mock.patch.dict(os.environ, self.env, clear=True): - return branch_chunks("main", functools.partial(run or git, cwd=str(self.checkout)), titles) + return branch_chunks("main", functools.partial(run or git, cwd=str(self.checkout)), titles) def fixing_history(self): """Merges seven chunks onto main, then checks out a branch off it. Returns each of main's chunks by label, with the chunks that fixed it. diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py index 2ba31dd8..e8837c80 100644 --- a/bin/chunk_driver/claims.py +++ b/bin/chunk_driver/claims.py @@ -1,12 +1,13 @@ """How entry points claim a checkout before they start a chunk in it, so that two never start the same chunk and do-epic never starts one where loop-claude runs. -An entry point holds `starting` on `project_lock` while it lists the windows of the checkout's chunks and starts new ones. It starts each chunk in a tmux window with CHUNK_FLAG, and hands that window the variables named with HANDED. +An entry point holds `starting` on `project_lock` while it lists the windows of the checkout's chunks and starts new ones. Where the lock cannot be taken, `starting` yields a Failure, and the entry point doesn't start any chunk. It starts each chunk in a tmux window with CHUNK_FLAG, and hands that window the variables named with HANDED. """ import contextlib import fcntl import pathlib import typing +from failure import Failure from transcript_archive.project_key import project_key from agent_cycle import tmux @@ -21,12 +22,28 @@ HANDED = "LOOP_CLAUDE_" @contextlib.contextmanager -def starting(folder: pathlib.Path) -> typing.Iterator[None]: - """Holds the LOCK in folder: project_lock's for a project, or do-epic's for an epic. Raises OSError where the file cannot be opened or locked.""" - folder.mkdir(parents=True, exist_ok=True) - with open(folder / LOCK, "a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - yield +def starting(folder: pathlib.Path) -> typing.Iterator[Failure | None]: + """Holds the LOCK in folder: project_lock's for a project, or do-epic's for an epic. It yields a Failure, and doesn't hold any lock, where the file cannot be opened or locked.""" + with locked(folder / LOCK) as failure: + yield failure + + +@contextlib.contextmanager +def locked(file: pathlib.Path) -> typing.Iterator[Failure | None]: + """Holds a flock on file, which it makes with its folder. It yields a Failure, and doesn't hold any lock, where the file cannot be opened or locked.""" + try: + file.parent.mkdir(parents=True, exist_ok=True) + lock = open(file, "a") + except OSError as failure: + yield Failure(f"cannot lock {failure.filename or file}: {failure.strerror}") + return + with lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX) + except OSError as failure: + yield Failure(f"cannot lock {file}: {failure.strerror}") + return + yield None def project_lock(root: str, home: pathlib.Path) -> pathlib.Path: diff --git a/bin/chunk_driver/project/model_choice.py b/bin/chunk_driver/project/model_choice.py index 5153c7f9..eedfb6b0 100644 --- a/bin/chunk_driver/project/model_choice.py +++ b/bin/chunk_driver/project/model_choice.py @@ -5,11 +5,11 @@ import sys import typing from claude_code.model_catalog import catalog_models +from chunk_driver.claims import CLAIMS, locked from loop_effects.effects import Effects, say from failure import Failure from agent_cycle.stop import needs_human, needs_terminal, Stop from loop_state.paths import Paths -from text_files.file_writes import replace_json @dataclasses.dataclass(frozen=True) @@ -21,6 +21,8 @@ class Models: # The environment variables that name the judge's and the worker's model for one run, over the model saved or configured. JUDGE_MODEL = "LOOP_CLAUDE_JUDGE_MODEL" WORKER_MODEL = "LOOP_CLAUDE_WORKER_MODEL" +# The file, in CLAIMS under the home folder, that save_model keeps locked with flock while it rereads and replaces the models file. The models file's own folder is a checkout of this setup, which takes no lock file. +MODELS_LOCK = "models.lock" def overridden(env: typing.Mapping[str, str], default: str) -> Models: @@ -48,18 +50,29 @@ def get_or_ask_model(project_key: str, paths: Paths, driver: str, effects: Effec chosen = ask_for_model(project_key, saved, paths.model_catalog, driver, effects) if isinstance(chosen, Stop): return chosen - # Reread: another loop may have saved its project while this one waited on the human. - models = read_models_file(saved) - if isinstance(models, Failure): - return Stop(1, models.reason) - if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True): - return Stop(1, f"could not save the model in {saved}: {failure.reason}") + if failure := save_model(project_key, chosen, paths, effects.replace_file): + return Stop(1, failure.reason) say(f"{project_key} runs on {chosen}", effects) return chosen +def save_model(project_key: str, chosen: str, paths: Paths, replace: typing.Callable[[pathlib.Path, bytes], Failure | None]) -> Failure | None: + """Adds the project's model to the models file, whose only writer this is, through replace, which writes a file as replace_file does. It holds MODELS_LOCK from its read to its write, so two drivers that save at once both keep their pick.""" + saved = paths.models_file + with locked(paths.home / CLAIMS / MODELS_LOCK) as unlocked: + if unlocked: + return Failure(f"could not save the model in {saved}: {unlocked.reason}") + # Read under the lock: another driver may have saved its project while this one waited on the human. + models = read_models_file(saved) + if isinstance(models, Failure): + return models + if failure := replace(saved, json.dumps({**models, project_key: chosen}, indent="\t", sort_keys=True).encode()): + return Failure(f"could not save the model in {saved}: {failure.reason}") + return None + + def read_models_file(saved: pathlib.Path) -> dict[str, str] | Failure: - """Each project's model, as the models file at saved maps them; none where there is no such file. loop-claude and the replay tools read it.""" + """Each project's model, as the models file at saved maps them; none where there is no such file. The chunk drivers and the replay tools read it, and only save_model writes it.""" try: with open(saved, encoding="utf-8") as handle: models = json.load(handle) diff --git a/bin/chunk_driver/project/test_model_choice.py b/bin/chunk_driver/project/test_model_choice.py index 356cb873..c7ea56c9 100644 --- a/bin/chunk_driver/project/test_model_choice.py +++ b/bin/chunk_driver/project/test_model_choice.py @@ -1,8 +1,10 @@ +import dataclasses +import fcntl +import json import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) @@ -10,6 +12,8 @@ from failure import Failure from loop_effects.doubles import FakeEffects from chunk_driver.drivers import LOOP_CLAUDE from chunk_driver.project import model_choice +from loop_state.paths import paths_from +from text_files.file_writes import replace_file from agent_cycle.stop import Stop @@ -20,6 +24,68 @@ class Overridden(unittest.TestCase): self.assertEqual(model_choice.overridden({"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}, "saved"), model_choice.Models("j", "w")) +class SavingAModel(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.paths = paths_from(pathlib.Path(temp.name)) + self.lock = self.paths.home / ".local/state/loop-claude/models.lock" + + def test_adds_the_projects_model_to_those_the_file_holds(self): + self.paths.models_file.parent.mkdir() + self.paths.models_file.write_text(json.dumps({"other": "model-x"})) + self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file)) + self.assertEqual(json.loads(self.paths.models_file.read_text()), {"other": "model-x", "proj": "model-b"}) + + def lock_is_held(self) -> bool: + with open(self.lock, "a") as other: + try: + fcntl.flock(other, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return True + return False + + def test_holds_the_models_lock_from_its_read_to_its_write(self): + self.paths.models_file.parent.mkdir() + held = [] + + class Watched(pathlib.PosixPath): + """The models file, which notes whether the lock is held each time it is opened.""" + + def __fspath__(watched) -> str: + held.append(self.lock_is_held()) + return super().__fspath__() + + def replace(path: pathlib.Path, data: bytes) -> None: + held.append(self.lock_is_held()) + + paths = dataclasses.replace(self.paths, models_file=Watched(self.paths.models_file)) + self.assertIsNone(model_choice.save_model("proj", "model-b", paths, replace)) + self.assertEqual(held, [True, True]) + self.assertFalse(self.lock_is_held()) + + def test_doesnt_save_anything_where_it_cannot_take_the_lock(self): + self.paths.models_file.parent.mkdir() + self.lock.parent.parent.mkdir(parents=True) + self.lock.parent.write_text("") + saved = model_choice.save_model("proj", "model-b", self.paths, replace_file) + assert isinstance(saved, Failure) + self.assertRegex(saved.reason, f"^could not save the model in {self.paths.models_file}: cannot lock {self.lock.parent}: \\w") + self.assertFalse(self.paths.models_file.exists()) + + def test_a_pick_is_saved_through_save_model_alone(self): + self.paths.models_file.parent.mkdir() + fake, held = FakeEffects(inputs=["my-model"]), [] + + def replace(path: pathlib.Path, data: bytes) -> Failure: + held.append(self.lock_is_held()) + return Failure("could not save") + + fake.replace_file = replace + self.assertEqual(model_choice.get_or_ask_model("proj", self.paths, LOOP_CLAUDE, fake.effects()), Stop(1, f"could not save the model in {self.paths.models_file}: could not save")) + self.assertEqual(held, [True]) + + class ModelPrompt(unittest.TestCase): OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")] diff --git a/bin/chunk_driver/project/test_records.py b/bin/chunk_driver/project/test_records.py index bafe0a2d..be0f4590 100644 --- a/bin/chunk_driver/project/test_records.py +++ b/bin/chunk_driver/project/test_records.py @@ -2,7 +2,6 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) diff --git a/bin/chunk_driver/test_chunk_run.py b/bin/chunk_driver/test_chunk_run.py index 1122a68e..1479dd10 100644 --- a/bin/chunk_driver/test_chunk_run.py +++ b/bin/chunk_driver/test_chunk_run.py @@ -16,6 +16,7 @@ from agent_cycle.verdicts import Finished, TakenIn, Unfinished from transcript_archive import outcomes, write from model_routing.ladder import ProjectRung, Rung from model_routing.ladder_file import read_ladder, SHIPPED +from text_files.file_writes import replace_file from model_routing.route import Route from agent_cycle import run from claude_code import session @@ -59,7 +60,7 @@ class Steps(unittest.TestCase): transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") before = Route(self.FABLE_LOW, 3, 3, 4) with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW, replace=replace_file)) after = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) with contextlib.redirect_stderr(io.StringIO()): @@ -79,6 +80,6 @@ class Steps(unittest.TestCase): transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") before = Route(self.FABLE_LOW, 3, 3, 4) with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW, replace=replace_file)) chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6)) diff --git a/bin/chunk_driver/test_claims.py b/bin/chunk_driver/test_claims.py new file mode 100644 index 00000000..9ccb694d --- /dev/null +++ b/bin/chunk_driver/test_claims.py @@ -0,0 +1,41 @@ +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from chunk_driver.claims import LOCK, starting + + +class Starting(unittest.TestCase): + def setUp(self) -> None: + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.folder = pathlib.Path(temp.name) + + def test_yields_none_while_it_holds_the_lock_in_a_folder_it_makes(self) -> None: + with starting(self.folder / "state" / "proj") as failure: + self.assertIsNone(failure) + self.assertTrue((self.folder / "state" / "proj" / LOCK).is_file()) + + def test_yields_a_failure_naming_the_path_it_could_not_make(self) -> None: + (self.folder / "state").write_text("", encoding="utf-8") + with starting(self.folder / "state") as failure: + assert isinstance(failure, Failure) + self.assertRegex(failure.reason, f"^cannot lock {self.folder}/state: \\w") + + def test_yields_a_failure_naming_the_lock_it_could_not_open(self) -> None: + (self.folder / LOCK).mkdir() + with starting(self.folder) as failure: + assert isinstance(failure, Failure) + self.assertRegex(failure.reason, f"^cannot lock {self.folder}/{LOCK}: \\w") + + def test_an_error_raised_while_the_lock_is_held_is_the_callers(self) -> None: + with self.assertRaises(OSError), starting(self.folder): + raise OSError("not the lock's") + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/chunk_driver/test_cycle_start.py b/bin/chunk_driver/test_cycle_start.py index 3a4ad967..0358d9f0 100644 --- a/bin/chunk_driver/test_cycle_start.py +++ b/bin/chunk_driver/test_cycle_start.py @@ -1,4 +1,5 @@ import contextlib +import functools import io import json import os @@ -7,7 +8,6 @@ import sys import tempfile import types import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -15,10 +15,11 @@ from chunk_driver.doubles import a_loop from chunk_driver import cycle_start from failure import Failure from loop_effects.doubles import FakeEffects, NOW, STAMP -from git_cli.git_repo import git +from git_cli import git_repo from transcript_archive import outcomes, write from model_routing.ladder import ProjectRung, Rung from model_routing.ladder_file import read_ladder, SHIPPED +from text_files.file_writes import replace_file from model_routing.route import Route, WorkerLine from claude_code import session @@ -28,19 +29,18 @@ OPUS_PROJECT = ProjectRung(read_ladder(SHIPPED), Rung("claude-opus-5-5", "medium class SetupVersion(unittest.TestCase): def test_names_the_release_and_the_commit_or_why_git_cannot_tell(self): with tempfile.TemporaryDirectory() as root: - isolated = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root} - with unittest.mock.patch.dict(os.environ, isolated): - gone = cycle_start.setup_version(pathlib.Path(root), git) - self.assertRegex(gone, r"^unknown: [^\n]*not a git repository") - for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]): - self.assertIsInstance(git(*step, cwd=root), str) - head = git("rev-parse", "HEAD", cwd=root).strip() - self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})") - git("tag", "v0.1.0", cwd=root) - self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})") - git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root) - head = git("rev-parse", "HEAD", cwd=root).strip() - self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})") + git = functools.partial(git_repo.git, env={**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root}) + gone = cycle_start.setup_version(pathlib.Path(root), git) + self.assertRegex(gone, r"^unknown: [^\n]*not a git repository") + for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]): + self.assertIsInstance(git(*step, cwd=root), str) + head = git("rev-parse", "HEAD", cwd=root).strip() + self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})") + git("tag", "v0.1.0", cwd=root) + self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})") + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root) + head = git("rev-parse", "HEAD", cwd=root).strip() + self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})") def test_names_why_git_cannot_name_the_commit_on_one_line(self): def fake_git(*args, cwd=None): @@ -79,12 +79,12 @@ class Routes(unittest.TestCase): transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW)) + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW, replace=replace_file)) with contextlib.redirect_stderr(stderr): self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), route) self.assertEqual(stderr.getvalue(), "") with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1)) + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1, replace=replace_file)) with contextlib.redirect_stderr(io.StringIO()) as stderr: self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened))) self.assertEqual(stderr.getvalue(), f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route that can be read: {{"model": "claude-opus-5-5", "rung": 3}}\n') diff --git a/bin/chunk_pr/approval.py b/bin/chunk_pr/approval.py index 2e6fa2d8..d143f1f9 100644 --- a/bin/chunk_pr/approval.py +++ b/bin/chunk_pr/approval.py @@ -1,5 +1,4 @@ """The human approval that `chunk-pr merge` waits for where the project's config sets `wait-for-approval`.""" -import time import typing from forge.reviews import APPROVED, CHANGES_REQUESTED, github_decision, REVIEW_REQUIRED, waiting_threads @@ -34,7 +33,7 @@ def approval(number: str, run: Run) -> bool | Failure: return decision == APPROVED -def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None: +def approved(number: str, run: Run, sleep: typing.Callable[[float], None]) -> Failure | None: """None once GitHub reports pull request number approved; a Failure where `approval` fails, where a reviewer's comment waits for an answer, or where no approval came within WAIT_SECONDS.""" for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS): read = approval(number, run) diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 158011d7..3601d624 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -139,7 +139,7 @@ def step(argv: list[str], run: Run, config: Config, parks: bool = False) -> str return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None) case ["merge", *given]: finishes = finishes_of(given) - return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes, parks=parks) + return Failure(USAGE) if finishes is None else merged(run, config, time.sleep, finishes=finishes, parks=parks) case ["clean"]: return cleaned(run) return Failure(USAGE) @@ -305,7 +305,7 @@ def finishes_of(given: list[str]) -> list[list[str]] | None: return finishes -def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = (), parks: bool = False) -> str | Failure: +def merged(run: Run, config: Config, sleep: typing.Callable[[float], None], finishes: typing.Sequence[list[str]] = (), parks: bool = False) -> str | Failure: """Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved. Where parks, it doesn't wait for the approval: it fails at once, as `left_to_park` says.""" found = pull(run) if isinstance(found, Failure): diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index 6fdfb43d..b4d678e3 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -603,7 +603,7 @@ class MergeQueue(unittest.TestCase): def test_a_branch_behind_the_default_branch_merges_it_in_and_pushes_before_the_checks(self): checkout = self.moved(Checkout(GITHUB, open=True)) - self.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None), "Merged pull request #12 (merge).") self.assertEqual(changes(checkout), [MERGE, self.PUSHED, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "decaf"]]) self.assertLess(checkout.ran.index(self.PUSHED), checkout.ran.index(GH_CHECKS)) @@ -611,7 +611,7 @@ class MergeQueue(unittest.TestCase): checkout = self.moved(Checkout(GITHUB, open=True)) checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT") checkout.answers[("git", "diff", "--name-only", "--diff-filter=U")] = "bin/tool.py\n" - failed = merged(checkout.__call__, checkout.config) + failed = merged(checkout.__call__, checkout.config, lambda seconds: None) self.assertIsInstance(failed, Failure) self.assertIn("conflicts in bin/tool.py; the merge stays in progress: resolve them, commit, push, and run chunk-pr merge again", failed.reason) self.assertEqual((changes(checkout), MERGE in checkout.ran), ([], True)) @@ -620,7 +620,7 @@ class MergeQueue(unittest.TestCase): def test_a_finished_item_is_committed_under_the_configs_title_and_pushed_before_the_merge(self): checkout, folder = self.with_plan(Checkout(GITHUB, open=True)) files = [f"{folder}/todo.md", f"{folder}/CHANGELOG.md"] - self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).") self.assertEqual(changes(checkout)[:1], [[self.TODO_ITEM, "finish", "7", "--changelog", "Exports keep their order."]]) self.assertEqual(changes(checkout)[-4:], [ ["git", "-C", folder, "add", "--", *files], @@ -637,7 +637,7 @@ class MergeQueue(unittest.TestCase): def test_an_item_the_plan_no_longer_holds_is_named_on_the_last_line_and_what_an_earlier_run_left_uncommitted_is_committed(self): checkout, folder = self.with_plan(Checkout(GITHUB, open=True), held=False) - self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.") + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.") self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran) self.assertEqual([command[3] for command in changes(checkout)[:-1]], ["add", "commit", "origin"]) self.assertEqual(changes(checkout)[-1], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"]) @@ -645,7 +645,7 @@ class MergeQueue(unittest.TestCase): def test_each_item_the_plan_no_longer_holds_is_named(self): checkout, _ = self.with_plan(Checkout(GITHUB, open=True), held=False) checkout.answers[(self.TODO_ITEM, "show", "8")] = Failure("todo-item show 8: todo.md holds no item 8") - self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, checkout.config, finishes=[["7"], ["8"]]))) + self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7"], ["8"]]))) def test_a_plan_that_turns_unreadable_inside_the_turn_leaves_it_unmerged(self): checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) @@ -653,7 +653,7 @@ class MergeQueue(unittest.TestCase): def run_whose_second_show_fails(command: list[str]) -> str | Failure: shows.extend([command] if command[1:2] == ["show"] else []) return Failure("todo-item show 7: unreadable") if command[1:2] == ["show"] and len(shows) == 2 else run(command) - self.assertEqual(merged(run_whose_second_show_fails, checkout.config, finishes=[["7"]]), Failure("todo-item show 7: unreadable")) + self.assertEqual(merged(run_whose_second_show_fails, checkout.config, lambda seconds: None, finishes=[["7"]]), Failure("todo-item show 7: unreadable")) self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran) def test_a_finish_that_changes_no_file_commits_and_pushes_nothing(self): @@ -664,13 +664,13 @@ class MergeQueue(unittest.TestCase): checkout.answers[("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md")] = "\n" else: checkout.answers.update({(self.CONFIG, "plan"): "PAY-1\n", (self.CONFIG, "changelog"): f"{folder}/none.md\n"}) - self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).") self.assertEqual(changes(checkout), [[self.TODO_ITEM, "finish", "7", "--no-changelog"], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) def test_a_branch_outside_the_branch_template_titles_the_finish_with_the_summary_alone(self): checkout, folder = self.with_plan(Checkout(GITHUB, open=True)) checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n" - merged(checkout.__call__, checkout.config, finishes=[["7"]]) + merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7"]]) self.assertIn("Finish item 7 in the plan", [command[6] for command in checkout.ran if command[3:4] == ["commit"]]) def test_a_plan_it_cannot_read_or_an_item_it_cannot_finish_leaves_it_unmerged(self): @@ -678,7 +678,7 @@ class MergeQueue(unittest.TestCase): with self.subTest(failing): checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) checkout.answers[(self.TODO_ITEM, failing, "7")] = Failure(f"todo-item {failing} 7: no config names the checkout") - self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout")) + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout")) self.assertNotIn(self.PUSHED, checkout.ran) def test_a_step_of_the_turn_that_fails_leaves_it_unmerged_with_that_failure(self): @@ -690,23 +690,23 @@ class MergeQueue(unittest.TestCase): def failing_run(command: list[str]) -> str | Failure: asked = ["" if part == folder else part for part in command] return Failure("that step failed") if tuple(asked[:len(failing)]) == tuple(failing) else run(command) - self.assertEqual(merged(failing_run, checkout.config, finishes=[["7"]]), Failure("that step failed")) + self.assertEqual(merged(failing_run, checkout.config, lambda seconds: None, finishes=[["7"]]), Failure("that step failed")) self.assertNotIn("merge", [command[2] for command in checkout.ran if command[0] == "gh"]) def test_a_finish_that_fails_after_the_default_branch_was_merged_in_still_pushes_the_branch(self): checkout, _ = self.with_plan(self.moved(Checkout(GITHUB, open=True))) checkout.answers[(self.TODO_ITEM, "finish", "7")] = Failure("todo-item finish 7: a decision cites item 7") - self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7")) + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7")) self.assertEqual(changes(checkout), [MERGE, self.PUSHED]) def test_the_scoring_run_is_asked_for_once_the_finish_is_committed_and_one_owed_leaves_it_unmerged(self): checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) commit = lambda: next(index for index, command in enumerate(checkout.ran) if command[3:4] == ["commit"]) - self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7"]]), "Merged pull request #12 (merge).") self.assertLess(commit(), checkout.ran.index(OWED)) checkout, _ = self.with_plan(Checkout(GITHUB, open=True)) checkout.answers[tuple(OWED)] = Failure("the chunk owes 1 scoring run") - self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("the chunk owes 1 scoring run")) + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None, finishes=[["7"]]), Failure("the chunk owes 1 scoring run")) self.assertEqual(changes(checkout)[-1], self.PUSHED) def test_a_merge_holds_the_queue_through_the_checks_and_frees_it_while_it_waits_for_an_approval(self): @@ -740,7 +740,7 @@ class MergeQueue(unittest.TestCase): checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(WAITS)] = "true\n" checkout.threads = [self.thread("bin/asked.py", "reviewer")] - failed = merged(checkout, checkout.config) + failed = merged(checkout, checkout.config, lambda seconds: None) self.assertIsInstance(failed, Failure) self.assertIn("waits for an answer, in bin/asked.py;", failed.reason) self.assertEqual(changes(checkout), []) @@ -766,7 +766,7 @@ class MergeQueue(unittest.TestCase): with self.subTest(name): checkout = Checkout(GITHUB, open=True) checkout.answers.update({(self.CONFIG, "comprehension-history"): f"{history}\n", **answers}) - done = merged(checkout.__call__, checkout.config) + done = merged(checkout.__call__, checkout.config, lambda seconds: None) self.assertEqual(isinstance(done, Failure) and "run the paired ruling again" in done.reason, stops, done) self.assertEqual(changes(checkout), [] if stops else [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]]) @@ -774,14 +774,14 @@ class MergeQueue(unittest.TestCase): ruled = ("git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", "/checkout/history.md") checkout = Checkout(GITHUB, open=True) checkout.answers[(self.CONFIG, "comprehension-history")] = "/elsewhere/history.md\n" - self.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).") + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None), "Merged pull request #12 (merge).") self.assertNotIn("log", [command[1] for command in checkout.ran]) for failing in (ruled, ("git", "rev-list", "--count", "bead..origin/main"), ("git", "rev-parse", "--show-toplevel")): with self.subTest(failing): checkout = Checkout(GITHUB, open=True) checkout.answers.update({(self.CONFIG, "comprehension-history"): "/checkout/history.md\n", ruled: "bead\n"}) checkout.answers[failing] = Failure("git failed") - self.assertEqual(merged(checkout.__call__, checkout.config), Failure("git failed")) + self.assertEqual(merged(checkout.__call__, checkout.config, lambda seconds: None), Failure("git failed")) def test_a_turn_keeps_every_other_merge_out_until_it_ends_even_by_an_error(self): with self.assertRaises(ValueError): @@ -809,7 +809,7 @@ class MergeQueue(unittest.TestCase): def test_a_queue_it_cannot_open_leaves_it_unmerged(self): checkout = Checkout(GITHUB, open=True) checkout.answers[tuple(COMMON)] = "/nonexistent/folder\n" - self.assertEqual(merged(checkout, checkout.config), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory")) + self.assertEqual(merged(checkout, checkout.config, lambda seconds: None), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory")) self.assertEqual(checkout.acted(), []) diff --git a/bin/compress-archives b/bin/compress-archives index 77a2684f..c7b02cc6 100755 --- a/bin/compress-archives +++ b/bin/compress-archives @@ -1,9 +1,15 @@ #!/usr/bin/env python3 +import functools +import gzip +import os import pathlib import sys +import time sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from compress_archives import main +from text_files.compressed import compress +from text_files.file_writes import replace_file -sys.exit(main.main(sys.argv[1:])) +sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), time.time, functools.partial(compress, pack=gzip.compress, replace=replace_file, sync=os.fsync))) diff --git a/bin/compress_archives/main.py b/bin/compress_archives/main.py index 4c61829f..38ba0205 100644 --- a/bin/compress_archives/main.py +++ b/bin/compress_archives/main.py @@ -14,31 +14,28 @@ its plain name. README.md → Install has the crontab line that runs it daily. It prints how many files it compressed. It exits 1, saying why, on any argument but --help or -h, and at the first file it cannot compress, leaving that file and every one after it plain. """ -import os import pathlib import stat import sys -import time import typing from transcript_archive.location import archive_root -from text_files.compressed import compress, SUFFIX from failure import Failure from review_rules.review_folder import REPORTS +from text_files.compressed import SUFFIX # Why 30 days: docs/decisions.md → `archives: gzip each transcript in loop-claude's archive and each file in the review folders 30 days after it last changed, keeping all of them`. AGE_DAYS = 30 -def main(argv: list[str], env: typing.Mapping[str, str] = os.environ, home: pathlib.Path | None = None, now: float | None = None) -> int: +def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, now: typing.Callable[[], float], compress: typing.Callable[[pathlib.Path], Failure | None]) -> int: if argv in (["-h"], ["--help"]): print(__doc__.strip()) return 0 if argv: print(f"unknown arguments {' '.join(argv)}; usage: compress-archives", file=sys.stderr) return 1 - home = home or pathlib.Path.home() - cutoff = (time.time() if now is None else now) - AGE_DAYS * 24 * 60 * 60 + cutoff = now() - AGE_DAYS * 24 * 60 * 60 count = 0 for path in [*old_files(archive_root(home, env), "*.jsonl", cutoff), *old_files(home / REPORTS, "*", cutoff)]: if failed := compress(path): diff --git a/bin/compress_archives/test_compress_archives.py b/bin/compress_archives/test_compress_archives.py index 83a0fdc1..0ee88655 100644 --- a/bin/compress_archives/test_compress_archives.py +++ b/bin/compress_archives/test_compress_archives.py @@ -11,6 +11,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from text_files.doubles import compress from failure import Failure from compress_archives import main @@ -43,10 +44,10 @@ class Main(unittest.TestCase): path.write_bytes(f"{path.name}\n".encode()) os.utime(path, (NOW - seconds_ago, NOW - seconds_ago)) - def run_main(self, argv=(), env=None, now=NOW): + def run_main(self, argv=(), env=None, now=NOW, compress=compress): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main(list(argv), env or {}, self.home, now) + code = main.main(list(argv), env or {}, self.home, lambda: now, compress) return code, out.getvalue(), err.getvalue() def kept(self): @@ -80,9 +81,8 @@ class Main(unittest.TestCase): self.assertEqual(self.run_main(now=now), (0, "Compressed 0 files.\n", "")) self.assertTrue((self.archive / "a.jsonl").is_file()) - def test_measures_the_30_days_from_the_clock_by_default(self): - with mock.patch.object(main.time, "time", return_value=NOW): - self.assertEqual(self.run_main(now=None), (0, "Compressed 4 files.\n", "")) + def test_measures_the_30_days_from_the_clock_it_is_given(self): + self.assertEqual(self.run_main(now=NOW), (0, "Compressed 4 files.\n", "")) def test_walks_on_past_a_gzip_a_link_and_a_file_removed_while_it_walks(self): gone = mock.Mock(**{"is_symlink.return_value": False, "stat.side_effect": FileNotFoundError}) @@ -109,8 +109,7 @@ class Main(unittest.TestCase): self.assertEqual(self.run_main(), (0, "Compressed 0 files.\n", "")) def test_stops_at_the_first_failure_keeping_that_file_and_every_later_one(self): - with mock.patch.object(main, "compress", return_value=Failure("could not compress x: full")): - code, out, err = self.run_main() + code, out, err = self.run_main(compress=lambda path: Failure("could not compress x: full")) self.assertEqual((code, out, err), (1, "", "could not compress x: full\n")) self.assertTrue((self.archive / "a.jsonl").is_file()) diff --git a/bin/deploy_release/cut.py b/bin/deploy_release/cut.py index b764bfbd..9245079b 100644 --- a/bin/deploy_release/cut.py +++ b/bin/deploy_release/cut.py @@ -6,6 +6,7 @@ import pathlib import shutil import sys import tempfile +import typing from release_plan.release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned from project_config.settings import DEFAULT_FLOOR @@ -21,7 +22,7 @@ from deploy_release import release_pull from project_config import templates -def cut(clone: str, checkout: str) -> str | Failure: +def cut(clone: str, checkout: str, sleep: typing.Callable[[float], None]) -> str | Failure: """What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped.""" if isinstance(same := same_origin(clone, checkout), Failure): return same @@ -39,7 +40,7 @@ def cut(clone: str, checkout: str) -> str | Failure: title, tag = f"Cut release {named}", f"v{named}" merged = commit_titled(title, ref, clone) if merged is None: - landed = land(clone, ref, named, title) + landed = land(clone, ref, named, title, sleep) if isinstance(landed, Failure): return landed if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure): @@ -149,7 +150,7 @@ def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure: return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None) -def land(clone: str, ref: str, named: str, title: str) -> Failure | None: +def land(clone: str, ref: str, named: str, title: str, sleep: typing.Callable[[float], None]) -> Failure | None: """Push the branch release- with the cut commit and open its pull request, where an earlier run hasn't; then wait for its checks and merge it.""" url = git("config", "--get", "remote.origin.url", cwd=clone) if isinstance(url, Failure): @@ -182,7 +183,7 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None: if isinstance(required, Failure): return required said(f"waiting for the checks of pull request {number}" + (f"; {base} requires {', '.join(sorted(required))}" if required else "")) - if isinstance(passed := pulls.checks_passed(on, number, head, required, run), Failure): + if isinstance(passed := pulls.checks_passed(on, number, head, required, run, sleep), Failure): return passed said(f"the checks of pull request {number} passed") if isinstance(merged := release_pull.merge(on, number, head, run), Failure): diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index 2742fc9f..c9a827e5 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -39,6 +39,7 @@ move stopped, fix what it names and run a bare deploy-release. import os import pathlib import sys +import time from deploy_release.cut import cut from deploy_release.deploy import deploy @@ -55,7 +56,7 @@ def main(argv: list[str]) -> int: print("deploy-release: usage: deploy-release [--cut] []", file=sys.stderr) return 1 checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude") - moved = cut(os.getcwd(), checkout) if cutting else deploy(checkout) + moved = cut(os.getcwd(), checkout, time.sleep) if cutting else deploy(checkout) if isinstance(moved, Failure): print(f"deploy-release: {moved.reason}", file=sys.stderr) return 1 diff --git a/bin/do-epic b/bin/do-epic index 9f0a3e71..0e812de1 100755 --- a/bin/do-epic +++ b/bin/do-epic @@ -10,4 +10,4 @@ from loop_effects import effects from do_epic import main from loop_state import paths -sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, effects.system_effects())) +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, effects.system_effects(pathlib.Path.home(), os.environ))) diff --git a/bin/do-epic-e2e b/bin/do-epic-e2e index 01856292..16db3ad8 100755 --- a/bin/do-epic-e2e +++ b/bin/do-epic-e2e @@ -6,6 +6,6 @@ import sys LAUNCHER = pathlib.Path(__file__).resolve() sys.path.insert(0, str(LAUNCHER.parent)) -from do_epic.e2e import main +from do_epic.e2e import main, sandbox, scenario -sys.exit(main.main(sys.argv[1:], os.environ, LAUNCHER.parent / "do-epic")) +sys.exit(main.main(sys.argv[1:], os.environ, LAUNCHER.parent / "do-epic", sandbox.epic_made, scenario.run)) diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 257d07d4..1d49e1ed 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -5,7 +5,7 @@ import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown -from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped +from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure @@ -33,6 +33,8 @@ class JiraEpic: to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf finish: Finish | None = None + # The pages a search may take before the read fails. + max_pages: int = MAX_PAGES @property def epic_key(self) -> str: @@ -223,7 +225,7 @@ class JiraEpic: def searched(self, what: str, parents: tuple[str, ...], authorization: str) -> list[Found] | Failure: """The issues whose parent is one of parents, in rank order.""" named = ", ".join(f'"{key}"' for key in parents) - answered = searched(self.epic.site, what, f"parent in ({named}) ORDER BY Rank ASC", {"fields": FIELDS, "properties": [PROPERTY]}, authorization, self.http) + answered = searched(self.epic.site, what, f"parent in ({named}) ORDER BY Rank ASC", {"fields": FIELDS, "properties": [PROPERTY]}, authorization, self.http, self.max_pages) if isinstance(answered, Failure): return answered found = [found_of(raw) for raw in answered] diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index d8e7b8b5..e516ab8a 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -5,7 +5,6 @@ import re import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) @@ -329,12 +328,13 @@ class Jira(Case): ({"key": "abc-34", "fields": valid}, "the search answered an issue without an issue key"), ({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}, "issuelinks": []}}, shape + ": KeyError('labels')"), *((({"key": "ABC-34", "fields": valid | changed}, shape + ": its summary, labels, assignee, status, parent, description or a linked issue's key holds another kind of value") for changed in ( - {"summary": 3}, {"labels": "api"}, {"labels": [3]}, {"assignee": {"displayName": 0}}, {"status": {"name": 0, "statusCategory": {"key": "new"}}}, {"parent": {"key": "ABC"}}, {"parent": {"key": 12}}, {"description": "text"}, {"issuelinks": [linked | {"inwardIssue": {"key": 7}}]}, {"issuelinks": [linked | {"inwardIssue": {"key": "ABC-x"}}]}, + {"summary": 3}, {"labels": "api"}, {"labels": [3]}, {"assignee": {"displayName": 0}}, {"status": {"name": 0, "statusCategory": {"key": "new"}}}, {"parent": {"key": "ABC"}}, {"parent": {"key": 12}}, {"description": "text"}, {"issuelinks": [linked | {"inwardIssue": {"key": "ABC-x"}}]}, ))), - ({"key": "ABC-34", "fields": {key: value for key, value in valid.items() if key != "issuelinks"}}, shape + ": KeyError('issuelinks')"), + ({"key": "ABC-34", "fields": {key: value for key, value in valid.items() if key != "issuelinks"}}, shape + ": its issuelinks are no list"), ({"key": "ABC-34", "fields": valid, "properties": {"plan-item": "L 2"}}, "ABC-34's issue property plan-item is not a JSON object"), ({"key": "ABC-34", "fields": valid, "properties": {"plan-item": {"L": "many"}}}, "item ABC-34's L 'many' is not a whole number from 1 to 4; ABC-34 holds it in its issue property plan-item"), - ({"key": "ABC-34", "fields": valid, "properties": None}, shape + ": AttributeError(\"'NoneType' object has no attribute 'get'\")"), + ({"key": "ABC-34", "fields": valid, "properties": None}, shape + ": its properties are no object"), + ({"key": "ABC-34", "fields": valid | {"issuelinks": [linked | {"inwardIssue": {"key": 7}}]}}, shape + ": its issuelinks hold a link whose id or whose linked issue's key is no text"), ): with self.subTest(raw=raw): self.jira.answers[("POST", SEARCH)] = {"issues": [raw]} @@ -347,14 +347,13 @@ class Jira(Case): self.assertEqual(JiraEpic(EPIC, self.env_file, self.jira, lambda documents: converted, to_adf).read(), Failure(reason)) def test_a_search_that_does_not_end_names_the_issues_it_sought(self) -> None: - store = self.new_store() + store = dataclasses.replace(self.new_store(), max_pages=1) children = [store.file("ABC-12", "Count the runs.", "", ()) for _ in range(2)] for _ in range(3): store.file(str(children[0]), "A task.", "", ()) - with unittest.mock.patch("atlassian.jira.MAX_PAGES", 1): - self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages")) - store.file("ABC-12", "Count the runs.", "", ()) - self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages")) + self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages")) + store.file("ABC-12", "Count the runs.", "", ()) + self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages")) def test_refuses_to_file_under_another_epics_child_or_an_issue_it_cannot_read(self) -> None: self.jira.issues.append({"key": "ABC-5", "fields": {"parent": {"key": "ABC-1"}, "status": TO_DO}}) diff --git a/bin/do_epic/e2e/main.py b/bin/do_epic/e2e/main.py index 1f568252..2d7592a1 100644 --- a/bin/do_epic/e2e/main.py +++ b/bin/do_epic/e2e/main.py @@ -13,8 +13,12 @@ It reads three environment variables and fails, naming each that is missing: {chr(10).join(f' {name}: {meaning}' for name, meaning in settings.MEANING.items())} It prints a line per check, and exits 0 only where every check held.""" +EpicMade = typing.Callable[[settings.Sandbox, str], typing.ContextManager[str | Failure]] +Run = typing.Callable[[settings.Sandbox, str, pathlib.Path, typing.Mapping[str, str]], scenario.Report] -def main(argv: list[str], env: typing.Mapping[str, str], launcher: pathlib.Path) -> int: + +def main(argv: list[str], env: typing.Mapping[str, str], launcher: pathlib.Path, epic_made: EpicMade, run: Run) -> int: + """Runs do-epic-e2e: epic_made makes the sandbox epic, as sandbox.epic_made does, and run drives do-epic against it, as scenario.run does.""" if argv: print(HELP, file=sys.stdout if argv in (["-h"], ["--help"]) else sys.stderr) return 0 if argv in (["-h"], ["--help"]) else 1 @@ -25,12 +29,12 @@ def main(argv: list[str], env: typing.Mapping[str, str], launcher: pathlib.Path) report = scenario.Report() left: sandbox.Leftover | None = None try: - with sandbox.epic_made(found, "do-epic e2e sandbox epic") as key: + with epic_made(found, "do-epic e2e sandbox epic") as key: if isinstance(key, Failure): print(f"do-epic-e2e: {key.reason}", file=sys.stderr) return 1 print(f"Sandbox epic {key} in {found.jira_url}") - report = scenario.run(found, key, launcher, env) + report = run(found, key, launcher, env) except sandbox.Leftover as failure: left = failure # The checks are printed even where the epic could not be deleted. diff --git a/bin/do_epic/e2e/test_main.py b/bin/do_epic/e2e/test_main.py index 4cd12dcf..e047b32b 100644 --- a/bin/do_epic/e2e/test_main.py +++ b/bin/do_epic/e2e/test_main.py @@ -1,6 +1,5 @@ import contextlib import io -from unittest import mock import pathlib import sys import tempfile @@ -18,7 +17,7 @@ class MainTest(unittest.TestCase): def run_main(self, argv: list[str]) -> tuple[int, str, str]: out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main(argv, {}, pathlib.Path("do-epic")) + code = main.main(argv, {}, pathlib.Path("do-epic"), sandbox.epic_made, scenario.run) return code, out.getvalue(), err.getvalue() def test_fails_naming_each_missing_setting_before_it_touches_anything(self) -> None: @@ -56,10 +55,14 @@ class ReportedTest(unittest.TestCase): out, err = io.StringIO(), io.StringIO() report = report or scenario.Report(["a check held"], ["a check broke"]) - with mock.patch.object(sandbox, "epic_made", epic_made), mock.patch.object(scenario, "run", return_value=report) as ran: - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main([], self.env, pathlib.Path("do-epic")) - self.ran_with = ran.call_args.args if ran.called else None + self.ran_with = None + + def ran(*args: object) -> scenario.Report: + self.ran_with = args + return report + + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = main.main([], self.env, pathlib.Path("do-epic"), epic_made, ran) return code, out.getvalue(), err.getvalue() def test_prints_each_check_and_fails_where_one_broke(self) -> None: diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index adda3270..f7f21ef9 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -251,6 +251,8 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: if isinstance(place, Stop): return place root, repo = place + if unmade := folder_made(root): + return Stop(1, unmade.reason) session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts) loop = Loop(root=root, session=session, window=tmux.Window(epic.session, key, pane), paths=epic.paths, env=epic.env, launcher=epic.launcher, effects=epic.effects) run = ChunkRun() @@ -263,6 +265,9 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: cycle = next_cycle(run, loop, repo is not None, epic, news) if isinstance(cycle, Stop): return cycle + if isinstance(cycle, EpicReopened): + say(f"the epic {epic.key} holds an open issue again, so its finishing chunk ends until none is open", epic.effects, stdout=True) + return handed_on(key, epic) run = dataclasses.replace(run, task=cycle.task) concluded = run_cycle(cycle) if isinstance(concluded, Stop): @@ -355,15 +360,22 @@ def chunk_root(key: str, issue: EpicIssue | None, epic: EpicRun) -> tuple[str, s if isinstance(pick, Failure): return Stop(1, pick.reason) if isinstance(pick, ClaudeWork): - folder = epic.paths.home / scheduler.STATE / epic.key - folder.mkdir(parents=True, exist_ok=True) - return str(folder), None + return str(epic.paths.home / scheduler.STATE / epic.key), None if not isinstance(pick, Repo): return Stop(1, f"{key} is no chunk: no label names its repo") found = locate(pick.name, [], epic.config, epic.paths.home, epic.effects.git) return Stop(1, found.reason) if isinstance(found, Failure) else (str(real(found.checkout)), pick.name) +def folder_made(root: str) -> Failure | None: + """Makes the folder a chunk works in where it is missing, as the epic's folder is before its first chunk without a repo.""" + try: + pathlib.Path(root).mkdir(parents=True, exist_ok=True) + except OSError as failure: + return Failure(f"could not make the chunk's folder {root}: {failure.strerror}") + return None + + def handed_on(key: str, epic: EpicRun) -> Stop: """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Its window closes as it exits.""" # The epic's finishing has no issue to move: the epic is closed by `--close-epic`. @@ -396,8 +408,8 @@ def split_items_closed(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue return issues -def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: str = "") -> Cycle | Stop: - """The cycle run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder.""" +def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: str = "") -> Cycle | EpicReopened | Stop: + """The cycle run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read, and EpicReopened where the epic's finishing has no cycle to run. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder.""" premises = premises_read(loop.root if in_repo else None, epic) if isinstance(premises, Failure): return Stop(1, premises.reason) @@ -408,7 +420,7 @@ def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: st if isinstance(records, Failure): return Stop(1, records.reason) work = chunk_work(loop.window.name, loop.root if in_repo else None, language or epic.config.language, epic) - if isinstance(work, Stop): + if isinstance(work, (Stop, EpicReopened)): return work task, issue = work routing = project_routing(loop, chunk_prompt.DRIVER) if in_repo else routing_on(repoless_models(epic), SHIPPED) @@ -420,8 +432,13 @@ def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: st return cycle_of(loop, routing, route, archive_folder, task=task, facts="", premises=premises, records=records, unfinished_evidence=run.unfinished_evidence, prompts=prompts, taken_in=lambda entries: TakenIn()) -def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> tuple[str, RoutingIssue | None] | Stop: - """The task of the chunk called key, and the issue that routes it, or None where that issue has no scores: both from the epic's issues, read afresh. The epic's finishing has no issue, and it ends here once the epic holds an open issue again, since working that issue comes first.""" +@dataclasses.dataclass(frozen=True) +class EpicReopened: + """The epic holds an open issue again, so its finishing chunk has no work until none is open: working that issue comes first.""" + + +def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> tuple[str, RoutingIssue | None] | EpicReopened | Stop: + """The task of the chunk called key, and the issue that routes it, or None where that issue has no scores: both from the epic's issues, read afresh. The epic's finishing has no issue, and its work is EpicReopened once the epic holds an open issue again.""" if key != epic.key: issue = issue_read(key, epic) if isinstance(issue, Stop): @@ -434,8 +451,7 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> if isinstance(issues, Failure): return Stop(1, issues.reason) if not finish.due(issues): - say(f"the epic {epic.key} holds an open issue again, so its finishing chunk ends until none is open", epic.effects, stdout=True) - return handed_on(key, epic) + return EpicReopened() return finish.task(epic.key, issues, epic.launcher, language), None diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 8f7b7d90..e2a8337c 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -140,45 +140,44 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str parked = parked_chunks(epic.folder) if isinstance(parked, Failure): return parked - try: - with starting(epic.folder): - windows = tmux.listed(session, run) - live = {window.name: window for window in windows if not window.dead and window.name != own} - running = {window.name for window in windows if not window.dead and not window.parked} - {own} - stopped = {window.name for window in windows if window.dead} - set(live) - # The windows this call started that take a running slot. - taken = 0 - for chunk in found: - if chunk.issue in running or chunk.issue == own: - continue - slot = chunk.issue not in parked and not chunk.human - if chunk.human and chunk.issue in live: - waits.append(Waits(chunk.issue, HUMAN_WAIT)) - elif chunk.issue in parked and chunk.issue in live: - waits.append(Waits(chunk.issue, parked[chunk.issue].waits(live[chunk.issue].awaits))) - elif own and (chunk.issue in stopped or chunk.issue in parked): - waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again")) - elif slot and len(running) + taken >= epic.cap: - waits.append(Waits(chunk.issue, f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}")) + with starting(epic.folder) as unlocked: + if unlocked: + return unlocked + windows = tmux.listed(session, run) + live = {window.name: window for window in windows if not window.dead and window.name != own} + running = {window.name for window in windows if not window.dead and not window.parked} - {own} + stopped = {window.name for window in windows if window.dead} - set(live) + # The windows this call started that take a running slot. + taken = 0 + for chunk in found: + if chunk.issue in running or chunk.issue == own: + continue + slot = chunk.issue not in parked and not chunk.human + if chunk.human and chunk.issue in live: + waits.append(Waits(chunk.issue, HUMAN_WAIT)) + elif chunk.issue in parked and chunk.issue in live: + waits.append(Waits(chunk.issue, parked[chunk.issue].waits(live[chunk.issue].awaits))) + elif own and (chunk.issue in stopped or chunk.issue in parked): + waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again")) + elif slot and len(running) + taken >= epic.cap: + waits.append(Waits(chunk.issue, f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}")) + else: + now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run) + if isinstance(now, Failure): + return now + if isinstance(now, str): + waits.append(Waits(chunk.issue, now)) else: - now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run) - if isinstance(now, Failure): - return now - if isinstance(now, str): - waits.append(Waits(chunk.issue, now)) - else: - windows = now - started.append(chunk.issue) - taken += slot - except OSError as failure: - return Failure(f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}") + windows = now + started.append(chunk.issue) + taken += slot # The epic's finishing is no issue: its wait is listed after every issue's. order = [*(issue.key for issue in issues), epic.key] return Started(started, sorted(waits, key=lambda wait: order.index(wait.issue))) def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | str | Failure: - """Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none. It holds the repo's lock from the check to the start. Raises OSError where that lock cannot be taken. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo.""" + """Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none, or where the repo's lock cannot be taken. It holds that lock from the check to the start. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo.""" session = tmux.session_name(tmux.EPIC, epic.key) handed = {**{name: value for name, value in epic.env.items() if name.startswith(HANDED)}, PARKS: "1"} command = [str(epic.launcher), CHUNK_FLAG, chunk.issue, epic.key] @@ -188,7 +187,9 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li if isinstance(located, Failure): return located.reason checkout, limit = located - with starting(project_lock(str(checkout), epic.home)): + with starting(project_lock(str(checkout), epic.home)) as unlocked: + if unlocked: + return unlocked if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.home, run)): return reason return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), handed, command, windows, False, run) @@ -202,19 +203,20 @@ def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pa def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | None: """Takes a running slot for the parked chunk in window, whose worker has something to do again in the repo called repo: None once the window counts as a running chunk, else why the chunk still waits. The limits are those a starting chunk meets, checked under the same locks. The window itself never counts against them: one started again for a parked chunk, as after a reboot, isn't named as parked until its first read of the gate.""" - try: - with starting(epic.folder): - running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked and listed.name != window.name] - if len(running) >= epic.cap: - return f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}" - located = epic.locate(repo) - if isinstance(located, Failure): - return located.reason - checkout, limit = located - with starting(project_lock(str(checkout), epic.home)): - if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.home, run)): - return reason - tmux.unpark(window, str(checkout), run) - return None - except OSError as failure: - return f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}" + with starting(epic.folder) as unlocked: + if unlocked: + return unlocked.reason + running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked and listed.name != window.name] + if len(running) >= epic.cap: + return f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}" + located = epic.locate(repo) + if isinstance(located, Failure): + return located.reason + checkout, limit = located + with starting(project_lock(str(checkout), epic.home)) as unlocked: + if unlocked: + return unlocked.reason + if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.home, run)): + return reason + tmux.unpark(window, str(checkout), run) + return None diff --git a/bin/do_epic/test_finish.py b/bin/do_epic/test_finish.py index 18f75bb5..9e90405b 100644 --- a/bin/do_epic/test_finish.py +++ b/bin/do_epic/test_finish.py @@ -233,3 +233,11 @@ class TheFinishingChunk(DoEpicTest): self.assertIn("the epic ABC-12 holds an open issue again, so its finishing chunk ends until none is open\n", out) self.assertIn("the chunk finished; started ABC-31\n", out) self.assertEqual([seam for seam, _ in fake.calls if seam == "stream_claude"], []) + + def test_asking_for_the_finishing_chunks_work_names_a_reopened_epic_and_doesnt_start_any_window(self) -> None: + self.issues = [*REVIEWED, issue("ABC-31", "do-epic-claude")] + fake = FakeEffects(windows="ABC-12\t0\t@9\n") + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(main.chunk_work("ABC-12", None, "English", self.epic_run(fake)), main.EpicReopened()) + self.assertEqual((out.getvalue(), fake.tmux_calls), ("", [])) diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index a983c4b0..76a1f4df 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -179,6 +179,20 @@ class TheCommand(DoEpicTest): class ACycleOfAChunkWithoutARepo(DoEpicTest): + def test_naming_the_chunks_folder_doesnt_make_it(self) -> None: + folder = self.home / ".local/state/do-epic/ABC-12" + self.assertEqual(main.chunk_root("ABC-21", self.issues[1], self.epic_run(FakeEffects())), (str(folder), None)) + self.assertFalse(folder.exists()) + self.assertIsNone(main.folder_made(str(folder))) + self.assertTrue(folder.is_dir()) + + def test_a_chunk_whose_folder_cannot_be_made_stops_with_the_reason(self) -> None: + (self.home / ".local/state").mkdir(parents=True, exist_ok=True) + (self.home / ".local/state/do-epic").write_text("", encoding="utf-8") + code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"}) + self.assertEqual(code, 1) + self.assertRegex(err, f"could not make the chunk's folder {self.home}/.local/state/do-epic/ABC-12: \\w") + def cycle(self, env: dict[str, str] | None = None) -> main.Cycle: fake = FakeEffects(git=[Failure("no git"), Failure("no git")]) paths = paths_from(self.home) @@ -186,6 +200,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest): place = main.chunk_root("ABC-21", self.issues[1], epic) assert isinstance(place, tuple) root, repo = place + self.assertIsNone(main.folder_made(root)) loop = Loop(root=root, session=main.session_named("A ABC-12 do-epic ABC-21", paths.claude_code_transcripts), window=tmux.Window("epic-ABC-12", "ABC-21", "%1"), paths=paths, env=env or {}, launcher=pathlib.Path("/b/do-epic"), effects=fake.effects()) with contextlib.redirect_stdout(io.StringIO()): found = main.next_cycle(ChunkRun(1), loop, repo is not None, epic) diff --git a/bin/do_epic/test_repos.py b/bin/do_epic/test_repos.py index fdd8d66e..1f59e1f7 100644 --- a/bin/do_epic/test_repos.py +++ b/bin/do_epic/test_repos.py @@ -2,10 +2,10 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from test_env import assert_not_root from do_epic.config import DoEpicConfig from failure import Failure from do_epic.repos import locate, Located, Unsure @@ -14,9 +14,9 @@ from project_config.doubles import write_config class FakeGit: - """git as locate calls it: origins maps a checkout to its origin URL, cloned holds each `clone` that worked, and refused names a URL whose clone fails after it made the checkout's `.git`, as a stopped git does.""" - def __init__(self, origins: dict[str, str | Failure], refused: str | None = None) -> None: - self.origins, self.refused = origins, refused + """git as locate calls it: origins maps a checkout to its origin URL, cloned holds each `clone` that worked, and refused names a URL whose clone fails after it made the checkout's `.git`, as a stopped git does. Where locked, that clone also takes away the right to remove what it made.""" + def __init__(self, origins: dict[str, str | Failure], refused: str | None = None, locked: bool = False) -> None: + self.origins, self.refused, self.locked = origins, refused, locked self.cloned: list[tuple[str, str]] = [] self.clone_timeouts: list[float | None] = [] self.clone_options: list[tuple[str, ...]] = [] @@ -30,6 +30,8 @@ class FakeGit: url, destination = args[clone + 2:clone + 4] pathlib.Path(destination, ".git").mkdir(parents=True) if url == self.refused: + if self.locked: + pathlib.Path(destination).chmod(0o500) return Failure("git clone: repository not found") self.cloned.append((url, destination)) self.clone_timeouts.append(timeout) @@ -110,9 +112,12 @@ class LocateTest(unittest.TestCase): self.assertIn(f"{self.billing} has an origin, billing, with no host and owner to put another repo under", self.unsure(FakeGit(self.origins))) def test_asks_all_the_same_where_the_leftovers_of_a_failed_clone_cannot_be_removed(self) -> None: + assert_not_root(self) self.configure() - with unittest.mock.patch("do_epic.repos.shutil.rmtree", side_effect=lambda path, ignore_errors: None if ignore_errors is True else self.fail("rmtree must ignore errors")): - self.assertIn("cannot clone", self.unsure(FakeGit(self.origins, refused="git@github.com:acme/ledger"))) + left = self.home / "code" / "ledger" + self.addCleanup(lambda: left.chmod(0o700)) + self.assertIn("cannot clone", self.unsure(FakeGit(self.origins, refused="git@github.com:acme/ledger", locked=True))) + self.assertTrue((left / ".git").is_dir()) def test_asks_where_the_clone_fails_naming_the_url_and_the_reason(self) -> None: self.configure() diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index 34d8424e..c255053b 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -315,6 +315,22 @@ class StartingAnEpicsChunks(unittest.TestCase): assert isinstance(found, Failure) self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/do-epic/ABC-12: \\w") + def test_says_which_repos_lock_it_could_not_take(self) -> None: + (self.home / ".local/state").mkdir(parents=True) + (self.home / ".local/state/loop-claude").write_text("", encoding="utf-8") + found = start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, Tmux()) + assert isinstance(found, Failure) + self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w") + self.assertRegex(self.resumed(self.epic(1, api=1), Tmux()) or "", f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w") + + def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self) -> None: + def failing(args: list[str]) -> subprocess.CompletedProcess[str]: + raise OSError("tmux is gone") + with self.assertRaisesRegex(OSError, "tmux is gone"): + start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, failing) + with self.assertRaisesRegex(OSError, "tmux is gone"): + resume(self.epic(1, api=1), "api", tmux.Window("epic-ABC-12", "ABC-20", "%0"), failing) + CONFIG = settings.ProjectConfig("api", pathlib.Path("/c/api"), pathlib.Path("/code/api"), {"changelog": pathlib.Path("/code/api/CHANGELOG.md")}, epic=settings.Epic("https://acme.atlassian.net", "API-1")) diff --git a/bin/forge/pulls.py b/bin/forge/pulls.py index 43f16ed6..42b1bd31 100644 --- a/bin/forge/pulls.py +++ b/bin/forge/pulls.py @@ -2,7 +2,6 @@ import dataclasses import fnmatch import json -import time import typing from failure import Failure @@ -104,7 +103,7 @@ def checks_now(forge: Forge, number: str, head: str, required: set[str], run: Ru return None if (count == 0 and settled or state == "success") and not missing else Pending(missing) -def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep, settle: int = 0) -> Failure | None: +def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None], settle: int = 0) -> Failure | None: """None once every check on pull request number, whose head commit is head, has passed, or where it has none for settle seconds; a Failure where one fails, or where they have not all passed within WAIT_SECONDS. checks_now says what counts as passed on Gitea.""" if forge == "gh": for waited in range(0, settle + 1, POLL_SECONDS): diff --git a/bin/forge/reviews.py b/bin/forge/reviews.py index f5487011..331d811b 100644 --- a/bin/forge/reviews.py +++ b/bin/forge/reviews.py @@ -1,6 +1,6 @@ """A pull request's review state, read once from its forge: the review decision, whether it is a draft, whether the worker answered the changes a reviewer requested, and the review threads that wait for an answer. chunk-pr and do-epic decide on what this reads, and run no review query of their own.""" +import dataclasses import json -import typing from failure import Failure from forge.commands import Forge, gitea, Run @@ -42,28 +42,64 @@ def answered_decision(pull: str, head: str, run: Run) -> str | None | Failure: viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"]) if isinstance(viewed, Failure): return viewed + view = pull_view(viewed) + if isinstance(view, Failure): + return view + if view.draft: + return None + return ANSWERED if view.decision == CHANGES_REQUESTED and answered(view, head) else view.decision + + +@dataclasses.dataclass(frozen=True) +class Review: + """One review of a pull request. GitHub lists a reply in a thread as a review of its own.""" + author: str + state: str + # Empty for a review its author has yet to submit. + submitted_at: str + # The commit a review that requested changes was made on; empty for any other review. + commit: str + + +@dataclasses.dataclass(frozen=True) +class PullView: + """A pull request as `gh pr view --json isDraft,reviewDecision,author,reviews,comments` prints it.""" + draft: bool + # Empty where its branch protection asks for no review. + decision: str + reviews: tuple[Review, ...] + # When its author submitted each review and made each comment. A review the author has yet to submit has no time: it is empty, and answers nobody. + said: tuple[str, ...] + + +def text(value: object) -> str: + """value, which a forge's answer must hold as a string. Raises TypeError where it is none.""" + if not isinstance(value, str): + raise TypeError(f"{value!r} is not a string") + return value + + +def pull_view(printed: str) -> PullView | Failure: + """The pull request that gh printed, with each field checked here, so what decides on it meets no other shape.""" try: - parsed = json.loads(viewed) - if parsed["isDraft"]: - return None - decision = str(parsed["reviewDecision"] or "") - return ANSWERED if decision == CHANGES_REQUESTED and answered(parsed, head) else decision + pull = json.loads(printed) + author = text(pull["author"]["login"]) + reviews = tuple(Review(text(review["author"]["login"]), text(review["state"]), text(review["submittedAt"] or ""), text(review["commit"]["oid"]) if review["state"] == CHANGES_REQUESTED else "") for review in pull["reviews"]) + commented = tuple(text(comment["createdAt"]) for comment in pull["comments"] if text(comment["author"]["login"]) == author) + return PullView(bool(pull["isDraft"]), text(pull["reviewDecision"] or ""), reviews, tuple(review.submitted_at for review in reviews if review.author == author) + commented) except (ValueError, KeyError, TypeError): - return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}") + return Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}") -def answered(pull: dict[str, typing.Any], head: str) -> bool: - """Whether the worker answered the newest review that requested changes on pull, as `gh pr view --json author,reviews,comments` prints it, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. GitHub lists a reply in a thread as a review of its own. False where it lists no review that requested changes. Raises KeyError or TypeError where pull has another shape. +def answered(pull: PullView, head: str) -> bool: + """Whether the worker answered the newest review that requested changes on pull, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. False where pull lists no review that requested changes. The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed. """ - asked = max((review for review in pull["reviews"] if review["state"] == CHANGES_REQUESTED), key=lambda review: review["submittedAt"], default=None) + asked = max((review for review in pull.reviews if review.state == CHANGES_REQUESTED), key=lambda review: review.submitted_at, default=None) if asked is None: return False - author = pull["author"]["login"] - # A review the author has yet to submit has no time, and answers nobody. - said = [review["submittedAt"] or "" for review in pull["reviews"] if review["author"]["login"] == author] + [comment["createdAt"] for comment in pull["comments"] if comment["author"]["login"] == author] - return asked["commit"]["oid"] != head or any(at > asked["submittedAt"] for at in said) + return asked.commit != head or any(at > asked.submitted_at for at in pull.said) def gitea_decision(pull: str, run: Run) -> str | None | Failure: @@ -71,10 +107,10 @@ def gitea_decision(pull: str, run: Run) -> str | None | Failure: viewed = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull}") if isinstance(viewed, Failure): return viewed - try: - return None if viewed["title"].upper().startswith(GITEA_DRAFT) else "" - except (KeyError, TypeError, AttributeError): + title = viewed.get("title") if isinstance(viewed, dict) else None + if not isinstance(title, str): return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}") + return None if title.upper().startswith(GITEA_DRAFT) else "" def waiting_threads(number: str, run: Run) -> list[str] | Failure: @@ -82,9 +118,31 @@ def waiting_threads(number: str, run: Run) -> list[str] | Failure: read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) if isinstance(read, Failure): return read + threads = threads_read(read) + if isinstance(threads, Failure): + return threads + return waits(*threads) + + +@dataclasses.dataclass(frozen=True) +class Thread: + """One review thread of a pull request.""" + path: str + resolved: bool + # Who wrote its last comment; empty for a thread without one. + last: tuple[str, ...] + + +def threads_read(printed: str) -> tuple[str, tuple[Thread, ...]] | Failure: + """Who opened the pull request and its review threads, as gh printed THREADS' answer, with each field checked here.""" try: - pull = json.loads(read)["data"]["repository"]["pullRequest"] - author = pull["author"]["login"] - return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) + pull = json.loads(printed)["data"]["repository"]["pullRequest"] + threads = tuple(Thread(text(thread["path"]), bool(thread["isResolved"]), tuple(text(comment["author"]["login"]) for comment in thread["comments"]["nodes"])) for thread in pull["reviewThreads"]["nodes"]) + return text(pull["author"]["login"]), threads except (ValueError, KeyError, TypeError): - return Failure(f"gh api graphql printed no review threads: {read.strip()[:200]}") + return Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}") + + +def waits(author: str, threads: tuple[Thread, ...]) -> list[str]: + """The files of the threads that wait for an answer from author, who opened the pull request.""" + return sorted({thread.path for thread in threads if not thread.resolved and any(last != author for last in thread.last)}) diff --git a/bin/forge/test_reviews.py b/bin/forge/test_reviews.py new file mode 100644 index 00000000..f1467d26 --- /dev/null +++ b/bin/forge/test_reviews.py @@ -0,0 +1,102 @@ +import json +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from forge.reviews import ANSWERED, CHANGES_REQUESTED, PullView, Review, Thread +from failure import Failure +from forge import reviews + +ASKED = {"author": {"login": "rev"}, "state": CHANGES_REQUESTED, "submittedAt": "2026-11-02T10:00:00Z", "commit": {"oid": "abc"}} +PULL = {"isDraft": False, "reviewDecision": CHANGES_REQUESTED, "author": {"login": "me"}, "reviews": [ASKED], "comments": []} + + +def printing(answer: object): + """A run whose command prints answer as JSON.""" + return lambda args: json.dumps(answer) + + +class Faulty: + """A pull request's number or head whose use in a comparison or in a command raises a fault of our own.""" + + def __ne__(self, other: object) -> bool: + raise TypeError("ours") + + def __format__(self, spec: str) -> str: + raise TypeError("ours") + + +class ThePullRequestAsViewed(unittest.TestCase): + def test_parses_what_gh_prints_into_one_value(self): + pending = {"author": {"login": "me"}, "state": "PENDING", "submittedAt": None, "commit": None} + printed = json.dumps(PULL | {"reviews": [ASKED, pending], "comments": [{"author": {"login": "me"}, "createdAt": "2026-11-02T11:00:00Z"}, {"author": {"login": "rev"}, "createdAt": "2026-11-02T12:00:00Z"}]}) + self.assertEqual(reviews.pull_view(printed), PullView(False, CHANGES_REQUESTED, (Review("rev", CHANGES_REQUESTED, "2026-11-02T10:00:00Z", "abc"), Review("me", "PENDING", "", "")), ("", "2026-11-02T11:00:00Z"))) + + def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self): + unshaped = ("not json", "[]", json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"})) + for printed in unshaped: + with self.subTest(printed=printed): + self.assertEqual(reviews.pull_view(printed), Failure(f"gh pr view printed no review decision: {printed[:200]}")) + self.assertEqual(reviews.answered_decision("7", "abc", lambda args: printed), Failure(f"gh pr view printed no review decision: {printed[:200]}")) + + +class WhetherTheWorkerAnswered(unittest.TestCase): + def view(self, *others: Review, said: tuple[str, ...] = ()) -> PullView: + return PullView(False, CHANGES_REQUESTED, (Review("rev", CHANGES_REQUESTED, "2026-11-02T10:00:00Z", "abc"), *others), tuple(review.submitted_at for review in others if review.author == "me") + said) + + def test_a_new_head_or_a_later_word_of_the_authors_answers_the_newest_request(self): + self.assertFalse(reviews.answered(self.view(), "abc")) + self.assertTrue(reviews.answered(self.view(), "def")) + self.assertTrue(reviews.answered(self.view(said=("2026-11-02T10:30:00Z",)), "abc")) + self.assertFalse(reviews.answered(self.view(said=("2026-11-02T09:00:00Z", "")), "abc")) + self.assertTrue(reviews.answered(self.view(Review("me", "COMMENTED", "2026-11-02T10:30:00Z", "")), "abc")) + self.assertFalse(reviews.answered(PullView(False, "", (), ()), "abc")) + + def test_the_decision_reads_answered_once_the_worker_answered(self): + self.assertEqual(reviews.answered_decision("7", "abc", printing(PULL)), CHANGES_REQUESTED) + self.assertEqual(reviews.answered_decision("7", "def", printing(PULL)), ANSWERED) + self.assertIsNone(reviews.answered_decision("7", "abc", printing(PULL | {"isDraft": True}))) + self.assertEqual(reviews.answered_decision("7", "abc", printing(PULL | {"reviewDecision": None, "reviews": []})), "") + + def test_a_fault_in_the_decision_is_not_reported_as_the_forges(self): + with self.assertRaisesRegex(TypeError, "ours"): + reviews.answered_decision("7", Faulty(), printing(PULL)) + + +class TheThreadsThatWait(unittest.TestCase): + def printed(self, *threads: tuple[str, bool, str]) -> str: + nodes = [{"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}} for path, resolved, last in threads] + return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": nodes}}}}}) + + def test_parses_what_gh_prints_into_the_author_and_each_thread(self): + self.assertEqual(reviews.threads_read(self.printed(("a.py", False, "rev"), ("b.py", True, "me"))), ("me", (Thread("a.py", False, ("rev",)), Thread("b.py", True, ("me",))))) + + def test_a_thread_waits_while_unresolved_with_a_reviewers_last_word(self): + printed = self.printed(("b.py", False, "rev"), ("a.py", False, "rev"), ("a.py", False, "rev"), ("c.py", True, "rev"), ("d.py", False, "me")) + self.assertEqual(reviews.waiting_threads("7", lambda args: printed), ["a.py", "b.py"]) + + def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self): + for printed in ("not json", "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}})): + with self.subTest(printed=printed): + self.assertEqual(reviews.waiting_threads("7", lambda args: printed), Failure(f"gh api graphql printed no review threads: {printed[:200]}")) + + def test_a_fault_in_the_choice_is_not_reported_as_the_forges(self): + with self.assertRaisesRegex(TypeError, "ours"): + reviews.waiting_threads(Faulty(), lambda args: self.printed(("a.py", False, "rev"))) + + +class TheDecisionOnGitea(unittest.TestCase): + def decision(self, answer: object): + return reviews.gitea_decision("7", printing(answer)) + + def test_a_title_tells_a_draft_and_an_answer_without_one_is_a_failure(self): + self.assertIsNone(self.decision({"title": "wip: later"})) + self.assertEqual(self.decision({"title": "Fix it"}), "") + self.assertEqual(self.decision({"title": 7}), Failure("tea api printed no title of pull request 7: {'title': 7}")) + self.assertEqual(self.decision([]), Failure("tea api printed no title of pull request 7: []")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/git_cli/git_repo.py b/bin/git_cli/git_repo.py index 82821b52..87fac04e 100644 --- a/bin/git_cli/git_repo.py +++ b/bin/git_cli/git_repo.py @@ -23,19 +23,20 @@ GUARD_SETTINGS = [ ] -def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure: +def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict", env: typing.Mapping[str, str] | None = None) -> str | Failure: """What git printed, run in cwd, else in the current directory. A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it. errors "replace" reads each byte that is not UTF-8 as U+FFFD instead of failing. It is for output, such as a diff, whose file text the caller skips. + env is the environment git runs in, else this process's. guarded turns off the fsmonitor, the signature check, each transport GUARD_SETTINGS names and a partial clone's fetch of its missing objects. It is for a checkout whose config may name a program. """ command = " ".join(args) guards = [option for setting in GUARD_SETTINGS for option in ("-c", setting)] if guarded else [] # GIT_NO_LAZY_FETCH needs git 2.44. - env = {**os.environ, "GIT_NO_LAZY_FETCH": "1"} if guarded else None + child_env = {**(os.environ if env is None else env), "GIT_NO_LAZY_FETCH": "1"} if guarded else env try: - ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", errors=errors, env=env, timeout=timeout) + ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", errors=errors, env=child_env, timeout=timeout) except UnicodeDecodeError as failure: return Failure(f"git {command} printed text that is not UTF-8: {failure}") except (OSError, ValueError) as failure: @@ -52,8 +53,8 @@ class Git(typing.Protocol): -def top() -> str | Failure: - found = git("rev-parse", "--show-toplevel") +def top(run: Git = git) -> str | Failure: + found = run("rev-parse", "--show-toplevel") return found if isinstance(found, Failure) else found.strip() diff --git a/bin/judge-replay b/bin/judge-replay index 0252c222..f574a3fe 100755 --- a/bin/judge-replay +++ b/bin/judge-replay @@ -8,4 +8,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from judge_replay import main from loop_effects.effects import system_effects -sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects())) +sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects(pathlib.Path.home(), os.environ))) diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index 42bd0a79..48693f33 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -56,15 +56,15 @@ import typing from chunk_driver.prompts import ANSWER_DESTINATIONS from transcript_archive.location import archive_root, transcript_of from transcript_archive.read import archived_outcomes -from rung_replay.archive import archiving, print_report, replay_folder -from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on +from rung_replay.archive import archiving, replay_folder +from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, print_report, projects_on, say +from rung_replay.search import AT_ONCE, first_reply, replayed from agent_cycle.judge import Brief, judge_archived, judge_once from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind from transcript_archive.project_key import checkout_of from loop_effects.effects import Effects from failure import Failure from judge_replay.offline import final_message, LEARNERS, offline_report, RULES, Sample -from rung_replay.search import first_reply, replayed from judge_replay.archived_prompt import grounds_of from transcript_archive.judge_run import JudgeRun from model_routing.ladder import Ladder, ProjectRung, REVIEW_STEPS, Rung @@ -101,10 +101,10 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff return offline(project.rung.model, cases, archive_root(home, env), effects) cases = sample(cases, PER_KIND) folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now()) - effects = archiving(effects, folder) + effects = archiving(effects, folder, say) reference = Rung(project.rung.model, REFERENCE_EFFORT) # The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge. - replay = replayed(cases, reference, down_from(ladder, project.rung, project.lowest_worker_rung()), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(project, reference)) + replay = replayed(cases, reference, down_from(ladder, project.rung, project.lowest_worker_rung()), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", say, AT_ONCE, climbs(project, reference)) if isinstance(replay, Limited): return limited_exit(TOOL, replay) print_report(folder, report(project.rung.model, reference, cases, replay)) diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 314a0637..3560ed2e 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -13,7 +13,7 @@ from chunk_driver.prompts import ANSWER_DESTINATIONS from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED from claude_code.entries import AssistantTurn, HumanTurn, LoopPrompt, Text from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind -from text_files import compressed +from text_files.doubles import compress from project_config.doubles import configured from loop_effects.effects import Effects from failure import Failure @@ -142,7 +142,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, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) @@ -276,7 +276,7 @@ class Main(unittest.TestCase): self.assertIn("replayed failed: could not read the transcript", out) def test_replays_a_verdict_whose_transcript_is_compressed(self): - self.assertIsNone(compressed.compress(self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" / "t0.jsonl")) + self.assertIsNone(compress(self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" / "t0.jsonl")) code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) self.assertEqual(code, 0, err) self.assertNotIn("replayed failed", out) @@ -343,7 +343,7 @@ class JudgeArchivedRuns(unittest.TestCase): cwds.append(cwd) return subprocess.CompletedProcess(args, 0, json.dumps({"type": "result", "structured_output": output, "total_cost_usd": 0.25}), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) grounds = grounds_of(prompt, self.ENTRIES) return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, LOOP_CLAUDE, effects)), cwds diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 88782485..8aba70b4 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -9,7 +9,6 @@ import sys import tempfile import textwrap import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -614,18 +613,18 @@ class LarvReviewTool(unittest.TestCase): (self.config.parent / "todo.md").write_text(todo(row, "| 2 | 0.2.0 | | **Reach the comprehension floor: do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")) self.addCleanup(os.chdir, os.getcwd()) os.chdir(self.checkout) - with unittest.mock.patch.dict(os.environ, {"HOME": str(self.config.parents[2])}): - self.assertEqual(plan_reasons("origin/main", [2], pathlib.Path.home()), ["ships item 2, a floor item", "leaves release 0.2.0 with no plan item"]) - (self.config.parent / "decisions.md").write_text("# Decisions\n\n## review opt-out: the comprehension check\n\nServes goal 1.\n") - self.assertEqual(plan_reasons("origin/main", [2], pathlib.Path.home()), []) - (self.config.parent / "decisions.md").unlink() - gone = plan_reasons("origin/main", [1, 7], pathlib.Path.home()) - assert isinstance(gone, Failure), gone - self.assertEqual(gone.reason, f"the plan as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md") - (self.config.parent / "todo.md").write_bytes(b"\xff") - unreadable = plan_reasons("origin/main", [2], pathlib.Path.home()) - assert isinstance(unreadable, Failure), unreadable - self.assertEqual(unreadable.reason, f"the project's plan: {self.config.parent}/todo.md: not UTF-8") + home = self.config.parents[2] + self.assertEqual(plan_reasons("origin/main", [2], home), ["ships item 2, a floor item", "leaves release 0.2.0 with no plan item"]) + (self.config.parent / "decisions.md").write_text("# Decisions\n\n## review opt-out: the comprehension check\n\nServes goal 1.\n") + self.assertEqual(plan_reasons("origin/main", [2], home), []) + (self.config.parent / "decisions.md").unlink() + gone = plan_reasons("origin/main", [1, 7], home) + assert isinstance(gone, Failure), gone + self.assertEqual(gone.reason, f"the plan as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md") + (self.config.parent / "todo.md").write_bytes(b"\xff") + unreadable = plan_reasons("origin/main", [2], home) + assert isinstance(unreadable, Failure), unreadable + self.assertEqual(unreadable.reason, f"the project's plan: {self.config.parent}/todo.md: not UTF-8") ROW = "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |" @@ -992,7 +991,7 @@ class LarvReviewTool(unittest.TestCase): (checkout / "todo.md").write_text("the owners' own notes\n") self.enterContext(contextlib.chdir(checkout)) said: list[str] = [] - self.assertIsNone(rerank(pathlib.Path.home(), said.append)) + self.assertIsNone(rerank(config.parents[2], said.append)) self.assertEqual((said, (checkout / "todo.md").read_text()), ([], "the owners' own notes\n")) def test_reranks_todo_md_by_the_overall_it_records(self): diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py index 59f97a15..51edfe61 100644 --- a/bin/larv_review/test_scoring_setup.py +++ b/bin/larv_review/test_scoring_setup.py @@ -1,4 +1,3 @@ -from unittest import mock import os import pathlib import re @@ -103,8 +102,7 @@ class PrepareScoring(unittest.TestCase): def prepare(self): """What prepare-scoring returns in the checkout, run in this process so mutation tests see the lines it runs.""" - with mock.patch.dict(os.environ, self.env, clear=True): - return prepare_scoring(str(self.checkout), pathlib.Path.home()) + return prepare_scoring(str(self.checkout), self.root) def run_tool(self, *args): return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True) @@ -139,8 +137,7 @@ class PrepareScoring(unittest.TestCase): self.commit() checkout = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "checkout" checkout.mkdir(parents=True) - with mock.patch.dict(os.environ, self.env, clear=True): - removed = removed_setup(str(self.checkout), pathlib.Path.home()) + removed = removed_setup(str(self.checkout), self.root) self.assertIsInstance(removed, Failure) self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason) self.assertTrue(checkout.exists()) diff --git a/bin/loop-claude b/bin/loop-claude index 8bfb9050..c9580a0f 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -10,4 +10,4 @@ from loop_effects import effects from loop_claude.loop import main from loop_state import paths -sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, pathlib.Path.cwd(), effects.system_effects())) +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, pathlib.Path.cwd(), effects.system_effects(pathlib.Path.home(), os.environ))) diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index 61570bba..b9776378 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -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 diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 69632c74..aae44311 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -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 ") - 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) diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index d938f934..57e032b1 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -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 diff --git a/bin/loop_claude/loop/test_chunk_start.py b/bin/loop_claude/loop/test_chunk_start.py index 15e9fc6e..ea8ffbef 100644 --- a/bin/loop_claude/loop/test_chunk_start.py +++ b/bin/loop_claude/loop/test_chunk_start.py @@ -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): diff --git a/bin/loop_claude/loop/test_chunk_windows.py b/bin/loop_claude/loop/test_chunk_windows.py index 9376890f..71099dfa 100644 --- a/bin/loop_claude/loop/test_chunk_windows.py +++ b/bin/loop_claude/loop/test_chunk_windows.py @@ -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) diff --git a/bin/loop_claude/loop/test_main.py b/bin/loop_claude/loop/test_main.py index 0f37bee2..8e955dda 100644 --- a/bin/loop_claude/loop/test_main.py +++ b/bin/loop_claude/loop/test_main.py @@ -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 ")) +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): diff --git a/bin/loop_claude/loop/test_routing_check.py b/bin/loop_claude/loop/test_routing_check.py index 4c510b97..6a925611 100644 --- a/bin/loop_claude/loop/test_routing_check.py +++ b/bin/loop_claude/loop/test_routing_check.py @@ -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) diff --git a/bin/loop_claude/loop/test_usage.py b/bin/loop_claude/loop/test_usage.py index a6da1337..af996f1d 100644 --- a/bin/loop_claude/loop/test_usage.py +++ b/bin/loop_claude/loop/test_usage.py @@ -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"), diff --git a/bin/loop_effects/child_shells.py b/bin/loop_effects/child_shells.py index 07648b8a..ee18379a 100644 --- a/bin/loop_effects/child_shells.py +++ b/bin/loop_effects/child_shells.py @@ -7,8 +7,8 @@ import os import pathlib import signal import stat +import typing -from machine_load.slots import slot_folder # The command names of a shell claude starts for a Bash call. SHELL_NAMES = frozenset({"bash", "dash", "sh", "zsh"}) @@ -149,15 +149,14 @@ def holds_slot(pid: int, slots: pathlib.Path) -> bool: return any(has_slot(each, slots) for each in descendants(pid)) -def shells_of(claude_pid: int) -> list[Shell]: - """The shells that are children of claude_pid; none where /proc doesn't exist, as off Linux.""" +def shells_of(claude_pid: int, slots: pathlib.Path, children: typing.Callable[[int], list[int]]) -> list[Shell]: + """The shells that are children of claude_pid, which children lists as children_of does, each knowing whether it holds a heavy slot in the folder slots; none where /proc doesn't exist, as off Linux.""" if not os.path.isdir("/proc"): return [] - slots = slot_folder(os.environ, pathlib.Path.home()) booted = boot_time() ticks = os.sysconf("SC_CLK_TCK") shells = [] - for pid in children_of(claude_pid): + for pid in children(claude_pid): found = parent_and_start(pid) if found is None or found[2] not in SHELL_NAMES: continue diff --git a/bin/loop_effects/doubles.py b/bin/loop_effects/doubles.py index 802abab9..1fd91b7a 100644 --- a/bin/loop_effects/doubles.py +++ b/bin/loop_effects/doubles.py @@ -9,6 +9,7 @@ from loop_effects.effects import Effects from claude_code import entries from failure import Failure from machine_load import memory +from text_files.file_writes import replace_file from loop_effects.child_shells import Shell @@ -51,6 +52,8 @@ class FakeEffects: self.terminal_folders: list[str] = [] # Each timer started, as its delay and action, which a test runs where the timer fires. self.timers: list[tuple[float, typing.Callable[[], None]]] = [] + # What writes a file: the real writer, until a test sets one that fails. + self.replace_file: typing.Callable[[pathlib.Path, bytes], Failure | None] = replace_file def effects(self) -> Effects: return Effects( @@ -66,6 +69,7 @@ class FakeEffects: now=lambda: NOW, on_terminal=lambda: self.terminal, python=lambda args, cwd: self.answer("python", (args, cwd)), + replace_file=lambda path, data: self.replace_file(path, data), sleep=lambda seconds: self.calls.append(("sleep", seconds)), stream_claude=self.stream, timer=self.timer, diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index dd32f0e2..d7d011f8 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -20,6 +20,8 @@ from failure import Failure from git_cli import git_repo from machine_load.memory import Memory, read_memory from project_config.settings import Notifier +from text_files.file_writes import replace_file +from machine_load.slots import slot_folder # 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 @@ -62,6 +64,8 @@ class Effects: on_terminal: typing.Callable[[], bool] # Runs a Python script in a directory, as run_python does. python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]] + # Writes a file whole, as text_files.file_writes.replace_file does. + replace_file: typing.Callable[[pathlib.Path, bytes], Failure | None] sleep: typing.Callable[[float], None] stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming] # Starts a timer, as start_timer does. @@ -96,7 +100,7 @@ class StreamingClaude: yield pending.decode("utf-8", errors="replace") def shells(self) -> list[child_shells.Shell]: - return child_shells.shells_of(self.proc.pid) + return child_shells.shells_of(self.proc.pid, slot_folder(os.environ, pathlib.Path.home()), child_shells.children_of) def stop(self, shell: child_shells.Shell) -> None: child_shells.stop(shell) @@ -105,13 +109,16 @@ class StreamingClaude: return self.proc.wait() -def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS) -> Effects: - """The effects on this machine; `backends` are the notifiers loop-claude's DM can go through, where a test swaps in one that sends nowhere.""" +def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS) -> Effects: + """The effects on this machine: the configs of its DM are under home, and tmux runs in env. + + A test hands in `backends`, the notifiers loop-claude's DM can go through, that send nowhere. + """ return Effects( claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True), claude_on_terminal=claude_on_terminal, discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), - dm=lambda text, directory: notify(text, directory, pathlib.Path.home(), backends), + dm=lambda text, directory: notify(text, directory, home, backends), execv=os.execv, git=git_repo.git, input=input, @@ -120,11 +127,12 @@ def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BAC now=time.time, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT), + replace_file=replace_file, sleep=time.sleep, stream_claude=StreamingClaude, timer=start_timer, - tmux=run_tmux, - tmux_on_terminal=lambda args: subprocess.run(["tmux", *args]).returncode, + tmux=lambda args: run_tmux(args, env), + tmux_on_terminal=lambda args: subprocess.run(["tmux", *args], env=env).returncode, ) @@ -162,11 +170,11 @@ def start_timer(delay: float, action: typing.Callable[[], None]) -> typing.Calla return stop -def run_tmux(args: list[str]) -> subprocess.CompletedProcess[str]: - """Runs tmux and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr.""" +def run_tmux(args: list[str], env: typing.Mapping[str, str] | None) -> subprocess.CompletedProcess[str]: + """Runs tmux in env, else in this process's environment, and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr.""" command = ["tmux", *args] try: - return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL) + return subprocess.run(command, capture_output=True, encoding="utf-8", env=env, errors="replace", stdin=subprocess.DEVNULL) except OSError as failure: return subprocess.CompletedProcess(command, 127, "", f"could not start: {failure}") diff --git a/bin/loop_effects/test_effects.py b/bin/loop_effects/test_effects.py index 0f58638e..b788d399 100644 --- a/bin/loop_effects/test_effects.py +++ b/bin/loop_effects/test_effects.py @@ -10,7 +10,6 @@ import tempfile import threading import time import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -24,7 +23,7 @@ STAMP = f"<{NOW}>" def clocked(): """The system's effects on a clock stopped at NOW, which renders a time as .""" - return dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW) + return dataclasses.replace(system_effects(pathlib.Path.home(), os.environ), local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW) def ticks(pid): @@ -78,13 +77,10 @@ class Said(unittest.TestCase): class LocalTime(unittest.TestCase): def test_renders_seconds_in_the_machines_zone(self): - # A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again. - self.addCleanup(time.tzset) - zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"}) - zone.start() - self.addCleanup(zone.stop) - time.tzset() - self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20") + # A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. A process reads its zone as it starts, so the clock runs in one of its own. + script = f"import os\nimport pathlib\nimport sys\nsys.path.insert(0, {str(pathlib.Path(__file__).resolve().parents[1])!r})\nfrom loop_effects.effects import system_effects\nprint(system_effects(pathlib.Path.home(), os.environ).local_time({NOW}))" + ran = subprocess.run([sys.executable, "-c", script], capture_output=True, check=True, env=os.environ | {"TZ": "XXX-2"}, text=True) + self.assertEqual(ran.stdout, "2026-09-21 16:13:20\n") @@ -98,7 +94,7 @@ class ClaudeOnTerminal(unittest.TestCase): # A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns. claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n") claude.chmod(0o755) - code = system_effects().claude_on_terminal([], folder, {"PATH": folder}) + code = system_effects(pathlib.Path.home(), os.environ).claude_on_terminal([], folder, {"PATH": folder}) self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before)) @@ -110,27 +106,28 @@ class TmuxEffect(unittest.TestCase): tmux = pathlib.Path(folder, "tmux") tmux.write_text(f"#!{sys.executable}\nimport sys\nprint(' '.join(sys.argv[1:]))\nsys.exit(4)\n") tmux.chmod(0o755) - return unittest.mock.patch.dict(os.environ, {"PATH": folder, "TMUX": "", "TMUX_PANE": ""}) + return system_effects(pathlib.Path.home(), os.environ | {"PATH": folder, "TMUX": "", "TMUX_PANE": ""}) def test_runs_tmux_and_returns_what_it_printed(self): - with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder): - done = system_effects().tmux(["list-windows", "-t", "=loop-proj"]) + with tempfile.TemporaryDirectory() as folder: + done = self.fake_tmux(folder).tmux(["list-windows", "-t", "=loop-proj"]) self.assertEqual((done.returncode, done.stdout), (4, "list-windows -t =loop-proj\n")) def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self): - with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder): + with tempfile.TemporaryDirectory() as folder: + effects = self.fake_tmux(folder) pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nsys.stdout.buffer.write(b'caf\\xe9')\n") - self.assertEqual(system_effects().tmux(["list-windows"]).stdout, "caf\ufffd") + self.assertEqual(effects.tmux(["list-windows"]).stdout, "caf\ufffd") def test_reads_a_tmux_that_cannot_start_as_exit_127(self): - with tempfile.TemporaryDirectory() as folder, unittest.mock.patch.dict(os.environ, {"PATH": folder}): - done = system_effects().tmux(["-V"]) + with tempfile.TemporaryDirectory() as folder: + done = system_effects(pathlib.Path.home(), os.environ | {"PATH": folder}).tmux(["-V"]) self.assertEqual((done.args, done.returncode, done.stdout), (["tmux", "-V"], 127, "")) self.assertIn("could not start", done.stderr) def test_runs_tmux_on_the_terminal_and_returns_its_exit_code(self): - with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(system_effects().tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4) + with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(self.fake_tmux(folder).tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4) class PythonEffect(unittest.TestCase): @@ -169,8 +166,8 @@ class ChildShells(unittest.TestCase): os.killpg(proc.pid, signal.SIGKILL) proc.wait() - def shell_of(self, proc): - [found] = [each for each in child_shells.shells_of(os.getpid()) if each.pid == proc.pid] + def shell_of(self, proc, slots=pathlib.Path("/no-slots")): + [found] = [each for each in child_shells.shells_of(os.getpid(), slots, child_shells.children_of) if each.pid == proc.pid] return found def test_reads_a_child_shells_command_and_whether_a_busy_tool_runs_below_it(self): @@ -189,12 +186,12 @@ class ChildShells(unittest.TestCase): def test_a_shell_below_which_a_process_holds_a_heavy_slot_file_holds_a_slot_and_runs_no_busy_tool(self): # run-heavy replaces itself with its command, which keeps the slot's file open. - with tempfile.TemporaryDirectory() as state, unittest.mock.patch.dict(os.environ, {"XDG_STATE_HOME": state}): + with tempfile.TemporaryDirectory() as state: slot = pathlib.Path(state, "run-heavy", "slot-0") slot.parent.mkdir() holding = self.started(f"exec 9>{slot}; sleep 60; true") plain = self.started("sleep 60; true") - self.assertEqual([(self.shell_of(each).holds_slot, self.shell_of(each).runs_busy_tool) for each in (holding, plain)], [(True, False), (False, False)]) + self.assertEqual([(self.shell_of(each, slot.parent).holds_slot, self.shell_of(each, slot.parent).runs_busy_tool) for each in (holding, plain)], [(True, False), (False, False)]) def test_a_shell_written_output_is_the_modified_time_of_its_output_file_and_else_its_start(self): with tempfile.NamedTemporaryFile() as output: @@ -264,8 +261,8 @@ class ChildShells(unittest.TestCase): self.assertFalse(child_shells.has_slot(2**30, pathlib.Path("/"))) shell = self.started("sleep 60; true") real = child_shells.children_of - with unittest.mock.patch.object(child_shells, "children_of", side_effect=lambda pid: [2**30, shell.pid] if pid == os.getpid() else real(pid)): - self.assertEqual([each.pid for each in child_shells.shells_of(os.getpid())], [shell.pid]) + children = lambda pid: [2**30, shell.pid] if pid == os.getpid() else real(pid) + self.assertEqual([each.pid for each in child_shells.shells_of(os.getpid(), pathlib.Path("/no-slots"), children)], [shell.pid]) def test_command_of_takes_the_text_of_the_last_eval_wrapper_and_else_the_whole_line(self): wrapped = ["/bin/bash", "-c", "source /s && eval 'echo a && eval b < /dev/null' < /dev/null && pwd -P >| /t"] @@ -330,7 +327,7 @@ class Timer(unittest.TestCase): self.assertTrue(ran.wait(10)) def test_the_systems_timer_runs_on_a_daemon_thread_so_a_loop_that_exits_while_it_waits_does_not_wait_for_it(self): - self.assertIs(system_effects().timer, start_timer) + self.assertIs(system_effects(pathlib.Path.home(), os.environ).timer, start_timer) before = set(threading.enumerate()) stop = start_timer(60, lambda: None) self.addCleanup(stop) diff --git a/bin/machine_load/slots.py b/bin/machine_load/slots.py index 9b2e9d64..1b8b77f7 100644 --- a/bin/machine_load/slots.py +++ b/bin/machine_load/slots.py @@ -2,7 +2,6 @@ import fcntl import os import pathlib -import time import typing CPUS_PER_SLOT = 4 @@ -26,12 +25,16 @@ def slot_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Pa return pathlib.Path(state) / "run-heavy" -def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None: - """The number and open file of the lowest slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked.""" +# Locks an open file, as fcntl.flock does. +Lock = typing.Callable[[int, int], None] + + +def taken_slot(folder: pathlib.Path, slots: int, lock: Lock) -> tuple[int, int] | None: + """The number and open file of the lowest slot this call locked, through lock; None while every slot is held. Raises OSError where a slot file cannot be opened or locked.""" for slot in range(slots): fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644) try: - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + lock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: os.close(fd) continue @@ -42,10 +45,10 @@ def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None: return None -def waited_slot(folder: pathlib.Path, slots: int, say: typing.Callable[[], None], sleep: typing.Callable[[float], None] = time.sleep) -> tuple[int, int]: - """The number and open file of a slot this call locked, once one frees. While every slot is held, it calls say once and tries again each POLL_SECONDS.""" +def waited_slot(folder: pathlib.Path, slots: int, say: typing.Callable[[], None], sleep: typing.Callable[[float], None], lock: Lock) -> tuple[int, int]: + """The number and open file of a slot this call locked, through lock, once one frees. While every slot is held, it calls say once and tries again each POLL_SECONDS.""" said = False - while (taken := taken_slot(folder, slots)) is None: + while (taken := taken_slot(folder, slots, lock)) is None: if not said: say() said = True diff --git a/bin/machine_load/test_machine_load.py b/bin/machine_load/test_machine_load.py index 9f434a9a..d79b2568 100644 --- a/bin/machine_load/test_machine_load.py +++ b/bin/machine_load/test_machine_load.py @@ -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[1])) @@ -57,13 +56,19 @@ class SlotFolder(unittest.TestCase): class TakenSlot(unittest.TestCase): def test_a_lock_that_fails_for_another_reason_than_a_holder_closes_its_file_and_raises(self): - closed = [] - with tempfile.TemporaryDirectory() as folder, unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")), unittest.mock.patch("os.close", side_effect=closed.append): + locked = [] + + def lock(fd, operation): + locked.append(fd) + raise OSError(errno.ENOLCK, "No locks available") + + with tempfile.TemporaryDirectory() as folder: with self.assertRaises(OSError): - slots.taken_slot(pathlib.Path(folder), 2) - self.assertEqual(len(closed), 1) - self.assertIsInstance(closed[0], int) - os.close(closed[0]) + slots.taken_slot(pathlib.Path(folder), 2, lock) + self.assertEqual(len(locked), 1) + with self.assertRaises(OSError) as closed: + os.fstat(locked[0]) + self.assertEqual(closed.exception.errno, errno.EBADF) class WaitedSlot(unittest.TestCase): @@ -79,14 +84,14 @@ class WaitedSlot(unittest.TestCase): if len(slept) == 2: held[1].close() - slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: said.append(True), sleep) + slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: said.append(True), sleep, fcntl.flock) os.close(fd) held[0].close() self.assertEqual((slot, said, slept), (1, [True], [slots.POLL_SECONDS] * 2)) def test_takes_a_free_slot_at_once(self): with tempfile.TemporaryDirectory() as folder: - slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: self.fail("said it waits"), lambda seconds: self.fail("slept")) + slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: self.fail("said it waits"), lambda seconds: self.fail("slept"), fcntl.flock) os.close(fd) self.assertEqual(slot, 0) diff --git a/bin/mutate-changes b/bin/mutate-changes index 648ad8e8..855b131b 100755 --- a/bin/mutate-changes +++ b/bin/mutate-changes @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import os import pathlib import signal import sys @@ -11,4 +12,4 @@ from mutate_changes import main # SystemExit, the run unwinds as on Ctrl-C. for number in (signal.SIGHUP, signal.SIGTERM): signal.signal(number, lambda number, frame: sys.exit(128 + number)) -sys.exit(main.main(sys.argv[1:])) +sys.exit(main.main(sys.argv[1:], os.environ)) diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index 27f98db5..fbe9611a 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -3,16 +3,16 @@ import os import pathlib from mutate_changes.changed_lines import by_folder, label, runs -from mutate_changes.tool_process import failed, Ran, remove, run_tool, scratch_folder +from mutate_changes.tool_process import failed, Ran, remove, Run, scratch_folder from failure import Failure -from git_cli.git_repo import git +from git_cli.git_repo import Git # cargo-mutants' exit codes for a run that finished: every mutant caught, some missed, and some timed out. CARGO_FINISHED = frozenset({0, 2, 3}) CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable") -def run_cargo_mutants(top: str, base: str, paths: list[str], prefix: str | None, jobs: int) -> list[str] | Failure: +def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git, jobs: int) -> list[str] | Failure: """A line with cargo-mutants' mutant count, then a line per mutant it missed or that timed out, as `::: : `. cargo-mutants runs in top.""" @@ -26,7 +26,7 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], prefix: str | None, try: pathlib.Path(scratch, "branch.diff").write_text(diff, encoding="utf-8") relative = os.path.relpath(scratch, top) - ran = run_tool(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top, prefix) + ran = run(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top) if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED: return ran if isinstance(ran, Failure) else failed("cargo mutants", ran) outcomes = {outcome: outcome_lines(pathlib.Path(scratch, "mutants.out", f"{outcome}.txt")) for outcome in CARGO_OUTCOMES} @@ -44,7 +44,7 @@ def outcome_lines(path: pathlib.Path) -> list[str]: # Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't # tell from a run that broke, so either fails the run. -def run_stryker(top: str, changed: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure: +def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: int) -> list[str] | Failure: """For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line naming the files with no package.json above them, if any. @@ -58,16 +58,16 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], prefix: str | None unplaced = sorted(files) continue mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines)) - ran = run_tool(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder), prefix) + ran = run(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder)) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran) report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()]) return [*report, *([f"Not mutated, as no package.json is above them: {', '.join(unplaced)}."] if unplaced else [])] -def run_infection(top: str, base: str, prefix: str | None, jobs: int) -> list[str] | Failure: +def run_infection(top: str, base: str, run: Run, jobs: int) -> list[str] | Failure: """A line naming where Infection ran, top, then its own report of the mutants on the lines the branch changes since base.""" - ran = run_tool(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top, prefix) + ran = run(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else whole_output("Infection", ran) return ["Infection in the checkout's top:", *ran.output.splitlines()] diff --git a/bin/mutate_changes/main.py b/bin/mutate_changes/main.py index 1da6b37b..d4afaec5 100644 --- a/bin/mutate_changes/main.py +++ b/bin/mutate_changes/main.py @@ -42,22 +42,28 @@ Exit 1 too when git fails, a file cannot be read or copied, a tool cannot start, Infection also exit nonzero on a mutation score below a threshold the project sets, which fails the run as well and prints their whole report. """ +import functools +import os import sys import time +import typing from mutate_changes.changed_lines import added_lines, not_mutated, tool_for from machine_load.slots import CPUS_PER_SLOT -from git_cli.git_repo import default_ref, git, top +from git_cli.git_repo import default_ref, Git, top from failure import Failure +from git_cli import git_repo from mutate_changes.in_diff_tools import run_cargo_mutants, run_infection, run_stryker from mutate_changes.mutmut_tool import run_mutmut +from mutate_changes.tool_process import run_tool USAGE = "usage: mutate-changes [--base ] [--prefix ] [--jobs ]" # A panel of three readers, seated as the README's audience, picked the command's name and these options on 2026-11-11. OPTIONS = ("--base", "--jobs", "--prefix") -def main(argv: list[str]) -> int: +def main(argv: list[str], env: typing.Mapping[str, str]) -> int: + """Runs mutate-changes with the arguments argv; git and each tool run in the environment env.""" if argv in (["-h"], ["--help"]): print(__doc__.strip()) return 0 @@ -66,7 +72,7 @@ def main(argv: list[str]) -> int: print(f"{given.reason}; {USAGE}", file=sys.stderr) return 1 started = time.monotonic() - report = mutate(given) + report = mutate(given, env) if isinstance(report, Failure): print(report.reason, file=sys.stderr) return 1 @@ -89,12 +95,13 @@ def options(argv: list[str]) -> dict[str, str] | Failure: return given -def mutate(given: dict[str, str]) -> list[str] | Failure: +def mutate(given: dict[str, str], env: typing.Mapping[str, str]) -> list[str] | Failure: """Each tool's report on the lines the branch adds, then the lines naming the changed files no tool mutates.""" - checkout = top() + git = functools.partial(git_repo.git, env=env) + checkout = top(git) if isinstance(checkout, Failure): return checkout - base = given.get("--base") or default_ref(cwd=checkout) + base = given.get("--base") or default_ref(cwd=checkout, run=git) if isinstance(base, Failure): return base found = git("merge-base", base, "HEAD", cwd=checkout) @@ -105,27 +112,28 @@ def mutate(given: dict[str, str]) -> list[str] | Failure: if isinstance(names, Failure): return names paths = list(filter(None, names.split("\0"))) - changed = changed_by_tool(checkout, merge_base, paths) + changed = changed_by_tool(checkout, merge_base, paths, git) if isinstance(changed, Failure): return changed - prefix, jobs = given.get("--prefix"), int(given.get("--jobs", CPUS_PER_SLOT)) + jobs = int(given.get("--jobs", CPUS_PER_SLOT)) + run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg) report = [] if changed else ["No tool ran: the branch adds no line to a file that a tool mutates."] for tool, files in sorted(changed.items()): if tool == "cargo-mutants": - lines = run_cargo_mutants(checkout, merge_base, sorted(files), prefix, jobs) + lines = run_cargo_mutants(checkout, merge_base, sorted(files), run, git, jobs) elif tool == "infection": - lines = run_infection(checkout, merge_base, prefix, jobs) + lines = run_infection(checkout, merge_base, run, jobs) elif tool == "stryker": - lines = run_stryker(checkout, files, prefix, jobs) + lines = run_stryker(checkout, files, run, jobs) else: - lines = run_mutmut(checkout, files, prefix, jobs) + lines = run_mutmut(checkout, files, run, git, jobs) if isinstance(lines, Failure): return lines report.extend(lines) return [*report, *not_mutated(paths)] -def changed_by_tool(checkout: str, merge_base: str, paths: list[str]) -> dict[str, dict[str, frozenset[int]]] | Failure: +def changed_by_tool(checkout: str, merge_base: str, paths: list[str], git: Git) -> dict[str, dict[str, frozenset[int]]] | Failure: """Each tool's files among paths, by path from the checkout's top, with the lines the working tree adds since merge_base.""" changed: dict[str, dict[str, frozenset[int]]] = {} for path in paths: diff --git a/bin/mutate_changes/mutmut_tool.py b/bin/mutate_changes/mutmut_tool.py index d49f2b19..f1f67c08 100644 --- a/bin/mutate_changes/mutmut_tool.py +++ b/bin/mutate_changes/mutmut_tool.py @@ -11,10 +11,10 @@ import shutil import tomllib from mutate_changes.changed_lines import by_folder, label -from mutate_changes.tool_process import failed, Ran, remove, run_tool, scratch_folder +from mutate_changes.tool_process import failed, Ran, remove, Run, scratch_folder from failure import Failure from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses -from git_cli.git_repo import git +from git_cli.git_repo import Git from mutate_changes.mutmut_setup import left_out, mutmut_config CAUGHT = frozenset({"caught by type check", "killed"}) @@ -42,20 +42,20 @@ class Folder: return label(self.path) -def run_mutmut(top: str, changed: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure: +def run_mutmut(top: str, changed: dict[str, frozenset[int]], run: Run, git: Git, jobs: int) -> list[str] | Failure: """For each folder mutmut runs in, a line on what it mutated and left out, then a line per mutant on a changed line that its tests don't kill. changed maps each file, by its path from top, to its changed lines.""" report: list[str] = [] for path, files in sorted(by_folder(top, changed, CONFIGS).items()): - lines = mutate_folder(top, path, files, prefix, jobs) + lines = mutate_folder(top, path, files, run, git, jobs) if isinstance(lines, Failure): return lines report.extend(lines) return report -def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure: +def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], run: Run, git: Git, jobs: int) -> list[str] | Failure: root = os.path.join(top, path) folder = read_folder(root, path, files) if isinstance(folder, Failure): @@ -72,7 +72,7 @@ def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], prefix: try: copy = os.path.join(scratch, "copy") copied = copy_files(root, listed.split("\0"), copy) - return mutate_copy(copy, copied, folder, ["mutmut", "run", "--max-children", str(jobs), *globs], prefix) + return mutate_copy(copy, copied, folder, ["mutmut", "run", "--max-children", str(jobs), *globs], run) except OSError as failure: return Failure(f"could not set mutmut up in {scratch}, a copy of {root}: {failure}") finally: @@ -122,8 +122,8 @@ def copy_files(root: str, paths: list[str], copy: str) -> list[str]: return sorted(copied) -def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], prefix: str | None) -> list[str] | Failure: - ran = run_until_stats_pass(copy, copied, folder, argv, prefix) +def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], run: Run) -> list[str] | Failure: + ran = run_until_stats_pass(copy, copied, folder, argv, run) if isinstance(ran, Failure): return ran output, left = ran @@ -131,7 +131,7 @@ def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], p return Failure(f"mutmut in {folder.label} wrote no mutants/ in {copy}; --prefix must run it in $PWD") if NO_MUTANT in output: return [f"mutmut in {folder.label}: none of the functions the changed lines fall in has a mutant."] - results = run_tool(["mutmut", "results", "--all", "true"], copy, prefix) + results = run(["mutmut", "results", "--all", "true"], copy) if isinstance(results, Failure) or results.code: return results if isinstance(results, Failure) else failed(f"mutmut results in {folder.label}", results) shown, counted = not_killed(folder, statuses(results.output), copy) @@ -141,14 +141,14 @@ def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], p return [f"mutmut in {folder.label}: {counted} mutants on changed lines, {len(shown)} not killed.{unreached}{left_note}", *shown] -def run_until_stats_pass(copy: str, copied: list[str], folder: Folder, argv: list[str], prefix: str | None) -> tuple[str, list[str]] | Failure: +def run_until_stats_pass(copy: str, copied: list[str], folder: Folder, argv: list[str], run: Run) -> tuple[str, list[str]] | Failure: """mutmut's output, and the options that left out each test that fails before any mutant: mutmut runs no mutant while one fails.""" - ran = configured_run(copy, copied, folder, [], argv, prefix) + ran = configured_run(copy, copied, folder, [], argv, run) left: list[str] = [] if isinstance(ran, Ran) and STATS_FAILED in ran.output: - ran = configured_run(copy, copied, folder, LIST_FAILURES, argv, prefix) + ran = configured_run(copy, copied, folder, LIST_FAILURES, argv, run) if isinstance(ran, Ran) and STATS_FAILED in ran.output and (left := left_out(ran.output)): - ran = configured_run(copy, copied, folder, left, argv, prefix) + ran = configured_run(copy, copied, folder, left, argv, run) if isinstance(ran, Failure): return ran if ran.code and NO_MUTANT not in ran.output and NO_TEST not in ran.output: @@ -156,12 +156,12 @@ def run_until_stats_pass(copy: str, copied: list[str], folder: Folder, argv: lis return ran.output, left -def configured_run(copy: str, copied: list[str], folder: Folder, options: list[str], argv: list[str], prefix: str | None) -> Ran | Failure: +def configured_run(copy: str, copied: list[str], folder: Folder, options: list[str], argv: list[str], run: Run) -> Ran | Failure: config = mutmut_config(folder.setup, sorted(folder.files), copied, options) if isinstance(config, Failure): return Failure(f"{folder.label}: {config.reason}") pathlib.Path(copy, "setup.cfg").write_text(config, encoding="utf-8") - return run_tool(argv, copy, prefix) + return run(argv, copy) def not_killed(folder: Folder, found: dict[str, str], copy: str) -> tuple[list[str], int]: diff --git a/bin/mutate_changes/test_mutate_changes.py b/bin/mutate_changes/test_mutate_changes.py index 3e9eeb68..59c3b01e 100644 --- a/bin/mutate_changes/test_mutate_changes.py +++ b/bin/mutate_changes/test_mutate_changes.py @@ -8,8 +8,8 @@ import tempfile import textwrap import threading import time +import typing import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -226,8 +226,8 @@ class ToolProcess(unittest.TestCase): self.assertTrue(pathlib.Path(folder, "stopped").is_file()) def test_an_interrupted_tool_that_ignores_sigint_is_killed_after_the_grace_period(self): - with tempfile.TemporaryDirectory() as folder, unittest.mock.patch("mutate_changes.tool_process.GRACE_SECONDS", 0.5): - self.assertLess(self.interrupted(folder, "trap '' INT; echo $$ > started; sleep 60;"), 30) + with tempfile.TemporaryDirectory() as folder: + self.assertLess(self.interrupted(folder, "trap '' INT; echo $$ > started; sleep 60;", grace=0.5), 30) self.assert_ends(int(pathlib.Path(folder, "started").read_text())) def test_an_interrupt_ends_the_run_where_the_tool_s_processes_end_first(self): @@ -237,10 +237,10 @@ class ToolProcess(unittest.TestCase): killpg(group, number) raise ProcessLookupError - with unittest.mock.patch("os.killpg", then_gone), tempfile.TemporaryDirectory() as folder: - self.interrupted(folder, "sleep 60 & echo $! > started; wait;") + with tempfile.TemporaryDirectory() as folder: + self.interrupted(folder, "sleep 60 & echo $! > started; wait;", killpg=then_gone) - def interrupted(self, folder: str, script: str) -> float: + def interrupted(self, folder: str, script: str, **seams: typing.Any) -> float: """Run script as the prefix of a tool in folder, interrupt run_tool once script writes folder/started, and return how long run_tool took.""" started = pathlib.Path(folder, "started") @@ -252,7 +252,7 @@ class ToolProcess(unittest.TestCase): threading.Thread(target=interrupt, daemon=True).start() began = time.monotonic() with self.assertRaises(KeyboardInterrupt): - run_tool(["true"], folder, script) + run_tool(["true"], folder, **{"prefix": script, "env": os.environ, "killpg": os.killpg, **seams}) return time.monotonic() - began def assert_ends(self, pid: int) -> None: diff --git a/bin/mutate_changes/test_mutate_changes_runs.py b/bin/mutate_changes/test_mutate_changes_runs.py index 31454165..610c38e6 100644 --- a/bin/mutate_changes/test_mutate_changes_runs.py +++ b/bin/mutate_changes/test_mutate_changes_runs.py @@ -1,5 +1,6 @@ """mutate-changes run on a branch, against fake mutation tools that log how they were called.""" import contextlib +import functools import io import os import pathlib @@ -11,14 +12,15 @@ import sys import tempfile import time import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from mutate_changes.test_mutate_changes import ended +from git_cli import git_repo from test_env import isolated_env from mutate_changes import main from mutate_changes.in_diff_tools import run_cargo_mutants +from mutate_changes.tool_process import run_tool TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes" SETUP = "[mutmut]\ndo_not_mutate = *_old.py\n" @@ -138,8 +140,8 @@ class MutateChangesRuns(unittest.TestCase): before = os.getcwd() os.chdir(cwd or self.checkout) try: - with unittest.mock.patch.dict(os.environ, {**isolated_env(), **(env or {})}, clear=True), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: - code = main.main(list(args)) + with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: + code = main.main(list(args), {**isolated_env(), **(env or {})}) finally: os.chdir(before) return subprocess.CompletedProcess(args, code, out.getvalue(), err.getvalue()) @@ -361,8 +363,10 @@ class MutateChangesRuns(unittest.TestCase): (self.checkout / "-x.py").write_text("def f():\n\treturn 1\n") (self.checkout / "-x.rs").write_text("fn f() {}\n") base = self.git("rev-parse", "HEAD").strip() - self.assertEqual(main.changed_by_tool(str(self.checkout), base, ["-x.py", "-x.rs"]), {"cargo-mutants": {"-x.rs": frozenset({1})}, "mutmut": {"-x.py": frozenset({1, 2})}}) - ran = run_cargo_mutants(str(self.checkout), base, ["-x.rs"], f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", 1) + git = functools.partial(git_repo.git, env=isolated_env()) + self.assertEqual(main.changed_by_tool(str(self.checkout), base, ["-x.py", "-x.rs"], git), {"cargo-mutants": {"-x.rs": frozenset({1})}, "mutmut": {"-x.py": frozenset({1, 2})}}) + run = functools.partial(run_tool, prefix=f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", env=isolated_env(), killpg=os.killpg) + ran = run_cargo_mutants(str(self.checkout), base, ["-x.rs"], run, git, 1) self.assertIsInstance(ran, list) self.assertIn("+++ b/-x.rs\n", self.log.read_text()) diff --git a/bin/mutate_changes/tool_process.py b/bin/mutate_changes/tool_process.py index c5ce0023..674380a5 100644 --- a/bin/mutate_changes/tool_process.py +++ b/bin/mutate_changes/tool_process.py @@ -1,7 +1,6 @@ """Start a mutation tool, through --prefix's shell text where the run gives one, and wait for it; and make and remove its scratch folder.""" import contextlib import dataclasses -import os import pathlib import shlex import shutil @@ -9,6 +8,7 @@ import signal import subprocess import sys import tempfile +import typing from failure import Failure @@ -21,14 +21,21 @@ class Ran: output: str # stdout and stderr, as the tool interleaved them -def run_tool(argv: list[str], cwd: str, prefix: str | None) -> Ran | Failure: - """Run a tool in cwd, reading each byte of its output that is not UTF-8 as U+FFFD. +class Run(typing.Protocol): + """Runs a tool in cwd as `run_tool` does, with the run's prefix, environment and killpg bound.""" + + def __call__(self, argv: list[str], cwd: str) -> Ran | Failure: ... + + +# The tests hand in a shorter grace, and a killpg that finds the tool's processes gone. +def run_tool(argv: list[str], cwd: str, *, prefix: str | None, env: typing.Mapping[str, str], killpg: typing.Callable[[int, int], None], grace: float = GRACE_SECONDS) -> Ran | Failure: + """Run a tool in cwd with the environment env, reading each byte of its output that is not UTF-8 as U+FFFD. With a prefix, sh runs ` "$@"` with argv as its arguments, so the prefix keeps its own quoting and each of argv stays one word.""" command = ["sh", "-c", f'{prefix} "$@"', "sh", *argv] if prefix else argv try: # In a session of its own, the tool and each process it starts share one process group, which ends whole below. - process = subprocess.Popen(command, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", start_new_session=True) + process = subprocess.Popen(command, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", start_new_session=True) except OSError as failure: return Failure(f"{shlex.join(argv)} could not start: {failure.strerror}") try: @@ -38,12 +45,12 @@ def run_tool(argv: list[str], cwd: str, prefix: str | None) -> Ran | Failure: # reaches only this process, so pass the tool SIGINT first: a container's CLI, such as docker compose, then stops its container. try: with contextlib.suppress(ProcessLookupError): - os.killpg(process.pid, signal.SIGINT) + killpg(process.pid, signal.SIGINT) with contextlib.suppress(subprocess.TimeoutExpired): - process.wait(timeout=GRACE_SECONDS) + process.wait(timeout=grace) finally: with contextlib.suppress(ProcessLookupError): - os.killpg(process.pid, signal.SIGKILL) + killpg(process.pid, signal.SIGKILL) process.wait() raise return Ran(process.returncode, output) diff --git a/bin/notifier/mattermost.py b/bin/notifier/mattermost.py index 85ed5683..f2b8c6aa 100644 --- a/bin/notifier/mattermost.py +++ b/bin/notifier/mattermost.py @@ -1,10 +1,11 @@ """Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4. The `notifier` setting `mattermost` picks it.""" import dataclasses import pathlib +import typing import urllib.parse from failure import Failure -from rest_client.json_request import Http +from rest_client.json_request import Http, MessageOf from rest_client import json_request from rest_client.env_file import read_env @@ -53,9 +54,10 @@ def id_of(answer: object, request: str) -> str | Failure: return found if isinstance(found, str) and found else Failure(f"{request} answered without an id") -def http_json(method: str, url: str, token: str, body: object) -> object: +# request is json_request.http_json, but in the test of what this hands it. +def http_json(method: str, url: str, token: str, body: object, request: typing.Callable[[str, str, str, object, int, MessageOf], object] = json_request.http_json) -> object: """The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none.""" - return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message) + return request(method, url, f"Bearer {token}", body, TIMEOUT, error_message) def error_message(answer: object) -> str: diff --git a/bin/notifier/slack.py b/bin/notifier/slack.py index f96fe94c..0bf80c9a 100644 --- a/bin/notifier/slack.py +++ b/bin/notifier/slack.py @@ -2,9 +2,10 @@ import dataclasses import html import pathlib +import typing from failure import Failure -from rest_client.json_request import Http +from rest_client.json_request import Http, MessageOf from rest_client import json_request from rest_client.env_file import read_env @@ -41,9 +42,10 @@ def send(config: Config, message: str, http: Http) -> Failure | None: return Failure(f"POST /api/chat.postMessage refused the message: {error if isinstance(error, str) and error else 'no error code'}") -def http_json(method: str, url: str, token: str, body: object) -> object: +# request is json_request.http_json, but in the test of what this hands it. +def http_json(method: str, url: str, token: str, body: object, request: typing.Callable[[str, str, str, object, int, MessageOf], object] = json_request.http_json) -> object: """The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none.""" - return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message) + return request(method, url, f"Bearer {token}", body, TIMEOUT, error_message) def error_message(answer: object) -> str: diff --git a/bin/notifier/test_mattermost.py b/bin/notifier/test_mattermost.py index f1619864..57b9c1e9 100644 --- a/bin/notifier/test_mattermost.py +++ b/bin/notifier/test_mattermost.py @@ -2,7 +2,6 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -102,9 +101,9 @@ class Send(unittest.TestCase): class HttpJson(unittest.TestCase): def test_sends_the_token_as_a_bearer_and_reads_mattermosts_message_from_an_error(self): - with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"id": "post-id"}) as sent: - self.assertEqual(dm.http_json("POST", "https://chat.example/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"}) - sent.assert_called_once_with("POST", "https://chat.example/api/v4/posts", "Bearer secret-token", {"message": "hi"}, dm.TIMEOUT, dm.error_message) + sent = [] + self.assertEqual(dm.http_json("POST", "https://chat.example/api/v4/posts", "secret-token", {"message": "hi"}, lambda *request: sent.append(request) or {"id": "post-id"}), {"id": "post-id"}) + self.assertEqual(sent, [("POST", "https://chat.example/api/v4/posts", "Bearer secret-token", {"message": "hi"}, dm.TIMEOUT, dm.error_message)]) self.assertEqual(dm.TIMEOUT, 10) def test_reads_mattermosts_message_from_an_error_answer(self): diff --git a/bin/notifier/test_notifier.py b/bin/notifier/test_notifier.py index 1961e536..df3c9aa6 100644 --- a/bin/notifier/test_notifier.py +++ b/bin/notifier/test_notifier.py @@ -1,6 +1,7 @@ import contextlib import dataclasses import io +import os import pathlib import subprocess import sys @@ -73,14 +74,14 @@ class Notify(Project): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) with contextlib.chdir(self.checkout): - self.assertIsNone(system_effects(through("slack", slack)).dm("Which one?", None)) + self.assertIsNone(system_effects(self.home, os.environ, through("slack", slack)).dm("Which one?", None)) self.assertEqual(slack.requests, [SLACK_POST]) def test_a_dm_that_names_a_directory_goes_through_the_notifier_for_the_project_holding_it_from_any_current_directory(self): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) with contextlib.chdir(self.home): - self.assertIsNone(system_effects(through("slack", slack)).dm("Which one?", str(self.checkout))) + self.assertIsNone(system_effects(self.home, os.environ, through("slack", slack)).dm("Which one?", str(self.checkout))) self.assertEqual(slack.requests, [SLACK_POST]) def test_skips_the_notice_for_a_project_that_names_no_notifier_even_where_its_env_file_holds_the_keys(self): diff --git a/bin/notifier/test_slack.py b/bin/notifier/test_slack.py index 298f9837..69d173b4 100644 --- a/bin/notifier/test_slack.py +++ b/bin/notifier/test_slack.py @@ -2,7 +2,6 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -76,9 +75,9 @@ class Send(unittest.TestCase): class HttpJson(unittest.TestCase): def test_sends_the_token_as_a_bearer_and_reads_slacks_code_from_an_error(self): - with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"ok": True}) as sent: - self.assertEqual(dm.http_json("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"text": "hi"}), {"ok": True}) - sent.assert_called_once_with("POST", "https://slack.com/api/chat.postMessage", "Bearer xoxb-secret", {"text": "hi"}, dm.TIMEOUT, dm.error_message) + sent = [] + self.assertEqual(dm.http_json("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"text": "hi"}, lambda *request: sent.append(request) or {"ok": True}), {"ok": True}) + self.assertEqual(sent, [("POST", "https://slack.com/api/chat.postMessage", "Bearer xoxb-secret", {"text": "hi"}, dm.TIMEOUT, dm.error_message)]) for answer, code in (({"error": "ratelimited"}, "ratelimited"), ({"error": 7}, ""), ({}, ""), (["error"], "")): with self.subTest(answer=answer): self.assertEqual(dm.error_message(answer), code) diff --git a/bin/plan/test_ranking.py b/bin/plan/test_ranking.py index d73f707b..8c892838 100644 --- a/bin/plan/test_ranking.py +++ b/bin/plan/test_ranking.py @@ -293,7 +293,7 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00")) with contextlib.redirect_stderr(io.StringIO()): - ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank() + ranked = file_plan(located(temp, folder.parents[1]), todo).rank() self.assertIsInstance(ranked, ranking.Ranked) self.assertEqual(ranked.under_bar, []) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) @@ -310,10 +310,10 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="6.50")) with contextlib.redirect_stderr(io.StringIO()): - ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank() + ranked = file_plan(located(temp, folder.parents[1]), todo).rank() self.assertIsInstance(ranked, ranking.Ranked) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) - self.assertEqual(file_plan(located(temp, pathlib.Path.home()), todo).check(), []) + self.assertEqual(file_plan(located(temp, folder.parents[1]), todo).check(), []) class Risk(unittest.TestCase): diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index fd5d5032..672a4936 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -12,7 +12,7 @@ from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE from plan_store.markdown_edits import bold_cell, plain, unfit_text from plan_store.plans import cells, no_item, Plan, Written -from atlassian.jira import entry_of, finishing_transition, ISSUE_KEY, Link, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped +from atlassian.jira import entry_of, finishing_transition, ISSUE_KEY, Link, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from failure import Failure from plan.release import parsed, Release, tagged @@ -71,6 +71,8 @@ class JiraPlan: to_adf: ToAdf = markdown_to_adf # How a finished item moves; None where the config doesn't say, and then `finish` is a Failure. finish_by: Finish | None = None + # The pages a search may take before the read fails. + max_pages: int = MAX_PAGES # How add scores an item: by the config's formula and bar, with the goal weights the project's records give. scoring: ReadsScoring = dataclasses.field(kw_only=True) @@ -86,7 +88,7 @@ class JiraPlan: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization - answered = children(self.epic, authorization, self.http) + answered = children(self.epic, authorization, self.http, self.max_pages) if isinstance(answered, Failure): return answered issues = [issue_of(raw) for raw in answered] @@ -115,7 +117,7 @@ class JiraPlan: version = self.fix_version(filing.release, authorization) if isinstance(version, Failure): return version - answered = children(self.epic, authorization, self.http) + answered = children(self.epic, authorization, self.http, self.max_pages) if isinstance(answered, Failure): return answered if missing := missing_blocker(filing.blockers, keys_of(answered), self.label): @@ -170,7 +172,7 @@ class JiraPlan: def child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure: """Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_.""" - answered = children(self.epic, authorization, self.http) + answered = children(self.epic, authorization, self.http, self.max_pages) return answered if isinstance(answered, Failure) else self.child_in(answered, id_) def child_in(self, answered: list[object], id_: int) -> dict[str, typing.Any] | Failure: @@ -200,7 +202,7 @@ class JiraPlan: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization - answered = children(self.epic, authorization, self.http) + answered = children(self.epic, authorization, self.http, self.max_pages) if isinstance(answered, Failure): return answered raw = self.child_in(answered, id_) @@ -376,13 +378,13 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment return Revision(body, release, tuple(dict.fromkeys(f"{project_of(issue.key)}-{blocker}" for blocker in checked.blocked_by)) if BLOCKED_BY in named else None) -def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure: +def children(epic: Epic, authorization: str, http: Http, max_pages: int) -> list[object] | Failure: """The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan.""" # The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart. seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None) if isinstance(seen, Failure): return Failure(f"cannot read the epic {epic.key}: {seen.reason}") - return searched(epic.site, f"{epic.key}'s children", f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC', {"fields": ["summary", "description", "fixVersions", "issuelinks"], "properties": [PROPERTY]}, authorization, http) + return searched(epic.site, f"{epic.key}'s children", f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC', {"fields": ["summary", "description", "fixVersions", "issuelinks"], "properties": [PROPERTY]}, authorization, http, max_pages) def issue_of(raw: object) -> Issue | Failure: diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 821e37f9..46b6bbc4 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -4,7 +4,6 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -171,8 +170,7 @@ class JiraPlan(unittest.TestCase): def test_a_search_that_never_names_a_last_page_fails_the_read(self): self.pages = [{"issues": [], "nextPageToken": "more"}] * 2 - with unittest.mock.patch("atlassian.jira.MAX_PAGES", 2): - self.assertEqual(self.store().read(), Failure("the search for ABC-12's children did not end within 2 pages")) + self.assertEqual(dataclasses.replace(self.store(), max_pages=2).read(), Failure("the search for ABC-12's children did not end within 2 pages")) def test_an_issue_in_another_shape_fails_the_read_naming_it(self): good = issue("ABC-1") diff --git a/bin/project_config/doubles.py b/bin/project_config/doubles.py index d38ab31e..61a2a6b1 100644 --- a/bin/project_config/doubles.py +++ b/bin/project_config/doubles.py @@ -1,10 +1,8 @@ """Test doubles for the tools that read a project's config: a client's config text, and a checkout that a config names.""" -import os import pathlib import subprocess import tempfile import unittest -import unittest.mock from test_env import isolated_env @@ -34,13 +32,10 @@ def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "check def configured(test: unittest.TestCase, checkout: pathlib.Path, goals: str = "checkout:README.md", home: pathlib.Path | None = None) -> pathlib.Path: - """Makes checkout a git checkout that a config names, under home, else a HOME of its own, for the rest of the test; the config's folder.""" + """Makes checkout a git checkout that a config names, under home, else under a folder of its own for the rest of the test; the config's folder, two levels under that home.""" subprocess.run(["git", "init", "--quiet", str(checkout)], check=True, env=isolated_env()) if home is None: made = tempfile.TemporaryDirectory() test.addCleanup(made.cleanup) home = pathlib.Path(made.name) - patched = unittest.mock.patch.dict(os.environ, {"HOME": str(home)}) - patched.start() - test.addCleanup(patched.stop) return write_config(home, checkout, goals) diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index 00739d8e..b2bc6528 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -4,7 +4,6 @@ import subprocess import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) diff --git a/bin/project_record/test_project_record.py b/bin/project_record/test_project_record.py index 2f7a872f..5ef5cde3 100644 --- a/bin/project_record/test_project_record.py +++ b/bin/project_record/test_project_record.py @@ -130,17 +130,17 @@ class Act(unittest.TestCase): class BlackBox(unittest.TestCase): def setUp(self) -> None: self.top = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())).resolve() - configured(self, self.top) + self.home = configured(self, self.top).parents[1] def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]: - return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.top, env=dict(os.environ), text=True) + return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.top, env=os.environ | {"HOME": str(self.home)}, text=True) def test_a_file_record_opens_as_its_own_file_and_save_has_nothing_to_store(self): opened = self.run_tool("open", "decisions") self.assertEqual((opened.returncode, opened.stdout, opened.stderr), (0, f"{self.top}/docs/decisions.md\n", "")) saved = self.run_tool("save", "decisions") self.assertEqual((saved.returncode, saved.stdout, saved.stderr), (0, f"{self.top}/docs/decisions.md is the record itself, so nothing is left to store.\n", "")) - self.assertFalse((pathlib.Path(os.environ["HOME"]) / ".local").exists(), "a file record gets no copy") + self.assertFalse((self.home / ".local").exists(), "a file record gets no copy") def test_the_goals_file_opens_as_the_config_names_it(self): opened = self.run_tool("open", "goals-and-audience") @@ -153,7 +153,7 @@ class BlackBox(unittest.TestCase): self.assertIn("usage: project-record open|save , where is one of decisions, score-anchors, comprehension-history, reading-cost, changelog, goals-and-audience", ran.stderr) def test_exits_1_saying_why_where_no_config_names_the_checkout(self): - (pathlib.Path(os.environ["HOME"]) / ".claude-projects" / self.top.name / "config.toml").unlink() + (self.home / ".claude-projects" / self.top.name / "config.toml").unlink() ran = self.run_tool("open", "decisions") self.assertEqual((ran.returncode, ran.stdout), (1, "")) self.assertIn("no config names the checkout", ran.stderr) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 47ad8c30..e193e20f 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -98,14 +98,14 @@ from plan_store.stores import file_plan from project_config.main import located -def main(argv: list[str]) -> int: +def main(argv: list[str], home: pathlib.Path) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 args = parse_args(argv) if isinstance(args, Failure): return fail(args) - config = located(None, pathlib.Path.home()) + config = located(None, home) if isinstance(config, Failure): return fail(config) if config.plan_file is None and args == (True, None): @@ -144,4 +144,4 @@ def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path | None] | Failure: if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) + sys.exit(main(sys.argv[1:], pathlib.Path.home())) diff --git a/bin/reading_cost/test_reading_cost.py b/bin/reading_cost/test_reading_cost.py index 101ab675..52e1a708 100644 --- a/bin/reading_cost/test_reading_cost.py +++ b/bin/reading_cost/test_reading_cost.py @@ -16,7 +16,7 @@ from transcript_archive.write import archive from claude_code.entries import AssistantTurn from project_config.templates import BRANCH from reading_cost.measure import Checkout, Reading -from text_files import compressed +from text_files.doubles import compress from failure import Failure from reading_cost import figures, main, measure from transcript_archive.read import finished_chunks, FinishedChunk @@ -26,6 +26,7 @@ from record_store.fakes import MemoryStore from transcript_archive import outcomes from transcript_archive.location import project_archive from reading_cost.shell_reads import Reads, shell_reads +from text_files.file_writes import replace_file from project_config.doubles import write_config TOOL = pathlib.Path(__file__).resolve().parents[1] / "reading-cost" @@ -154,7 +155,7 @@ class ReadingCostTool(unittest.TestCase): transcript.write_bytes(jsonl([{"timestamp": str(at)}, *worker])) (transcript.with_suffix("") / "subagents" / "agent-a.jsonl").write_bytes(jsonl([said("1", "s1", tokens=1)])) with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(archive(self.archive, str(transcript), "Do it.", outcome("m", "merged", "j"), at)) + self.assertIsNone(archive(self.archive, str(transcript), "Do it.", outcome("m", "merged", "j"), at, replace=replace_file)) def run_tool(self, cwd, *args): return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd, env=self.env, text=True) @@ -177,7 +178,7 @@ class ReadingCostTool(unittest.TestCase): def test_measures_a_chunk_whose_archived_transcripts_are_compressed(self): self.archive_chunk(1790000000) for copy in self.archive.rglob("*.jsonl"): - self.assertIsNone(compressed.compress(copy)) + self.assertIsNone(compress(copy)) ran = self.run_tool(self.checkout) self.assertEqual(ran.returncode, 0, ran.stderr) self.assertIn("33 new input tokens before the first commit.", (self.checkout / "docs" / "reading-cost.md").read_text()) diff --git a/bin/repo_checks/test_no_patched_globals.py b/bin/repo_checks/test_no_patched_globals.py new file mode 100644 index 00000000..56a7bc88 --- /dev/null +++ b/bin/repo_checks/test_no_patched_globals.py @@ -0,0 +1,36 @@ +import ast +import pathlib +import subprocess +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from repo_checks import ROOT + +def patches(source: str) -> list[int]: + """The line numbers where source names mock's patch, as an attribute of mock or imported from it.""" + found = [] + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.Attribute) and node.attr == "patch" and ast.unparse(node.value).split(".")[-1] == "mock": + found.append(node.lineno) + elif isinstance(node, ast.ImportFrom) and node.module == "unittest.mock" and any(alias.name == "patch" for alias in node.names): + found.append(node.lineno) + return sorted(found) + + +class NoPatchedGlobals(unittest.TestCase): + def test_no_python_file_under_bin_patches_a_global(self): + # A file not yet staged counts too, so a new suite is checked before its first commit. + listed = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "bin/*.py"],capture_output=True, check=True, cwd=ROOT, text=True).stdout.split() + self.assertIn("bin/repo_checks/test_no_patched_globals.py", listed) + patching = {name for name in listed if patches((ROOT / name).read_text(encoding="utf-8"))} + self.assertEqual(patching, set(), "hand the code under test its effect as an argument instead") + + def test_each_spelling_of_patch_is_found(self): + source = "import unittest.mock\nfrom unittest import mock\nfrom unittest.mock import Mock, patch\n\nunittest.mock.patch.dict(a, b)\nmock.patch.object(a, 'b')\nmock.patch('a.b')\nmock.Mock()\n" + self.assertEqual(patches(source), [3, 5, 6, 7]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/repo_checks/test_package_cycles.py b/bin/repo_checks/test_package_cycles.py index 6b261ce8..103fa4ae 100644 --- a/bin/repo_checks/test_package_cycles.py +++ b/bin/repo_checks/test_package_cycles.py @@ -81,6 +81,13 @@ def cycle(imported: dict[str, set[str]]) -> list[str]: return [] +def tree(folder: pathlib.Path, sources: dict[str, str]) -> None: + """Writes each source to its path under folder.""" + for path, source in sources.items(): + (folder / path).parent.mkdir(parents=True, exist_ok=True) + (folder / path).write_text(source, encoding="utf-8") + + class PackageCycles(unittest.TestCase): def test_no_package_under_bin_imports_one_that_imports_it_back(self): self.assertEqual(cycle(package_imports(ROOT / "bin")), [], "move what both packages need into a package that imports neither") @@ -94,17 +101,13 @@ class PackageCycles(unittest.TestCase): def test_an_import_of_the_layer_above_is_found_in_tests_too(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) - for package, name, source in (("low", "mod.py", "import other\n"), ("low", "test_mod.py", "from high.mod import x\n"), ("low", "run.py", "def f():\n\timport high\n"), ("high", "mod.py", "import low\n")): - (folder / package).mkdir(exist_ok=True) - (folder / package / name).write_text(source) + tree(folder, {"low/mod.py": "import other\n", "low/test_mod.py": "from high.mod import x\n", "low/run.py": "def f():\n\timport high\n", "high/mod.py": "import low\n"}) self.assertEqual(upward_imports(folder, {"low": ("high",)}), ["low/run.py imports high", "low/test_mod.py imports high"]) def test_a_driver_imported_from_another_package_is_found_in_tests_too(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) - for package, name, source in (("a", "mod.py", "import a.other\n"), ("b", "test_mod.py", "from a.mod import x\n"), ("b", "mod.py", "def f():\n\timport a\n"), ("c", "mod.py", "import b\n")): - (folder / package).mkdir(exist_ok=True) - (folder / package / name).write_text(source) + tree(folder, {"a/mod.py": "import a.other\n", "b/test_mod.py": "from a.mod import x\n", "b/mod.py": "def f():\n\timport a\n", "c/mod.py": "import b\n"}) self.assertEqual(driver_imports(folder, ("a",)), ["b/mod.py imports a", "b/test_mod.py imports a"]) def test_no_module_imports_a_test_module_of_another_package(self): @@ -113,26 +116,23 @@ class PackageCycles(unittest.TestCase): def test_a_test_module_imported_from_another_package_is_found_however_it_is_spelled(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) - sources = ( - ("a", "test_mod.py", "from a.test_other import x\nfrom test_env import y\nfrom a.doubles import z\n"), - ("b", "test_mod.py", "from a.test_mod import x\n"), - ("b", "mod.py", "def f():\n\timport a.deep.test_far\n"), - ("c", "test_mod.py", "from a import test_mod\nfrom a.test_mod import x, y\n"), - ) - for package, name, source in sources: - (folder / package).mkdir(exist_ok=True) - (folder / package / name).write_text(source) - (folder / "test_root.py").write_text("from a.test_mod import x\n") + tree(folder, { + "a/test_mod.py": "from a.test_other import x\nfrom test_env import y\nfrom a.doubles import z\n", + "b/test_mod.py": "from a.test_mod import x\n", + "b/mod.py": "def f():\n\timport a.deep.test_far\n", + "c/test_mod.py": "from a import test_mod\nfrom a.test_mod import x, y\n", + "test_root.py": "from a.test_mod import x\n", + }) self.assertEqual(imports_of_test_modules(folder), ["b/mod.py imports a.deep.test_far", "b/test_mod.py imports a.test_mod", "c/test_mod.py imports a.test_mod", "test_root.py imports a.test_mod"]) def test_reads_an_import_deferred_into_a_function_and_leaves_out_tests(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) - for package, source in (("a", "def f():\n\tfrom b.mod import x\n"), ("b", "import a.mod\n"), ("c", "")): - (folder / package).mkdir() - (folder / package / "__init__.py").write_text("") - (folder / package / "mod.py").write_text(source) - (folder / "c" / "test_mod.py").write_text("import a\n") + tree(folder, { + "a/__init__.py": "", "a/mod.py": "def f():\n\tfrom b.mod import x\n", + "b/__init__.py": "", "b/mod.py": "import a.mod\n", + "c/__init__.py": "", "c/mod.py": "", "c/test_mod.py": "import a\n", + }) self.assertEqual(package_imports(folder), {"a": {"b"}, "b": {"a"}, "c": set()}) def test_a_cycle_through_a_deferred_import_is_found(self): diff --git a/bin/review-replay b/bin/review-replay index d8a8dee9..d0bdd0c4 100755 --- a/bin/review-replay +++ b/bin/review-replay @@ -8,4 +8,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from review_replay import main from loop_effects.effects import system_effects -sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects())) +sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects(pathlib.Path.home(), os.environ))) diff --git a/bin/review_replay/change_comparison.py b/bin/review_replay/change_comparison.py index 6eda0e9d..186e2ee1 100644 --- a/bin/review_replay/change_comparison.py +++ b/bin/review_replay/change_comparison.py @@ -1,5 +1,4 @@ """The experiment behind review-replay's --omit-claude-md, --bash-ceiling and --read-limit: three replays of a pass's rounds unchanged, one with the change, and the report that holds the one with it to what the others found: docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass missed no more findings than the most an unchanged replay missed`.""" -import sys import typing from review_replay.changes import Change @@ -10,8 +9,8 @@ from review_replay.rounds import Round from model_routing.ladder import Rung -def compared(reviewed: str, project: Rung, chosen: list[Round], change: Change, found_on: typing.Callable[[Round, Change | None], set[int] | Failure | Limited]) -> str | Limited: - """Replays chosen three times unchanged and once with change, as found_on(round, change or None) finds, and reports the comparison of the rounds no replay failed on; the Limited where claude hit its usage limit.""" +def compared(reviewed: str, project: Rung, chosen: list[Round], change: Change, found_on: typing.Callable[[Round, Change | None], set[int] | Failure | Limited], say: typing.Callable[[str], None], at_once: int) -> str | Limited: + """Replays chosen three times unchanged and once with change, as found_on(round, change or None) finds, and reports the comparison of the rounds no replay failed on; the Limited where claude hit its usage limit. It tells say each round a failed replay leaves out.""" runs: list[list[set[int] | Failure]] = [] for applied in (None, None, None, change): label = change.changed if applied else change.unchanged @@ -19,10 +18,10 @@ def compared(reviewed: str, project: Rung, chosen: list[Round], change: Change, def replay_one(one: Round, _: Rung, applied: Change | None = applied, label: str = label) -> set[int] | Failure | Limited: found = found_on(one, applied) if isinstance(found, Failure): - print(f" {one.root} {one.at} {label} failed, so the round is left out: {found.reason}", file=sys.stderr) + say(f" {one.root} {one.at} {label} failed, so the round is left out: {found.reason}") return found - found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, f"{reviewed} rounds {label}") + found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, f"{reviewed} rounds {label}", say, at_once) if isinstance(found, Limited): return found runs.append(found) diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index 87a6590b..8d9d4b40 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -67,22 +67,22 @@ none. Exit 1, saying why, on bad arguments, an unreadable archive or models file round to replay, or a usage limit. """ import pathlib -import sys import typing from transcript_archive.location import archive_root from review_replay.rounds import archived_rounds, Round, sample -from rung_replay.archive import archiving, print_report, replay_folder -from rung_replay.command import arguments_or_exit, failed, limited_exit +from rung_replay.archive import archiving, replay_folder +from rung_replay.command import arguments_or_exit, failed, limited_exit, print_report, say +from rung_replay.search import AT_ONCE from review_replay.changes import Change, CHANGES from review_replay.replay import codes_found, findings_replayed from review_replay.change_comparison import compared from loop_effects.effects import Effects +from review_replay.recall import ENOUGH_ROUNDS, recall_report, recalled from failure import Failure from model_routing.ladder import Ladder, Rung from claude_code.reply import Limited from model_routing.ladder_file import read_ladder, SHIPPED -from review_replay.recall import recall_report, recalled from review_rules.review_passes import ReviewedPass, REVIEWERS TOOL = "review-replay" @@ -90,7 +90,8 @@ USAGE = f"{TOOL} [{' | '.join(change.flag for change in CHANGES)} LATEST = 10 -def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int: +# A test sets the three limits: the fewest rounds a rung is tried on, the rounds replayed at once, and the folder each clone is made in, the system's temporary folder where None. +def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects, *, enough_rounds: int = ENOUGH_ROUNDS, at_once: int = AT_ONCE, scratch: pathlib.Path | None = None) -> int: # The shipped ladder, not a project's: the replay spans every project on the model. ladder = read_ladder(SHIPPED) if isinstance(ladder, Failure): @@ -105,29 +106,29 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff rounds = archived_rounds(REVIEWERS[reviewed], project.model, archive_root(home, env), home) if isinstance(rounds, Failure): return failed(TOOL, rounds.reason) - codes = codes_found(rounds, effects) + codes = codes_found(rounds, effects, say) if not codes: return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find") chosen = sample(list(codes), LATEST) folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now()) - effects = archiving(effects, folder) + effects = archiving(effects, folder, say) if change: - report = compared(reviewed, project, chosen, change, lambda found, applied: findings_replayed(found, codes[found], project, project, home, effects, applied)) + report = compared(reviewed, project, chosen, change, lambda found, applied: findings_replayed(found, codes[found], project, project, home, effects, applied, scratch), say, at_once) if isinstance(report, Limited): return limited_exit(TOOL, report) print_report(folder, report) return 0 def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited: - matched = findings_replayed(found, codes[found], rung, project, home, effects, None) + matched = findings_replayed(found, codes[found], rung, project, home, effects, None, scratch) if isinstance(matched, Failure): - print(f" {found.root} {found.at} on {rung} failed: {matched.reason}", file=sys.stderr, flush=True) + say(f" {found.root} {found.at} on {rung} failed: {matched.reason}") return matched - recall = recalled(chosen, ladder, project, replay_one, f"{reviewed} rounds") + recall = recalled(chosen, ladder, project, replay_one, f"{reviewed} rounds", say, at_once, enough_rounds) if isinstance(recall, Limited): return limited_exit(TOOL, recall) - print_report(folder, recall_report(reviewed, project, recall)) + print_report(folder, recall_report(reviewed, project, recall, enough_rounds)) return 0 diff --git a/bin/review_replay/recall.py b/bin/review_replay/recall.py index cd95cc26..e2b1e695 100644 --- a/bin/review_replay/recall.py +++ b/bin/review_replay/recall.py @@ -43,10 +43,6 @@ def candidates(ladder: Ladder, project: Rung) -> list[Rung]: return lower_efforts + down_from(ladder, project, ladder.rungs[0])[1:] -def enough(rounds: list[Round]) -> bool: - return len(rounds) >= ENOUGH_ROUNDS - - def count(found: list[set[int]]) -> int: return sum(map(len, found)) @@ -72,14 +68,14 @@ def tried(rung: Rung, rounds: list[Round], reference: Reference, found: list[set return RungRecall(rung, count(found), missed_red, 0 < needed(rounds, reference) <= count(found) and not missed_red) -def recall_report(reviewed: str, project: Rung, recall: Recall) -> str: +def recall_report(reviewed: str, project: Rung, recall: Recall, enough_rounds: int) -> str: rounds, (first, second) = recall.rounds, recall.reference lines = [ f"Replayed {len(rounds)} {reviewed} rounds of {project.model} projects, which hold {held(rounds)} 🔴 and 🟡 findings, twice on the project's rung, {project}.", *([f"Left out {recall.left_out} more, which a replay on the project's rung failed on; stderr says why."] if recall.left_out else []), ] - if not enough(rounds): - return "\n".join([*lines, f"No rung tried: fewer than {ENOUGH_ROUNDS} rounds were replayed on the project's rung without a failure."]) + if len(rounds) < enough_rounds: + return "\n".join([*lines, f"No rung tried: fewer than {enough_rounds} rounds were replayed on the project's rung without a failure."]) if needed(rounds, recall.reference) <= 0: return "\n".join([*lines, "No rung tried: the project's rung found too few of them to hold a rung to."]) lines.append(f"The project's rung found {count(first)} and then {count(second)} of the {held(rounds)}, {percent(mean_share(rounds, recall.reference))} on average, so a rung qualifies finding {needed(rounds, recall.reference)} or more of them, missing no 🔴 that both of its replays found.") @@ -95,11 +91,11 @@ def percent(fraction: Fraction) -> str: return f"{float(fraction):.0%}" -def recalled(chosen: list[Round], ladder: Ladder, project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited: - """Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify.""" +def recalled(chosen: list[Round], ladder: Ladder, project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str, say: typing.Callable[[str], None], at_once: int, enough_rounds: int) -> Recall | Limited: + """Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify; no candidate where fewer than enough_rounds rounds are left.""" runs: list[list[set[int] | Failure]] = [] for _ in range(2): - found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, what) + found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, what, say, at_once) if isinstance(found, Limited): return found runs.append(found) @@ -112,8 +108,8 @@ def recalled(chosen: list[Round], ladder: Ladder, project: Rung, replay_one: typ reference[1].append(second) recalls: list[RungRecall] = [] lowest = None - for rung in candidates(ladder, project) if enough(rounds) and needed(rounds, reference) > 0 else []: - on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what) + for rung in candidates(ladder, project) if len(rounds) >= enough_rounds and needed(rounds, reference) > 0 else []: + on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what, say, at_once) if isinstance(on_rung, Limited): return on_rung # A failed replay on a candidate found none, so it lowers that rung's count and never lifts it to what a rung needs. diff --git a/bin/review_replay/replay.py b/bin/review_replay/replay.py index ee66be74..8e3606f7 100644 --- a/bin/review_replay/replay.py +++ b/bin/review_replay/replay.py @@ -4,8 +4,8 @@ import json import os import pathlib import shutil -import sys import tempfile +import typing from review_replay.rounds import authored_by, lost_inputs, reviewed_path, Round from review_replay.changes import Change @@ -34,12 +34,12 @@ class Code: base: str -def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]: - """The code each round reviewed, as code_of finds it; stderr names each round left out, and why.""" +def codes_found(rounds: list[Round], effects: Effects, say: typing.Callable[[str], None]) -> dict[Round, Code]: + """The code each round reviewed, as code_of finds it; say is told each round left out, and why.""" codes = {} for found in rounds: if isinstance(code := code_of(found, effects), Failure): - print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True) + say(f"{found.root} {found.at} is left out: {code.reason}") else: codes[found] = code return codes @@ -75,9 +75,9 @@ def commit_log(listed: str) -> list[tuple[str, float]]: return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())] -def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects, change: Change | None) -> set[int] | Failure | Limited: - """The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them, or the Failure of the review or the match; where change is given, the replay runs with it, as `launch` says.""" - reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects, change)) +def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects, change: Change | None, scratch: pathlib.Path | None) -> set[int] | Failure | Limited: + """The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them, or the Failure of the review or the match; where change is given, the replay runs with it, as `launch` says. The clone is made under scratch, or under the system's temporary folder where it is None.""" + reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects, change, scratch)) if isinstance(reviewed, (Failure, Limited)): return reviewed return first_reply(lambda: match(found.findings, reviewed, found.root, project, effects)) @@ -91,10 +91,10 @@ class Copies: # The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is. -def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, change: Change | None) -> str | Failure | Limited: +def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, change: Change | None, scratch: pathlib.Path | None) -> str | Failure | Limited: try: (home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports: + with tempfile.TemporaryDirectory(prefix="review-replay-", dir=scratch, ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports: return reviewed_in(found, code, rung, Copies(clone, reports), home, effects, change) except OSError as failure: return Failure(f"could not prepare the replay: {failure}") diff --git a/bin/review_replay/test_recall.py b/bin/review_replay/test_recall.py index 1b4a926b..0889f537 100644 --- a/bin/review_replay/test_recall.py +++ b/bin/review_replay/test_recall.py @@ -1,12 +1,11 @@ -import contextlib -import io import pathlib import sys import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from review_replay.recall import candidates, needed, Recall, recall_report, recalled, tried +from rung_replay.search import AT_ONCE +from review_replay.recall import candidates, ENOUGH_ROUNDS, needed, Recall, recall_report, recalled, tried from review_replay.rounds import is_red, Round from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder import Rung @@ -44,8 +43,7 @@ class Recalled(unittest.TestCase): def test_tries_the_rungs_below_where_the_project_rung_needs_one_finding(self): # Eight findings, of which both replays on the project's rung find one: a share of an eighth, a tenth under which leaves one finding needed. rounds = [a_round(at, ("🟡 a",)) for at in range(8)] - with contextlib.redirect_stderr(io.StringIO()): - recall = recalled(rounds, LADDER, REFERENCE, lambda one, rung: {0} if one == rounds[0] else set(), "prose rounds") + recall = recalled(rounds, LADDER, REFERENCE, lambda one, rung: {0} if one == rounds[0] else set(), "prose rounds", lambda text: None, AT_ONCE, ENOUGH_ROUNDS) self.assertEqual(([one.rung for one in recall.tried], recall.lowest), ([LOW, SONNET], SONNET)) @@ -96,7 +94,7 @@ class RecallReport(unittest.TestCase): rounds, reference = self.EIGHT low = tried(LOW, rounds, reference, [{0, 1, 2}, {0, 1, 2}] * 4) sonnet = tried(SONNET, rounds, reference, [{1, 2, 3, 4}, {0}] * 4) - lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 1, [low, sonnet], LOW)).splitlines() + lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 1, [low, sonnet], LOW), ENOUGH_ROUNDS).splitlines() self.assertEqual(lines, [ "Replayed 8 prose rounds of claude-opus-5-5 projects, which hold 40 🔴 and 🟡 findings, twice on the project's rung, claude-opus-5-5 at medium effort.", "Left out 1 more, which a replay on the project's rung failed on; stderr says why.", @@ -108,17 +106,17 @@ class RecallReport(unittest.TestCase): ]) def test_says_why_no_rung_was_tried(self): - few = recall_report("prose", REFERENCE, Recall(ROUNDS, (FIRST, SECOND), 0, [], None)).splitlines() + few = recall_report("prose", REFERENCE, Recall(ROUNDS, (FIRST, SECOND), 0, [], None), ENOUGH_ROUNDS).splitlines() self.assertEqual(few[1:], ["No rung tried: fewer than 8 rounds were replayed on the project's rung without a failure."]) rounds, _ = self.EIGHT for reference in (([set()] * 8, [set()] * 8), (TENTH[0] * 4, TENTH[1] * 4)): - too_few = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [], None)).splitlines() + too_few = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [], None), ENOUGH_ROUNDS).splitlines() self.assertEqual(too_few[1:], ["No rung tried: the project's rung found too few of them to hold a rung to."]) def test_names_no_rung_where_none_qualifies(self): rounds, reference = self.EIGHT low = tried(LOW, rounds, reference, [{0}, {0}] * 4) - lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [low], None)).splitlines() + lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [low], None), ENOUGH_ROUNDS).splitlines() self.assertEqual(lines[-2:], ["claude-opus-5-5 at low effort found 8, 20%, and missed no such 🔴: it doesn't qualify.", "Lowest rung that qualifies: none below the project's rung"]) diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index cd6004c6..feb9c22c 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -10,13 +10,12 @@ import subprocess import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from review_replay.rounds import authored_by, lost_inputs, recorded_findings, reviewed_path, Round, round_from, sample, stamp_seconds -from review_replay import changes, main, recall, replay -from text_files import compressed +from review_replay import changes, main, replay +from text_files.doubles import compress from project_config.doubles import configured, write_config from loop_effects.effects import Effects, system_effects from claude_code.entries import entry_from @@ -24,7 +23,6 @@ from failure import Failure from review_rules.reviewer_context import reviewer_context from review_rules.review_passes import REVIEWERS from model_routing.ladder import Rung -from rung_replay import search TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay" REFERENCE = Rung("claude-opus-5-5", "medium") @@ -172,7 +170,7 @@ class Match(unittest.TestCase): self.asked.append((args, cwd, prompt)) return subprocess.CompletedProcess(args, 0, stdout, "") - return replay.match(("🔴 a", "🟡 b"), "the other report", "/code/p", REFERENCE, dataclasses.replace(system_effects(), claude=claude)) + return replay.match(("🔴 a", "🟡 b"), "the other report", "/code/p", REFERENCE, dataclasses.replace(system_effects(pathlib.Path.home(), os.environ), claude=claude)) def test_asks_for_the_numbered_findings_the_other_report_raises_as_json_with_no_tools(self): self.run_match("{}") @@ -222,7 +220,7 @@ class Main(unittest.TestCase): self.write_chunk(key, "c1", "2026-10-14T10:00:00Z") (self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n") # The fixture holds one round. - self.enterContext(unittest.mock.patch.object(recall, "ENOUGH_ROUNDS", 1)) + self.limits = {"enough_rounds": 1} self.reviews = [] self.review_settings = [] self.agents = set() @@ -270,10 +268,10 @@ 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, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects(pathlib.Path.home(), os.environ).git, input=unused, local_time=unused, memory=unused, now=lambda: 1790000000.0, on_terminal=unused, python=unused, replace_file=unused, sleep=unused, stream_claude=unused, timer=unused, tmux=unused, tmux_on_terminal=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main(argv, env, self.home, effects) + code = main.main(argv, env, self.home, effects, **self.limits) return code, out.getvalue(), err.getvalue() def test_keeps_each_reviewer_and_match_run_and_the_printed_report_in_one_folder_of_the_archive(self): @@ -428,14 +426,14 @@ class Main(unittest.TestCase): def test_replays_rounds_whose_archived_transcripts_are_compressed(self): for copy in self.archive.rglob("*.jsonl"): - self.assertIsNone(compressed.compress(copy)) + self.assertIsNone(compress(copy)) code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [1] if rung == LOW else [0, 1]}) self.assertEqual(code, 0, err) self.assertTrue(out.startswith("Replayed 1 stability rounds of claude-opus-5-5 projects,"), out) def test_copies_a_compressed_report_from_before_the_round_under_its_plain_name(self): folder = self.review_folder_with_round_1() - self.assertIsNone(compressed.compress(folder / "stability-round-1.md")) + self.assertIsNone(compress(folder / "stability-round-1.md")) self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.") seen = [] @@ -513,7 +511,7 @@ class Main(unittest.TestCase): (folder / "stability-round-1.md").chmod(0) self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.") scratch = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) - self.enterContext(unittest.mock.patch.object(tempfile, "tempdir", str(scratch))) + self.limits["scratch"] = scratch code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused) self.assertEqual(code, 0, err) self.assertEqual(self.reviews, []) @@ -529,7 +527,7 @@ class Main(unittest.TestCase): def test_leaves_out_a_round_that_either_replay_on_the_project_rung_failed_on(self): self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z") - self.enterContext(unittest.mock.patch.object(search, "AT_ONCE", 1)) + self.limits["at_once"] = 1 # One round at a time, three tries on a round reply with no report: the first replay's on its first round, then the second replay's on its first, after the first replay's two reviews. Every other review replies. for failing in (range(3), range(2, 5)): with self.subTest(failing=failing): diff --git a/bin/routing_figures/state.py b/bin/routing_figures/state.py index 5db0255d..19054022 100644 --- a/bin/routing_figures/state.py +++ b/bin/routing_figures/state.py @@ -5,10 +5,11 @@ import dataclasses import json import pathlib import re +import typing from routing_figures.calls import Call, SENTENCES from failure import Failure -from text_files.file_writes import replace_file, replace_json +from text_files.file_writes import replace_json from text_files.utc_stamp import STAMPED CYCLES_PER_CHECK = 20 @@ -100,8 +101,8 @@ def raised(root: pathlib.Path) -> Raised | Failure: return Raised(since, frozenset(entry.call for entry in kept.raised if entry.at > since)) -def mark_raised(root: pathlib.Path, calls: list[Call], at: str) -> Failure | None: - """Keeps the calls in STATE, and adds a line for each to RAISED.""" +def mark_raised(root: pathlib.Path, calls: list[Call], at: str, replace: typing.Callable[[pathlib.Path, bytes], Failure | None]) -> Failure | None: + """Keeps the calls in STATE, and adds a line for each to RAISED, which replace writes as replace_file does.""" kept = read_state(root) if isinstance(kept, Failure): return kept @@ -112,7 +113,7 @@ def mark_raised(root: pathlib.Path, calls: list[Call], at: str) -> Failure | Non return unwritten # The first line opens a list below the heading; each later one joins it. gap = "\n" if RAISED_LINE.search(text) else "\n\n" - unwritten = replace_file(root / RAISED, (text.rstrip("\n") + gap + "".join(f"- {at} {call.sentence()}\n" for call in calls)).encode()) + unwritten = replace(root / RAISED, (text.rstrip("\n") + gap + "".join(f"- {at} {call.sentence()}\n" for call in calls)).encode()) return Failure(f"could not write {root / RAISED}: {unwritten.reason}") if unwritten else None diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index c7b9e68a..badf3b78 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -10,7 +10,6 @@ import subprocess import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -20,7 +19,7 @@ from project_config.templates import BARE, Titles from branch_chunks.cut import BranchChunk from routing_figures.calls import Call, calls, totals from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Reports, Subagent -from text_files import compressed +from text_files.doubles import compress from project_config.doubles import configured, write_config from routing_figures.state import due from claude_code.entries import entry_from @@ -30,6 +29,7 @@ from plan.todo_table import Item from transcript_archive import outcomes, write from model_routing.ladder_file import read_ladder, SHIPPED from routing_figures.render import render +from text_files.file_writes import replace_file from model_routing.route import Route from model_routing.ladder import Rung @@ -356,7 +356,7 @@ class Archive(unittest.TestCase): def test_measures_a_chunk_whose_transcripts_are_compressed(self): self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")])) for copy in self.root.rglob("*.jsonl"): - self.assertIsNone(compressed.compress(copy)) + self.assertIsNone(compress(copy)) found = archive.measure_archive(self.root, "/h", "", no_checkout) self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0}) @@ -365,8 +365,7 @@ class Archive(unittest.TestCase): env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)} self.ship_then_fix(home / "code" / "log", env) self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - with unittest.mock.patch.dict(os.environ, env, clear=True): - found = archive.measure_archive(self.root, str(home), "", git_repo.git) + found = archive.measure_archive(self.root, str(home), "", git_repo.git) self.assertEqual([(chunk.dollars["project"].keys(), chunk.fixed_later) for chunk in found.chunks], [({"log": 0}.keys(), 1)]) def test_reads_a_projects_round_titles_and_its_branchs_history_through_its_configs_templates(self): @@ -377,10 +376,9 @@ class Archive(unittest.TestCase): config = write_config(home, home / "code" / "log") / "config.toml" worker = [message(f"m{n}", "2026-10-14T09:00:00Z", call("Bash", command=f"git commit -m '{round_title.format(n)}'")) for n in (1, 2)] self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), worker) - with unittest.mock.patch.dict(os.environ, env, clear=True): - bare = archive.measure_archive(self.root, str(home), "", git_repo.git) - config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\n') - templated = archive.measure_archive(self.root, str(home), "", git_repo.git) + bare = archive.measure_archive(self.root, str(home), "", git_repo.git) + config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\n') + templated = archive.measure_archive(self.root, str(home), "", git_repo.git) self.assertEqual([(chunk.rounds_past_first, chunk.fixed_later) for chunk in bare.chunks], [(0, 0)]) self.assertEqual([(chunk.rounds_past_first, chunk.fixed_later) for chunk in templated.chunks], [(1, 1)]) @@ -391,8 +389,7 @@ class Archive(unittest.TestCase): config = write_config(home, home / "code" / "log") / "config.toml" config.write_text(config.read_text() + 'commit-title = "PAY-{id}"\n') self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - with unittest.mock.patch.dict(os.environ, env, clear=True): - found = archive.measure_archive(self.root, str(home), "", git_repo.git) + found = archive.measure_archive(self.root, str(home), "", git_repo.git) self.assertEqual(found.chunks, []) self.assertEqual(len(found.unread), 1) self.assertRegex(found.unread[0], r"^log: none of its chunks is measured: .*`commit-title` is 'PAY-\{id\}'") @@ -407,8 +404,7 @@ class Archive(unittest.TestCase): def recording(*args, **options): made.append((args[0], options)) return git_repo.git(*args, **options) - with unittest.mock.patch.dict(os.environ, env, clear=True): - archive.measure_archive(self.root, str(home), "", recording) + archive.measure_archive(self.root, str(home), "", recording) self.assertTrue(all(options.get("guarded") is True for _, options in made)) read = [options.get("timeout") for command, options in made if command in ("log", "ls-tree", "show", "diff", "blame")] self.assertEqual(set(read), {archive.GIT_TIMEOUT}) @@ -420,8 +416,7 @@ class Archive(unittest.TestCase): (home / "code" / "log").mkdir(parents=True) subprocess.run(["git", "init", "-q"], cwd=home / "code" / "log", check=True, env=env, capture_output=True) self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - with unittest.mock.patch.dict(os.environ, env, clear=True): - found = archive.measure_archive(self.root, str(home), "", git_repo.git) + found = archive.measure_archive(self.root, str(home), "", git_repo.git) self.assertEqual(found.unread, ("log: no origin remote, and no main or master branch to take as the default branch",)) def test_names_each_project_whose_history_it_cannot_read(self): @@ -458,9 +453,9 @@ class Archive(unittest.TestCase): first = message("m1", "2026-09-21T00:00:00Z") transcript.write_text(json.dumps(first) + "\n") with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000)) + self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000, replace=replace_file)) transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n") - self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800)) + self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800, replace=replace_file)) (found,) = archive.measure_archive(kept, "/h", "", no_checkout).chunks self.assertEqual((found.start, found.unfinished), (LOW, 1)) self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0}) @@ -485,14 +480,14 @@ class Archive(unittest.TestCase): def test_reads_the_calls_raised_since_the_latest_reset(self): a, b, c = Call("reports", ("Explore",)), Call("rounds", ("x", "y")), Call("unfinished", ("x", "y")) self.assertEqual(state.raised(self.root), state.Raised("", frozenset())) - self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T00:00:00Z")) - self.assertIsNone(state.mark_raised(self.root, [b, c], "2026-10-15T01:00:00Z")) + self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T00:00:00Z", replace_file)) + self.assertIsNone(state.mark_raised(self.root, [b, c], "2026-10-15T01:00:00Z", replace_file)) self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n- 2026-10-15T00:00:00Z {a.sentence()}\n- 2026-10-15T01:00:00Z {b.sentence()}\n- 2026-10-15T01:00:00Z {c.sentence()}\n") self.assertEqual(state.raised(self.root), state.Raised("", frozenset({a, b, c}))) with open(self.root / state.RAISED, "a") as handle: handle.write("- 2026-10-15T01:00:00Z Reset\n") self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset()), "a call stamped at the reset's second was raised before it") - self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T02:00:00Z")) + self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T02:00:00Z", replace_file)) self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset({a}))) def test_fails_when_it_cannot_keep_the_state(self): @@ -500,17 +495,15 @@ class Archive(unittest.TestCase): self.root.chmod(0o555) self.addCleanup(self.root.chmod, 0o755) self.assertIsInstance(state.mark_measured(self.root, 40), Failure) - self.assertIsInstance(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure) + self.assertIsInstance(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", replace_file), Failure) def test_fails_when_it_cannot_list_a_raised_call_for_the_human(self): self.assertIsNone(state.mark_measured(self.root, 40)) - written = state.replace_file - with unittest.mock.patch.object(state, "replace_file", lambda path, data: Failure("full") if path.name == state.RAISED else written(path, data)): - self.assertEqual(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure(f"could not write {self.root / state.RAISED}: full")) + self.assertEqual(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", replace=lambda path, data: Failure("full")), Failure(f"could not write {self.root / state.RAISED}: full")) def test_knows_a_raised_call_by_its_fields_whatever_its_line_reads(self): call = Call("reports", ("Explore",)) - self.assertIsNone(state.mark_raised(self.root, [call], "2026-10-15T00:00:00Z")) + self.assertIsNone(state.mark_raised(self.root, [call], "2026-10-15T00:00:00Z", replace_file)) (self.root / state.RAISED).write_text("# Routing calls raised\n\n- 2026-10-15T00:00:00Z Reworded.\n") self.assertEqual(state.raised(self.root).calls, frozenset({call})) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 7e969d38..ec9bbd9e 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -9,7 +9,6 @@ import sys import tempfile import typing import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -982,6 +981,12 @@ class Hook(unittest.TestCase): git(self.repo, "init", "-q", "-b", "main") git(self.repo, "commit", "-q", "--allow-empty", "-m", "base") git(self.repo, "checkout", "-q", "-b", "chunk") + self.env: dict[str, str] = {} + + def configured(self) -> pathlib.Path: + folder = configured(self, pathlib.Path(self.repo)) + self.env = {"HOME": str(folder.parents[1])} + return folder def test_runs_git_guarded(self): git(self.repo, "config", "core.fsmonitor", "/bin/false") @@ -1109,7 +1114,7 @@ class Hook(unittest.TestCase): self.assertEqual(hook(call, self.repo).returncode, 2) def round_commit(self, title: str, given: str = "") -> subprocess.CompletedProcess: - return hook({"cwd": self.repo, "tool_input": {"command": f"git commit {given}-m '{title}'"}, "tool_name": "Bash"}, self.repo) + return hook({"cwd": self.repo, "tool_input": {"command": f"git commit {given}-m '{title}'"}, "tool_name": "Bash"}, self.repo, self.env) def test_a_round_commit_whose_counts_differ_from_its_report_is_refused(self): home = tempfile.mkdtemp() @@ -1189,7 +1194,7 @@ class Hook(unittest.TestCase): self.assertEqual(self.round_commit("Answer stability round 1: 0 🔴, 1 🟡 (0 misread); c").returncode, 0, "another chunk's rounds, fast-forwarded into the default branch, are not this chunk's") def test_a_commit_is_titled_by_the_configs_template_and_its_round_title_read_through_it(self): - config = configured(self, pathlib.Path(self.repo)) / "config.toml" + config = self.configured() / "config.toml" config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\n') git(self.repo, "checkout", "-q", "-b", "item-7") for title in ["PAY-7 - Answer stability round 1: 1 🔴, 0 🟡 (0 misread); a", "PAY-7 - Answer stability round 2: 0 🔴, 1 🟡 (0 misread); c"]: @@ -1205,7 +1210,7 @@ class Hook(unittest.TestCase): self.assertEqual(self.round_commit("Tidy # rule-override commit-title: the client asked for this title").returncode, 0) def test_a_commit_on_a_branch_that_doesnt_fit_the_configs_branch_template_takes_a_bare_title(self): - config = configured(self, pathlib.Path(self.repo)) / "config.toml" + config = self.configured() / "config.toml" config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\nbranch = "feature/PAY-{id}"\n') git(self.repo, "checkout", "-q", "-b", "release-review-0.3.0") self.assertEqual(self.round_commit("Release review of 0.3.0", "--allow-empty ").returncode, 0) @@ -1217,7 +1222,7 @@ class Hook(unittest.TestCase): self.assertEqual(self.round_commit("PAY-7 - Tidy").returncode, 0) def test_a_commit_is_refused_naming_the_fault_while_a_config_cannot_be_read(self): - config = configured(self, pathlib.Path(self.repo)) / "config.toml" + config = self.configured() / "config.toml" config.write_text(config.read_text() + 'commit-title = "PAY-{id}"\n') refused = self.round_commit("PAY-7 - Tidy") self.assertEqual(refused.returncode, 2) @@ -1234,21 +1239,21 @@ class Hook(unittest.TestCase): self.assertEqual(self.round_commit("Tidy").returncode, 0) def test_a_commit_while_an_unranked_todo_has_changes_is_blocked(self): - configured(self, pathlib.Path(self.repo)) + self.configured() pathlib.Path(self.repo, "docs").mkdir() for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO)]: pathlib.Path(self.repo, name).write_text(content) git(self.repo, "add", "README.md", "docs", "todo.md") git(self.repo, "commit", "-qm", "x", "--no-verify") call = {"cwd": self.repo, "tool_input": {"command": "git add -A && git commit -m x"}, "tool_name": "Bash"} - self.assertEqual(hook(call, self.repo).returncode, 0, "todo.md is unchanged") + self.assertEqual(hook(call, self.repo, self.env).returncode, 0, "todo.md is unchanged") pathlib.Path(self.repo, "todo.md").write_text(TODO + "\n") - ran = hook(call, self.repo) + ran = hook(call, self.repo, self.env) self.assertEqual(ran.returncode, 2) self.assertIn("todo.md: not ranked", ran.stderr) def test_a_staged_todo_change_is_checked_and_no_clean_filter_runs(self): - configured(self, pathlib.Path(self.repo)) + self.configured() pathlib.Path(self.repo, "docs").mkdir() for name, content in [("README.md", README), ("docs/decisions.md", DECISIONS), ("todo.md", TODO), (".gitattributes", "todo.md filter=planted\n")]: pathlib.Path(self.repo, name).write_text(content) @@ -1257,7 +1262,7 @@ class Hook(unittest.TestCase): pathlib.Path(self.repo, "ran").unlink(missing_ok=True) # A stat-dirty index entry, as extracting an archive leaves, is what makes `git status` re-run the filter. os.utime(pathlib.Path(self.repo, "todo.md"), (1, 1)) - ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, self.repo) + ran = hook({"cwd": self.repo, "tool_input": {"command": "git commit -m x"}, "tool_name": "Bash"}, self.repo, self.env) self.assertEqual(ran.returncode, 2, ran.stderr) self.assertFalse(pathlib.Path(self.repo, "ran").exists()) @@ -1316,6 +1321,7 @@ class TodoRankCheck(unittest.TestCase): pathlib.Path(checkout, "bin", "rank_todo.py").write_text(stub) pathlib.Path(checkout, "todo.md").write_text("# todo\n") self.config = configured(self, pathlib.Path(checkout)) / "config.toml" + self.home = self.config.parents[2] return checkout def test_a_changed_plan_that_cannot_be_read_is_a_breach(self): @@ -1324,16 +1330,16 @@ class TodoRankCheck(unittest.TestCase): self.addCleanup(pathlib.Path(checkout, "todo.md").chmod, 0o600) self.assertEqual(["Permission denied" in detail for detail in self.details(checkout)], [True]) - def details(self, checkout: str) -> list[str]: - return [breach.detail for breach in todo_breaches(checkout, pathlib.Path.home(), pathlib.Path(self.own))] + def details(self, checkout: str, **limit: float) -> list[str]: + return [breach.detail for breach in todo_breaches(checkout, self.home, pathlib.Path(self.own), **limit)] def test_a_checkout_of_the_hooks_repo_runs_its_own_rank_todo(self): checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) self.assertEqual(self.details(checkout), [f"own script checked {checkout}/todo.md"]) top = str(pathlib.Path(checkout).resolve()) - self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, pathlib.Path.home(), pathlib.Path(self.own))], [("todo-rank-check", top)]) + self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, self.home, pathlib.Path(self.own))], [("todo-rank-check", top)]) self.config.unlink() - self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, pathlib.Path.home(), pathlib.Path(self.own))], [("todo-rank-check", top)], "a todo.md with no config") + self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, self.home, pathlib.Path(self.own))], [("todo-rank-check", top)], "a todo.md with no config") def test_its_own_rank_todo_passing_passes(self): self.assertEqual(self.details(self.changed_plan(f"{self.folder}/clone", "")), []) @@ -1344,8 +1350,7 @@ class TodoRankCheck(unittest.TestCase): def test_its_own_rank_todo_running_past_the_limit_is_named(self): checkout = self.changed_plan(f"{self.folder}/clone", "import signal\nsignal.pause()\n") - with unittest.mock.patch("rule_hook.todo_check.OWN_CHECK_SECONDS", 0.2): - self.assertEqual(self.details(checkout), [f"{checkout}/bin/rank_todo.py --check did not finish in 0.2 seconds"]) + self.assertEqual(self.details(checkout, seconds=0.2), [f"{checkout}/bin/rank_todo.py --check did not finish in 0.2 seconds"]) def test_another_repos_rank_todo_never_runs(self): reasons = self.details(self.changed_plan(self.other, self.STUB)) @@ -1375,7 +1380,7 @@ class TodoRankCheck(unittest.TestCase): self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) (self.config.parent / "todo.md").write_text("# todo\n") self.assertEqual(self.details(folder), [f"own script checked {folder}/todo.md"], "checked with the checkout's own rank_todo.py, as a commit there would be") - self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(folder, pathlib.Path.home(), pathlib.Path(self.own))], [("todo-rank-check", str(pathlib.Path(folder).resolve()))]) + self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(folder, self.home, pathlib.Path(self.own))], [("todo-rank-check", str(pathlib.Path(folder).resolve()))]) git(folder, "add", "-A") git(folder, "commit", "-q", "-m", "plan") self.assertEqual(self.details(folder), [], "committed, so unchanged") diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index 0a938af3..e40c3082 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -19,14 +19,14 @@ OWN = pathlib.Path(__file__).resolve().parents[2] OWN_CHECK_SECONDS = 20 -def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN) -> list[Breach]: +def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN, seconds: float = OWN_CHECK_SECONDS) -> list[Breach]: """Why the plan of directory's project is not ranked, where the plan has changed; the plan is the todo.md its config names. directory may also be in a config's folder, a git repo of its own.""" top = guarded_git(directory, "rev-parse", "--show-toplevel") if isinstance(top, Failure): return [] held_here = held(pathlib.Path(top), home) if held_here is not None: - return folder_breaches(top, held_here, own) + return folder_breaches(top, held_here, own, seconds) config = located(top, home, functools.partial(git, guarded=True)) if isinstance(config, Failure): # A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config. @@ -39,10 +39,10 @@ def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN) - # A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call. if tracked is not None and not changed(top, todo, tracked): return [] - return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own)] + return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own, seconds)] -def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path) -> list[Breach]: +def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path, seconds: float) -> list[Breach]: """Why the plan kept in top, a config's folder, is not ranked, where the plan has changed in that folder's repo; ranked as for a commit in the project's checkout. A config that fails to load doesn't block anything here, so that the commit that fixes it goes through.""" @@ -53,18 +53,18 @@ def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path return [] if not todo.is_file() or not changed(str(config.folder), todo, todo.relative_to(config.folder).as_posix()): return [] - return [Breach("todo-rank-check", line, top) for line in check_failures(str(config.top), todo, config, own)] + return [Breach("todo-rank-check", line, top) for line in check_failures(str(config.top), todo, config, own, seconds)] -def check_failures(top: str, todo: pathlib.Path, config: ProjectConfig, own: pathlib.Path) -> list[str]: +def check_failures(top: str, todo: pathlib.Path, config: ProjectConfig, own: pathlib.Path, seconds: float) -> list[str]: """Why rank_todo.py --check fails on todo. A checkout of the repo the hook runs from checks with its own bin/rank_todo.py, so a branch that changes the table's shape is held to its own rules. Any other checkout checks with the hook's ranking: running its script would run its code before every commit.""" script = pathlib.Path(top) / "bin" / "rank_todo.py" if not script.is_file() or not same_repo(top, own): return file_plan(config, todo).check() try: - ran = subprocess.run([sys.executable, str(script), "--check", str(todo)], capture_output=True, cwd=top, text=True, timeout=OWN_CHECK_SECONDS) + ran = subprocess.run([sys.executable, str(script), "--check", str(todo)], capture_output=True, cwd=top, text=True, timeout=seconds) except subprocess.TimeoutExpired: - return [f"{script} --check did not finish in {OWN_CHECK_SECONDS} seconds"] + return [f"{script} --check did not finish in {seconds} seconds"] except OSError as failure: return [f"{script} --check could not run: {failure}"] if ran.returncode == 0: diff --git a/bin/run-tests b/bin/run-tests index e070a876..05f84ee1 100755 --- a/bin/run-tests +++ b/bin/run-tests @@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from run_tests import main -sys.exit(main.main(sys.argv[1:])) +sys.exit(main.main(sys.argv[1:], main.run)) diff --git a/bin/run_heavy/main.py b/bin/run_heavy/main.py index 27e7a965..4b12e509 100644 --- a/bin/run_heavy/main.py +++ b/bin/run_heavy/main.py @@ -28,15 +28,17 @@ runs its command at once, so a gate that wraps its own steps cannot wait on itse As GNU env, nice and timeout do, it exits 125, saying why, when no command is given or the slot folder or a slot file cannot be made or locked; 126 when the command is found but cannot run; and 127 when it is not found. """ +import fcntl import os import pathlib import shutil import sys +import time import typing from run_heavy.capped_docker import CANNOT_RUN, NOT_FOUND, PATH_ENTRY, SHARE_VARIABLE, without_path_entry from failure import Failure -from machine_load.slots import HELD, slot_count, slot_folder, waited_slot +from machine_load.slots import HELD, Lock, slot_count, slot_folder, waited_slot from machine_load.memory import Memory OWN_FAILURE = 125 @@ -51,7 +53,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memor print(f"run-heavy: no command given; {USAGE}", file=sys.stderr) return OWN_FAILURE if HELD not in env: - slot = held_slot(slot_folder(env, pathlib.Path.home()), slot_count(cpus)) + slot = held_slot(slot_folder(env, pathlib.Path.home()), slot_count(cpus), time.sleep, fcntl.flock) if isinstance(slot, Failure): print(f"run-heavy: {slot.reason}", file=sys.stderr) return OWN_FAILURE @@ -67,11 +69,11 @@ def capping(memory: Memory | None, slots: int, env: typing.Mapping[str, str]) -> return {SHARE_VARIABLE: str(memory.slot_share(slots)), "PATH": os.pathsep.join([str(PATH_ENTRY), path])} -def held_slot(folder: pathlib.Path, slots: int) -> int | Failure: - """The number of the slot this call holds, its lock left for the command to inherit, or why no slot could be taken.""" +def held_slot(folder: pathlib.Path, slots: int, sleep: typing.Callable[[float], None], lock: Lock) -> int | Failure: + """The number of the slot this call holds, its lock left for the command to inherit, or why no slot could be taken; it waits for one with sleep, and locks it with lock.""" try: folder.mkdir(parents=True, exist_ok=True) - slot, fd = waited_slot(folder, slots, lambda: print(f"run-heavy: waiting for a heavy slot, of {slots} on this machine, in {folder}; `fuser {folder}/slot-*` names the processes that hold them", file=sys.stderr, flush=True)) + slot, fd = waited_slot(folder, slots, lambda: print(f"run-heavy: waiting for a heavy slot, of {slots} on this machine, in {folder}; `fuser {folder}/slot-*` names the processes that hold them", file=sys.stderr, flush=True), sleep, lock) except OSError as failure: return Failure(f"cannot take a heavy slot in {folder}: {failure.strerror}") os.set_inheritable(fd, True) diff --git a/bin/run_tests/main.py b/bin/run_tests/main.py index 6bc51c5e..c339649a 100644 --- a/bin/run_tests/main.py +++ b/bin/run_tests/main.py @@ -17,6 +17,7 @@ import shutil import subprocess import sys import tempfile +import typing from machine_load.slots import CPUS_PER_SLOT @@ -92,7 +93,7 @@ def run(argv: list[str], pytest: list[str] = PYTEST, cwd: str | None = None) -> return 0 if code == 0 else 1 -def main(argv: list[str]) -> int: +def main(argv: list[str], run: typing.Callable[[list[str]], int]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 diff --git a/bin/run_tests/test_run_tests.py b/bin/run_tests/test_run_tests.py index 538385b1..d8d1c151 100644 --- a/bin/run_tests/test_run_tests.py +++ b/bin/run_tests/test_run_tests.py @@ -1,6 +1,5 @@ import contextlib import io -from unittest import mock import os import pathlib import re @@ -57,13 +56,12 @@ class Main(unittest.TestCase): for argv in (["-h"], ["--help"], ["--help", "bin/x"]): with self.subTest(argv=argv): out = io.StringIO() - with contextlib.redirect_stdout(out), mock.patch.object(main, "run") as run: - self.assertEqual(main.main(argv), 0) + with contextlib.redirect_stdout(out): + self.assertEqual(main.main(argv, self.fail), 0) self.assertEqual(out.getvalue(), main.__doc__.strip() + "\n") - run.assert_not_called() - with mock.patch.object(main, "run", return_value=1) as run: - self.assertEqual(main.main(["bin/x", "-h"]), 1) - run.assert_called_once_with(["bin/x", "-h"]) + ran = [] + self.assertEqual(main.main(["bin/x", "-h"], lambda argv: ran.append(argv) or 1), 1) + self.assertEqual(ran, [["bin/x", "-h"]]) class RunWithAStandIn(unittest.TestCase): diff --git a/bin/rung_replay/archive.py b/bin/rung_replay/archive.py index 8ee9b28e..ff02578a 100644 --- a/bin/rung_replay/archive.py +++ b/bin/rung_replay/archive.py @@ -5,10 +5,11 @@ import json import pathlib import re import subprocess -import sys import time +import typing from loop_effects.effects import Effects +from failure import Failure # The type of the first line of a run's file, which holds what the stream lacks: claude's arguments, working directory, prompt, exit code and stderr. No event claude writes has this type. HEADER = "replay_run" @@ -21,8 +22,8 @@ def replay_folder(root: pathlib.Path, tool: str, argv: list[str], now: float) -> return root / "replays" / re.sub(r"[^A-Za-z0-9._-]", "_", name) -def archiving(effects: Effects, folder: pathlib.Path) -> Effects: - """effects whose claude also writes each run into folder: a header line, then the stream claude printed. A run is kept whether it failed or not, and a run that repeats another word for word is kept once. A folder that can't be written is reported on stderr, and the replay goes on.""" +def archiving(effects: Effects, folder: pathlib.Path, say: typing.Callable[[str], None]) -> Effects: + """effects whose claude also writes each run into folder: a header line, then the stream claude printed. A run is kept whether it failed or not, and a run that repeats another word for word is kept once. A folder that can't be written is reported to say, and the replay goes on.""" claude = effects.claude def run(args: list[str], cwd: str, prompt: str) -> subprocess.CompletedProcess[str]: @@ -32,17 +33,17 @@ def archiving(effects: Effects, folder: pathlib.Path) -> Effects: folder.mkdir(mode=0o700, parents=True, exist_ok=True) (folder / f"{hashlib.sha256(content.encode()).hexdigest()}.jsonl").write_text(content, encoding="utf-8") except OSError as failure: - print(f"could not keep the run in {folder}: {failure}", file=sys.stderr, flush=True) + say(f"could not keep the run in {folder}: {failure}") return proc return dataclasses.replace(effects, claude=run) -def print_report(folder: pathlib.Path, report: str) -> None: - """Prints the report a replay ends with, and keeps it in folder, beside the runs.""" - print(report) +def kept_report(folder: pathlib.Path, report: str) -> Failure | None: + """Keeps the report a replay ends with in folder, beside the runs; the Failure where it can't.""" try: folder.mkdir(mode=0o700, parents=True, exist_ok=True) (folder / RESULT).write_text(report + "\n", encoding="utf-8") except OSError as failure: - print(f"could not keep the result in {folder}: {failure}", file=sys.stderr, flush=True) + return Failure(f"could not keep the result in {folder}: {failure}") + return None diff --git a/bin/rung_replay/command.py b/bin/rung_replay/command.py index 241cbdae..89467082 100644 --- a/bin/rung_replay/command.py +++ b/bin/rung_replay/command.py @@ -4,6 +4,7 @@ import sys import typing from failure import Failure +from rung_replay.archive import kept_report from model_routing.ladder import Ladder, Rung from claude_code.reply import Limited from loop_state.paths import paths_from @@ -44,3 +45,15 @@ def limited_exit(tool: str, limited: Limited) -> int: def failed(tool: str, reason: str) -> int: print(f"{tool}: {reason}", file=sys.stderr) return 1 + + +def say(text: str) -> None: + """Writes text to stderr, as each replay's progress and each round it leaves out are told.""" + print(text, file=sys.stderr, flush=True) + + +def print_report(folder: pathlib.Path, report: str) -> None: + """Prints the report a replay ends with, and keeps it in folder, beside the runs.""" + print(report) + if kept := kept_report(folder, report): + say(kept.reason) diff --git a/bin/rung_replay/search.py b/bin/rung_replay/search.py index 0e34af0e..84416bbb 100644 --- a/bin/rung_replay/search.py +++ b/bin/rung_replay/search.py @@ -1,7 +1,6 @@ """Replay archived cases on a rung, as judge-replay and review-replay both do; and judge-replay's rung search, which holds each candidate rung to what a reference rung reproduced.""" import concurrent.futures import dataclasses -import sys import typing from failure import Failure @@ -49,6 +48,8 @@ def replayed( replay_one: typing.Callable[[Case, Rung], Answer | Limited], reproduced: typing.Callable[[Case, Answer], list[Aim]], what: str, + say: typing.Callable[[str], None], + at_once: int, climbs: typing.Sequence[Rung] = (), ) -> Replay[Case, Aim, Answer] | Limited: """Replays the cases on the reference rung, then on each climb and each candidate, on the cases where the reference reproduced anything. @@ -57,7 +58,7 @@ def replayed( The candidates are tried highest first, until one misses an item the reference reproduced. Going down, every candidate at or above the one named was tried and didn't miss anything, so the result needs no assumption that a higher rung does at least as well; and a miss high up spares the cheaper rungs their replays. """ - on_reference = replayed_on(cases, reference, replay_one, what) + on_reference = replayed_on(cases, reference, replay_one, what, say, at_once) if isinstance(on_reference, Limited): return on_reference held = [(case, aim) for case, reply in zip(cases, on_reference) if (aim := reproduced(case, reply))] @@ -66,14 +67,14 @@ def replayed( return Replay(on_reference, [], None) climbed: list[Tried[Case, Aim, Answer]] = [] for rung in climbs: - climb = tried_on(held, rung, replay_one, reproduced, what) + climb = tried_on(held, rung, replay_one, reproduced, what, say, at_once) if isinstance(climb, Limited): return climb climbed.append(climb) tried: list[Tried[Case, Aim, Answer]] = [] lowest = None for rung in candidates: - candidate = tried_on(held, rung, replay_one, reproduced, what) + candidate = tried_on(held, rung, replay_one, reproduced, what, say, at_once) if isinstance(candidate, Limited): return candidate tried.append(candidate) @@ -89,9 +90,11 @@ def tried_on( replay_one: typing.Callable[[Case, Rung], Answer | Limited], reproduced: typing.Callable[[Case, Answer], list[Aim]], what: str, + say: typing.Callable[[str], None], + at_once: int, ) -> Tried[Case, Aim, Answer] | Limited: """rung and each item, of those the reference reproduced in the held cases, that its replies missed.""" - replies = replayed_on([case for case, _ in held], rung, replay_one, what) + replies = replayed_on([case for case, _ in held], rung, replay_one, what, say, at_once) if isinstance(replies, Limited): return replies misses: list[Miss[Case, Aim, Answer]] = [] @@ -101,10 +104,10 @@ def tried_on( return Tried(rung, misses) -def replayed_on(cases: list[Case], rung: Rung, replay_one: typing.Callable[[Case, Rung], Answer | Limited], what: str) -> list[Answer] | Limited: - """Each case's reply on rung, AT_ONCE at a time; a usage limit cancels the rest.""" - print(f"replaying {len(cases)} {what} on {rung}", file=sys.stderr, flush=True) - with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool: +def replayed_on(cases: list[Case], rung: Rung, replay_one: typing.Callable[[Case, Rung], Answer | Limited], what: str, say: typing.Callable[[str], None], at_once: int) -> list[Answer] | Limited: + """Each case's reply on rung, at_once at a time, after telling say what it replays; a usage limit cancels the rest.""" + say(f"replaying {len(cases)} {what} on {rung}") + with concurrent.futures.ThreadPoolExecutor(at_once) as pool: running = [pool.submit(replay_one, case, rung) for case in cases] replies: list[Answer] = [] for future in running: diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index f22a5082..21dd083b 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -9,11 +9,11 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from rung_replay.archive import archiving, print_report, replay_folder -from rung_replay.command import down_from +from rung_replay.archive import archiving, replay_folder +from rung_replay.search import AT_ONCE, first_reply, Miss, Replay, replayed, Tried +from rung_replay.command import down_from, print_report from loop_effects.effects import Effects from failure import Failure -from rung_replay.search import first_reply, Miss, Replay, replayed, Tried from claude_code.reply import Limited from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder import Rung @@ -34,8 +34,7 @@ def search(cases, candidates, replies, climbs=()): reply = replies[rung] return reply if isinstance(reply, Limited) else reply[case] - with contextlib.redirect_stderr(io.StringIO()): - return replayed(cases, REFERENCE, candidates, replay_one, lambda _, reply: sorted(reply), "cases", climbs), asked + return replayed(cases, REFERENCE, candidates, replay_one, lambda _, reply: sorted(reply), "cases", lambda text: None, AT_ONCE, climbs), asked class Replayed(unittest.TestCase): @@ -96,8 +95,8 @@ class ArchivedRuns(unittest.TestCase): def setUp(self): self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "replays" / "tool-1" - def run_archived(self, replies): - return archiving(effects(lambda args, cwd, prompt: replies.pop(0)), self.folder).claude + def run_archived(self, replies, say=lambda text: None): + return archiving(effects(lambda args, cwd, prompt: replies.pop(0)), self.folder, say).claude def kept(self): return sorted(self.folder.glob("*.jsonl")) @@ -134,16 +133,15 @@ class ArchivedRuns(unittest.TestCase): raise FileNotFoundError(2, "No such file or directory") with self.assertRaises(FileNotFoundError): - archiving(effects(missing), self.folder).claude([], "/r", "p") + archiving(effects(missing), self.folder, self.fail).claude([], "/r", "p") self.assertFalse(self.folder.exists()) # A file where the folder's parent should be. self.folder.parent.parent.mkdir(exist_ok=True) self.folder.parent.write_text("") proc = subprocess.CompletedProcess(["claude"], 0, "{}", "") - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertIs(self.run_archived([proc])([], "/r", "p"), proc) - self.assertIn(f"could not keep the run in {self.folder}: ", err.getvalue()) + said = [] + self.assertIs(self.run_archived([proc], said.append)([], "/r", "p"), proc) + self.assertEqual([text.startswith(f"could not keep the run in {self.folder}: ") for text in said], [True]) def test_prints_the_report_and_keeps_it_beside_the_runs(self): out = io.StringIO() diff --git a/bin/score-outcomes b/bin/score-outcomes index b28b6bdd..f29ff785 100755 --- a/bin/score-outcomes +++ b/bin/score-outcomes @@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from score_outcomes import main -sys.exit(main.main(sys.argv[1:])) +sys.exit(main.main(sys.argv[1:], pathlib.Path.home())) diff --git a/bin/score_outcomes/main.py b/bin/score_outcomes/main.py index d3c9452f..4c79bb9f 100644 --- a/bin/score_outcomes/main.py +++ b/bin/score_outcomes/main.py @@ -100,8 +100,8 @@ from failure import Failure from score_outcomes.results import file_lines, fixed_later, item_text, misreads, nearest, render, report, Result, results_of from plan.todo_table import item_details, LEVELS, risk, TOP_SCORE from text_files.markdown_text import listed +from project_config.main import located, title_templates from plan.named_paths import named_files -from project_config.main import project, title_templates from transcript_archive.location import project_archive from score_outcomes.reversals import reversal_lines from record_store.stores import store @@ -119,7 +119,7 @@ UNMERGED = [ ] -def main(argv: list[str]) -> int: +def main(argv: list[str], home: pathlib.Path) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 @@ -133,11 +133,11 @@ def main(argv: list[str]) -> int: default, note = found if note: print(f"score-outcomes: {note}", file=sys.stderr) - results = read_results(default) + results = read_results(default, home) if isinstance(results, Failure): return failed(results) - anchored = read_anchors() - reversal = read_reversals() + anchored = read_anchors(home) + reversal = read_reversals(home) print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None, reversal)) unread = [found for found in (anchored, reversal) if isinstance(found, Failure)] for failure in unread: @@ -167,34 +167,34 @@ def failed(failure: Failure) -> int: return 1 -def read_anchors() -> Anchors | Failure: +def read_anchors(home: pathlib.Path) -> Anchors | Failure: """The project's anchors as they stand in the store its config names, so a branch that edits them shows its edit; none where it keeps none.""" - config = project() + config = located(None, home) if isinstance(config, Failure): return config text = store(config, "score-anchors").read() return text if isinstance(text, Failure) else parse_anchors(text) -def read_reversals() -> list[str] | Failure: +def read_reversals(home: pathlib.Path) -> list[str] | Failure: """The reversals in loop-claude's archive of this project, which the main checkout's path keys, whichever worktree this runs in.""" common = git("rev-parse", "--path-format=absolute", "--git-common-dir") if isinstance(common, Failure): return common - return reversal_lines(project_archive(str(pathlib.Path(common.strip()).parent), pathlib.Path.home(), os.environ)) + return reversal_lines(project_archive(str(pathlib.Path(common.strip()).parent), home, os.environ)) -def read_results(default: str) -> list[Result] | Failure: +def read_results(default: str, home: pathlib.Path) -> list[Result] | Failure: """What each chunk on the default branch's first-parent line measured.""" if partial := full_history(): return partial - if why := unsupported(None, pathlib.Path.home()): + if why := unsupported(None, home): return Failure(f"this project is not supported yet: {why}") root = top() if isinstance(root, Failure): return root run = functools.partial(git, cwd=root) - templates = title_templates(None, pathlib.Path.home()) + templates = title_templates(None, home) if isinstance(templates, Failure): return templates chunks = branch_chunks(default, run, templates) diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index fe9c8bfe..58c9de22 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -570,12 +570,12 @@ class Reversals(unittest.TestCase): class ReadAnchors(unittest.TestCase): def test_fails_on_anchors_it_cannot_read_rather_than_scoring_without_them(self): checkout = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) - configured(self, checkout) + home = configured(self, checkout).parents[1] self.enterContext(contextlib.chdir(checkout)) anchors = checkout.resolve() / "docs" / "score-anchors.md" anchors.parent.mkdir() anchors.write_bytes(b"\xff") - self.assertEqual(read_anchors(), Failure(f"cannot read {anchors}: not UTF-8 on line 1")) + self.assertEqual(read_anchors(home), Failure(f"cannot read {anchors}: not UTF-8 on line 1")) if __name__ == "__main__": diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index ba56c8d8..19053a6e 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -16,15 +16,23 @@ from todo_item.doubles import READABLE_TOUCHES, UNREADABLE_BULLETS class Main(unittest.TestCase): + # The home of a test that writes no config. + home = pathlib.Path("/no-home") + + def configured(self, checkout: str) -> pathlib.Path: + folder = configured(self, pathlib.Path(checkout)) + self.home = folder.parents[1] + return folder + def run_main(self, *argv): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: - code = rank_todo.main(list(argv)) + code = rank_todo.main(list(argv), self.home) return code, said.getvalue() def test_ranks_the_file_in_place_and_check_writes_nothing(self): with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") - configured(self, pathlib.Path(temp)) + self.configured(temp) self.enterContext(contextlib.chdir(temp)) todo.write_text(TODO) pathlib.Path(temp, "README.md").write_text(README) @@ -43,7 +51,7 @@ class Main(unittest.TestCase): def test_ranks_the_plan_and_reads_the_decisions_where_the_config_puts_them(self): with tempfile.TemporaryDirectory() as temp: - folder = configured(self, pathlib.Path(temp)) + folder = self.configured(temp) self.enterContext(contextlib.chdir(temp)) config = folder / "config.toml" config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"').replace('"checkout:docs/decisions.md"', '"folder:decisions.md"')) @@ -61,7 +69,7 @@ class Main(unittest.TestCase): def test_refuses_a_project_whose_plan_is_in_jira_and_writes_no_file(self): with tempfile.TemporaryDirectory() as temp: - config = configured(self, pathlib.Path(temp)) / "config.toml" + config = self.configured(temp) / "config.toml" self.enterContext(contextlib.chdir(temp)) config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n') todo = pathlib.Path(temp, "todo.md") @@ -74,7 +82,7 @@ class Main(unittest.TestCase): def test_refuses_a_file_that_is_not_the_plan_the_config_names_and_a_checkout_no_config_names(self): with tempfile.TemporaryDirectory() as temp: - folder = configured(self, pathlib.Path(temp)) + folder = self.configured(temp) self.enterContext(contextlib.chdir(temp)) pathlib.Path(temp, "todo.md").write_text(TODO) pathlib.Path(temp, "README.md").write_text(README) @@ -94,7 +102,7 @@ class Main(unittest.TestCase): under = "item 2 scores 3.1, under the bar 4; delete it, or mark it with a reason the bar does not apply" with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") - configured(self, pathlib.Path(temp)) + self.configured(temp) self.enterContext(contextlib.chdir(temp)) todo.write_text(TODO.replace("`Bar = 2`", "`Bar = 4`")) pathlib.Path(temp, "README.md").write_text(README) @@ -106,7 +114,7 @@ class Main(unittest.TestCase): def test_check_fails_on_each_item_whose_touches_list_it_cannot_read(self): with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") - configured(self, pathlib.Path(temp)) + self.configured(temp) self.enterContext(contextlib.chdir(temp)) pathlib.Path(temp, "README.md").write_text(README) pathlib.Path(temp, "docs").mkdir() @@ -125,7 +133,7 @@ class Main(unittest.TestCase): def test_says_to_reshape_an_old_shape_table_but_passes_the_check(self): with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") - configured(self, pathlib.Path(temp)) + self.configured(temp) self.enterContext(contextlib.chdir(temp)) todo.write_text(OLD_SHAPE) pathlib.Path(temp, "README.md").write_text(README) diff --git a/bin/text_files/compressed.py b/bin/text_files/compressed.py index d640f494..37b31c45 100644 --- a/bin/text_files/compressed.py +++ b/bin/text_files/compressed.py @@ -6,10 +6,10 @@ import errno import gzip import os import pathlib +import typing import zlib from failure import Failure -from text_files.file_writes import replace_file SUFFIX = ".gz" @@ -43,20 +43,20 @@ def stored_glob(folder: pathlib.Path, pattern: str) -> list[pathlib.Path]: return sorted({*folder.glob(pattern), *(path.with_name(path.name.removesuffix(SUFFIX)) for path in folder.glob(pattern + SUFFIX))}) -def compress(path: pathlib.Path) -> Failure | None: - """Replaces path with its gzip, which keeps path's times: writes the gzip, reads it back, and removes path only once it reads back path's bytes. A failure keeps path.""" +def compress(path: pathlib.Path, *, pack: typing.Callable[..., bytes], replace: typing.Callable[[pathlib.Path, bytes], Failure | None], sync: typing.Callable[[int], None]) -> Failure | None: + """Replaces path with its gzip, which keeps path's times: writes the gzip, reads it back, and removes path only once it reads back path's bytes. A failure keeps path. pack compresses as gzip.compress does, replace writes as replace_file does, and sync flushes as os.fsync does.""" packed = gzipped(path) try: before = path.stat() data = path.read_bytes() - if unwritten := replace_file(packed, gzip.compress(data, mtime=0)): + if unwritten := replace(packed, pack(data, mtime=0)): return Failure(f"could not compress {path}: {unwritten.reason}") if gzip.decompress(packed.read_bytes()) != data: return Failure(f"could not compress {path}: {packed} reads back other bytes") os.utime(packed, ns=(before.st_atime_ns, before.st_mtime_ns)) # On disk before the plain file goes, so a crash cannot leave an empty gzip in its place. - synced(packed) - synced(packed.parent) + synced(packed, sync) + synced(packed.parent, sync) after = path.stat() # Written while it compressed: the plain file keeps the newer bytes, which readers prefer, and a later run compresses them. if (after.st_size, after.st_mtime_ns) == (before.st_size, before.st_mtime_ns): @@ -66,10 +66,10 @@ def compress(path: pathlib.Path) -> Failure | None: return None -def synced(path: pathlib.Path) -> None: +def synced(path: pathlib.Path, sync: typing.Callable[[int], None]) -> None: handle = os.open(path, os.O_RDONLY) try: - os.fsync(handle) + sync(handle) finally: os.close(handle) diff --git a/bin/text_files/doubles.py b/bin/text_files/doubles.py new file mode 100644 index 00000000..c8563b8b --- /dev/null +++ b/bin/text_files/doubles.py @@ -0,0 +1,10 @@ +"""What the suites that compress a file share: compress, bound to what really compresses, writes and flushes.""" +import functools +import gzip +import os + +from text_files import compressed +from text_files.file_writes import replace_file + +# A test names pack, replace or sync to swap that one. +compress = functools.partial(compressed.compress, pack=gzip.compress, replace=replace_file, sync=os.fsync) diff --git a/bin/text_files/test_compressed.py b/bin/text_files/test_compressed.py index e2e01b10..479866f5 100644 --- a/bin/text_files/test_compressed.py +++ b/bin/text_files/test_compressed.py @@ -1,6 +1,5 @@ import errno import gzip -from unittest import mock import os import pathlib import sys @@ -9,6 +8,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from text_files.doubles import compress from text_files import compressed from failure import Failure @@ -19,7 +19,7 @@ class Compress(unittest.TestCase): plain = pathlib.Path(root, "t.jsonl") plain.write_bytes(b'{"a": 1}\n') os.utime(plain, (1000, 2000)) - self.assertIsNone(compressed.compress(plain)) + self.assertIsNone(compress(plain)) self.assertFalse(plain.exists()) packed = pathlib.Path(root, "t.jsonl.gz") # A gzip header's own time is 0, so compressing the same bytes twice writes the same file. @@ -37,31 +37,28 @@ class Compress(unittest.TestCase): synced.append((os.readlink(f"/proc/self/fd/{handle}"), plain.exists())) fsync(handle) - with mock.patch.object(compressed.os, "fsync", record): - self.assertIsNone(compressed.compress(plain)) + self.assertIsNone(compress(plain, sync=record)) self.assertEqual(synced, [(os.path.realpath(f"{plain}.gz"), True), (os.path.realpath(root), True)]) def test_a_gzip_it_cannot_write_keeps_the_original_and_says_why(self): with tempfile.TemporaryDirectory() as root: plain = pathlib.Path(root, "t.jsonl") plain.write_bytes(b"kept\n") - with mock.patch.object(compressed, "replace_file", return_value=Failure("disk full")): - self.assertEqual(compressed.compress(plain), Failure(f"could not compress {plain}: disk full")) + self.assertEqual(compress(plain, replace=lambda path, data: Failure("disk full")), Failure(f"could not compress {plain}: disk full")) self.assertEqual(plain.read_bytes(), b"kept\n") def test_a_file_it_cannot_read_fails_naming_it(self): with tempfile.TemporaryDirectory() as root: folder = pathlib.Path(root, "t.jsonl") folder.mkdir() - failed = compressed.compress(folder) + failed = compress(folder) self.assertTrue(failed.reason.startswith(f"could not compress {folder}: [Errno {errno.EISDIR}]"), failed.reason) def test_a_copy_that_reads_back_other_bytes_keeps_the_original_and_fails(self): with tempfile.TemporaryDirectory() as root: plain = pathlib.Path(root, "t.jsonl") plain.write_bytes(b"kept\n") - with mock.patch.object(compressed.gzip, "compress", return_value=gzip.compress(b"other\n")): - failed = compressed.compress(plain) + failed = compress(plain, pack=lambda data, **kwargs: gzip.compress(b"other\n")) self.assertIsInstance(failed, Failure) self.assertIn(str(plain), failed.reason) self.assertEqual(plain.read_bytes(), b"kept\n") @@ -70,15 +67,12 @@ class Compress(unittest.TestCase): with tempfile.TemporaryDirectory() as root: plain = pathlib.Path(root, "t.jsonl") plain.write_bytes(b"one\n") - packing = compressed.gzip.compress - def grow_meanwhile(data, **kwargs): with open(plain, "ab") as handle: handle.write(b"two\n") - return packing(data, **kwargs) + return gzip.compress(data, **kwargs) - with mock.patch.object(compressed.gzip, "compress", grow_meanwhile): - self.assertIsNone(compressed.compress(plain)) + self.assertIsNone(compress(plain, pack=grow_meanwhile)) self.assertEqual(plain.read_bytes(), b"one\ntwo\n") self.assertEqual(compressed.read_stored(plain), b"one\ntwo\n") diff --git a/bin/todo-item b/bin/todo-item index 1f73d950..09ba0244 100755 --- a/bin/todo-item +++ b/bin/todo-item @@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from todo_item import main -sys.exit(main.main(sys.argv[1:])) +sys.exit(main.main(sys.argv[1:], pathlib.Path(), pathlib.Path.home(), sys.stdin)) diff --git a/bin/todo_item/main.py b/bin/todo_item/main.py index 1749843d..f59fcfcf 100644 --- a/bin/todo_item/main.py +++ b/bin/todo_item/main.py @@ -94,6 +94,7 @@ from plan_store.plans import no_item, PlanStore, TAGLINE, Written from plan.release import parsed, Release, version as release_version from plan_store.stores import store as plan_store from plan.touches import predicted +from project_config.settings import ProjectConfig from record_store.stores import RecordStore, store from todo_item.table import shown, table from todo_item.edits import with_bullet @@ -104,16 +105,17 @@ LETTERS = ("L", "E", "I", "S") NAMED = {"release": "Release", "blocked_by": BLOCKED_BY, "exempt": "Exempt", "tagline": TAGLINE, "moves": MOVES} -def main(argv: list[str], folder: pathlib.Path = pathlib.Path(), stdin: typing.TextIO = sys.stdin) -> int: +# plan_of is plan_store, but in the tests of a plan in Jira, which hand it a plan in memory. +def main(argv: list[str], folder: pathlib.Path, home: pathlib.Path, stdin: typing.TextIO, plan_of: typing.Callable[[ProjectConfig], PlanStore] = plan_store) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 args = parser().parse_args(argv) - config = located(str(folder), pathlib.Path.home()) + config = located(str(folder), home) if isinstance(config, Failure): done: str | Failure = config else: - plan = plan_store(config) + plan = plan_of(config) match args.command: case "list": done = list_(args, plan) diff --git a/bin/todo_item/test_todo_item.py b/bin/todo_item/test_todo_item.py index c95157ff..1e88b82d 100644 --- a/bin/todo_item/test_todo_item.py +++ b/bin/todo_item/test_todo_item.py @@ -4,7 +4,6 @@ import pathlib import sys import tempfile import unittest -import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) @@ -41,6 +40,9 @@ class TodoItem(unittest.TestCase): self.addCleanup(temp.cleanup) self.folder = pathlib.Path(temp.name) self.config = configured(self, self.folder) / "config.toml" + self.home = self.config.parents[2] + # The plan main is handed in place of the one the config names. + self.plan_of = {} self.todo = self.folder / "todo.md" self.changelog = self.folder / "CHANGELOG.md" (self.folder / "README.md").write_text(README) @@ -52,16 +54,16 @@ class TodoItem(unittest.TestCase): def run_main(self, *argv, stdin: str | io.StringIO = ""): with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: - code = main.main(list(argv), self.folder, io.StringIO(stdin) if isinstance(stdin, str) else stdin) + code = main.main(list(argv), self.folder, self.home, io.StringIO(stdin) if isinstance(stdin, str) else stdin, **self.plan_of) return code, out.getvalue(), err.getvalue() def exit_code(self, *argv): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as raised: - main.main(list(argv), self.folder, io.StringIO()) + main.main(list(argv), self.folder, self.home, io.StringIO()) return raised.exception.code def assert_ranked(self): - self.assertEqual(file_plan(located(str(self.folder), pathlib.Path.home()), self.todo).check(), []) + self.assertEqual(file_plan(located(str(self.folder), self.home), self.todo).check(), []) def details(self): text = self.todo.read_text() @@ -275,9 +277,7 @@ class FinishInJira(TodoItem): super().setUp() self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', f'"{JIRA_PLAN}"') + 'env-file = "~/acme.env"\n' + JIRA_SCORING) self.plan = MemoryPlan({3: {"Release": "0.1.0", "Item": "**Count the runs.**", "L": "1", "E": "2", "I": "3", "S": "1"}}) - patched = unittest.mock.patch.object(main, "plan_store", return_value=self.plan) - patched.start() - self.addCleanup(patched.stop) + self.plan_of = {"plan_of": lambda config: self.plan} def test_finishes_without_either_flag_and_doesnt_touch_the_changelog(self): self.changelog.write_text(CHANGELOG) @@ -409,7 +409,7 @@ class List(TodoItem): def test_fails_on_a_release_that_is_no_version(self): errors = io.StringIO() with contextlib.redirect_stderr(errors), self.assertRaises(SystemExit) as raised: - main.main(["list", "--release", "next"], self.folder, io.StringIO()) + main.main(["list", "--release", "next"], self.folder, self.home, io.StringIO()) self.assertEqual(raised.exception.code, 2) self.assertIn("argument --release: 'next' is not a semver version", errors.getvalue()) @@ -513,7 +513,7 @@ class UnreadableTouches(TodoItem): def test_a_plan_in_jira_gets_no_unreadable_list_either(self): self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', f'"{JIRA_PLAN}"') + 'env-file = "~/acme.env"\n' + JIRA_SCORING) plan = MemoryPlan({3: {"Release": "0.1.0", "Item": "**Count the runs.**", "L": "1", "E": "2", "I": "3", "S": "1"}}) - self.enterContext(unittest.mock.patch.object(main, "plan_store", return_value=plan)) + self.plan_of = {"plan_of": lambda config: plan} detail = f"Touches:\n\n{UNREADABLE_BULLETS[0]}\n" self.assertEqual(self.run_main(*ADD, stdin=detail)[:2], (1, "")) self.assertEqual(self.run_main("edit", "3", "--detail", stdin=detail)[:2], (1, "")) @@ -536,7 +536,7 @@ class Move(TodoItem): class OtherFile(TodoItem): def test_ranking_works_on_the_file_it_is_given_not_the_configured_plan(self): - config = located(str(self.folder), pathlib.Path.home()) + config = located(str(self.folder), self.home) other = self.folder / "other.md" other.write_text("not a plan\n") self.assertNotEqual(file_plan(config, other).check(), []) diff --git a/bin/touch_predictions/doubles.py b/bin/touch_predictions/doubles.py index 22189131..6798e7b3 100644 --- a/bin/touch_predictions/doubles.py +++ b/bin/touch_predictions/doubles.py @@ -3,10 +3,15 @@ from failure import Failure from plan_store.todo_md import plan_of -def plan(*items: tuple[int, str, str, str]) -> list: - """A plan's items, each given as its ID, release, the IDs that block it and the bullets of its prediction, none for an item without one.""" +def todo(*items: tuple[int, str, str, str]) -> str: + """A todo.md's text for items, each given as its ID, release, the IDs that block it and the bullets of its prediction, none for an item without one.""" rows = "".join(f"| {id_} | {release} | {blocked} | | **Do {id_}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" for id_, release, blocked, _ in items) details = "".join(f"### {id_}. Do {id_}.\n\nTouches:\n\n{bullets}\n\n" for id_, _, _, bullets in items if bullets) - found = plan_of(f"# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 99`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n{rows}\n## Details\n\n{details}") + return f"# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 99`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n{rows}\n## Details\n\n{details}" + + +def plan(*items: tuple[int, str, str, str]) -> list: + """The items of the plan that todo writes for items.""" + found = plan_of(todo(*items)) assert not isinstance(found, Failure), found return found.items diff --git a/bin/touch_predictions/main.py b/bin/touch_predictions/main.py index 2c77b66a..65314b33 100644 --- a/bin/touch_predictions/main.py +++ b/bin/touch_predictions/main.py @@ -66,7 +66,7 @@ def main(argv: list[str]) -> int: print("usage: touch-predictions record ...", file=sys.stderr) return 1 config = project() - done = config if isinstance(config, Failure) else recorded(config, sorted({int(id_) for id_ in argv[1:]})) + done = config if isinstance(config, Failure) else recorded(config, sorted({int(id_) for id_ in argv[1:]}), time.time, git) if isinstance(done, Failure): print(f"touch-predictions: {done.reason}", file=sys.stderr) return 1 @@ -74,7 +74,7 @@ def main(argv: list[str]) -> int: return 0 -def recorded(config: ProjectConfig, ids: list[int], now: typing.Callable[[], float] = time.time, run: Git = git) -> str | Failure: +def recorded(config: ProjectConfig, ids: list[int], now: typing.Callable[[], float], run: Git) -> str | Failure: """Appends the entry of the chunk that takes the items ids, stamped at now and read from the commits run shows, and says so; or says that the project keeps no record.""" store = touch_predictions_store(config) if store is None: diff --git a/bin/touch_predictions/test_touch_predictions.py b/bin/touch_predictions/test_touch_predictions.py index 1d2e1659..4c92aaac 100644 --- a/bin/touch_predictions/test_touch_predictions.py +++ b/bin/touch_predictions/test_touch_predictions.py @@ -343,7 +343,7 @@ class RecordCommandTest(unittest.TestCase): path = self.set_record() config = located(str(self.checkout), self.home) assert isinstance(config, ProjectConfig), config - self.assertNotIsInstance(main.recorded(config, [3], now=lambda: 0.0), Failure) + self.assertNotIsInstance(main.recorded(config, [3], lambda: 0.0, main.git), Failure) self.assertIn("## Chunk 3, 1970-01-01T00:00:00Z, at ", path.read_text(encoding="utf-8")) def test_a_second_run_replaces_the_entry_and_leaves_the_record_out_of_what_was_touched(self) -> None: diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index 6438b90b..438291d0 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -10,11 +10,12 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from transcript_archive.project_key import checkout_of, project_key -from text_files import compressed +from text_files.doubles import compress from failure import Failure from transcript_archive.judge_run import JudgeRun from transcript_archive import outcomes, read, write from transcript_archive.location import project_archive +from text_files.file_writes import replace_file from text_files.utc_stamp import utc NOW = 1790000000 @@ -27,10 +28,10 @@ class Archive(unittest.TestCase): transcript = pathlib.Path(root, "t.jsonl") transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n') with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("m", "working", "j", ""), NOW)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("m", "working", "j", ""), NOW, replace=replace_file)) (kept_outcomes,) = kept.glob("*/*.outcomes.md") kept_outcomes.unlink() - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("m", "Ctrl-C"), NOW)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("m", "Ctrl-C"), NOW, replace=replace_file)) self.assertEqual(kept_outcomes.read_text(), "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: m\n") @@ -45,7 +46,7 @@ class JudgeRuns(unittest.TestCase): with contextlib.redirect_stderr(io.StringIO()): for offset in (0, 1): outcome = outcomes.finished("w", "merged", "j", judge_run=self.judged) - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcome, NOW + offset, judge_run=self.judged)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcome, NOW + offset, judge_run=self.judged, replace=replace_file)) (folder,) = kept.glob("*/") (file,) = folder.glob("judge/*") self.assertEqual(file, folder / self.judged.file) @@ -91,7 +92,7 @@ class JudgeRuns(unittest.TestCase): def test_names_the_folder_it_cannot_make_in_the_failure_to_keep_a_run(self): with tempfile.TemporaryDirectory() as root: (pathlib.Path(root) / "judge").write_text("a file where the folder should be") - failure = write.keep_judge_run(pathlib.Path(root), self.judged) + failure = write.keep_judge_run(pathlib.Path(root), self.judged, replace_file) self.assertRegex(failure.reason, f"^could not archive the transcript: {root}/judge: ") self.assertNotIn("None", failure.reason) @@ -101,10 +102,10 @@ class JudgeRuns(unittest.TestCase): transcript = pathlib.Path(root, "t.jsonl") transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n') with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "x"), NOW)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "x"), NOW, replace=replace_file)) (folder,) = kept.glob("*/") (folder / "judge").write_text("a file where the folder should be") - failure = write.archive(kept, str(transcript), "Do it.", outcomes.finished("w", "e", "j", judge_run=self.judged), NOW + 1, judge_run=self.judged) + failure = write.archive(kept, str(transcript), "Do it.", outcomes.finished("w", "e", "j", judge_run=self.judged), NOW + 1, judge_run=self.judged, replace=replace_file) self.assertIsInstance(failure, Failure) self.assertNotIn("Verdict: finished", next(folder.glob("*.outcomes.md")).read_text()) @@ -124,7 +125,7 @@ class CopyFor(unittest.TestCase): with tempfile.TemporaryDirectory() as temp: copy = pathlib.Path(temp, "agent-a.jsonl") copy.write_bytes(b"first\n") - self.assertIsNone(compressed.compress(copy)) + self.assertIsNone(compress(copy)) self.assertIsNone(write.copy_for(copy, b"first\n")) self.assertEqual(write.copy_for(copy, b"first\nsecond\n"), copy) self.assertEqual(write.copy_for(copy, b"other\n"), copy.with_name(f"agent-a.jsonl.{hashlib.sha256(b'other' + bytes([10])).hexdigest()}")) @@ -141,9 +142,9 @@ class Compressed(unittest.TestCase): subagent.parent.mkdir(parents=True) subagent.write_text('{"sub": 1}\n') with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.finished("w", "merged", "j"), NOW)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.finished("w", "merged", "j"), NOW, replace=replace_file)) for copy in kept.rglob("*.jsonl"): - self.assertIsNone(compressed.compress(copy)) + self.assertIsNone(compress(copy)) return transcript def test_a_compressed_copy_takes_the_next_outcome_and_is_not_copied_again(self): @@ -151,7 +152,7 @@ class Compressed(unittest.TestCase): transcript = self.archived(root) kept = pathlib.Path(root, "archive") with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1, replace=replace_file)) self.assertEqual([path.name.endswith(".gz") for path in kept.rglob("*.jsonl*")], [True, True]) self.assertIn("Stopped: Ctrl-C", next(kept.glob("*/*.outcomes.md")).read_text()) @@ -208,7 +209,7 @@ class Outcomes(unittest.TestCase): transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n') with contextlib.redirect_stderr(io.StringIO()): for worker in ("z-first", "a-last"): - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished(worker, "working", "j", ""), NOW)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished(worker, "working", "j", ""), NOW, replace=replace_file)) self.assertEqual(read.latest_worker(kept, str(transcript)), "a-last") def test_names_the_worker_the_latest_outcome_of_the_transcripts_chunk_records(self): @@ -218,9 +219,9 @@ class Outcomes(unittest.TestCase): transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n') self.assertIsNone(read.latest_worker(kept, str(transcript))) with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w1", "working", "j", ""), NOW)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w1", "working", "j", ""), NOW, replace=replace_file)) transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n{"more": 1}\n') - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w2", "Ctrl-C"), NOW + 1)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w2", "Ctrl-C"), NOW + 1, replace=replace_file)) self.assertEqual(read.latest_worker(kept, str(transcript)), "w2") self.assertIsInstance(read.latest_worker(kept, str(pathlib.Path(root, "gone.jsonl"))), Failure) @@ -247,8 +248,8 @@ class Outcomes(unittest.TestCase): transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n') self.assertEqual(read.last_spent(kept, str(transcript)), "") with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) - self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW, replace=replace_file)) + self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w", "Ctrl-C"), NOW + 1, replace=replace_file)) self.assertEqual(read.last_spent(kept, str(transcript)), utc(NOW)) gone = read.last_spent(kept, str(pathlib.Path(root, "gone.jsonl"))) self.assertIsInstance(gone, Failure) diff --git a/bin/transcript_archive/write.py b/bin/transcript_archive/write.py index 683d857b..00837bff 100644 --- a/bin/transcript_archive/write.py +++ b/bin/transcript_archive/write.py @@ -6,15 +6,18 @@ import typing from transcript_archive.location import chunk_folder, outcomes_of from failure import Failure from transcript_archive.judge_run import JudgeRun -from text_files.file_writes import make_private, replace_file +from text_files.file_writes import make_private from text_files.compressed import read_stored, stored from claude_code.session import session_files from transcript_archive.outcomes import TASK from text_files.utc_stamp import utc +# Writes a file whole, as text_files.file_writes.replace_file does. +Replace = typing.Callable[[pathlib.Path, bytes], Failure | None] -def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float, note: typing.Callable[[str], None] = lambda text: None, judge_run: JudgeRun | None = None) -> Failure | None: - """Keeps the transcript at path, its outcomes file and its session's files in project_archive, in the layout this package's docstring gives; the failure that stopped it, or None. The outcome is stamped and appended to the outcomes file, which opens with the task only when the copy is new. Where a new copy lands, note is told where. A judge_run the outcome names is kept first, so the outcome never names a run the archive lacks.""" + +def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float, note: typing.Callable[[str], None] = lambda text: None, judge_run: JudgeRun | None = None, *, replace: Replace) -> Failure | None: + """Keeps the transcript at path, its outcomes file and its session's files in project_archive, in the layout this package's docstring gives; the failure that stopped it, or None. The outcome is stamped and appended to the outcomes file, which opens with the task only when the copy is new. Where a new copy lands, note is told where. replace writes each file, as replace_file does. A judge_run the outcome names is kept first, so the outcome never names a run the archive lacks.""" try: with open(path, "rb") as handle: raw = handle.read() @@ -23,24 +26,24 @@ def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, a except OSError as failure: return unarchived(failure.filename, failure.strerror) for sibling in session_files(path): - if sibling != path and (unkept := mirror(pathlib.Path(sibling), folder / "session" / os.path.basename(sibling))): + if sibling != path and (unkept := mirror(pathlib.Path(sibling), folder / "session" / os.path.basename(sibling), replace)): return unkept - if judge_run and (unkept := keep_judge_run(folder, judge_run)): + if judge_run and (unkept := keep_judge_run(folder, judge_run, replace)): return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" outcomes = outcomes_of(copy) stamped = f"{utc(at)} {outcome}" if stored(copy) and outcomes.exists(): - return add_outcome(outcomes, stamped) + return add_outcome(outcomes, stamped, replace) # The copy lands last, so a copy on disk always has its outcomes and its session's files beside it. for dest, data in ((outcomes, f"{TASK}{task}\n\n{stamped}\n".encode()), (copy, raw)): - if unwritten := replace_file(dest, data): + if unwritten := replace(dest, data): return unarchived(dest, unwritten.reason) note(f"transcript: {copy}") return None -def keep_judge_run(folder: pathlib.Path, run: JudgeRun) -> Failure | None: +def keep_judge_run(folder: pathlib.Path, run: JudgeRun, replace: Replace) -> Failure | None: kept = folder / run.file if stored(kept): return None @@ -48,7 +51,7 @@ def keep_judge_run(folder: pathlib.Path, run: JudgeRun) -> Failure | None: make_private(kept.parent) except OSError as failure: return unarchived(failure.filename, failure.strerror) - if unwritten := replace_file(kept, run.content()): + if unwritten := replace(kept, run.content()): return unarchived(kept, unwritten.reason) return None @@ -57,17 +60,17 @@ def unarchived(where: object, why: str | None) -> Failure: return Failure(f"could not archive the transcript: {where}: {why}") -def add_outcome(outcomes: pathlib.Path, outcome: str) -> Failure | None: +def add_outcome(outcomes: pathlib.Path, outcome: str, replace: Replace) -> Failure | None: try: kept = outcomes.read_bytes() except OSError as failure: return unarchived(failure.filename, failure.strerror) - if unwritten := replace_file(outcomes, kept + f"\n{outcome}\n".encode()): + if unwritten := replace(outcomes, kept + f"\n{outcome}\n".encode()): return unarchived(outcomes, unwritten.reason) return None -def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: +def mirror(source: pathlib.Path, dest: pathlib.Path, replace: Replace) -> Failure | None: try: files = [source] if source.is_file() else files_under(source) except OSError as failure: @@ -81,7 +84,7 @@ def mirror(source: pathlib.Path, dest: pathlib.Path) -> Failure | None: make_private(copy.parent) except OSError as failure: return unarchived(failure.filename, failure.strerror) - if unwritten := replace_file(copy, data): + if unwritten := replace(copy, data): return unarchived(copy, unwritten.reason) return None diff --git a/docs/decisions.md b/docs/decisions.md index 06cc0ebb..64a14f5f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -4,7 +4,7 @@ Each project principle states one rule that the decisions below apply; their ent 1. **Cut cost only where a measurement of archived chunks shows quality holds.** Chunk bundling, the round cap, which fixes rerun a pass, a reviewer of its own for each pass, the review a branch changing only Markdown no agent follows gets, the passes kept for the release review, review opt-outs, the security pass, compaction and the routing ladder all apply it. 2. **A measurement files or ranks work, and never blocks a merge.** The comprehension floor and check, and a reading-cost rise, apply it. A merge waits on a scoring run the plan calls for only until the run is recorded, whatever it scores. -3. **Each file has one writer.** `~/.claude/loop-claude-models.json` is loop-claude's, `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo. +3. **Each file has one writer.** `~/.claude/loop-claude-models.json` is `save_model`'s, the one function loop-claude and do-epic both write it through, `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo. 4. **A rule a program can check is enforced by a program, and reviewers rule on the rest.** rule-hook and its overrides, `docker-run-memory`, the refused writes of reviewers under `agents/`, and CI with `main`'s branch protection apply it. 5. **A chunk can't vouch for itself.** What a chunk writes is approved by a review pass, by the human, or by a precedent the repo held before the chunk began. So an unanswered ask leaves the PR unmerged, the human approves the premises chunk and runs `deploy-release --cut`, and the judge holds a chunk open while an answer the human typed isn't recorded anywhere. 6. **An unattended run never waits on a prompt, and a lasting failure stops it.** Every claude loop-claude starts bypasses permissions inside its sandbox, each claude it opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, and interactive sessions run in auto mode with the dangerous-mode prompt skipped. A failed archive stops the loop, while a `claude` that cannot start, as during an update, is retried. @@ -96,7 +96,7 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo ## bin/: the tools send no OTLP traces, logs or metrics, and loop-claude's archive holds the trace of each cycle -2026-11-16, lilleman, from the release review of 0.11.0. The tools send no traces, logs or metrics over OTLP, the OpenTelemetry protocol, to any collector. That departs from `principles/technical-principles.md` → "All critical flows should have good traces", whose sub-bullet asks for traceparent OTLP. lilleman ruled the departure permanent, so no plan item ends it. Serves goal 4: the tools run on the human's own machines, beside client code and transcripts, and whatever goes to a collector leaves the machine. loop-claude's archive holds the trace of each cycle instead: its transcripts and its `.outcomes.md` entry, from the worker's first run to the judge's verdict. Valid while goal 4 holds. +2026-11-16, lilleman, from the release review of 0.11.0. The tools send no traces, logs or metrics over OTLP, the OpenTelemetry protocol, to any collector. That applies `principles/technical-principles.md` → "All critical flows should have good traces", whose last sub-bullet keeps the trace of a tool that runs only on its user's own machine on that machine. lilleman ruled this permanent, and the release review of 0.12.0 wrote the sub-bullet from that ruling. Serves goal 4: the tools run on the human's own machines, beside client code and transcripts, and whatever goes to a collector leaves the machine. loop-claude's archive holds the trace of each cycle instead: its transcripts and its `.outcomes.md` entry, from the worker's first run to the judge's verdict. Valid while goal 4 holds. ## bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers @@ -191,9 +191,9 @@ Valid while `~/.claude` is a checkout of this repo. 2026-10-30, lilleman, todo item 6. Serves goal 1. Until then loop-claude marked each worktree trusted in `~/.claude.json`, reading the file, changing it and writing it back. Claude Code owns and writes that file, so a write it made in between could be lost. Claude Code 2.1.314 treats every folder as trusted while `CLAUDE_CODE_SANDBOXED` is set, and doesn't persist that trust. A claude started in a new folder with the variable set showed no dialog, and Claude Code recorded the folder untrusted. `hand_over` sets the variable for every claude it opens on a terminal: for `/talk`, a release ready to cut and the routing calls. The variable tells Claude Code it runs inside a sandbox, which holds here: loop-claude runs only in the sandbox README → Install names (`loop-claude: every claude it starts bypasses permissions inside its sandbox`). Claude Code doesn't document the variable. Where a later version drops it, the trust dialog comes back on those claudes, and nothing is lost. Valid while Claude Code honours `CLAUDE_CODE_SANDBOXED`. -## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes +## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only the chunk drivers write, through one locked function -2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session. +2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has one writer, `save_model` in `bin/chunk_driver/project/model_choice.py`, which loop-claude and do-epic both call and which holds a lock from its read to its write; every claude they start gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session. ## loop-claude: every claude it starts bypasses permissions inside its sandbox diff --git a/principles/technical-principles.md b/principles/technical-principles.md index ca64ef0b..95e988a9 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -101,6 +101,7 @@ - Two spellings that can disagree are a correctness bug, whatever the reason for having both: derive one from the other, or reject the combination. * All critical flows should have good traces, from where something was initiated until it completed. - Use traceparent OTLP and standardized logging for this. + - A tool that runs only on its user's own machine keeps its trace on that machine, as an archive of each run, and doesn't send anything to a collector. * Prefer the vendor-neutral option, and know what leaving would cost. - A supplier is a component like any other, so compose-not-entangle's test is the whole test. - Where two options do the job, the one that ties us to no supplier wins by default — dependency, protocol, format, service, provider and storage alike. Choosing neutral is usually free; it is the leaving that is expensive, so the test is what an exit costs and whether anyone has priced it. -- 2.52.0 From 762614353c7d4f14e613f52bb272cb289190f2ca Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 12:55:35 +0100 Subject: [PATCH 08/14] =?UTF-8?q?Answer=20principles=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20workflow-be?= =?UTF-8?q?nch=20hands=20its=20effects=20in=20as=20arguments,=20and=20no?= =?UTF-8?q?=20Python=20file=20of=20the=20repo=20patches=20a=20global?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/atlassian/jira.py | 14 +++- bin/atlassian/test_jira.py | 10 +++ bin/do_epic/backend/jira.py | 11 ++- bin/do_epic/backend/test_jira.py | 2 +- bin/do_epic/scheduler.py | 12 +-- bin/forge/reviews.py | 64 +++++++++++---- bin/forge/test_reviews.py | 4 +- bin/repo_checks/test_no_patched_globals.py | 5 +- bin/wait-for | 3 +- bin/wait_for/main.py | 91 +++++++++++----------- bin/wait_for/test_wait_for.py | 2 +- workflow-bench/advisor_bench.py | 63 +++++++++------ workflow-bench/bench.py | 22 +++--- workflow-bench/handoff_bench.py | 66 ++++++++++------ workflow-bench/test_advisor_bench.py | 76 +++++++++--------- workflow-bench/test_bench.py | 34 +++++--- workflow-bench/test_handoff_bench.py | 85 ++++++++++---------- 18 files changed, 335 insertions(+), 231 deletions(-) diff --git a/README.md b/README.md index 3550176a..3a41898a 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a ### Packages under `bin/` -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No test swaps a global with `mock.patch`: the code under test takes each effect as an argument, and the test hands it a double, which `repo_checks/test_no_patched_globals.py` checks. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No test swaps a global with `mock.patch`: the code under test takes each effect as an argument, and the test hands it a double, which `repo_checks/test_no_patched_globals.py` checks in every Python file of the repo, `workflow-bench/`'s included. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. - `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. `doubles.py` holds the doubles its tests share with `chunk_driver`'s. diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py index db5ed9e6..c14cb0ed 100644 --- a/bin/atlassian/jira.py +++ b/bin/atlassian/jira.py @@ -13,11 +13,12 @@ PAGE = 100 MAX_PAGES = 100 # The key of the status category Jira Cloud gives every done status. DONE = "done" +# How a Failure names an answer in which a field is missing or of another type. +SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents" # What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue. PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {under} before filing it again" # What a failed move ends with, for the same reason. -SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents" -PERHAPS_MOVED ="unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again" +PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again" @dataclasses.dataclass(frozen=True) @@ -72,6 +73,15 @@ def offer_of(raw: object) -> tuple[str, str, str, str] | None: return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None +def status_category(issue: object) -> str | Failure: + """The key of the category of the status in Jira's answer about one issue, or how the answer is not in the shape Jira documents.""" + fields = issue.get("fields") if isinstance(issue, dict) else None + status = fields.get("status") if isinstance(fields, dict) else None + category = status.get("statusCategory") if isinstance(status, dict) else None + key = category.get("key") if isinstance(category, dict) else None + return key if isinstance(key, str) else Failure("its status category has no key that is text") + + def finishing_transition(site: str, key: str, finish: Finish, authorization: str, http: Http) -> str | Failure: """The ID of the transition finish names, as Jira offers it now for the issue named key, which is a plan item or an epic; or why none of those offered finishes it.""" offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None) diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py index f2fcea04..5133e6e7 100644 --- a/bin/atlassian/test_jira.py +++ b/bin/atlassian/test_jira.py @@ -53,5 +53,15 @@ class TheHeadOfAnEntry(unittest.TestCase): entry_of({"key": "ABC-1", "fields": Faulty()}, "plan") +class TheCategoryOfAnIssuesStatus(unittest.TestCase): + def test_is_the_key_jira_gives_the_category(self): + self.assertEqual(jira.status_category({"fields": {"status": {"statusCategory": {"key": "done"}}}}), "done") + + def test_an_answer_in_another_shape_is_a_failure_naming_the_field(self): + for wrong in (["ABC-1"], {}, {"fields": []}, {"fields": {}}, {"fields": {"status": "Done"}}, {"fields": {"status": {}}}, {"fields": {"status": {"statusCategory": "done"}}}, {"fields": {"status": {"statusCategory": {}}}}, {"fields": {"status": {"statusCategory": {"key": 3}}}}): + with self.subTest(wrong=wrong): + self.assertEqual(jira.status_category(wrong), Failure("its status category has no key that is text")) + + if __name__ == "__main__": unittest.main() diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 1d49e1ed..79ad2548 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -5,7 +5,7 @@ import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown -from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped +from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure @@ -127,11 +127,10 @@ class JiraEpic: answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}?fields=status", authorization, None) if isinstance(answered, Failure): return Failure(f"cannot read {self.epic_key}'s status: {answered.reason}") - try: - category = answered["fields"]["status"]["statusCategory"]["key"] # type: ignore[index] - except (KeyError, TypeError) as failure: - return Failure(f"{self.epic_key}'s status is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") - return bool(category == DONE) + category = status_category(answered) + if isinstance(category, Failure): + return Failure(f"{self.epic_key}'s status {SHAPE}: {category.reason}") + return category == DONE def close(self, summary: str) -> None | Failure: if self.finish is None: diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index e516ab8a..89c56635 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -212,7 +212,7 @@ class Jira(Case): self.assertEqual(self.new_store().close("Shipped."), Failure("posted the summary on ABC-12, but cannot move ABC-12 by 'Mark as done': Jira answered 503; close the epic in Jira rather than posting the summary again")) def test_says_why_the_epics_status_cannot_be_read(self) -> None: - for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: TypeError('list indices must be integers or slices, not str')")): + for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text"), ({"fields": {"status": {"statusCategory": {"key": 3}}}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: its status category has no key that is text")): self.jira.answers[("GET", EPIC_STATUS)] = answer self.assertEqual(self.new_store().closed(), Failure(reason)) diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index e2a8337c..09bca3d4 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -165,8 +165,8 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run) if isinstance(now, Failure): return now - if isinstance(now, str): - waits.append(Waits(chunk.issue, now)) + if isinstance(now, Waits): + waits.append(now) else: windows = now started.append(chunk.issue) @@ -176,8 +176,8 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str return Started(started, sorted(waits, key=lambda wait: order.index(wait.issue))) -def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | str | Failure: - """Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none, or where the repo's lock cannot be taken. It holds that lock from the check to the start. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo.""" +def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | Waits | Failure: + """Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; a Waits with the reason where its repo takes no chunk now, and a Failure where tmux started none, or where the repo's lock cannot be taken. It holds that lock from the check to the start. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo.""" session = tmux.session_name(tmux.EPIC, epic.key) handed = {**{name: value for name, value in epic.env.items() if name.startswith(HANDED)}, PARKS: "1"} command = [str(epic.launcher), CHUNK_FLAG, chunk.issue, epic.key] @@ -185,13 +185,13 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(epic.folder), handed, command, windows, False, run) located = epic.locate(chunk.repo) if isinstance(located, Failure): - return located.reason + return Waits(chunk.issue, located.reason) checkout, limit = located with starting(project_lock(str(checkout), epic.home)) as unlocked: if unlocked: return unlocked if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.home, run)): - return reason + return Waits(chunk.issue, reason) return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), handed, command, windows, False, run) diff --git a/bin/forge/reviews.py b/bin/forge/reviews.py index 331d811b..a64141f6 100644 --- a/bin/forge/reviews.py +++ b/bin/forge/reviews.py @@ -72,23 +72,45 @@ class PullView: said: tuple[str, ...] -def text(value: object) -> str: - """value, which a forge's answer must hold as a string. Raises TypeError where it is none.""" - if not isinstance(value, str): - raise TypeError(f"{value!r} is not a string") +# What `held` gives where the answer lacks the key asked for: no text, so the check of the field refuses it. +MISSING = object() + + +def held(value: object, *path: str) -> object: + """What a forge's answer holds along path, one key per level; MISSING where a level is no object or lacks its key.""" + for key in path: + value = value.get(key, MISSING) if isinstance(value, dict) else MISSING return value def pull_view(printed: str) -> PullView | Failure: """The pull request that gh printed, with each field checked here, so what decides on it meets no other shape.""" + unshaped = Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}") try: pull = json.loads(printed) - author = text(pull["author"]["login"]) - reviews = tuple(Review(text(review["author"]["login"]), text(review["state"]), text(review["submittedAt"] or ""), text(review["commit"]["oid"]) if review["state"] == CHANGES_REQUESTED else "") for review in pull["reviews"]) - commented = tuple(text(comment["createdAt"]) for comment in pull["comments"] if text(comment["author"]["login"]) == author) - return PullView(bool(pull["isDraft"]), text(pull["reviewDecision"] or ""), reviews, tuple(review.submitted_at for review in reviews if review.author == author) + commented) - except (ValueError, KeyError, TypeError): - return Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}") + except ValueError: + return unshaped + author, draft, decision, listed, comments = held(pull, "author", "login"), held(pull, "isDraft"), held(pull, "reviewDecision") or "", held(pull, "reviews"), held(pull, "comments") + if not isinstance(author, str) or draft is MISSING or not isinstance(decision, str) or not isinstance(listed, list) or not isinstance(comments, list): + return unshaped + reviews = [] + for review in listed: + reviewer, state, submitted_at = held(review, "author", "login"), held(review, "state"), held(review, "submittedAt") or "" + commit = held(review, "commit", "oid") if state == CHANGES_REQUESTED else "" + if not isinstance(reviewer, str) or not isinstance(state, str) or not isinstance(submitted_at, str) or not isinstance(commit, str): + return unshaped + reviews.append(Review(reviewer, state, submitted_at, commit)) + commented = [] + for comment in comments: + commenter, created_at = held(comment, "author", "login"), held(comment, "createdAt") + if not isinstance(commenter, str): + return unshaped + if commenter != author: + continue + if not isinstance(created_at, str): + return unshaped + commented.append(created_at) + return PullView(bool(draft), decision, tuple(reviews), tuple(review.submitted_at for review in reviews if review.author == author) + tuple(commented)) def answered(pull: PullView, head: str) -> bool: @@ -135,12 +157,24 @@ class Thread: def threads_read(printed: str) -> tuple[str, tuple[Thread, ...]] | Failure: """Who opened the pull request and its review threads, as gh printed THREADS' answer, with each field checked here.""" + unshaped = Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}") try: - pull = json.loads(printed)["data"]["repository"]["pullRequest"] - threads = tuple(Thread(text(thread["path"]), bool(thread["isResolved"]), tuple(text(comment["author"]["login"]) for comment in thread["comments"]["nodes"])) for thread in pull["reviewThreads"]["nodes"]) - return text(pull["author"]["login"]), threads - except (ValueError, KeyError, TypeError): - return Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}") + pull = held(json.loads(printed), "data", "repository", "pullRequest") + except ValueError: + return unshaped + author, nodes = held(pull, "author", "login"), held(pull, "reviewThreads", "nodes") + if not isinstance(author, str) or not isinstance(nodes, list): + return unshaped + threads = [] + for thread in nodes: + path, resolved, comments = held(thread, "path"), held(thread, "isResolved"), held(thread, "comments", "nodes") + if not isinstance(path, str) or resolved is MISSING or not isinstance(comments, list): + return unshaped + last = tuple(login for comment in comments if isinstance(login := held(comment, "author", "login"), str)) + if len(last) != len(comments): + return unshaped + threads.append(Thread(path, bool(resolved), last)) + return author, tuple(threads) def waits(author: str, threads: tuple[Thread, ...]) -> list[str]: diff --git a/bin/forge/test_reviews.py b/bin/forge/test_reviews.py index f1467d26..dc618052 100644 --- a/bin/forge/test_reviews.py +++ b/bin/forge/test_reviews.py @@ -35,7 +35,7 @@ class ThePullRequestAsViewed(unittest.TestCase): self.assertEqual(reviews.pull_view(printed), PullView(False, CHANGES_REQUESTED, (Review("rev", CHANGES_REQUESTED, "2026-11-02T10:00:00Z", "abc"), Review("me", "PENDING", "", "")), ("", "2026-11-02T11:00:00Z"))) def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self): - unshaped = ("not json", "[]", json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"})) + unshaped = ("not json", "[]", json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps(PULL | {"comments": [{"author": {"login": 7}, "createdAt": "2026-11-02T11:00:00Z"}]}), json.dumps(PULL | {"comments": [{"author": {"login": PULL["author"]["login"]}, "createdAt": None}]}), json.dumps(PULL | {"reviews": [{key: value for key, value in ASKED.items() if key != "submittedAt"}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"})) for printed in unshaped: with self.subTest(printed=printed): self.assertEqual(reviews.pull_view(printed), Failure(f"gh pr view printed no review decision: {printed[:200]}")) @@ -78,7 +78,7 @@ class TheThreadsThatWait(unittest.TestCase): self.assertEqual(reviews.waiting_threads("7", lambda args: printed), ["a.py", "b.py"]) def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self): - for printed in ("not json", "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}})): + for printed in ("not json", "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": {"login": 7}}]}}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"path": "a.py", "comments": {"nodes": []}}]}}}}})): with self.subTest(printed=printed): self.assertEqual(reviews.waiting_threads("7", lambda args: printed), Failure(f"gh api graphql printed no review threads: {printed[:200]}")) diff --git a/bin/repo_checks/test_no_patched_globals.py b/bin/repo_checks/test_no_patched_globals.py index 56a7bc88..faf74c00 100644 --- a/bin/repo_checks/test_no_patched_globals.py +++ b/bin/repo_checks/test_no_patched_globals.py @@ -20,10 +20,11 @@ def patches(source: str) -> list[int]: class NoPatchedGlobals(unittest.TestCase): - def test_no_python_file_under_bin_patches_a_global(self): + def test_no_python_file_patches_a_global(self): # A file not yet staged counts too, so a new suite is checked before its first commit. - listed = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "bin/*.py"],capture_output=True, check=True, cwd=ROOT, text=True).stdout.split() + listed = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "*.py"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split() self.assertIn("bin/repo_checks/test_no_patched_globals.py", listed) + self.assertIn("workflow-bench/test_bench.py", listed) patching = {name for name in listed if patches((ROOT / name).read_text(encoding="utf-8"))} self.assertEqual(patching, set(), "hand the code under test its effect as an argument instead") diff --git a/bin/wait-for b/bin/wait-for index 6b1379ae..96469b09 100755 --- a/bin/wait-for +++ b/bin/wait-for @@ -1,9 +1,10 @@ #!/usr/bin/env python3 import pathlib import sys +import time sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from wait_for import main -sys.exit(main.main(sys.argv[1:])) +sys.exit(main.main(sys.argv[1:], time)) diff --git a/bin/wait_for/main.py b/bin/wait_for/main.py index 9023f106..1755e09c 100644 --- a/bin/wait_for/main.py +++ b/bin/wait_for/main.py @@ -13,7 +13,6 @@ Exit 0 on the line, 1 on the timeout, bad arguments or a file it cannot read, sa import pathlib import re import sys -import time import typing from failure import Failure @@ -28,25 +27,41 @@ class Clock(typing.Protocol): def sleep(self, seconds: float) -> None: ... -def text_of(path: pathlib.Path) -> str | None | Failure: - """What the file holds; None where it doesn't exist.""" - try: - return path.read_text(errors="replace") - except FileNotFoundError: - return None - except OSError as error: - return Failure(f"cannot read {path}: {error.strerror}") +def main(argv: list[str], clock: Clock) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + parsed = arguments(argv) + done = parsed if isinstance(parsed, Failure) else waited(*parsed, clock) + if isinstance(done, Failure): + print(f"wait-for: {done.reason}", file=sys.stderr) + return 1 + print(done) + return 0 -def line_in(text: str, pattern: re.Pattern[str] | None) -> str | None: - """The first line of text matching pattern, or without one its last line; None where there is none.""" - lines = text.splitlines() - if pattern is None: - return lines[-1] if lines else None - return next((line for line in lines if pattern.search(line)), None) +def arguments(argv: list[str]) -> tuple[str, str | None, float] | Failure: + operands = list(argv) + timeout = float(TIMEOUT_SECONDS) + if "--timeout" in operands: + at = operands.index("--timeout") + given = operands[at + 1:at + 2] + if not given or not re.fullmatch(r"[0-9]+(\.[0-9]+)?", given[0]) or float(given[0]) <= 0: + return Failure(f"give --timeout a number of seconds above 0; {USAGE}") + timeout = float(given[0]) + del operands[at:at + 2] + if not 1 <= len(operands) <= 2: + return Failure(USAGE) + pattern = operands[1] if len(operands) == 2 else None + if pattern is not None: + try: + re.compile(pattern) + except re.error as error: + return Failure(f"cannot read the pattern `{pattern}`: {error}") + return operands[0], pattern, timeout -def waited(file: str, pattern: str | None, timeout: float, clock: Clock = time) -> str | Failure: +def waited(file: str, pattern: str | None, timeout: float, clock: Clock) -> str | Failure: path = pathlib.Path(file) compiled = re.compile(pattern) if pattern is not None else None deadline = clock.monotonic() + timeout @@ -72,35 +87,19 @@ def waited(file: str, pattern: str | None, timeout: float, clock: Clock = time) clock.sleep(min(POLL_SECONDS, left)) -def arguments(argv: list[str]) -> tuple[str, str | None, float] | Failure: - operands = list(argv) - timeout = float(TIMEOUT_SECONDS) - if "--timeout" in operands: - at = operands.index("--timeout") - given = operands[at + 1:at + 2] - if not given or not re.fullmatch(r"[0-9]+(\.[0-9]+)?", given[0]) or float(given[0]) <= 0: - return Failure(f"give --timeout a number of seconds above 0; {USAGE}") - timeout = float(given[0]) - del operands[at:at + 2] - if not 1 <= len(operands) <= 2: - return Failure(USAGE) - pattern = operands[1] if len(operands) == 2 else None - if pattern is not None: - try: - re.compile(pattern) - except re.error as error: - return Failure(f"cannot read the pattern `{pattern}`: {error}") - return operands[0], pattern, timeout +def text_of(path: pathlib.Path) -> str | None | Failure: + """What the file holds; None where it doesn't exist.""" + try: + return path.read_text(errors="replace") + except FileNotFoundError: + return None + except OSError as error: + return Failure(f"cannot read {path}: {error.strerror}") -def main(argv: list[str]) -> int: - if argv[:1] in (["-h"], ["--help"]): - print(__doc__.strip()) - return 0 - parsed = arguments(argv) - done = parsed if isinstance(parsed, Failure) else waited(*parsed) - if isinstance(done, Failure): - print(f"wait-for: {done.reason}", file=sys.stderr) - return 1 - print(done) - return 0 +def line_in(text: str, pattern: re.Pattern[str] | None) -> str | None: + """The first line of text matching pattern, or without one its last line; None where there is none.""" + lines = text.splitlines() + if pattern is None: + return lines[-1] if lines else None + return next((line for line in lines if pattern.search(line)), None) diff --git a/bin/wait_for/test_wait_for.py b/bin/wait_for/test_wait_for.py index 57a77f3e..9021a0e9 100644 --- a/bin/wait_for/test_wait_for.py +++ b/bin/wait_for/test_wait_for.py @@ -116,7 +116,7 @@ class WaitFor(unittest.TestCase): with self.subTest(argv=argv): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main(argv) + code = main.main(argv, Clock()) self.assertEqual((code, out.getvalue(), err.getvalue()), expected) def test_arguments_take_the_timeout_anywhere_and_refuse_a_bad_one(self): diff --git a/workflow-bench/advisor_bench.py b/workflow-bench/advisor_bench.py index 5d83a3f6..ea294554 100644 --- a/workflow-bench/advisor_bench.py +++ b/workflow-bench/advisor_bench.py @@ -13,11 +13,13 @@ Run each arm of each case once; the table shows a direction, not a significance. """ import concurrent.futures import dataclasses +import functools import json import pathlib import re import subprocess import sys +import typing BENCH = pathlib.Path(__file__).resolve().parent REPO = BENCH.parent @@ -52,6 +54,17 @@ VERDICTS = ("pass", "partial", "fail") JUDGE = Arm("claude-opus-5-5", "medium") +@dataclasses.dataclass(frozen=True) +class Bench: + """What a bench's steps act on, which the script's entry point hands them.""" + # The repo whose archived chunks the bench reruns. + repo: pathlib.Path + # Each case's start commit and the commit it merged at, by todo item. + cases: dict + # Runs claude and the tests, as subprocess.run does. + process: typing.Callable + + @dataclasses.dataclass(frozen=True) class Outcome: cost: float @@ -124,51 +137,51 @@ def git(repo, *args): return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout -def fresh_clone(base, dest): - """A clone of this repo at base, with no remote to push to.""" - subprocess.run(["git", "clone", "-q", "--no-local", str(REPO), str(dest)], check=True) +def fresh_clone(repo, base, dest): + """A clone of repo at base, with no remote to push to.""" + subprocess.run(["git", "clone", "-q", "--no-local", str(repo), str(dest)], check=True) git(dest, "checkout", "-q", "--detach", base) git(dest, "remote", "remove", "origin") -def run(work, name): +def run(bench, work, name): """One worker run of --; the files it leaves are in the module docstring.""" case, arm, _ = split_name(name) - base = CASES[case][0] + base = bench.cases[case][0] clone = work / name if clone.exists(): raise ValueError(f"{name} already ran: remove {clone}") - fresh_clone(base, clone) - prompt = (BENCH / "advisor-run-prompt.md").read_text().format(base=base, item=case, text=item_text(git(REPO, "show", f"{base}:todo.md"), case)) + fresh_clone(bench.repo, base, clone) + prompt = (BENCH / "advisor-run-prompt.md").read_text().format(base=base, item=case, text=item_text(git(bench.repo, "show", f"{base}:todo.md"), case)) with (work / f"{name}.jsonl").open("w") as out: - subprocess.run( + bench.process( ["claude", "-p", prompt, *ARMS[arm].flags(), "--setting-sources", "project", "--permission-mode", "bypassPermissions", "--no-session-persistence", "--output-format", "stream-json", "--verbose"], cwd=clone, stdout=out, stderr=subprocess.STDOUT) read_result((work / f"{name}.jsonl").read_text().splitlines()) - save_change(work, name, clone, CASES[case]) + save_change(bench, work, name, clone, bench.cases[case]) return f"{name}: ran" -def save_change(work, name, clone, commits): +def save_change(bench, work, name, clone, commits): """Save the clone's change since the case's start commit as .diff, and as .tests the result of the tests of the packages that the clone's change or the merged change touches.""" base, merged = commits git(clone, "add", "--all") (work / f"{name}.diff").write_text(git(clone, "diff", "--cached", base)) - changed = [*git(clone, "diff", "--cached", "--name-only", base).split(), *git(REPO, "diff", "--name-only", base, merged).split()] + changed = [*git(clone, "diff", "--cached", "--name-only", base).split(), *git(bench.repo, "diff", "--name-only", base, merged).split()] targets = [target for target in suite_targets(changed) if (clone / target).exists()] or ["bin"] - tests = subprocess.run([str(RUN_HEAVY), *SUITE, *targets], cwd=clone, capture_output=True, text=True) + tests = bench.process([str(RUN_HEAVY), *SUITE, *targets], cwd=clone, capture_output=True, text=True) (work / f"{name}.tests").write_text(f"exit {tests.returncode}\n{tests.stdout[-1500:]}") -def grade(work, name, cases=None): - """Have the judge rule on one run's diff, blind to its arm, and save the verdict beside it. cases stands in for CASES where another bench grades its own.""" +def grade(bench, work, name): + """Have the judge rule on one run's diff, blind to its arm, and save the verdict beside it.""" case = split_name(name)[0] - base, merged = (cases or CASES)[case] + base, merged = bench.cases[case] prompt = (BENCH / "advisor-judge-prompt.md").read_text().format( - text=item_text(git(REPO, "show", f"{base}:todo.md"), case), reference=git(REPO, "diff", base, merged, "--", ".", ":!todo.md", ":!docs", ":!CHANGELOG.md"), + text=item_text(git(bench.repo, "show", f"{base}:todo.md"), case), reference=git(bench.repo, "diff", base, merged, "--", ".", ":!todo.md", ":!docs", ":!CHANGELOG.md"), diff=(work / f"{name}.diff").read_text(), tests=(work / f"{name}.tests").read_text()) - reply = subprocess.run( + reply = bench.process( ["claude", "-p", prompt, *JUDGE.flags(), "--setting-sources", "", "--no-session-persistence", "--output-format", "json", "--tools", ""], capture_output=True, text=True, check=True).stdout verdict = verdict_of(reply) @@ -196,15 +209,21 @@ def rows_of(work): return rows -def main(argv): +def steps_of(bench): + """The steps main runs by name, each on bench.""" + return {"run": functools.partial(run, bench), "grade": functools.partial(grade, bench)} + + +def main(argv, steps, say): + """Runs the step argv names on each run it names, and hands say each result line; or hands say the summary.""" work, step, names = pathlib.Path(argv[0]), argv[1], argv[2:] if step == "summary": - print(summary(rows_of(work))) + say(summary(rows_of(work))) return with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool: - for result in pool.map(lambda name: attempted({"run": run, "grade": grade}[step], work, name), names): - print(result, flush=True) + for result in pool.map(lambda name: attempted(steps[step], work, name), names): + say(result) if __name__ == "__main__": - main(sys.argv[1:]) + main(sys.argv[1:], steps_of(Bench(REPO, CASES, subprocess.run)), functools.partial(print, flush=True)) diff --git a/workflow-bench/bench.py b/workflow-bench/bench.py index f014c3a8..961a06db 100755 --- a/workflow-bench/bench.py +++ b/workflow-bench/bench.py @@ -14,6 +14,7 @@ other. The bench's inputs are untracked: Each run leaves its clone in /, its report in .md and its claude stream in logs/. """ import concurrent.futures +import functools import json import os import pathlib @@ -24,7 +25,6 @@ import time BENCH = pathlib.Path(__file__).resolve().parent REVIEW_GIT = BENCH / "review_git.py" -SOURCES = pathlib.Path(os.environ["BENCH_SOURCES"]) CASES = { "cjk": ("151bf38^", "6c49912"), "35b": ("692433b", "1d369ec"), @@ -61,10 +61,10 @@ def git(repo, *args): return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout.strip() -def fresh_clone(case, dest): +def fresh_clone(case, dest, sources): if dest.exists(): shutil.rmtree(dest) - source = SOURCES / f"{case}-main" + source = sources / f"{case}-main" base_ref, head_ref = CASES[case] base = git(source, "rev-parse", base_ref) head = git(source, "rev-parse", head_ref) @@ -89,14 +89,15 @@ def rate_limit_reset(log): return max(resets) -def run(name): +def run(name, sources): + """One review run of --, whose case's clone is in the folder sources.""" case, version, _ = name.split("-") clone = BENCH / name report = BENCH / f"{name}.md" for attempt in range(1, ATTEMPTS + 1): if report.exists(): return f"{name}: done" - base, head = fresh_clone(case, clone) + base, head = fresh_clone(case, clone, sources) version_dir = BENCH / "versions" / version prompt = (BENCH / "run-prompt.md").read_text().format( version_dir=version_dir, base=base, head=head, case=case, report=report, review_git=REVIEW_GIT) @@ -113,19 +114,20 @@ def run(name): return f"{name}: FAILED after {ATTEMPTS} attempts" -def attempted(name): - """run's result line, or a line naming the failure, so one failed run doesn't stop the other runs' results printing.""" +def attempted(name, run): + """run's result line for name, or a line naming the failure, so one failed run doesn't stop the other runs' results printing.""" try: return run(name) except (KeyError, ValueError, subprocess.CalledProcessError, OSError) as failure: return f"{name}: FAILED: {type(failure).__name__}: {failure}" -def main(): +def main(names, run): + """Prints the result line of each run named, which run makes.""" with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: - for result in pool.map(attempted, sys.argv[1:]): + for result in pool.map(lambda name: attempted(name, run), names): print(result, flush=True) if __name__ == "__main__": - main() + main(sys.argv[1:], functools.partial(run, sources=pathlib.Path(os.environ["BENCH_SOURCES"]))) diff --git a/workflow-bench/handoff_bench.py b/workflow-bench/handoff_bench.py index 0fa7d299..ffa8e295 100644 --- a/workflow-bench/handoff_bench.py +++ b/workflow-bench/handoff_bench.py @@ -18,12 +18,15 @@ Run each arm of each case once; the table shows a direction, not a significance. """ import collections import concurrent.futures +import dataclasses +import functools import json import pathlib import shutil import subprocess import sys import threading +import typing import uuid import advisor_bench @@ -54,6 +57,18 @@ START_BUDGET = 0.36 CLAUDE_FLAGS = ["--setting-sources", "project", "--permission-mode", "bypassPermissions", "--output-format", "stream-json", "--verbose"] +@dataclasses.dataclass(frozen=True) +class Handoff: + """What this bench's steps act on, which the script's entry point hands them.""" + bench: advisor_bench.Bench + # Dollars WEAK may spend before the handoff. + budget: float + # Where Claude Code keeps each session's transcript. + projects: pathlib.Path + # Makes the ID of the session `start` opens, as uuid.uuid4 does. + new_session: typing.Callable + + def stopped_at_budget(lines): """Whether a claude stream's first result line, the worker's own, says the run stopped at --max-budget-usd.""" for line in lines: @@ -66,34 +81,35 @@ def stopped_at_budget(lines): return False -def run_prompt(case): +def run_prompt(bench, case): """advisor_bench's prompt for the case's item, as the item's text stood at the start commit.""" - base = CASES[case][0] - text = advisor_bench.item_text(advisor_bench.git(advisor_bench.REPO, "show", f"{base}:todo.md"), case) + base = bench.cases[case][0] + text = advisor_bench.item_text(advisor_bench.git(bench.repo, "show", f"{base}:todo.md"), case) return (BENCH / "advisor-run-prompt.md").read_text().format(base=base, item=case, text=text) -def claude(prompt, flags, clone, stream): +def claude(process, prompt, flags, clone, stream): with stream.open("w") as out: - subprocess.run(["claude", "-p", prompt, *flags, *CLAUDE_FLAGS], cwd=clone, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT) + process(["claude", "-p", prompt, *flags, *CLAUDE_FLAGS], cwd=clone, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT) -def start(work, name): +def start(handoff, work, name): """WEAK's capped run of -, and the tree and session it leaves the arms; the files are in the module docstring.""" case, number = name.split("-") - base = CASES[case][0] + bench = handoff.bench + base = bench.cases[case][0] clone, saved = work / name, work / f"{case}-start-{number}" if clone.exists(): raise ValueError(f"{name} already started: remove {clone}") - advisor_bench.fresh_clone(base, clone) - session = str(uuid.uuid4()) + advisor_bench.fresh_clone(bench.repo, base, clone) + session = str(handoff.new_session()) stream = saved.with_suffix(".jsonl") - claude(run_prompt(case), [*WEAK.flags(), "--session-id", session, "--max-budget-usd", str(START_BUDGET)], clone, stream) + claude(bench.process, run_prompt(bench, case), [*WEAK.flags(), "--session-id", session, "--max-budget-usd", str(handoff.budget)], clone, stream) if not stopped_at_budget(stream.read_text().splitlines()): raise ValueError("the weak worker finished within its budget, or its run failed, so there is no handoff to bench") - transcripts = list(CLAUDE_PROJECTS.glob(f"*/{session}.jsonl")) + transcripts = list(handoff.projects.glob(f"*/{session}.jsonl")) if len(transcripts) != 1: - raise ValueError(f"expected one transcript of session {session} under {CLAUDE_PROJECTS}, found {len(transcripts)}") + raise ValueError(f"expected one transcript of session {session} under {handoff.projects}, found {len(transcripts)}") shutil.copy(transcripts[0], saved.with_suffix(".session.jsonl")) saved.with_suffix(".session").write_text(str(transcripts[0])) # The worker may have committed against the bench rules, so the arms get its whole change since base, uncommitted. @@ -104,9 +120,10 @@ def start(work, name): return f"{name}: started" -def run(work, name): +def run(handoff, work, name): """STRONG's run of one arm, --, from the tree and session `start` left.""" case, arm, number = advisor_bench.split_name(name) + bench = handoff.bench if arm not in ARMS: raise ValueError(f"the arm {arm!r} is none of {ARMS}") clone, saved = work / f"{case}-{number}", work / f"{case}-start-{number}" @@ -122,15 +139,15 @@ def run(work, name): shutil.copy(saved.with_suffix(".session.jsonl"), transcript) resumed = ["--resume", transcript.stem] if arm == "compact": - claude("/compact", [*WEAK.flags(), *resumed], clone, work / f"{name}.compact.jsonl") + claude(bench.process, "/compact", [*WEAK.flags(), *resumed], clone, work / f"{name}.compact.jsonl") finished(work / f"{name}.compact.jsonl") if arm == "brief": - claude(run_prompt(case) + "\n" + (BENCH / "handoff-brief-prompt.md").read_text(), [*STRONG.flags(), "--no-session-persistence"], clone, stream) + claude(bench.process, run_prompt(bench, case) + "\n" + (BENCH / "handoff-brief-prompt.md").read_text(), [*STRONG.flags(), "--no-session-persistence"], clone, stream) else: prompt = (BENCH / "handoff-resume-prompt.md").read_text().format(rung=f"{STRONG.model} at {STRONG.effort} effort") - claude(prompt, [*STRONG.flags(), *resumed], clone, stream) + claude(bench.process, prompt, [*STRONG.flags(), *resumed], clone, stream) outcome(work, name) - advisor_bench.save_change(work, name, clone, CASES[case]) + advisor_bench.save_change(bench, work, name, clone, bench.cases[case]) return f"{name}: ran" @@ -185,16 +202,21 @@ def summary(rows): return "\n".join(lines) -def main(argv): +def steps_of(handoff): + """The steps main runs by name, each on handoff; the grade is advisor_bench's, over handoff's cases.""" + return {"start": functools.partial(start, handoff), "run": functools.partial(run, handoff), "grade": functools.partial(advisor_bench.grade, handoff.bench)} + + +def main(argv, steps, say): + """Runs the step argv names on each run it names, and hands say each result line; or hands say the summary.""" work, step, names = pathlib.Path(argv[0]), argv[1], argv[2:] if step == "summary": - print(summary(rows_of(work))) + say(summary(rows_of(work))) return - steps = {"start": start, "run": run, "grade": lambda work, name: advisor_bench.grade(work, name, CASES)} with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool: for result in pool.map(lambda name: advisor_bench.attempted(steps[step], work, name), names): - print(result, flush=True) + say(result) if __name__ == "__main__": - main(sys.argv[1:]) + main(sys.argv[1:], steps_of(Handoff(advisor_bench.Bench(advisor_bench.REPO, CASES, subprocess.run), START_BUDGET, CLAUDE_PROJECTS, uuid.uuid4)), functools.partial(print, flush=True)) diff --git a/workflow-bench/test_advisor_bench.py b/workflow-bench/test_advisor_bench.py index eb47c324..3ab75b44 100644 --- a/workflow-bench/test_advisor_bench.py +++ b/workflow-bench/test_advisor_bench.py @@ -1,11 +1,9 @@ -import contextlib -import io import json import pathlib +import shutil import subprocess import tempfile import unittest -import unittest.mock import advisor_bench @@ -149,15 +147,11 @@ class Orchestration(unittest.TestCase): merged = self.commit({"todo.md": TODO + "\nmore\n", "bin/pkg/mod.py": "x = 2\n", "bin/other/mod.py": "z = 1\n", "docs/notes.md": "b\n", "CHANGELOG.md": "b\n"}) self.commit({"bin/pkg/mod.py": "x = 5\n", "bin/later/mod.py": "y = 1\n"}) self.calls = [] - real_run = subprocess.run - for patch in ( - unittest.mock.patch.object(advisor_bench, "REPO", self.repo), unittest.mock.patch.object(advisor_bench, "CASES", {"7": (base, merged)}), - unittest.mock.patch.object(advisor_bench.subprocess, "run", side_effect=lambda args, **kwargs: self.fake(real_run, args, **kwargs)), - ): - patch.start() - self.addCleanup(patch.stop) + self.bench = advisor_bench.Bench(self.repo, {"7": (base, merged)}, self.fake) self.tests_output = "3 passed\n" self.worker_result = {} + # Whether the fake worker removes bin/ in place of changing it. + self.worker_removes_bin = False self.base = base def commit(self, files): @@ -168,26 +162,30 @@ class Orchestration(unittest.TestCase): commit(self.repo, "a commit") return advisor_bench.git(self.repo, "rev-parse", "HEAD").strip() - def fake(self, real_run, args, **kwargs): + def fake(self, args, **kwargs): + """Stands in for subprocess.run where the bench runs claude or the tests.""" if args[0] == "claude": self.calls.append((args, kwargs)) if "--tools" in args: return subprocess.CompletedProcess(args, 0, stdout=json.dumps({"result": '{"verdict": "pass", "why": "ok"}'}), stderr="") - pathlib.Path(kwargs["cwd"], "bin/pkg/mod.py").write_text("x = 3\n") - pathlib.Path(kwargs["cwd"], "bin/pkg/new.py").write_text("n = 1\n") - pathlib.Path(kwargs["cwd"], "bin/third").mkdir() - pathlib.Path(kwargs["cwd"], "bin/third/mod.py").write_text("t = 1\n") - subprocess.run(["git", "-C", str(kwargs["cwd"]), "add", "bin/third"], check=True) + if self.worker_removes_bin: + shutil.rmtree(pathlib.Path(kwargs["cwd"], "bin")) + else: + pathlib.Path(kwargs["cwd"], "bin/pkg/mod.py").write_text("x = 3\n") + pathlib.Path(kwargs["cwd"], "bin/pkg/new.py").write_text("n = 1\n") + pathlib.Path(kwargs["cwd"], "bin/third").mkdir() + pathlib.Path(kwargs["cwd"], "bin/third/mod.py").write_text("t = 1\n") + subprocess.run(["git", "-C", str(kwargs["cwd"]), "add", "bin/third"], check=True) commit(kwargs["cwd"], "the worker commits") kwargs["stdout"].write(result_line(**self.worker_result) + "\n") return subprocess.CompletedProcess(args, 0) if args[0] == str(advisor_bench.RUN_HEAVY): self.calls.append((args, kwargs)) return subprocess.CompletedProcess(args, 4, stdout=self.tests_output, stderr="") - return real_run(args, **kwargs) + raise AssertionError(f"the bench ran {args}") def test_run_clones_at_the_start_commit_and_saves_the_stream_the_diff_and_the_tests(self): - self.assertEqual(advisor_bench.run(self.work, "7-sonnet-advisor-1"), "7-sonnet-advisor-1: ran") + self.assertEqual(advisor_bench.run(self.bench, self.work, "7-sonnet-advisor-1"), "7-sonnet-advisor-1: ran") (claude, claude_kwargs), (tests, tests_kwargs) = self.calls clone = self.work / "7-sonnet-advisor-1" self.assertEqual((claude_kwargs["cwd"], tests_kwargs["cwd"]), (clone, clone)) @@ -211,39 +209,39 @@ class Orchestration(unittest.TestCase): self.assertEqual((self.work / "7-sonnet-advisor-1.tests").read_text(), "exit 4\n3 passed\n") def test_run_tests_all_of_bin_where_no_touched_package_is_in_the_clone(self): - with unittest.mock.patch.object(advisor_bench, "suite_targets", return_value=["bin/absent"]): - advisor_bench.run(self.work, "7-sonnet-1") + self.worker_removes_bin = True + advisor_bench.run(self.bench, self.work, "7-sonnet-1") self.assertEqual(self.calls[1][0][-1:], ["bin"]) def test_run_refuses_a_run_that_ended_in_an_error_before_it_tests(self): self.worker_result = {"is_error": True, "result": "API Error"} with self.assertRaisesRegex(ValueError, "API Error"): - advisor_bench.run(self.work, "7-sonnet-1") + advisor_bench.run(self.bench, self.work, "7-sonnet-1") self.assertEqual(len(self.calls), 1) self.assertFalse((self.work / "7-sonnet-1.tests").exists()) def test_run_keeps_the_last_1500_characters_of_the_tests(self): self.tests_output = "a" * 2000 + "b" * 1500 - advisor_bench.run(self.work, "7-sonnet-1") + advisor_bench.run(self.bench, self.work, "7-sonnet-1") self.assertEqual((self.work / "7-sonnet-1.tests").read_text(), "exit 4\n" + "b" * 1500) def test_run_refuses_a_name_that_already_ran(self): - advisor_bench.run(self.work, "7-sonnet-1") + advisor_bench.run(self.bench, self.work, "7-sonnet-1") with self.assertRaisesRegex(ValueError, "7-sonnet-1 already ran: remove .*7-sonnet-1"): - advisor_bench.run(self.work, "7-sonnet-1") + advisor_bench.run(self.bench, self.work, "7-sonnet-1") def test_a_clone_of_a_missing_repo_fails(self): - with unittest.mock.patch.object(advisor_bench, "REPO", self.work / "missing"), self.assertRaises(subprocess.CalledProcessError): - advisor_bench.fresh_clone(self.base, self.work / "clone") + with self.assertRaises(subprocess.CalledProcessError): + advisor_bench.fresh_clone(self.work / "missing", self.base, self.work / "clone") def test_git_fails_where_git_does(self): with self.assertRaises(subprocess.CalledProcessError): advisor_bench.git(self.repo, "rev-parse", "no-such-revision") def test_grade_saves_the_verdict_and_shows_the_judge_both_changes_but_not_the_arm(self): - advisor_bench.run(self.work, "7-sonnet-advisor-1") + advisor_bench.run(self.bench, self.work, "7-sonnet-advisor-1") self.calls.clear() - self.assertEqual(advisor_bench.grade(self.work, "7-sonnet-advisor-1"), "7-sonnet-advisor-1: pass") + self.assertEqual(advisor_bench.grade(self.bench, self.work, "7-sonnet-advisor-1"), "7-sonnet-advisor-1: pass") ((judge, kwargs),) = self.calls self.assertEqual(judge[:2] + judge[3:], [ "claude", "-p", *advisor_bench.JUDGE.flags(), "--setting-sources", "", "--no-session-persistence", "--output-format", "json", "--tools", ""]) @@ -281,28 +279,30 @@ class Orchestration(unittest.TestCase): with self.assertRaisesRegex(ValueError, "^7-sonnet-1: the stream has no result line$"): advisor_bench.rows_of(self.work) - def run_main(self, *argv): - out = io.StringIO() - with contextlib.redirect_stdout(out): - advisor_bench.main([str(self.work), *argv]) - return out.getvalue() + def run_main(self, steps, *argv): + said = [] + advisor_bench.main([str(self.work), *argv], steps, said.append) + return "".join(f"{line}\n" for line in said) def test_main_prints_each_runs_line_though_an_earlier_run_failed(self): def step(work, name): if name == "7-a-1": raise ValueError("no") return f"{name}: ran" - with unittest.mock.patch.object(advisor_bench, "run", step): - self.assertEqual(self.run_main("run", "7-a-1", "7-b-1"), "7-a-1: FAILED: ValueError: no\n7-b-1: ran\n") + self.assertEqual(self.run_main({"run": step}, "run", "7-a-1", "7-b-1"), "7-a-1: FAILED: ValueError: no\n7-b-1: ran\n") def test_main_grades_on_grade(self): - with unittest.mock.patch.object(advisor_bench, "grade", lambda work, name: f"{work.name} {name}: graded"): - self.assertEqual(self.run_main("grade", "7-a-1"), "work 7-a-1: graded\n") + self.assertEqual(self.run_main({"grade": lambda work, name: f"{work.name} {name}: graded"}, "grade", "7-a-1"), "work 7-a-1: graded\n") + + def test_the_steps_run_and_grade_on_the_bench_they_are_given(self): + steps = advisor_bench.steps_of(self.bench) + self.assertEqual(self.run_main(steps, "run", "7-sonnet-1"), "7-sonnet-1: ran\n") + self.assertEqual(self.run_main(steps, "grade", "7-sonnet-1"), "7-sonnet-1: pass\n") def test_main_prints_the_work_dirs_summary_on_summary(self): (self.work / "7-sonnet-1.jsonl").write_text(result_line() + "\n") (self.work / "7-sonnet-1.verdict").write_text(json.dumps({"verdict": "pass"})) - self.assertIn("| sonnet | 1 | 1 | 0 | 0.50 | 0.0 | 12 |", self.run_main("summary")) + self.assertIn("| sonnet | 1 | 1 | 0 | 0.50 | 0.0 | 12 |", self.run_main({}, "summary")) if __name__ == "__main__": diff --git a/workflow-bench/test_bench.py b/workflow-bench/test_bench.py index de1f7a3e..adb803a4 100644 --- a/workflow-bench/test_bench.py +++ b/workflow-bench/test_bench.py @@ -1,13 +1,23 @@ import contextlib +import functools import io -import os +import pathlib import subprocess -import sys import unittest -import unittest.mock -with unittest.mock.patch.dict(os.environ, {"BENCH_SOURCES": "/nonexistent"}): - import bench +import bench + + +def answering(*answers): + """A run that gives the next of answers on each call, raising the one that is a failure.""" + left = list(answers) + + def run(name): + answer = left.pop(0) + if isinstance(answer, Exception): + raise answer + return answer + return run class Main(unittest.TestCase): @@ -17,27 +27,27 @@ class Main(unittest.TestCase): raise KeyError("a") return f"{name}: done" out = io.StringIO() - with unittest.mock.patch.object(bench, "run", side_effect=run), unittest.mock.patch.object(sys, "argv", ["bench.py", "a-v-1", "b-v-1"]), contextlib.redirect_stdout(out): - bench.main() + with contextlib.redirect_stdout(out): + bench.main(["a-v-1", "b-v-1"], run) self.assertEqual(out.getvalue().splitlines(), ["a-v-1: FAILED: KeyError: 'a'", "b-v-1: done"]) class Attempted(unittest.TestCase): def test_returns_the_run_result_of_a_run_that_finished(self): - with unittest.mock.patch.object(bench, "run", return_value="a-v-1: done"): - self.assertEqual(bench.attempted("a-v-1"), "a-v-1: done") + self.assertEqual(bench.attempted("a-v-1", answering("a-v-1: done")), "a-v-1: done") def test_returns_a_failed_run_as_a_line_naming_the_run_and_its_error_so_later_runs_still_report(self): failures = [KeyError("nope"), ValueError("not enough values to unpack"), subprocess.CalledProcessError(128, ["git", "clone"]), FileNotFoundError("claude")] for failure in failures: - with self.subTest(failure=type(failure).__name__), unittest.mock.patch.object(bench, "run", side_effect=[failure, "b-v-1: done"]): - results = [bench.attempted("a-v-1"), bench.attempted("b-v-1")] + with self.subTest(failure=type(failure).__name__): + run = answering(failure, "b-v-1: done") + results = [bench.attempted("a-v-1", run), bench.attempted("b-v-1", run)] self.assertTrue(results[0].startswith("a-v-1: FAILED: "), results[0]) self.assertIn(type(failure).__name__, results[0]) self.assertEqual(results[1], "b-v-1: done") def test_a_run_of_an_unknown_case_fails_as_a_line(self): - self.assertRegex(bench.attempted("nope-v-1"), r"^nope-v-1: FAILED: KeyError") + self.assertRegex(bench.attempted("nope-v-1", functools.partial(bench.run, sources=pathlib.Path("/nonexistent"))), r"^nope-v-1: FAILED: KeyError") if __name__ == "__main__": diff --git a/workflow-bench/test_handoff_bench.py b/workflow-bench/test_handoff_bench.py index 49b275f3..718763fe 100644 --- a/workflow-bench/test_handoff_bench.py +++ b/workflow-bench/test_handoff_bench.py @@ -3,7 +3,6 @@ import pathlib import subprocess import tempfile import unittest -import unittest.mock import uuid import advisor_bench @@ -62,17 +61,9 @@ class Orchestration(unittest.TestCase): self.calls, self.heavy = [], [] self.start_result = {"subtype": "error_max_budget_usd", "is_error": True, "total_cost_usd": 1.0} self.compact_result, self.strong_result = {}, {} - real_run = subprocess.run - for patch in ( - unittest.mock.patch.object(advisor_bench, "REPO", self.repo), - unittest.mock.patch.object(handoff_bench, "CASES", {"7": (self.base, merged)}), - unittest.mock.patch.object(handoff_bench, "START_BUDGET", 0.25), - unittest.mock.patch.object(handoff_bench, "CLAUDE_PROJECTS", self.projects), - unittest.mock.patch.object(handoff_bench.uuid, "uuid4", return_value=SESSION), - unittest.mock.patch.object(advisor_bench.subprocess, "run", side_effect=lambda args, **kwargs: self.fake(real_run, args, **kwargs)), - ): - patch.start() - self.addCleanup(patch.stop) + # The prompts the judge was given. + self.judged = [] + self.handoff = handoff_bench.Handoff(advisor_bench.Bench(self.repo, {"7": (self.base, merged)}, self.fake), 0.25, self.projects, lambda: SESSION) self.transcript = self.projects / "slug" / f"{SESSION}.jsonl" def commit(self, files): @@ -83,7 +74,11 @@ class Orchestration(unittest.TestCase): commit(self.repo, "a commit") return advisor_bench.git(self.repo, "rev-parse", "HEAD").strip() - def fake(self, real_run, args, **kwargs): + def fake(self, args, **kwargs): + """Stands in for subprocess.run where the bench runs claude or the tests.""" + if args[0] == "claude" and "--tools" in args: + self.judged.append(args[2]) + return subprocess.CompletedProcess(args, 0, stdout=json.dumps({"result": '{"verdict": "pass"}'}), stderr="") if args[0] == "claude": cwd = pathlib.Path(kwargs["cwd"]) # What the run found as it began: the session's transcript and the files under bin/pkg. @@ -92,7 +87,7 @@ class Orchestration(unittest.TestCase): if "--max-budget-usd" in args: (cwd / "bin/pkg/mod.py").write_text("x = 3\n") # Against the bench rules, the worker commits a part of its change. - real_run(["git", "-C", str(cwd), "add", "bin/pkg/mod.py"], check=True) + subprocess.run(["git", "-C", str(cwd), "add", "bin/pkg/mod.py"], check=True) commit(cwd, "against the rules") (cwd / "bin/pkg/new.py").write_text("n = 1\n") self.transcript.parent.mkdir(parents=True) @@ -113,14 +108,14 @@ class Orchestration(unittest.TestCase): if args[0] == str(advisor_bench.RUN_HEAVY): self.heavy.append(args) return subprocess.CompletedProcess(args, 0, stdout="3 passed\n", stderr="") - return real_run(args, **kwargs) + raise AssertionError(f"the bench ran {args}") def started(self): - handoff_bench.start(self.work, "7-1") + handoff_bench.start(self.handoff, self.work, "7-1") self.calls.clear() def test_start_runs_the_weak_worker_to_its_budget_and_saves_the_tree_and_the_session(self): - self.assertEqual(handoff_bench.start(self.work, "7-1"), "7-1: started") + self.assertEqual(handoff_bench.start(self.handoff, self.work, "7-1"), "7-1: started") (claude, kwargs, _), = self.calls self.assertEqual(kwargs["cwd"], self.work / "7-1") self.assertEqual((kwargs["stdin"], kwargs["stderr"]), (subprocess.DEVNULL, subprocess.STDOUT)) @@ -142,21 +137,21 @@ class Orchestration(unittest.TestCase): def test_start_refuses_a_worker_that_finished_within_its_budget(self): self.start_result = {} with self.assertRaisesRegex(ValueError, "^the weak worker finished within its budget, or its run failed, so there is no handoff to bench$"): - handoff_bench.start(self.work, "7-1") + handoff_bench.start(self.handoff, self.work, "7-1") def test_start_refuses_a_name_that_already_started(self): (self.work / "7-1").mkdir() with self.assertRaisesRegex(ValueError, "already started"): - handoff_bench.start(self.work, "7-1") + handoff_bench.start(self.handoff, self.work, "7-1") def test_start_refuses_a_session_whose_transcript_it_cannot_find(self): self.transcript = self.work / "elsewhere" / f"{SESSION}.jsonl" with self.assertRaisesRegex(ValueError, "found 0"): - handoff_bench.start(self.work, "7-1") + handoff_bench.start(self.handoff, self.work, "7-1") def test_the_resume_arm_resumes_the_weak_workers_session_on_the_strong_rung(self): self.started() - self.assertEqual(handoff_bench.run(self.work, "7-resume-1"), "7-resume-1: ran") + self.assertEqual(handoff_bench.run(self.handoff, self.work, "7-resume-1"), "7-resume-1: ran") (claude, kwargs, _), = self.calls self.assertEqual(kwargs["cwd"], self.work / "7-1") self.assertEqual(claude[:2] + claude[3:], [ @@ -174,7 +169,7 @@ class Orchestration(unittest.TestCase): def test_the_compact_arm_has_the_weak_model_compact_the_session_before_the_strong_one_resumes_it(self): self.started() - handoff_bench.run(self.work, "7-compact-1") + handoff_bench.run(self.handoff, self.work, "7-compact-1") (compact, _, _), (claude, _, found) = self.calls self.assertEqual(compact[:2] + compact[3:], [ "claude", "-p", *handoff_bench.WEAK.flags(), "--resume", str(SESSION), "--setting-sources", "project", @@ -187,7 +182,7 @@ class Orchestration(unittest.TestCase): def test_the_brief_arm_starts_a_fresh_session_with_the_item_and_the_brief(self): self.started() - self.assertEqual(handoff_bench.run(self.work, "7-brief-1"), "7-brief-1: ran") + self.assertEqual(handoff_bench.run(self.handoff, self.work, "7-brief-1"), "7-brief-1: ran") (claude, kwargs, _), = self.calls self.assertEqual(kwargs["cwd"], self.work / "7-1") self.assertEqual(claude[:2] + claude[3:], [ @@ -200,36 +195,36 @@ class Orchestration(unittest.TestCase): def test_each_arm_begins_on_the_tree_and_the_session_that_start_left(self): self.started() for arm in ("resume", "compact", "brief"): - handoff_bench.run(self.work, f"7-{arm}-1") + handoff_bench.run(self.handoff, self.work, f"7-{arm}-1") self.assertEqual([found for _, _, found in self.calls if found[0] != "weak\ncompacted\n"], [("weak\n", ["mod.py", "new.py"])] * 3) self.assertNotIn("done_1.py", (self.work / "7-brief-1.diff").read_text()) def test_run_refuses_an_arm_that_already_ran_or_never_started(self): with self.assertRaisesRegex(ValueError, "start 7-1 first"): - handoff_bench.run(self.work, "7-brief-1") + handoff_bench.run(self.handoff, self.work, "7-brief-1") self.started() - handoff_bench.run(self.work, "7-brief-1") + handoff_bench.run(self.handoff, self.work, "7-brief-1") with self.assertRaisesRegex(ValueError, "already ran"): - handoff_bench.run(self.work, "7-brief-1") + handoff_bench.run(self.handoff, self.work, "7-brief-1") def test_run_refuses_an_unknown_arm(self): self.started() with self.assertRaisesRegex(ValueError, "arm"): - handoff_bench.run(self.work, "7-sonnet-1") + handoff_bench.run(self.handoff, self.work, "7-sonnet-1") def test_run_refuses_an_arm_whose_run_ended_in_an_error_before_it_tests(self): self.started() self.strong_result = {"is_error": True, "result": "overloaded"} - with unittest.mock.patch.object(advisor_bench, "save_change") as save_change: - with self.assertRaisesRegex(ValueError, "ended in an error: overloaded"): - handoff_bench.run(self.work, "7-brief-1") - save_change.assert_not_called() + with self.assertRaisesRegex(ValueError, "ended in an error: overloaded"): + handoff_bench.run(self.handoff, self.work, "7-brief-1") + self.assertEqual(self.heavy, []) + self.assertFalse((self.work / "7-brief-1.diff").exists()) def test_run_refuses_a_compact_arm_whose_compaction_failed_before_the_strong_model_runs(self): self.started() self.compact_result = {"is_error": True, "result": "no conversation to compact"} with self.assertRaisesRegex(ValueError, "^the run ended in an error: no conversation to compact$"): - handoff_bench.run(self.work, "7-compact-1") + handoff_bench.run(self.handoff, self.work, "7-compact-1") self.assertEqual([args[2] for args, _, _ in self.calls], ["/compact"]) self.assertFalse((self.work / "7-compact-1.jsonl").exists()) @@ -240,18 +235,20 @@ class Orchestration(unittest.TestCase): handoff_bench.outcome(self.work, "7-brief-1") def test_main_grades_with_the_handoff_cases_and_prints_the_summary(self): - with unittest.mock.patch("builtins.print") as printed: - handoff_bench.main([str(self.work), "start", "7-1"]) - handoff_bench.main([str(self.work), "run", "7-brief-1"]) - self.assertEqual([call.args[0] for call in printed.call_args_list], ["7-1: started", "7-brief-1: ran"]) - with unittest.mock.patch.object(advisor_bench, "grade", return_value="7-brief-1: pass") as grade, unittest.mock.patch("builtins.print") as printed: - handoff_bench.main([str(self.work), "grade", "7-brief-1"]) - grade.assert_called_once_with(self.work, "7-brief-1", handoff_bench.CASES) - printed.assert_called_once_with("7-brief-1: pass", flush=True) + steps, printed = handoff_bench.steps_of(self.handoff), [] + handoff_bench.main([str(self.work), "start", "7-1"], steps, printed.append) + handoff_bench.main([str(self.work), "run", "7-brief-1"], steps, printed.append) + self.assertEqual(printed, ["7-1: started", "7-brief-1: ran"]) + printed.clear() + handoff_bench.main([str(self.work), "grade", "7-brief-1"], steps, printed.append) + self.assertEqual(printed, ["7-brief-1: pass"]) + # The judge saw the handoff case's merged change, so the grade ran over the handoff's cases. + (prompt,) = self.judged + self.assertIn("-x = 1\n+x = 2\n", prompt) (self.work / "7-brief-1.verdict").write_text(json.dumps({"verdict": "pass"})) - with unittest.mock.patch("builtins.print") as printed: - handoff_bench.main([str(self.work), "summary"]) - self.assertIn("| brief | 1 | 1 | 0 | 0.50 | 12 |", printed.call_args.args[0]) + printed.clear() + handoff_bench.main([str(self.work), "summary"], steps, printed.append) + self.assertIn("| brief | 1 | 1 | 0 | 0.50 | 12 |", printed[-1]) if __name__ == "__main__": -- 2.52.0 From 2edbde807158b125333839b0117dd325e9a48e0f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 12:57:03 +0100 Subject: [PATCH 09/14] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20nothing=20t?= =?UTF-8?q?o=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 2806a8edc9abbaf87239856ab2186c481152665b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 13:44:12 +0100 Subject: [PATCH 10/14] Kill the mutants that survived on the lines the release review changed --- bin/agent_cycle/test_run.py | 7 ++ bin/atlassian/test_jira.py | 7 ++ bin/chunk_driver/project/test_model_choice.py | 56 ++++++++++ bin/chunk_driver/test_chunk_run.py | 28 +++++ bin/chunk_driver/test_cycle_start.py | 102 ++++++++++++++++++ bin/do_epic/main.py | 1 - bin/do_epic/test_main.py | 29 ++++- bin/do_epic/test_scheduler.py | 4 + bin/forge/test_reviews.py | 29 ++++- bin/git_cli/test_git_repo.py | 9 ++ bin/judge_replay/test_judge_replay.py | 47 ++++++++ bin/loop_claude/loop/test_main.py | 45 ++++++++ bin/loop_effects/test_effects.py | 12 +++ bin/plan_store/test_jira_epic.py | 5 + bin/review_replay/test_review_replay.py | 38 +++++++ bin/routing_figures/test_routing_figures.py | 8 ++ bin/rung_replay/test_rung_replay.py | 16 +++ bin/text_files/doubles.py | 2 +- bin/text_files/test_compressed.py | 13 +++ 19 files changed, 452 insertions(+), 6 deletions(-) diff --git a/bin/agent_cycle/test_run.py b/bin/agent_cycle/test_run.py index 64440dc0..99f2320a 100644 --- a/bin/agent_cycle/test_run.py +++ b/bin/agent_cycle/test_run.py @@ -80,6 +80,13 @@ class Cycles(unittest.TestCase): self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) + def test_says_where_it_archived_the_transcript(self): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) + with contextlib.redirect_stderr(io.StringIO()) as said: + run.run_cycle(self.cycle(fake)) + copy, = self.archive.glob("*/*.jsonl") + self.assertIn(f"transcript: {copy}\n", said.getvalue()) + def test_archives_the_cost_the_judges_reply_records_beside_its_verdict(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished", cost=0.25)]) self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working", judged=Judged(cost=0.25))) diff --git a/bin/atlassian/test_jira.py b/bin/atlassian/test_jira.py index 5133e6e7..180ed046 100644 --- a/bin/atlassian/test_jira.py +++ b/bin/atlassian/test_jira.py @@ -24,6 +24,13 @@ class TheHeadOfAnEntry(unittest.TestCase): self.assertEqual(found, Entry("ABC-1", {"issuelinks": [BLOCKED, outward, relates]}, (Link("ABC-2", "9"),), {"L": 2})) self.assertEqual(entry_of(raw(), "plan"), Entry("ABC-1", {"issuelinks": []}, (), {})) + def test_finds_a_blocked_by_link_listed_after_a_link_of_another_kind(self): + outward = {"id": "3", "type": {"inward": "is blocked by"}, "outwardIssue": {"key": "ABC-3"}} + relates = {"id": "4", "type": {"inward": "relates to"}, "inwardIssue": {"key": "ABC-4"}} + for other in (outward, relates): + with self.subTest(other=other): + self.assertEqual(jira.blocked_by_links({"issuelinks": [other, BLOCKED]}), (Link("ABC-2", "9"),)) + def test_an_entry_without_an_issue_key_is_a_failure(self): for wrong in ([], {}, {"key": 7}, {"key": "abc"}): with self.subTest(wrong=wrong): diff --git a/bin/chunk_driver/project/test_model_choice.py b/bin/chunk_driver/project/test_model_choice.py index c7ea56c9..54562e26 100644 --- a/bin/chunk_driver/project/test_model_choice.py +++ b/bin/chunk_driver/project/test_model_choice.py @@ -1,5 +1,7 @@ +import contextlib import dataclasses import fcntl +import io import json import pathlib import sys @@ -24,6 +26,52 @@ class Overridden(unittest.TestCase): self.assertEqual(model_choice.overridden({"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}, "saved"), model_choice.Models("j", "w")) +class ModelsOfARun(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.paths = paths_from(pathlib.Path(temp.name)) + self.paths.models_file.parent.mkdir() + + def test_a_run_that_names_both_models_reads_no_models_file_and_asks_nothing(self): + self.paths.models_file.write_text("not json") + fake = FakeEffects() + env = {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"} + self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, env, LOOP_CLAUDE, fake.effects()), model_choice.Models("j", "w")) + self.assertEqual(fake.calls, []) + + def test_a_run_that_names_one_model_takes_the_other_from_the_models_file(self): + self.paths.models_file.write_text(json.dumps({"proj": "saved"})) + fake = FakeEffects() + self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}, LOOP_CLAUDE, fake.effects()), model_choice.Models("j", "saved")) + self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, {"LOOP_CLAUDE_WORKER_MODEL": "w"}, LOOP_CLAUDE, fake.effects()), model_choice.Models("saved", "w")) + self.assertEqual(fake.calls, []) + + def test_a_run_that_names_one_model_asks_for_the_projects_where_none_is_saved_and_saves_the_pick(self): + fake, said = FakeEffects(inputs=["my-model"]), io.StringIO() + with contextlib.redirect_stderr(said): + models = model_choice.get_or_ask_models("proj", self.paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}, LOOP_CLAUDE, fake.effects()) + self.assertEqual(models, model_choice.Models("j", "my-model")) + self.assertEqual(json.loads(self.paths.models_file.read_text()), {"proj": "my-model"}) + self.assertIn(" proj runs on my-model\n", said.getvalue()) + + def test_off_a_terminal_it_stops_naming_the_driver_to_rerun_and_the_file_to_merge_the_model_into(self): + fake = FakeEffects(on_terminal=False) + stop = model_choice.get_or_ask_models("proj", self.paths, {}, LOOP_CLAUDE, fake.effects()) + assert isinstance(stop, Stop) + self.assertEqual(stop.code, 2) + self.assertIn(f"pick proj's model, or merge {{\"proj\": \"\"}} into {self.paths.models_file}", stop.reason) + self.assertIn(LOOP_CLAUDE, stop.reason) + self.assertFalse(self.paths.models_file.exists()) + + def test_stops_with_exit_1_where_the_models_file_maps_no_projects_to_model_names(self): + for held in ("[]", '{"proj": 5}', '{"proj": ""}'): + with self.subTest(held=held): + self.paths.models_file.write_text(held) + stop = model_choice.get_or_ask_models("proj", self.paths, {}, LOOP_CLAUDE, FakeEffects().effects()) + self.assertEqual(stop, Stop(1, f"could not read {self.paths.models_file}: not an object mapping projects to model names")) + + class SavingAModel(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() @@ -37,6 +85,12 @@ class SavingAModel(unittest.TestCase): self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file)) self.assertEqual(json.loads(self.paths.models_file.read_text()), {"other": "model-x", "proj": "model-b"}) + def test_writes_the_file_for_a_human_to_merge_into_a_project_per_tab_indented_line_in_the_order_of_their_keys(self): + self.paths.models_file.parent.mkdir() + self.paths.models_file.write_text(json.dumps({"zebra": "model-z", "other": "model-x"})) + self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file)) + self.assertEqual(self.paths.models_file.read_text(), '{\n\t"other": "model-x",\n\t"proj": "model-b",\n\t"zebra": "model-z"\n}') + def lock_is_held(self) -> bool: with open(self.lock, "a") as other: try: @@ -91,6 +145,8 @@ class ModelPrompt(unittest.TestCase): def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self): self.assertEqual(model_choice.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5") + self.assertEqual(model_choice.model_picked("1", self.OFFERED), "claude-opus-5-5") + self.assertEqual(model_choice.model_picked("0", self.OFFERED), Failure("pick 1 to 2")) self.assertEqual(model_choice.model_picked("opus", self.OFFERED), "opus") self.assertEqual(model_choice.model_picked("3", []), "3") self.assertEqual(model_choice.model_picked("3", self.OFFERED), Failure("pick 1 to 2")) diff --git a/bin/chunk_driver/test_chunk_run.py b/bin/chunk_driver/test_chunk_run.py index 1479dd10..fd991ba9 100644 --- a/bin/chunk_driver/test_chunk_run.py +++ b/bin/chunk_driver/test_chunk_run.py @@ -20,6 +20,7 @@ from text_files.file_writes import replace_file from model_routing.route import Route from agent_cycle import run from claude_code import session +from agent_cycle.stop import Stop OPUS_PROJECT = ProjectRung(read_ladder(SHIPPED), Rung("claude-opus-5-5", "medium")) @@ -71,6 +72,33 @@ class Steps(unittest.TestCase): stop = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, "a-driver", a_loop(FakeEffects().effects(), session=opened)) self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) + def outcomes_after(self, unfinished_run: int, taken_in: TakenIn) -> tuple[object, str]: + """What closed_cycle answers for a-driver's chunk `Do it.`, after an unfinished verdict that follows unfinished_run others, and the outcomes it archived for a transcript not archived before.""" + with tempfile.TemporaryDirectory() as home: + opened = session.session_named("A proj a-driver", pathlib.Path(home, "projects")) + archive = pathlib.Path(home, "archive") + transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") + transcript.parent.mkdir(parents=True) + transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") + before = Route(self.FABLE_LOW, 3, 3, 4) + with contextlib.redirect_stderr(io.StringIO()): + closed = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence="", unfinished_run=unfinished_run), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=taken_in), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + return closed, "".join(file.read_text() for file in archive.rglob("*") if file.is_file() and file.suffix != ".jsonl") + + def test_a_step_up_archived_first_for_its_transcript_names_the_chunks_task(self): + closed, outcomes_kept = self.outcomes_after(0, TakenIn(highest_likelihood=4)) + self.assertEqual(closed.route.rung, self.FABLE_MEDIUM) + self.assertIn("Do it.\n", outcomes_kept) + + def test_the_sixth_unfinished_verdict_running_stops_for_the_human_naming_the_driver_to_rerun_and_archives_why_with_the_task(self): + reason = "the human is needed to go on with the chunk, but the judge ruled it unfinished 6 cycles running; finish the chunk yourself, or rerun a-driver to give it 6 more cycles" + closed, outcomes_kept = self.outcomes_after(5, TakenIn()) + self.assertEqual(closed, Stop(2, reason)) + self.assertIn("Do it.\n", outcomes_kept) + self.assertIn(f"Stopped: {reason}\n", outcomes_kept) + closed, outcomes_kept = self.outcomes_after(4, TakenIn()) + self.assertEqual((closed.unfinished_run, outcomes_kept), (5, "")) + def test_archives_a_higher_e_plus_i_taken_in_so_a_rerun_keeps_it(self): with tempfile.TemporaryDirectory() as home: opened = session.session_named("A proj a-driver", pathlib.Path(home, "projects")) diff --git a/bin/chunk_driver/test_cycle_start.py b/bin/chunk_driver/test_cycle_start.py index 0358d9f0..182f87f3 100644 --- a/bin/chunk_driver/test_cycle_start.py +++ b/bin/chunk_driver/test_cycle_start.py @@ -1,4 +1,5 @@ import contextlib +import dataclasses import functools import io import json @@ -12,16 +13,23 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from chunk_driver.doubles import a_loop +from project_config.doubles import configured +from agent_cycle.run import Cycle from chunk_driver import cycle_start from failure import Failure from loop_effects.doubles import FakeEffects, NOW, STAMP from git_cli import git_repo +from chunk_driver.project.model_choice import Models from transcript_archive import outcomes, write +from loop_state.paths import paths_from from model_routing.ladder import ProjectRung, Rung from model_routing.ladder_file import read_ladder, SHIPPED from text_files.file_writes import replace_file from model_routing.route import Route, WorkerLine from claude_code import session +from agent_cycle.stop import Stop +from agent_cycle.verdicts import TakenIn +from agent_cycle.worker_prompts import WorkerPrompts OPUS_PROJECT = ProjectRung(read_ladder(SHIPPED), Rung("claude-opus-5-5", "medium")) @@ -49,6 +57,100 @@ class SetupVersion(unittest.TestCase): self.assertEqual(cycle_start.setup_version(pathlib.Path("/r"), fake_git), "unknown: fatal: bad HEAD hint: repair it") +class ProjectRouting(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.home = pathlib.Path(temp.name) + self.paths = paths_from(self.home) + self.checkout = self.home / "code" / "acme" + self.checkout.mkdir(parents=True) + self.config = configured(self, self.checkout, home=self.home) + self.paths.models_file.parent.mkdir(exist_ok=True) + + def routing(self, fake=None, env=None): + return cycle_start.project_routing(a_loop((fake or FakeEffects()).effects(), root=str(self.checkout), paths=self.paths, env=env or {}), "a-driver") + + def test_routes_on_the_projects_saved_model_and_names_the_shipped_ladder_or_the_projects_own_as_its_file(self): + self.paths.models_file.write_text(json.dumps({"acme": "claude-opus-5-5"})) + shipped = read_ladder(SHIPPED) + self.assertEqual(self.routing(), cycle_start.Routing(Models("claude-opus-5-5", "claude-opus-5-5"), shipped, SHIPPED)) + self.assertEqual(self.routing(env={"LOOP_CLAUDE_JUDGE_MODEL": "j"}), cycle_start.Routing(Models("j", "claude-opus-5-5"), shipped, SHIPPED)) + own = self.config / "routing-ladder.json" + own.write_text('[{"model": "claude-fable-5-2", "effort": "low"}]', encoding="utf-8") + routing = self.routing() + assert isinstance(routing, cycle_start.Routing) + self.assertEqual((routing.ladder_file, [str(rung) for rung in routing.ladder.rungs]), (own, ["claude-fable-5-2 at low effort"])) + + def test_stops_with_exit_1_naming_the_ladder_file_that_cannot_be_read(self): + self.paths.models_file.write_text(json.dumps({"acme": "claude-opus-5-5"})) + own = self.config / "routing-ladder.json" + own.write_text("not json", encoding="utf-8") + stop = self.routing() + assert isinstance(stop, Stop) + self.assertEqual(stop.code, 1) + self.assertIn(str(own), stop.reason) + + def test_stops_with_exit_1_naming_the_config_that_cannot_be_read(self): + self.paths.models_file.write_text(json.dumps({"acme": "claude-opus-5-5"})) + (self.config / "config.toml").write_text("not toml", encoding="utf-8") + stop = self.routing() + assert isinstance(stop, Stop) + self.assertEqual(stop.code, 1) + self.assertIn(str(self.config / "config.toml"), stop.reason) + + def test_asks_for_the_model_where_none_is_saved_and_off_a_terminal_stops_naming_the_driver_to_rerun(self): + stop = self.routing(FakeEffects(on_terminal=False)) + assert isinstance(stop, Stop) + self.assertEqual(stop.code, 2) + self.assertIn("pick acme's model", stop.reason) + self.assertIn("rerun a-driver on a terminal", stop.reason) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(self.routing(FakeEffects(inputs=["claude-opus-5-5"])), cycle_start.Routing(Models("claude-opus-5-5", "claude-opus-5-5"), read_ladder(SHIPPED), SHIPPED)) + + +class CycleStart(unittest.TestCase): + ROUTING = cycle_start.Routing(Models("judge-model", "claude-opus-5-5"), OPUS_PROJECT.ladder, SHIPPED) + + def test_announces_the_route_the_chunks_run_holds_and_else_the_one_its_archive_last_names(self): + def never(): + raise AssertionError("not asked") + + kept = Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5) + with tempfile.TemporaryDirectory() as home: + opened = session.session_named("A proj a-driver", pathlib.Path(home, "projects")) + loop = a_loop(FakeEffects().effects(), session=opened) + archive = pathlib.Path(home, "archive") + with contextlib.redirect_stdout(io.StringIO()) as said: + self.assertEqual(cycle_start.announced_route(4, kept, self.ROUTING, archive, never, loop), kept) + self.assertEqual(said.getvalue(), f"\n{STAMP} === cycle 4, worker on claude-opus-5-5 at xhigh effort ===\n") + transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") + transcript.parent.mkdir(parents=True) + transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(kept.worker_line(), "working", "j", ""), NOW, replace=replace_file)) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(cycle_start.announced_route(1, None, self.ROUTING, archive, never, loop), kept) + + def test_builds_the_cycle_from_the_loop_the_routing_and_what_the_entry_point_knows(self): + asked = [] + + def git(*args, cwd=None): + asked.append(cwd) + return "v0.1.0\n" if args[0] == "describe" else "abc\n" + + effects = dataclasses.replace(FakeEffects().effects(), git=git) + loop, route, archive = a_loop(effects), Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), pathlib.Path("/t/r") + prompts = WorkerPrompts("a-driver", lambda *args: "fresh", lambda *args: "resumed", lambda *args: "", "the sources", "the destinations", "the records named") + def taken_in(entries): + return TakenIn() + + cycle = cycle_start.cycle_of(loop, self.ROUTING, route, archive, task="the task", facts="the facts", premises="the premises", records="the records", unfinished_evidence="the evidence", prompts=prompts, taken_in=taken_in) + self.assertEqual(cycle, Cycle(config="v0.1.0 (abc)", effects=effects, facts="the facts", judge=Rung("judge-model"), premises="the premises", project=OPUS_PROJECT, project_archive=archive, records="the records", root="/r", + route=route, session=loop.session, task="the task", prompts=prompts, taken_in=taken_in, unfinished_evidence="the evidence", window=loop.window)) + self.assertEqual(asked, ["/h/.claude", "/h/.claude"]) + + class Routes(unittest.TestCase): OPUS = Rung("claude-opus-5-5", "medium") SONNET = Rung("claude-sonnet-5-5", "high") diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index f7f21ef9..977e5f07 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -268,7 +268,6 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: if isinstance(cycle, EpicReopened): say(f"the epic {epic.key} holds an open issue again, so its finishing chunk ends until none is open", epic.effects, stdout=True) return handed_on(key, epic) - run = dataclasses.replace(run, task=cycle.task) concluded = run_cycle(cycle) if isinstance(concluded, Stop): return concluded diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 76a1f4df..346e6737 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -193,7 +193,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest): self.assertEqual(code, 1) self.assertRegex(err, f"could not make the chunk's folder {self.home}/.local/state/do-epic/ABC-12: \\w") - def cycle(self, env: dict[str, str] | None = None) -> main.Cycle: + def cycle(self, env: dict[str, str] | None = None, run: ChunkRun = ChunkRun(1)) -> main.Cycle: fake = FakeEffects(git=[Failure("no git"), Failure("no git")]) paths = paths_from(self.home) epic = self.epic_run(fake, env) @@ -203,7 +203,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest): self.assertIsNone(main.folder_made(root)) loop = Loop(root=root, session=main.session_named("A ABC-12 do-epic ABC-21", paths.claude_code_transcripts), window=tmux.Window("epic-ABC-12", "ABC-21", "%1"), paths=paths, env=env or {}, launcher=pathlib.Path("/b/do-epic"), effects=fake.effects()) with contextlib.redirect_stdout(io.StringIO()): - found = main.next_cycle(ChunkRun(1), loop, repo is not None, epic) + found = main.next_cycle(run, loop, repo is not None, epic) assert isinstance(found, main.Cycle), found return found @@ -216,6 +216,16 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest): self.assertEqual(self.cycle({"LOOP_CLAUDE_WORKER_MODEL": "off-the-ladder"}).route, Route(Rung("off-the-ladder"))) self.assertEqual(self.cycle({"LOOP_CLAUDE_JUDGE_MODEL": "claude-fable-5-2"}).judge.model, "claude-fable-5-2") + def test_keeps_the_route_and_the_evidence_its_run_holds(self) -> None: + kept = Route(Rung("claude-opus-5-5", "xhigh"), 21, 3, 5) + cycle = self.cycle(run=ChunkRun(2, unfinished_evidence="the evidence", route=kept)) + self.assertEqual((cycle.route, cycle.unfinished_evidence), (kept, "the evidence")) + + def test_a_chunk_that_was_not_parked_starts_on_the_drivers_own_prompts_with_no_facts(self) -> None: + cycle = self.cycle() + self.assertIs(cycle.prompts, chunk_prompt.WORKER) + self.assertEqual(cycle.facts, "") + def test_works_in_the_epics_folder_and_archives_apart_from_loop_claude(self) -> None: cycle = self.cycle() self.assertEqual((cycle.root, cycle.project_archive, cycle.records), (str(self.home / ".local/state/do-epic/ABC-12"), self.home / ".claude/do-epic-transcripts/ABC-12", "")) @@ -392,6 +402,14 @@ class AChunksRun(DoEpicTest): self.assertEqual(code, 2, out) self.assertIn("the judge ruled it unfinished 6 cycles running; finish the chunk yourself, or rerun do-epic to give it 6 more cycles", err + out) + def test_every_archived_transcript_opens_with_the_chunks_task_through_step_ups_and_the_stop_for_the_human(self) -> None: + fake = FakeEffects(streams=[self.worker()] * 6, claude=[judged("unfinished", escalation="working")] + [judged("unfinished")] * 5, git=UNREAD) + code, out, _ = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS) + self.assertEqual(code, 2, out) + outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".claude/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")] + self.assertTrue(any("Z Stepped up\n" in text for text in outcomes) and any("Z Stopped: " in text for text in outcomes), outcomes) + self.assertEqual([text for text in outcomes if not text.startswith("Task: Work the Jira issue ABC-21 of the epic ABC-12 as one chunk")], []) + def test_a_finished_chunk_moves_its_issue_to_done_before_the_chunk_it_blocks_starts(self) -> None: store = MemoryEpic("ABC-12", [self.issues[0], self.issues[1], issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))]) self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] @@ -507,6 +525,13 @@ class AChunksRun(DoEpicTest): self.assertEqual(code, 0, err) self.assertIn("=== cycle 1, worker on claude-fable-5-2 at low effort ===\n", out) + def test_a_chunk_in_a_repo_without_a_saved_model_stops_off_a_terminal_naming_do_epic_as_what_to_rerun(self) -> None: + self.repo_chunk() + code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], FakeEffects(git=UNREAD, on_terminal=False), {"TMUX_PANE": "%1"}) + self.assertEqual((code, out), (2, "")) + self.assertIn("pick api's model", err) + self.assertIn("rerun do-epic on a terminal", err) + def test_a_chunk_in_a_repo_stops_where_the_repos_ladder_or_records_cannot_be_read(self) -> None: folder = self.repo_chunk() (folder / "routing-ladder.json").write_text("[", encoding="utf-8") diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index c255053b..cd853477 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -296,6 +296,10 @@ class StartingAnEpicsChunks(unittest.TestCase): self.assertTrue((self.home / ".local/state/loop-claude/api/starting").is_file()) self.assertTrue((self.home / ".local/state/do-epic/ABC-12/starting").is_file()) + def test_a_parked_chunk_resumes_under_the_starting_lock_of_its_repos_checkout(self) -> None: + self.assertIsNone(self.resumed(self.epic(1, api=1), Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, "")))) + self.assertEqual([lock.parent.name for lock in (self.home / ".local/state/loop-claude").glob("*/starting")], ["api"]) + def test_the_waits_keep_the_trackers_rank_order(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20", True, str(self.home / "code/api")), ("epic-ABC-12", "ABC-22", False, str(self.home / "code/api"))) found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21"), issue("ABC-22", "repo:api")], run, own="ABC-22") diff --git a/bin/forge/test_reviews.py b/bin/forge/test_reviews.py index dc618052..6f1b6671 100644 --- a/bin/forge/test_reviews.py +++ b/bin/forge/test_reviews.py @@ -34,8 +34,14 @@ class ThePullRequestAsViewed(unittest.TestCase): printed = json.dumps(PULL | {"reviews": [ASKED, pending], "comments": [{"author": {"login": "me"}, "createdAt": "2026-11-02T11:00:00Z"}, {"author": {"login": "rev"}, "createdAt": "2026-11-02T12:00:00Z"}]}) self.assertEqual(reviews.pull_view(printed), PullView(False, CHANGES_REQUESTED, (Review("rev", CHANGES_REQUESTED, "2026-11-02T10:00:00Z", "abc"), Review("me", "PENDING", "", "")), ("", "2026-11-02T11:00:00Z"))) + def test_keeps_each_comment_of_the_authors_whoever_commented_before_it(self): + printed = json.dumps(PULL | {"comments": [{"author": {"login": "rev"}, "createdAt": "2026-11-02T12:00:00Z"}, {"author": {"login": "me"}, "createdAt": "2026-11-02T13:00:00Z"}]}) + viewed = reviews.pull_view(printed) + assert isinstance(viewed, PullView) + self.assertEqual(viewed.said, ("2026-11-02T13:00:00Z",)) + def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self): - unshaped = ("not json", "[]", json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps(PULL | {"comments": [{"author": {"login": 7}, "createdAt": "2026-11-02T11:00:00Z"}]}), json.dumps(PULL | {"comments": [{"author": {"login": PULL["author"]["login"]}, "createdAt": None}]}), json.dumps(PULL | {"reviews": [{key: value for key, value in ASKED.items() if key != "submittedAt"}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"})) + unshaped = ("not json", "x" * 300, "[]", json.dumps(PULL | {"reviews": [ASKED | {"author": {"login": 7}}]}), json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps(PULL | {"comments": [{"author": {"login": 7}, "createdAt": "2026-11-02T11:00:00Z"}]}), json.dumps(PULL | {"comments": [{"author": {"login": PULL["author"]["login"]}, "createdAt": None}]}), json.dumps(PULL | {"reviews": [{key: value for key, value in ASKED.items() if key != "submittedAt"}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"})) for printed in unshaped: with self.subTest(printed=printed): self.assertEqual(reviews.pull_view(printed), Failure(f"gh pr view printed no review decision: {printed[:200]}")) @@ -51,6 +57,7 @@ class WhetherTheWorkerAnswered(unittest.TestCase): self.assertTrue(reviews.answered(self.view(), "def")) self.assertTrue(reviews.answered(self.view(said=("2026-11-02T10:30:00Z",)), "abc")) self.assertFalse(reviews.answered(self.view(said=("2026-11-02T09:00:00Z", "")), "abc")) + self.assertFalse(reviews.answered(self.view(said=("2026-11-02T10:00:00Z",)), "abc"), "a word at the review's own instant is not after it") self.assertTrue(reviews.answered(self.view(Review("me", "COMMENTED", "2026-11-02T10:30:00Z", "")), "abc")) self.assertFalse(reviews.answered(PullView(False, "", (), ()), "abc")) @@ -78,7 +85,7 @@ class TheThreadsThatWait(unittest.TestCase): self.assertEqual(reviews.waiting_threads("7", lambda args: printed), ["a.py", "b.py"]) def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self): - for printed in ("not json", "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": {"login": 7}}]}}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"path": "a.py", "comments": {"nodes": []}}]}}}}})): + for printed in ("not json", "x" * 300, "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": 7}, "reviewThreads": {"nodes": []}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": {"login": 7}}]}}]}}}}}), json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"path": "a.py", "comments": {"nodes": []}}]}}}}})): with self.subTest(printed=printed): self.assertEqual(reviews.waiting_threads("7", lambda args: printed), Failure(f"gh api graphql printed no review threads: {printed[:200]}")) @@ -96,6 +103,24 @@ class TheDecisionOnGitea(unittest.TestCase): self.assertEqual(self.decision({"title": "Fix it"}), "") self.assertEqual(self.decision({"title": 7}), Failure("tea api printed no title of pull request 7: {'title': 7}")) self.assertEqual(self.decision([]), Failure("tea api printed no title of pull request 7: []")) + self.assertEqual(self.decision("y" * 300), Failure(f"tea api printed no title of pull request 7: {'y' * 200}")) + + +class TheDecisionOnGitHub(unittest.TestCase): + def test_reads_the_review_decision_and_empty_where_no_review_is_asked_for(self): + asked = [] + self.assertEqual(reviews.github_decision("7", lambda args: asked.append(args) or '{"reviewDecision": "APPROVED"}'), "APPROVED") + self.assertEqual(asked, [["gh", "pr", "view", "7", "--json", "reviewDecision"]]) + self.assertEqual(reviews.github_decision("7", printing({"reviewDecision": None})), "") + self.assertEqual(reviews.github_decision("7", printing({"reviewDecision": ""})), "") + + def test_an_answer_without_a_decision_is_a_failure_naming_the_first_200_characters_gh_printed(self): + for printed in ("not json", "{}", "[]", " " + "x" * 300): + with self.subTest(printed=printed): + self.assertEqual(reviews.github_decision("7", lambda args: printed), Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}")) + + def test_a_command_that_fails_is_that_failure(self): + self.assertEqual(reviews.github_decision("7", lambda args: Failure("gh cannot start")), Failure("gh cannot start")) if __name__ == "__main__": diff --git a/bin/git_cli/test_git_repo.py b/bin/git_cli/test_git_repo.py index 5ad51a55..9f58fda4 100644 --- a/bin/git_cli/test_git_repo.py +++ b/bin/git_cli/test_git_repo.py @@ -1,4 +1,5 @@ import contextlib +import os import pathlib import subprocess import sys @@ -35,6 +36,14 @@ class Git(unittest.TestCase): self.assertTrue(done.reason.startswith("git log could not start: "), done.reason) self.assertIn("/code/gone", done.reason) + def test_runs_git_in_the_environment_given_and_only_guarded_stops_the_fetch_of_missing_objects(self): + shown = ("-c", "alias.shown=!echo \"$SHOWN_TO_GIT/$GIT_NO_LAZY_FETCH\"", "shown") + given = {**{name: value for name, value in os.environ.items() if name != "GIT_NO_LAZY_FETCH"}, "SHOWN_TO_GIT": "given"} + self.assertEqual(git_repo.git(*shown, env=given), "given/\n") + self.assertEqual(git_repo.git(*shown, env=given, guarded=True), "given/1\n") + self.assertNotIn("SHOWN_TO_GIT", os.environ) + self.assertEqual(git_repo.git(*shown, guarded=True), "/1\n") + class Guarded(unittest.TestCase): """A checkout whose own config may name a program for git to run.""" diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 3560ed2e..67eca5ed 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -5,6 +5,7 @@ import pathlib import subprocess import sys import tempfile +import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -134,11 +135,13 @@ class Main(unittest.TestCase): (chunk / f"t{n}.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:0{n}Z {verdict}\n\nEvidence:\n> e\n") self.calls = [] self.prompts = [] + self.schemas = [] def run_main(self, argv, reply): def claude(args, cwd, prompt): self.calls.append((args[args.index("--model") + 1], args[args.index("--effort") + 1], cwd)) self.prompts.append(prompt) + self.schemas.append(args[args.index("--json-schema") + 1]) 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), "") @@ -224,6 +227,48 @@ class Main(unittest.TestCase): runs = [json.loads(path.read_text(encoding="utf-8").splitlines()[0]) for path in folder.glob("*.jsonl")] self.assertEqual({run["prompt"] for run in runs}, set(self.prompts)) + def test_says_where_it_could_not_keep_a_run_and_still_prints_the_report(self): + replays = self.home / ".claude" / "loop-claude-transcripts" / "replays" + replays.write_text("") + code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) + self.assertEqual(code, 0, err) + self.assertIn(f"could not keep the run in {replays}/judge-replay-claude-opus-5-5-20260921T141320Z: ", err) + self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out) + + def test_says_how_many_verdicts_it_replays_on_each_rung(self): + code, _, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) + self.assertEqual(code, 0, err) + self.assertEqual(err.splitlines()[:2], ["replaying 2 verdicts on claude-opus-5-5 at xhigh effort", "replaying 2 verdicts on claude-fable-5-2 at low effort"]) + + def test_replays_four_verdicts_at_once(self): + chunk = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" + for n in range(2, 8): + (chunk / f"t{n}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": f"said {FINISHED} {n}"}]}}) + "\n") + (chunk / f"t{n}.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:0{n}Z {FINISHED}\n\nEvidence:\n> e\n") + running, most = [], [] + + def reply(rung, interrupted): + running.append(rung) + most.append(len(running)) + time.sleep(0.05) + running.remove(rung) + return self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}") + + code, _, err = self.run_main(["claude-opus-5-5"], reply) + self.assertEqual(code, 0, err) + self.assertIn("replaying 8 verdicts on ", err) + self.assertEqual(max(most), 4) + + def test_the_prompt_and_the_reply_schema_of_a_rebuilt_run_name_loop_claude_and_the_records_and_show_the_transcript_once(self): + code, _, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) + self.assertEqual(code, 0, err) + for prompt, schema in zip(self.prompts, self.schemas, strict=True): + self.assertIn("\n\nThe records: the project's working rules and decisions, then the human's rules for every project:\n", prompt) + self.assertIn("what loop-claude told it on [loop] lines, latest last:\n", prompt) + self.assertEqual(prompt.count("said Verdict: "), 1) + self.assertIn("loop-claude", schema) + self.assertNotIn("None", schema) + def test_hands_the_judge_the_prompt_the_archive_kept_and_rebuilds_the_prompt_of_a_verdict_with_none(self): kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" prompt = "From the goals file, OLD premises\n\nThe records: none\n\nThe task the worker was given:\nDo it.\n\nWhat the worker did and said, what the human typed on [human] lines and what loop-claude told it on [loop] lines, latest last:\nsaid Verdict: finished\n\nOLD rules" @@ -235,6 +280,8 @@ class Main(unittest.TestCase): self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out) # The first replay, on the finished verdict, reads the archived prompt; the second, on the interrupt, is rebuilt from the records of today. self.assertEqual(self.prompts[0], prompt) + # The reply's schema names loop-claude to the judge of either prompt. + self.assertEqual([schema for schema in self.schemas if "loop-claude" not in schema or "None" in schema], []) self.assertEqual(self.calls[0][2], self.calls[1][2]) self.assertTrue(self.calls[0][2].endswith("/code/proj")) self.assertIn("The task the worker was given:\nDo it.", self.prompts[1]) diff --git a/bin/loop_claude/loop/test_main.py b/bin/loop_claude/loop/test_main.py index 8e955dda..6dc90446 100644 --- a/bin/loop_claude/loop/test_main.py +++ b/bin/loop_claude/loop/test_main.py @@ -177,6 +177,51 @@ class WindowStarts(unittest.TestCase): 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 window_loop(self, cycles, env, **doubles): + """run_loop's stop for item-3's window loop, and each step it took with what it handed that step. Each step answers as its double in `doubles` does, else as a cycle without a stop: next_cycle answers the next of `cycles`, run_cycle an unfinished verdict, and closed_cycle the run with one more unfinished verdict.""" + fake, calls, cycles = FakeEffects(git=["/r\n"]), [], list(cycles) + effects, launcher, home = fake.effects(), pathlib.Path("/b/loop-claude"), paths.paths_from(self.HOME) + self.unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished)) + answers = {"fingerprint": lambda *args: "print-1", "exec_if_edited": lambda *args: None, "next_cycle": lambda *args: cycles.pop(0), "run_cycle": lambda *args: self.unfinished, + "closed_cycle": lambda run, *args: dataclasses.replace(run, unfinished_run=run.unfinished_run + 1), "check_routing": lambda *args: None, **doubles} + + def step(name): + return lambda *args: calls.append((name, *args)) or answers[name](*args) + + stop = main.run_loop(["--chunk", "item-3", "do it"], env, home, launcher, CWD, effects, steps(lambda *args: self.fail(args), **{name: step(name) for name in answers})) + self.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=home, env=env, launcher=launcher, effects=effects) + return stop, calls + + def test_a_window_loop_hands_each_step_of_a_cycle_what_the_steps_before_it_made(self): + env = {"TMUX_PANE": "%4", "LOOP_CLAUDE_TRANSCRIPTS": "/t"} + on_ladder = unittest.mock.Mock(project=OPUS_PROJECT, project_archive=pathlib.Path("/t/r")) + off_ladder = unittest.mock.Mock(project=None, project_archive=pathlib.Path("/t/r"), route=unittest.mock.Mock(rung=Rung("my-model"))) + stop, calls = self.window_loop([on_ladder, off_ladder, Stop(2, "the human is needed")], env) + self.assertEqual(stop, Stop(2, "the human is needed")) + before, first, second, third = (main.LoopRun(number, "/r", "do it", "", unfinished_run=max(number - 1, 0), chunk="item-3") for number in range(4)) + self.assertEqual(calls, [ + ("fingerprint", pathlib.Path("/b/loop-claude")), + ("exec_if_edited", self.loop, "print-1", before), + ("next_cycle", first, self.loop), + ("run_cycle", on_ladder), + ("closed_cycle", first, OPUS_PROJECT, self.unfinished, pathlib.Path("/t/r"), "loop-claude", self.loop), + ("check_routing", pathlib.Path("/t"), Rung("claude-opus-5-5", "medium"), self.loop), + ("exec_if_edited", self.loop, "print-1", dataclasses.replace(first, unfinished_run=1)), + ("next_cycle", second, self.loop), + ("run_cycle", off_ladder), + ("closed_cycle", second, None, self.unfinished, pathlib.Path("/t/r"), "loop-claude", self.loop), + ("check_routing", pathlib.Path("/t"), Rung("my-model"), self.loop), + ("exec_if_edited", self.loop, "print-1", dataclasses.replace(second, unfinished_run=2)), + ("next_cycle", third, self.loop), + ]) + + def test_a_window_loop_stops_with_the_stop_of_the_step_that_made_one(self): + cycle = unittest.mock.Mock(project=OPUS_PROJECT, project_archive=pathlib.Path("/t/r")) + for name, taken in (("exec_if_edited", 2), ("run_cycle", 4), ("closed_cycle", 5), ("check_routing", 6)): + with self.subTest(step=name): + stop, calls = self.window_loop([cycle], {"TMUX_PANE": "%4"}, **{name: lambda *args: Stop(1, f"{name} stopped")}) + self.assertEqual((stop, len(calls), calls[-1][0]), (Stop(1, f"{name} stopped"), taken, name)) + 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)) diff --git a/bin/loop_effects/test_effects.py b/bin/loop_effects/test_effects.py index b788d399..de024575 100644 --- a/bin/loop_effects/test_effects.py +++ b/bin/loop_effects/test_effects.py @@ -119,6 +119,18 @@ class TmuxEffect(unittest.TestCase): pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nsys.stdout.buffer.write(b'caf\\xe9')\n") self.assertEqual(effects.tmux(["list-windows"]).stdout, "caf\ufffd") + def test_runs_tmux_without_this_processs_input(self): + with tempfile.TemporaryDirectory() as folder: + effects = self.fake_tmux(folder) + pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nprint(repr(sys.stdin.read()))\n") + pathlib.Path(folder, "typed").write_text("what the human types\n") + kept = os.dup(0) + self.addCleanup(os.close, kept) + self.addCleanup(os.dup2, kept, 0) + with open(pathlib.Path(folder, "typed")) as typed: + os.dup2(typed.fileno(), 0) + self.assertEqual(effects.tmux(["list-windows"]).stdout, "''\n") + def test_reads_a_tmux_that_cannot_start_as_exit_127(self): with tempfile.TemporaryDirectory() as folder: done = system_effects(pathlib.Path.home(), os.environ | {"PATH": folder}).tmux(["-V"]) diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 46b6bbc4..6f1e3b5b 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -180,6 +180,11 @@ class JiraPlan(unittest.TestCase): self.assertIsInstance(failure, Failure) self.assertTrue(failure.reason.startswith("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: "), failure) # type: ignore[union-attr] + def test_an_issue_that_lacks_a_field_fails_the_read_naming_the_field(self) -> None: + good = issue("ABC-1") + lacking = good | {"fields": {name: value for name, value in good["fields"].items() if name != "fixVersions"}} + self.assertEqual(self.read(lacking), Failure("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: KeyError('fixVersions')")) # type: ignore[arg-type] + def test_converts_every_description_in_one_run_and_none_for_an_issue_without_one(self): found = self.items(issue("ABC-1", description=adf("One.")), issue("ABC-2"), issue("ABC-3", description=adf("Three.")), issue("ABC-4", description=adf("Four."))) self.assertEqual([item.detail for item in found], ["One.", "", "Three.", "Four."]) diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index feb9c22c..bca01233 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -9,6 +9,7 @@ import shutil import subprocess import sys import tempfile +import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -284,6 +285,43 @@ class Main(unittest.TestCase): self.assertEqual({run["prompt"] for run in runs if "--agent" in run["args"]}, {prompt for *_, prompt, _ in self.reviews}) self.assertTrue(any("--json-schema" in run["args"] for run in runs)) + def test_says_where_it_could_not_keep_a_run_and_still_prints_the_report(self): + (self.archive / "replays").write_text("") + code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}) + self.assertEqual(code, 0, err) + self.assertIn(f"could not keep the run in {self.archive}/replays/review-replay-stability-claude-opus-5-5-20260921T141320Z: ", err) + self.assertTrue(out.startswith("Replayed 1 stability rounds"), out) + + def test_makes_each_clone_in_the_scratch_folder_under_a_name_that_says_whose_it_is(self): + scratch = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) + self.limits["scratch"] = scratch + for argv, replays in ((["stability", "claude-opus-5-5"], 4), (["stability", "claude-opus-5-5", "--omit-claude-md"], 4)): + with self.subTest(argv=argv): + self.reviews.clear() + code, _, err = self.run_main(argv, lambda rung: {"found": [0, 1]}) + self.assertEqual(code, 0, err) + clones = [pathlib.Path(cwd) for *_, cwd in self.reviews] + self.assertEqual(([clone.parent for clone in clones], [clone.name[:14] for clone in clones]), ([scratch] * replays, ["review-replay-"] * replays)) + self.assertEqual(list(scratch.iterdir()), [], "each clone is removed") + + def test_replays_no_more_rounds_at_once_than_asked_on_any_rung(self): + self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z") + self.limits["at_once"] = 1 + for argv, rungs in ((["stability", "claude-opus-5-5"], {REFERENCE, Rung("claude-opus-5-5", "low"), Rung("claude-sonnet-5-5", "high")}), (["stability", "claude-opus-5-5", "--omit-claude-md"], {REFERENCE})): + with self.subTest(argv=argv): + running, most = [], {} + + def review(rung): + running.append(rung) + most[rung] = max(most.get(rung, 0), len(running)) + time.sleep(0.05) + running.remove(rung) + return {"type": "result", "result": f"review on {rung.model} {rung.effort}"} + + code, _, err = self.run_main(argv, lambda rung: {"found": [0, 1]}, review=review) + self.assertEqual(code, 0, err) + self.assertEqual(most, dict.fromkeys(rungs, 1)) + def test_without_claude_md_replays_each_round_three_times_with_it_and_once_without_on_the_project_rung(self): finds = iter(([0, 1], [0], [0, 1], [1])) code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)}) diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index badf3b78..aa6efc96 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -490,6 +490,14 @@ class Archive(unittest.TestCase): self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T02:00:00Z", replace_file)) self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset({a}))) + def test_adds_a_raised_call_after_the_files_text_less_only_the_newlines_that_end_it(self): + call = Call("reports", ("Explore",)) + for ending in ("what the human wrote XX", "a line that breaks in markdown ", "a line that ends in a tab\t"): + with self.subTest(ending=ending): + (self.root / state.RAISED).write_text(f"# Routing calls raised\n\n{ending}\n\n\n") + self.assertIsNone(state.mark_raised(self.root, [call], "2026-10-15T00:00:00Z", replace_file)) + self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n{ending}\n\n- 2026-10-15T00:00:00Z {call.sentence()}\n") + def test_fails_when_it_cannot_keep_the_state(self): assert_not_root(self) self.root.chmod(0o555) diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index 21dd083b..f4b276f1 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -5,6 +5,7 @@ import pathlib import subprocess import sys import tempfile +import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -60,6 +61,21 @@ class Replayed(unittest.TestCase): self.assertNotIn(("b", high), asked) self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": set()}}, [high]), (Replay([set()], [], None, []), [("a", REFERENCE)])) + def test_says_what_it_replays_on_each_rung_and_replays_no_more_cases_at_once_than_asked(self): + high = Rung("claude-fable-5-2", "low") + said, running, most = [], [], {} + + def replay_one(case, rung): + running.append(case) + most[rung] = max(most.get(rung, 0), len(running)) + time.sleep(0.02) + running.remove(case) + return {0} + + replayed(["a", "b", "c"], REFERENCE, [MIDDLE], replay_one, lambda _, reply: sorted(reply), "verdicts", said.append, 1, [high]) + self.assertEqual(said, [f"replaying 3 verdicts on {REFERENCE}", f"replaying 3 verdicts on {high}", f"replaying 3 verdicts on {MIDDLE}"]) + self.assertEqual(most, {REFERENCE: 1, high: 1, MIDDLE: 1}) + def test_stops_at_a_usage_limit(self): limit = Limited(None, "limit") self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": {0}}, MIDDLE: {"a": {0}}, CHEAP: limit}, [CHEAP])[0], limit) diff --git a/bin/text_files/doubles.py b/bin/text_files/doubles.py index c8563b8b..1c6850e2 100644 --- a/bin/text_files/doubles.py +++ b/bin/text_files/doubles.py @@ -1,4 +1,4 @@ -"""What the suites that compress a file share: compress, bound to what really compresses, writes and flushes.""" +"""What the suites that compress a file share: compress with gzip.compress, replace_file and os.fsync bound.""" import functools import gzip import os diff --git a/bin/text_files/test_compressed.py b/bin/text_files/test_compressed.py index 479866f5..e1acd86f 100644 --- a/bin/text_files/test_compressed.py +++ b/bin/text_files/test_compressed.py @@ -26,6 +26,19 @@ class Compress(unittest.TestCase): self.assertEqual(packed.read_bytes(), gzip.compress(b'{"a": 1}\n', mtime=0)) self.assertEqual(packed.stat().st_mtime, 2000) + def test_asks_for_a_gzip_whose_header_holds_no_time_whatever_the_packer_would_write_unasked(self): + with tempfile.TemporaryDirectory() as root: + plain = pathlib.Path(root, "t.jsonl") + plain.write_bytes(b"a\n") + asked = [] + + def pack(data, **kwargs): + asked.append(kwargs) + return gzip.compress(data, **kwargs) + + self.assertIsNone(compress(plain, pack=pack)) + self.assertEqual(asked, [{"mtime": 0}]) + def test_syncs_the_gzip_and_its_folder_before_removing_the_file(self): with tempfile.TemporaryDirectory() as root: plain = pathlib.Path(root, "t.jsonl") -- 2.52.0 From aafe75e16f7a54c68d182f72cbc0a312fd283dda Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 13:44:20 +0100 Subject: [PATCH 11/14] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=2011=20=F0=9F=9F=A1=20(0=20misread);=20loop-claud?= =?UTF-8?q?e=20and=20do-epic=20are=20entry=20points=20everywhere,=20and=20?= =?UTF-8?q?each=20new=20sentence=20holds=20one=20idea?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 13 ++++++------- bin/adf_codec/convert.py | 6 +++--- bin/atlassian/jira.py | 6 +++--- bin/chunk_driver/project/model_choice.py | 6 +++--- bin/forge/reviews.py | 6 +++--- bin/notifier/mattermost.py | 2 +- bin/notifier/slack.py | 2 +- bin/todo_item/main.py | 2 +- docs/decisions.md | 8 ++++---- todo.md | 2 +- 10 files changed, 26 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 3a41898a..250d1d18 100644 --- a/README.md +++ b/README.md @@ -219,22 +219,21 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a ### Packages under `bin/` -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No test swaps a global with `mock.patch`: the code under test takes each effect as an argument, and the test hands it a double, which `repo_checks/test_no_patched_globals.py` checks in every Python file of the repo, `workflow-bench/`'s included. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `agent_cycle/`, `atlassian/`, `branch_chunks/`, `chunk_driver/`, `claude_code/`, `command_lines/`, `forge/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, and a package's `doubles.py` holds the test doubles that other packages' tests use, so no module imports a `test_*` module of another package; `repo_checks/test_package_cycles.py` checks both. No Python file of the repo, `workflow-bench/`'s included, uses `mock.patch`, which `repo_checks/test_no_patched_globals.py` checks. - `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. -- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The tool that drives the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. `doubles.py` holds the doubles its tests share with `chunk_driver`'s. -- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the head of each entry it answers, an issue's links and the transition that finishes it, for `plan_store` and `do_epic`. +- `agent_cycle/` runs one cycle (`run.py`): a headless claude worker, then the judge of its transcript. It also holds the interrupt, the tmux window and the routing of the worker's rung. The entry point that runs the cycles supplies the prompts and file names of its own workflow (`worker_prompts.py`), and reads which items a worker took in. `loop_claude` and `do_epic` drive it; `agent_cycle` doesn't import either. +- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages. `jira.py` holds what every reader of Jira shares: a search read page by page, the key, fields, links and property of each issue it finds, checked for their shape, and the transition that finishes an issue, for `plan_store` and `do_epic`. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. -- `chunk_driver/` holds what `loop_claude` and `do_epic` share as they drive chunks through `agent_cycle`: how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). `doubles.py` holds the loop its tests share with `loop_claude`'s. It imports neither tool, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included. +- `chunk_driver/` holds what the entry points share. An entry point is a tool that drives chunks through `agent_cycle`: `loop_claude` and `do_epic` are the two. They share how a cycle starts (`cycle_start.py`) and closes (`chunk_run.py`), the claim on a checkout before a chunk starts in it (`claims.py`), the prompts every worker gets (`prompts.py`), and a checkout's premises, records and saved models (`project/`). It imports neither entry point, and `repo_checks` fails any package that imports one of the two. `agent_cycle` is the layer below it, and `repo_checks` fails `agent_cycle` where it imports `chunk_driver`, tests included. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. - `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `planning.py` settles, before the chunks start, where each open issue is worked and the order of the issues do-epic filed, through `split.py`, `repo_pick.py` and `ranking.py`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. `e2e/` holds `do-epic-e2e`. -- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. +- `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), finds a pull request and reads its checks, once or until they settle (`pulls.py`), and reads a pull request's review state (`reviews.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `chunk_driver`'s premises, records and `ANSWER_DESTINATIONS`. - `loop_claude` runs `chunk-preflight` as a process of its own. -- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it. `doubles.py` holds the doubles their tests share, such as `FakeEffects`. -- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. +- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, do-epic, both replay tools and `reviewer-merge-trials`' driver use it.- `loop_state/` holds where loop-claude and do-epic keep their files (`paths.py`), which `rung_replay` reads too. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, `do_epic`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read. - `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`. diff --git a/bin/adf_codec/convert.py b/bin/adf_codec/convert.py index fe3f4720..fa33f700 100644 --- a/bin/adf_codec/convert.py +++ b/bin/adf_codec/convert.py @@ -65,12 +65,12 @@ def docker_args(image: str, mode: str) -> list[str]: def docker(args: list[str], text: str, seconds: int) -> Ran | Failure: - """Runs a docker command line as a process of this one: the shim's shell, as git_repo.git is git's.""" + """docker_ran with subprocess.run: the one place that starts docker as a process.""" return docker_ran(args, text, seconds, subprocess.run) def docker_ran(args: list[str], text: str, seconds: int, call: typing.Callable[..., typing.Any]) -> Ran | Failure: - """What call, which runs a command line as subprocess.run does, made of a docker command line on text.""" + """Runs a docker command line through call, with text on its stdin: what it exited with and printed, or a Failure where docker is missing or takes more than seconds. call runs a command line as subprocess.run does.""" try: done = call(args, input=text, capture_output=True, text=True, encoding="utf-8", timeout=seconds) except FileNotFoundError: @@ -82,7 +82,7 @@ def docker_ran(args: list[str], text: str, seconds: int, call: typing.Callable[. @contextlib.contextmanager def machine_slot() -> typing.Iterator[Failure | None]: - """heavy_slot on this process's environment, home, processors, stderr and clock: the shim's shell, as docker is.""" + """heavy_slot with this process's environment, home folder, processor count, stderr, sleep and flock.""" with heavy_slot(os.environ, pathlib.Path.home(), slot_count(usable_cpus()), lambda text: print(text, file=sys.stderr, flush=True), time.sleep, fcntl.flock) as refused: yield refused diff --git a/bin/atlassian/jira.py b/bin/atlassian/jira.py index c14cb0ed..466216c0 100644 --- a/bin/atlassian/jira.py +++ b/bin/atlassian/jira.py @@ -1,4 +1,4 @@ -"""What every reader of Jira Cloud's REST API version 3 shares: a search read page by page, the head of each entry it answers, an issue's "is blocked by" links, and the transition that finishes an issue.""" +"""What every reader of Jira Cloud's REST API version 3 shares: a search read page by page, the key, fields, "is blocked by" links and property of each issue it finds, checked for their shape, and the transition that finishes an issue.""" import dataclasses import re import typing @@ -32,7 +32,7 @@ class Link: @dataclasses.dataclass(frozen=True) class Entry: - """The head of one entry of a search's answer, which every reader checks alike.""" + """The key, fields, links and property of one issue a search finds, which every reader checks alike.""" key: str # The entry's `fields`, from which each reader takes the ones it asked for. fields: dict[str, typing.Any] @@ -42,7 +42,7 @@ class Entry: def entry_of(raw: object, property_: str) -> Entry | Failure: - """The head of one entry of a search's answer, or which issue is not in the shape Jira documents, and how. property_ names the issue property the search asked for.""" + """The Entry of one issue a search finds, or which issue is not in the shape Jira documents, and how. property_ names the issue property the search asked for.""" key = raw.get("key") if isinstance(raw, dict) else None if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): return Failure("the search answered an issue without an issue key") diff --git a/bin/chunk_driver/project/model_choice.py b/bin/chunk_driver/project/model_choice.py index eedfb6b0..3f7ea701 100644 --- a/bin/chunk_driver/project/model_choice.py +++ b/bin/chunk_driver/project/model_choice.py @@ -57,12 +57,12 @@ def get_or_ask_model(project_key: str, paths: Paths, driver: str, effects: Effec def save_model(project_key: str, chosen: str, paths: Paths, replace: typing.Callable[[pathlib.Path, bytes], Failure | None]) -> Failure | None: - """Adds the project's model to the models file, whose only writer this is, through replace, which writes a file as replace_file does. It holds MODELS_LOCK from its read to its write, so two drivers that save at once both keep their pick.""" + """Adds the project's model to the models file, whose only writer this is, through replace, which writes a file as replace_file does. It holds MODELS_LOCK from its read to its write, so two entry points that save at once both keep their pick.""" saved = paths.models_file with locked(paths.home / CLAIMS / MODELS_LOCK) as unlocked: if unlocked: return Failure(f"could not save the model in {saved}: {unlocked.reason}") - # Read under the lock: another driver may have saved its project while this one waited on the human. + # Read under the lock: another entry point may have saved its project while this one waited on the human. models = read_models_file(saved) if isinstance(models, Failure): return models @@ -72,7 +72,7 @@ def save_model(project_key: str, chosen: str, paths: Paths, replace: typing.Call def read_models_file(saved: pathlib.Path) -> dict[str, str] | Failure: - """Each project's model, as the models file at saved maps them; none where there is no such file. The chunk drivers and the replay tools read it, and only save_model writes it.""" + """Each project's model, as the models file at saved maps them; none where there is no such file. The entry points, loop-claude and do-epic, and the replay tools read it.""" try: with open(saved, encoding="utf-8") as handle: models = json.load(handle) diff --git a/bin/forge/reviews.py b/bin/forge/reviews.py index a64141f6..161efee9 100644 --- a/bin/forge/reviews.py +++ b/bin/forge/reviews.py @@ -68,11 +68,11 @@ class PullView: # Empty where its branch protection asks for no review. decision: str reviews: tuple[Review, ...] - # When its author submitted each review and made each comment. A review the author has yet to submit has no time: it is empty, and answers nobody. + # When its author submitted each review and made each comment. A review the author has yet to submit has an empty time, and doesn't answer anyone. said: tuple[str, ...] -# What `held` gives where the answer lacks the key asked for: no text, so the check of the field refuses it. +# What `held` gives where the answer lacks the key asked for: of no type a field may have, so each field's check refuses it. MISSING = object() @@ -116,7 +116,7 @@ def pull_view(printed: str) -> PullView | Failure: def answered(pull: PullView, head: str) -> bool: """Whether the worker answered the newest review that requested changes on pull, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. False where pull lists no review that requested changes. - The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed. + The review names the commit it was made on, so a head that differs shows the worker pushed. A commit's date cannot show that: it says when the commit was made, never when it was pushed. """ asked = max((review for review in pull.reviews if review.state == CHANGES_REQUESTED), key=lambda review: review.submitted_at, default=None) if asked is None: diff --git a/bin/notifier/mattermost.py b/bin/notifier/mattermost.py index f2b8c6aa..f172b02a 100644 --- a/bin/notifier/mattermost.py +++ b/bin/notifier/mattermost.py @@ -54,7 +54,7 @@ def id_of(answer: object, request: str) -> str | Failure: return found if isinstance(found, str) and found else Failure(f"{request} answered without an id") -# request is json_request.http_json, but in the test of what this hands it. +# request is json_request.http_json, except in the test of what this hands it. def http_json(method: str, url: str, token: str, body: object, request: typing.Callable[[str, str, str, object, int, MessageOf], object] = json_request.http_json) -> object: """The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none.""" return request(method, url, f"Bearer {token}", body, TIMEOUT, error_message) diff --git a/bin/notifier/slack.py b/bin/notifier/slack.py index 0bf80c9a..3ce3a3d1 100644 --- a/bin/notifier/slack.py +++ b/bin/notifier/slack.py @@ -42,7 +42,7 @@ def send(config: Config, message: str, http: Http) -> Failure | None: return Failure(f"POST /api/chat.postMessage refused the message: {error if isinstance(error, str) and error else 'no error code'}") -# request is json_request.http_json, but in the test of what this hands it. +# request is json_request.http_json, except in the test of what this hands it. def http_json(method: str, url: str, token: str, body: object, request: typing.Callable[[str, str, str, object, int, MessageOf], object] = json_request.http_json) -> object: """The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none.""" return request(method, url, f"Bearer {token}", body, TIMEOUT, error_message) diff --git a/bin/todo_item/main.py b/bin/todo_item/main.py index f59fcfcf..022ce724 100644 --- a/bin/todo_item/main.py +++ b/bin/todo_item/main.py @@ -105,7 +105,7 @@ LETTERS = ("L", "E", "I", "S") NAMED = {"release": "Release", "blocked_by": BLOCKED_BY, "exempt": "Exempt", "tagline": TAGLINE, "moves": MOVES} -# plan_of is plan_store, but in the tests of a plan in Jira, which hand it a plan in memory. +# plan_of is plan_store, except in the tests of a plan in Jira, which hand it a plan in memory. def main(argv: list[str], folder: pathlib.Path, home: pathlib.Path, stdin: typing.TextIO, plan_of: typing.Callable[[ProjectConfig], PlanStore] = plan_store) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) diff --git a/docs/decisions.md b/docs/decisions.md index 64a14f5f..d45998bb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -4,7 +4,7 @@ Each project principle states one rule that the decisions below apply; their ent 1. **Cut cost only where a measurement of archived chunks shows quality holds.** Chunk bundling, the round cap, which fixes rerun a pass, a reviewer of its own for each pass, the review a branch changing only Markdown no agent follows gets, the passes kept for the release review, review opt-outs, the security pass, compaction and the routing ladder all apply it. 2. **A measurement files or ranks work, and never blocks a merge.** The comprehension floor and check, and a reading-cost rise, apply it. A merge waits on a scoring run the plan calls for only until the run is recorded, whatever it scores. -3. **Each file has one writer.** `~/.claude/loop-claude-models.json` is `save_model`'s, the one function loop-claude and do-epic both write it through, `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo. +3. **Each file has one writer.** `~/.claude/loop-claude-models.json` is written only by `save_model`, which the entry points, loop-claude and do-epic, both call. `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo. 4. **A rule a program can check is enforced by a program, and reviewers rule on the rest.** rule-hook and its overrides, `docker-run-memory`, the refused writes of reviewers under `agents/`, and CI with `main`'s branch protection apply it. 5. **A chunk can't vouch for itself.** What a chunk writes is approved by a review pass, by the human, or by a precedent the repo held before the chunk began. So an unanswered ask leaves the PR unmerged, the human approves the premises chunk and runs `deploy-release --cut`, and the judge holds a chunk open while an answer the human typed isn't recorded anywhere. 6. **An unattended run never waits on a prompt, and a lasting failure stops it.** Every claude loop-claude starts bypasses permissions inside its sandbox, each claude it opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, and interactive sessions run in auto mode with the dangerous-mode prompt skipped. A failed archive stops the loop, while a `claude` that cannot start, as during an update, is retried. @@ -96,7 +96,7 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo ## bin/: the tools send no OTLP traces, logs or metrics, and loop-claude's archive holds the trace of each cycle -2026-11-16, lilleman, from the release review of 0.11.0. The tools send no traces, logs or metrics over OTLP, the OpenTelemetry protocol, to any collector. That applies `principles/technical-principles.md` → "All critical flows should have good traces", whose last sub-bullet keeps the trace of a tool that runs only on its user's own machine on that machine. lilleman ruled this permanent, and the release review of 0.12.0 wrote the sub-bullet from that ruling. Serves goal 4: the tools run on the human's own machines, beside client code and transcripts, and whatever goes to a collector leaves the machine. loop-claude's archive holds the trace of each cycle instead: its transcripts and its `.outcomes.md` entry, from the worker's first run to the judge's verdict. Valid while goal 4 holds. +2026-11-16, lilleman, from the release review of 0.11.0. The tools send no traces, logs or metrics over OTLP, the OpenTelemetry protocol, to any collector. That applies the last sub-bullet of `principles/technical-principles.md` → "All critical flows should have good traces": a tool that runs only on its user's own machine keeps its trace there. lilleman ruled that the tools never send to a collector, and the release review of 0.12.0 wrote the sub-bullet from that ruling. Serves goal 4: the tools run on the human's own machines, beside client code and transcripts, and whatever goes to a collector leaves the machine. loop-claude's archive holds the trace of each cycle instead: its transcripts and its `.outcomes.md` entry, from the worker's first run to the judge's verdict. Valid while goal 4 holds. ## bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers @@ -191,9 +191,9 @@ Valid while `~/.claude` is a checkout of this repo. 2026-10-30, lilleman, todo item 6. Serves goal 1. Until then loop-claude marked each worktree trusted in `~/.claude.json`, reading the file, changing it and writing it back. Claude Code owns and writes that file, so a write it made in between could be lost. Claude Code 2.1.314 treats every folder as trusted while `CLAUDE_CODE_SANDBOXED` is set, and doesn't persist that trust. A claude started in a new folder with the variable set showed no dialog, and Claude Code recorded the folder untrusted. `hand_over` sets the variable for every claude it opens on a terminal: for `/talk`, a release ready to cut and the routing calls. The variable tells Claude Code it runs inside a sandbox, which holds here: loop-claude runs only in the sandbox README → Install names (`loop-claude: every claude it starts bypasses permissions inside its sandbox`). Claude Code doesn't document the variable. Where a later version drops it, the trust dialog comes back on those claudes, and nothing is lost. Valid while Claude Code honours `CLAUDE_CODE_SANDBOXED`. -## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only the chunk drivers write, through one locked function +## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude and do-epic write, through one locked function -2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has one writer, `save_model` in `bin/chunk_driver/project/model_choice.py`, which loop-claude and do-epic both call and which holds a lock from its read to its write; every claude they start gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session. +2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last. `~/.claude/loop-claude-models.json` has one writer: `save_model` in `bin/chunk_driver/project/model_choice.py`. The entry points, loop-claude and do-epic, both call it, and it holds a lock from its read to its write. Every claude they start gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session. ## loop-claude: every claude it starts bypasses permissions inside its sandbox diff --git a/todo.md b/todo.md index c9701e5f..eee305a1 100644 --- a/todo.md +++ b/todo.md @@ -329,7 +329,7 @@ A release's capacity is a sum of its items' cost, as the formula counts it. Each ### 165. Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant. -A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: many tests under `bin/loop_claude/` pin whole sentences of the question, archive, prompt or help text, up to about 750 characters. `test_every_exit_1_stop_has_its_clause_in_help` and `test_every_failed_judge_run_has_its_clause_in_help` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py` asserts `len(LADDER) == 6`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills. +A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: many tests under `bin/loop_claude/`, `bin/chunk_driver/` and `bin/agent_cycle/` pin whole sentences of the question, archive, prompt or help text, up to about 750 characters. `test_every_exit_1_stop_has_its_clause_in_help` and `test_every_failed_judge_run_has_its_clause_in_help` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py` asserts `len(LADDER) == 6`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills. ### 392. Group bin/'s packages by concern into seven folders (plan, records, integrations, loop, review, forge and host), so a newcomer finds a tool's neighbours in one place. -- 2.52.0 From 914b8dc2d4ec289794d02200300e4a461f3672a0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 14:04:11 +0100 Subject: [PATCH 12/14] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20a=20cycle's?= =?UTF-8?q?=20close=20takes=20the=20task=20from=20the=20cycle,=20a=20resol?= =?UTF-8?q?ved=20thread=20is=20skipped=20unread,=20and=20tests=20run=20git?= =?UTF-8?q?=20in=20their=20own=20environment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/branch_chunks/test_branch_chunks.py | 11 +++++---- bin/chunk_driver/chunk_run.py | 11 ++++----- bin/chunk_driver/test_chunk_run.py | 18 +++++++------- bin/do_epic/main.py | 2 +- bin/do_epic/scheduler.py | 4 ++-- bin/do_epic/test_finish.py | 5 ++-- bin/do_epic/test_main.py | 20 ++++++++++++++++ bin/forge/reviews.py | 19 +++++++++------ bin/forge/test_reviews.py | 16 +++++++++++-- bin/judge_replay/test_judge_replay.py | 11 ++++----- bin/larv_review/scoring_setup.py | 22 ++++++++--------- bin/larv_review/test_scoring_setup.py | 6 +++-- bin/loop_claude/loop/chunk_windows.py | 4 ++-- bin/loop_claude/loop/main.py | 4 ++-- bin/loop_claude/loop/test_main.py | 8 +++---- bin/review_replay/test_review_replay.py | 13 ++++------- bin/routing_figures/test_routing_figures.py | 15 ++++++------ bin/rung_replay/doubles.py | 26 +++++++++++++++++++++ bin/rung_replay/test_rung_replay.py | 15 +++++------- 19 files changed, 143 insertions(+), 87 deletions(-) create mode 100644 bin/rung_replay/doubles.py diff --git a/bin/branch_chunks/test_branch_chunks.py b/bin/branch_chunks/test_branch_chunks.py index 16aa0877..333cfa4a 100644 --- a/bin/branch_chunks/test_branch_chunks.py +++ b/bin/branch_chunks/test_branch_chunks.py @@ -206,13 +206,14 @@ class Blamed(unittest.TestCase): class Unsupported(unittest.TestCase): def test_says_which_files_the_config_puts_where_no_commits_are_read(self): checkout = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())).resolve() - self.assertIsNone(unsupported(str(checkout), checkout), "no git checkout, so no config names it") + run = functools.partial(git, env=isolated_env()) + self.assertIsNone(unsupported(str(checkout), checkout, run), "no git checkout, so no config names it") folder = configured(self, checkout) home = folder.parents[1] - self.assertIsNone(unsupported(str(checkout), home)) + self.assertIsNone(unsupported(str(checkout), home, run)) config = folder / "config.toml" config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"').replace('"checkout:docs/reading-cost.md"', '"checkout:records/reading-cost.md"')) - self.assertEqual(unsupported(str(checkout), home), f"the project's config puts {folder}/todo.md, {checkout}/records/reading-cost.md elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far") + self.assertEqual(unsupported(str(checkout), home, run), f"the project's config puts {folder}/todo.md, {checkout}/records/reading-cost.md elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far") class TracedTo(unittest.TestCase): @@ -256,8 +257,8 @@ class BranchChunks(unittest.TestCase): return self.git("rev-parse", "--short", "HEAD").strip() def read(self, run=None, titles=BARE): - """branch_chunks over main, run by git_repo's git, or else by run.""" - return branch_chunks("main", functools.partial(run or git, cwd=str(self.checkout)), titles) + """branch_chunks over main, run by git_repo's git, or else by run, in the test's own environment.""" + return branch_chunks("main", functools.partial(run or git, cwd=str(self.checkout), env=self.env), titles) def fixing_history(self): """Merges seven chunks onto main, then checks out a branch off it. Returns each of main's chunks by label, with the chunks that fixed it. diff --git a/bin/chunk_driver/chunk_run.py b/bin/chunk_driver/chunk_run.py index cf536edd..a4c24313 100644 --- a/bin/chunk_driver/chunk_run.py +++ b/bin/chunk_driver/chunk_run.py @@ -21,8 +21,6 @@ class Run(typing.Protocol): # Every run is a dataclass, which is what lets closing a cycle replace its fields. __dataclass_fields__: typing.ClassVar[dict[str, typing.Any]] - @property - def task(self) -> str: ... @property def unfinished_evidence(self) -> str: ... @property @@ -35,7 +33,6 @@ class Run(typing.Protocol): class ChunkRun: """The run of one chunk, for an entry point that never hands it to another process, such as do-epic.""" cycle_number: int = 0 - task: str = "" # The evidence of the latest unfinished verdict; empty before the chunk's first one, and once it finishes. unfinished_evidence: str = "" # Set by each unfinished verdict; None before the chunk's first one, and once it finishes. @@ -44,19 +41,19 @@ class ChunkRun: unfinished_run: int = 0 -def closed_cycle[R: Run](run: R, project: ProjectRung | None, concluded: Concluded, archive_folder: pathlib.Path, driver: str, loop: Loop) -> R | Stop: - """The run after a cycle of driver, the entry point, concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running.""" +def closed_cycle[R: Run](run: R, task: str, project: ProjectRung | None, concluded: Concluded, archive_folder: pathlib.Path, driver: str, loop: Loop) -> R | Stop: + """The run after a cycle of driver, the entry point, concluded on the chunk's task, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running.""" after = after_verdict(run, project, concluded) # A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts. if after.route is None: return after # The unfinished verdict, archived as the cycle closed, names the route its cycle ended on; the step-up names the one the next cycle runs on. path = transcript_file(loop.session) - if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), loop.effects)): + if path and (failure := archived_step(archive_folder, path, task, step_up(concluded.route, after.route), loop.effects)): return Stop(1, failure.reason) if limit := reached_limit(after, driver): # Archived with the route the next cycle would run on, so a rerun resumes there. - return archived_stop(archive_folder, loop.session, after.task, after.route, limit, limit.reason, loop.effects) + return archived_stop(archive_folder, loop.session, task, after.route, limit, limit.reason, loop.effects) return after diff --git a/bin/chunk_driver/test_chunk_run.py b/bin/chunk_driver/test_chunk_run.py index fd991ba9..c4e207e0 100644 --- a/bin/chunk_driver/test_chunk_run.py +++ b/bin/chunk_driver/test_chunk_run.py @@ -32,23 +32,23 @@ class Steps(unittest.TestCase): FABLE_MEDIUM = Rung("claude-fable-5-2", "medium") def test_a_finished_verdict_clears_the_route_and_the_evidence(self): - run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="old", route=Route(self.OPUS)) + run_with = chunk_run.ChunkRun(cycle_number=1, unfinished_evidence="old", route=Route(self.OPUS)) self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence="")) self.assertEqual(chunk_run.after_verdict(dataclasses.replace(run_with, unfinished_run=3), OPUS_PROJECT, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0) self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(self.FABLE_MEDIUM, unfinished=1), unfinished_evidence="new", unfinished_run=1)) def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self): - run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4)) + run_with = chunk_run.ChunkRun(cycle_number=1, unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4)) raised = Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=5) self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1)) def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self): off_ladder = Route(Rung("worker-model")) - run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="") + run_with = chunk_run.ChunkRun(cycle_number=1, unfinished_evidence="") self.assertEqual(chunk_run.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder) def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self): - run_with = chunk_run.ChunkRun(cycle_number=1, task="do it", unfinished_evidence="", route=Route(self.FABLE_LOW, 3, 3, 4, escalated_at=2)) + run_with = chunk_run.ChunkRun(cycle_number=1, unfinished_evidence="", route=Route(self.FABLE_LOW, 3, 3, 4, escalated_at=2)) self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(self.FABLE_MEDIUM, 3, 3, 4, escalated_at=9)) self.assertEqual(chunk_run.after_verdict(run_with, OPUS_PROJECT, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.FABLE_LOW, 3, 3, 4, unfinished=1, escalated_at=2)) @@ -62,14 +62,14 @@ class Steps(unittest.TestCase): before = Route(self.FABLE_LOW, 3, 3, 4) with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW, replace=replace_file)) - after = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + after = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, unfinished_evidence=""), "Do it.", OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) with contextlib.redirect_stderr(io.StringIO()): - chunk_run.closed_cycle(after, OPUS_PROJECT, run.Concluded(Finished("done"), after.route), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + chunk_run.closed_cycle(after, "Do it.", OPUS_PROJECT, run.Concluded(Finished("done"), after.route), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4)) blocked = pathlib.Path(home, "blocked") blocked.write_text("") - stop = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + stop = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, unfinished_evidence=""), "Do it.", OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, "a-driver", a_loop(FakeEffects().effects(), session=opened)) self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) def outcomes_after(self, unfinished_run: int, taken_in: TakenIn) -> tuple[object, str]: @@ -82,7 +82,7 @@ class Steps(unittest.TestCase): transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") before = Route(self.FABLE_LOW, 3, 3, 4) with contextlib.redirect_stderr(io.StringIO()): - closed = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence="", unfinished_run=unfinished_run), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=taken_in), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + closed = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, unfinished_evidence="", unfinished_run=unfinished_run), "Do it.", OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=taken_in), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) return closed, "".join(file.read_text() for file in archive.rglob("*") if file.is_file() and file.suffix != ".jsonl") def test_a_step_up_archived_first_for_its_transcript_names_the_chunks_task(self): @@ -109,5 +109,5 @@ class Steps(unittest.TestCase): before = Route(self.FABLE_LOW, 3, 3, 4) with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW, replace=replace_file)) - chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) + chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, unfinished_evidence=""), "Do it.", OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened)) self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6)) diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 977e5f07..0fa60304 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -271,7 +271,7 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: concluded = run_cycle(cycle) if isinstance(concluded, Stop): return concluded - closed = closed_cycle(run, cycle.project, concluded, cycle.project_archive, chunk_prompt.DRIVER, loop) + closed = closed_cycle(run, cycle.task, cycle.project, concluded, cycle.project_archive, chunk_prompt.DRIVER, loop) if isinstance(closed, Stop): return closed run = closed diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 09bca3d4..8109a4e9 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -6,7 +6,7 @@ import pathlib import typing from do_epic.epic_record import CAP -from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, LOCK, loop_chunks, project_lock, starting +from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_chunks, project_lock, starting from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.repo_pick import HumanTask, recorded, Repo @@ -16,7 +16,7 @@ from chunk_pr.approval import PARKS from do_epic.split import SPLIT_LABEL from agent_cycle import tmux -# Under the home folder, a folder per epic key holds the epic's LOCK. A chunk without a repo works there. +# Under the home folder, a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. STATE = ".local/state/do-epic" # Why a human's task with a live window waits, as the epic's status says. HUMAN_WAIT = "it is a human's task; do-epic polls Jira until you close it" diff --git a/bin/do_epic/test_finish.py b/bin/do_epic/test_finish.py index 9e90405b..7ead16b2 100644 --- a/bin/do_epic/test_finish.py +++ b/bin/do_epic/test_finish.py @@ -10,9 +10,10 @@ from do_epic.config import DoEpicConfig, load from do_epic.epic_record import EpicRecord from failure import Failure from loop_effects.doubles import FakeEffects, judged, Worker -from do_epic import findings, finish, main, scheduler +from do_epic import findings, finish, main from project_config.settings import Finish from do_epic.test_scheduler import issue +from chunk_driver.claims import LOCK from do_epic.backend.fake import MemoryEpic from loop_state.paths import paths_from from claude_code.session import session_named @@ -215,7 +216,7 @@ class TheFinishingChunk(DoEpicTest): def test_stops_where_the_epics_issues_cannot_be_read_or_its_lock_cannot_be_taken(self) -> None: self.issues = [issue("ABC-20", "do-epic-claude", done=True)] - (self.home / ".local/state/do-epic/ABC-12" / scheduler.LOCK).mkdir(parents=True) + (self.home / ".local/state/do-epic/ABC-12" / LOCK).mkdir(parents=True) code, _, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False)) self.assertEqual(code, 1) self.assertIn("cannot lock ", err) diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 346e6737..a5e71a47 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -26,6 +26,7 @@ from chunk_driver.this_loop import Loop from do_epic.backend.fake import MemoryEpic from do_epic import parked from loop_state.paths import paths_from +from text_files.file_writes import replace_file from model_routing.route import Route from model_routing.ladder import Rung from do_epic.test_do_epic import SETTINGS @@ -410,6 +411,25 @@ class AChunksRun(DoEpicTest): self.assertTrue(any("Z Stepped up\n" in text for text in outcomes) and any("Z Stopped: " in text for text in outcomes), outcomes) self.assertEqual([text for text in outcomes if not text.startswith("Task: Work the Jira issue ABC-21 of the epic ABC-12 as one chunk")], []) + def test_a_step_up_archived_beside_a_new_copy_of_the_transcript_opens_with_the_chunks_task(self) -> None: + fake = FakeEffects(streams=[self.worker()] * 6, claude=[judged("unfinished", escalation="working")] + [judged("unfinished")] * 5, git=UNREAD) + + def grown_after_each_copy(path: pathlib.Path, data: bytes) -> Failure | None: + """Writes the file, and adds a line to the worker's transcript after each copy of it, as a worker that still writes does.""" + unwritten = replace_file(path, data) + if path.suffix == ".jsonl": + for transcript in (paths_from(self.home).claude_code_transcripts.parent / "projects" / "-fake").glob("*.jsonl"): + with open(transcript, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"type": "queue-operation", "timestamp": str(path)}) + "\n") + return unwritten + + fake.replace_file = grown_after_each_copy + code, out, _ = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS) + self.assertEqual(code, 2, out) + outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".claude/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")] + self.assertTrue(any("Z Stepped up\n" in text for text in outcomes) and any("Z Stopped: " in text for text in outcomes), outcomes) + self.assertEqual([text for text in outcomes if not text.startswith("Task: Work the Jira issue ABC-21 of the epic ABC-12 as one chunk")], []) + def test_a_finished_chunk_moves_its_issue_to_done_before_the_chunk_it_blocks_starts(self) -> None: store = MemoryEpic("ABC-12", [self.issues[0], self.issues[1], issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))]) self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] diff --git a/bin/forge/reviews.py b/bin/forge/reviews.py index 161efee9..04098d9b 100644 --- a/bin/forge/reviews.py +++ b/bin/forge/reviews.py @@ -148,15 +148,14 @@ def waiting_threads(number: str, run: Run) -> list[str] | Failure: @dataclasses.dataclass(frozen=True) class Thread: - """One review thread of a pull request.""" + """One review thread of a pull request that nobody resolved.""" path: str - resolved: bool # Who wrote its last comment; empty for a thread without one. last: tuple[str, ...] def threads_read(printed: str) -> tuple[str, tuple[Thread, ...]] | Failure: - """Who opened the pull request and its review threads, as gh printed THREADS' answer, with each field checked here.""" + """Who opened the pull request and its review threads that nobody resolved, as gh printed THREADS' answer, with each field checked here.""" unshaped = Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}") try: pull = held(json.loads(printed), "data", "repository", "pullRequest") @@ -167,16 +166,22 @@ def threads_read(printed: str) -> tuple[str, tuple[Thread, ...]] | Failure: return unshaped threads = [] for thread in nodes: - path, resolved, comments = held(thread, "path"), held(thread, "isResolved"), held(thread, "comments", "nodes") - if not isinstance(path, str) or resolved is MISSING or not isinstance(comments, list): + resolved = held(thread, "isResolved") + if resolved is MISSING: + return unshaped + # A resolved thread is skipped unread: its last comment may be a deleted account's, whose author gh prints as null. + if resolved: + continue + path, comments = held(thread, "path"), held(thread, "comments", "nodes") + if not isinstance(path, str) or not isinstance(comments, list): return unshaped last = tuple(login for comment in comments if isinstance(login := held(comment, "author", "login"), str)) if len(last) != len(comments): return unshaped - threads.append(Thread(path, bool(resolved), last)) + threads.append(Thread(path, last)) return author, tuple(threads) def waits(author: str, threads: tuple[Thread, ...]) -> list[str]: """The files of the threads that wait for an answer from author, who opened the pull request.""" - return sorted({thread.path for thread in threads if not thread.resolved and any(last != author for last in thread.last)}) + return sorted({thread.path for thread in threads if any(last != author for last in thread.last)}) diff --git a/bin/forge/test_reviews.py b/bin/forge/test_reviews.py index 6f1b6671..aeabef46 100644 --- a/bin/forge/test_reviews.py +++ b/bin/forge/test_reviews.py @@ -77,8 +77,20 @@ class TheThreadsThatWait(unittest.TestCase): nodes = [{"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}} for path, resolved, last in threads] return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": nodes}}}}}) - def test_parses_what_gh_prints_into_the_author_and_each_thread(self): - self.assertEqual(reviews.threads_read(self.printed(("a.py", False, "rev"), ("b.py", True, "me"))), ("me", (Thread("a.py", False, ("rev",)), Thread("b.py", True, ("me",))))) + def test_parses_what_gh_prints_into_the_author_and_each_thread_nobody_resolved(self): + self.assertEqual(reviews.threads_read(self.printed(("a.py", False, "rev"), ("b.py", True, "me"), ("c.py", False, "me"))), ("me", (Thread("a.py", ("rev",)), Thread("c.py", ("me",))))) + + def pull_with(self, *nodes: dict[str, object]) -> str: + return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": nodes}}}}}) + + def test_skips_a_resolved_thread_unread_so_a_deleted_accounts_comment_there_doesnt_fail_the_read(self): + deleted = {"comments": {"nodes": [{"author": None}]}} + printed = self.pull_with({"isResolved": True, "path": "b.py", **deleted}, {"isResolved": True}, {"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": {"login": "rev"}}]}}) + self.assertEqual(reviews.waiting_threads("7", lambda args: printed), ["a.py"]) + + def test_a_deleted_accounts_last_word_in_a_thread_nobody_resolved_is_a_failure(self): + printed = self.pull_with({"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": None}]}}) + self.assertEqual(reviews.waiting_threads("7", lambda args: printed), Failure(f"gh api graphql printed no review threads: {printed[:200]}")) def test_a_thread_waits_while_unresolved_with_a_reviewers_last_word(self): printed = self.printed(("b.py", False, "rev"), ("a.py", False, "rev"), ("a.py", False, "rev"), ("c.py", True, "rev"), ("d.py", False, "me")) diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 67eca5ed..9142d6a4 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -5,7 +5,6 @@ import pathlib import subprocess import sys import tempfile -import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -25,6 +24,7 @@ from chunk_driver.drivers import LOOP_CLAUDE from judge_replay import main from rung_replay.search import Miss, Replay, Tried from model_routing.ladder import Rung +from rung_replay.doubles import Together TOOL = pathlib.Path(__file__).resolve().parents[1] / "judge-replay" TRANSCRIPT = pathlib.Path("/archive/p/c/a.jsonl") @@ -245,19 +245,16 @@ class Main(unittest.TestCase): for n in range(2, 8): (chunk / f"t{n}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": f"said {FINISHED} {n}"}]}}) + "\n") (chunk / f"t{n}.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:0{n}Z {FINISHED}\n\nEvidence:\n> e\n") - running, most = [], [] + together = Together(4) def reply(rung, interrupted): - running.append(rung) - most.append(len(running)) - time.sleep(0.05) - running.remove(rung) + together(rung) return self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}") code, _, err = self.run_main(["claude-opus-5-5"], reply) self.assertEqual(code, 0, err) self.assertIn("replaying 8 verdicts on ", err) - self.assertEqual(max(most), 4) + self.assertEqual(set(together.most.values()), {4}) def test_the_prompt_and_the_reply_schema_of_a_rebuilt_run_name_loop_claude_and_the_records_and_show_the_transcript_once(self): code, _, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) diff --git a/bin/larv_review/scoring_setup.py b/bin/larv_review/scoring_setup.py index 10aae6f8..806ef509 100644 --- a/bin/larv_review/scoring_setup.py +++ b/bin/larv_review/scoring_setup.py @@ -6,7 +6,7 @@ import shutil from review_rules.comprehension_history import DIMENSIONS from failure import Failure from text_files.markdown_text import FENCE, listed, section -from git_cli.git_repo import git +from git_cli.git_repo import git, Git from project_config.main import located from review_rules.review_folder import made_review_folder, review_folder from project_config.settings import ProjectConfig @@ -127,14 +127,14 @@ def scoring_folder(worktree: str, home: pathlib.Path) -> pathlib.Path: return pathlib.Path(review_folder(str(home), worktree)) / "scoring" -def prepare_scoring(worktree: str, home: pathlib.Path) -> str | Failure: +def prepare_scoring(worktree: str, home: pathlib.Path, run: Git = git) -> str | Failure: """Makes the scoring run's worktree at worktree's HEAD and writes each seat's prompt beside it, in the chunk's review folder; what it made, as the tool prints it.""" folder = scoring_folder(worktree, home) # A setup record-scoring never removed, as where the seats failed, would otherwise block every later run. replaced = folder.exists() - if replaced and isinstance(removed := removed_setup(worktree, home), Failure): + if replaced and isinstance(removed := removed_setup(worktree, home, run), Failure): return removed - config = located(worktree, home) + config = located(worktree, home, run) if isinstance(config, Failure): return config # Where AGENTS.md is missing, this repo keeps the values in seat-prompts.md: .claude/rules/this-repo-keeps-no-agents-md.md. @@ -156,9 +156,9 @@ def prepare_scoring(worktree: str, home: pathlib.Path) -> str | Failure: score = score_bullets(skill) if isinstance(score, Failure): return score - listing = git("worktree", "list", "--porcelain", cwd=worktree) - branch = git("symbolic-ref", "--short", "-q", "HEAD", cwd=worktree) - head = git("rev-parse", "--short", "HEAD", cwd=worktree) + listing = run("worktree", "list", "--porcelain", cwd=worktree) + branch = run("symbolic-ref", "--short", "-q", "HEAD", cwd=worktree) + head = run("rev-parse", "--short", "HEAD", cwd=worktree) if isinstance(listing, Failure): return listing if isinstance(head, Failure): @@ -169,8 +169,8 @@ def prepare_scoring(worktree: str, home: pathlib.Path) -> str | Failure: return made checkout = folder / "checkout" # The seats score the chunk's head, which holds origin's default branch since larv-review §4 step 1, as larv-review → "Scoring run" says. - added = git("worktree", "add", "--quiet", "--detach", str(checkout), "HEAD", cwd=worktree) - tracked = added if isinstance(added, Failure) else git("ls-files", cwd=str(checkout)) + added = run("worktree", "add", "--quiet", "--detach", str(checkout), "HEAD", cwd=worktree) + tracked = added if isinstance(added, Failure) else run("ls-files", cwd=str(checkout)) if isinstance(tracked, Failure): shutil.rmtree(folder, ignore_errors=True) return tracked @@ -200,12 +200,12 @@ def prepare_scoring(worktree: str, home: pathlib.Path) -> str | Failure: return before + f"Scoring worktree, at {head.strip()}: {checkout}\nPrompts, each for one {SEAT_AGENT} agent:\n" + "\n".join(written) -def removed_setup(worktree: str, home: pathlib.Path) -> Failure | None: +def removed_setup(worktree: str, home: pathlib.Path, run: Git = git) -> Failure | None: """Removes the scoring worktree and prompts prepare_scoring made for the chunk at worktree, where they exist.""" folder = scoring_folder(worktree, home) if not folder.exists(): return None - if (folder / "checkout").exists() and isinstance(removed := git("worktree", "remove", "--force", str(folder / "checkout"), cwd=worktree), Failure): + if (folder / "checkout").exists() and isinstance(removed := run("worktree", "remove", "--force", str(folder / "checkout"), cwd=worktree), Failure): return Failure(f"could not remove the scoring worktree {folder / 'checkout'}: {removed.reason}") shutil.rmtree(folder, ignore_errors=True) return None diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py index 51edfe61..4e3eebc9 100644 --- a/bin/larv_review/test_scoring_setup.py +++ b/bin/larv_review/test_scoring_setup.py @@ -1,3 +1,4 @@ +import functools import os import pathlib import re @@ -10,6 +11,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from larv_review.scoring_setup import bullets, file_globs, prepare_scoring, project_values, removed_setup, score_bullets from failure import Failure +from git_cli.git_repo import git from test_env import isolated_env from project_config.doubles import write_config @@ -102,7 +104,7 @@ class PrepareScoring(unittest.TestCase): def prepare(self): """What prepare-scoring returns in the checkout, run in this process so mutation tests see the lines it runs.""" - return prepare_scoring(str(self.checkout), self.root) + return prepare_scoring(str(self.checkout), self.root, functools.partial(git, env=self.env)) def run_tool(self, *args): return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True) @@ -137,7 +139,7 @@ class PrepareScoring(unittest.TestCase): self.commit() checkout = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "checkout" checkout.mkdir(parents=True) - removed = removed_setup(str(self.checkout), self.root) + removed = removed_setup(str(self.checkout), self.root, functools.partial(git, env=self.env)) self.assertIsInstance(removed, Failure) self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason) self.assertTrue(checkout.exists()) diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index b9776378..8531209e 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -5,7 +5,7 @@ import re import typing from touch_predictions.beside import Beside, chunks_beside -from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, LOCK, loop_session, project_lock, starting +from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_session, project_lock, starting from loop_claude.chunk import chunk_items from git_cli.git_repo import default_ref from loop_effects.effects import Effects, say @@ -161,6 +161,6 @@ 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.""" + """Returns once no loop of the project is starting windows: start_chunks holds the lock file `claims.LOCK` names while it starts them. Where the lock cannot be taken, it returns at once.""" with starting(project_lock(root, home)): pass diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index aae44311..8cf9a848 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -41,7 +41,7 @@ class Steps: 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] + closed_cycle: typing.Callable[[LoopRun, str, ProjectRung | None, Concluded, pathlib.Path, str, Loop], LoopRun | Stop] check_routing: typing.Callable[[pathlib.Path, Rung, Loop], Stop | None] @@ -93,7 +93,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc concluded = steps.run_cycle(cycle) if isinstance(concluded, Stop): return concluded - closed = steps.closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, fresh_prompt.DRIVER, loop) + closed = steps.closed_cycle(loop_run, cycle.task, cycle.project, concluded, cycle.project_archive, fresh_prompt.DRIVER, loop) if isinstance(closed, Stop): return closed loop_run = closed diff --git a/bin/loop_claude/loop/test_main.py b/bin/loop_claude/loop/test_main.py index 6dc90446..ba5a6346 100644 --- a/bin/loop_claude/loop/test_main.py +++ b/bin/loop_claude/loop/test_main.py @@ -194,8 +194,8 @@ class WindowStarts(unittest.TestCase): def test_a_window_loop_hands_each_step_of_a_cycle_what_the_steps_before_it_made(self): env = {"TMUX_PANE": "%4", "LOOP_CLAUDE_TRANSCRIPTS": "/t"} - on_ladder = unittest.mock.Mock(project=OPUS_PROJECT, project_archive=pathlib.Path("/t/r")) - off_ladder = unittest.mock.Mock(project=None, project_archive=pathlib.Path("/t/r"), route=unittest.mock.Mock(rung=Rung("my-model"))) + on_ladder = unittest.mock.Mock(task="the cycle's task", project=OPUS_PROJECT, project_archive=pathlib.Path("/t/r")) + off_ladder = unittest.mock.Mock(task="the cycle's task", project=None, project_archive=pathlib.Path("/t/r"), route=unittest.mock.Mock(rung=Rung("my-model"))) stop, calls = self.window_loop([on_ladder, off_ladder, Stop(2, "the human is needed")], env) self.assertEqual(stop, Stop(2, "the human is needed")) before, first, second, third = (main.LoopRun(number, "/r", "do it", "", unfinished_run=max(number - 1, 0), chunk="item-3") for number in range(4)) @@ -204,12 +204,12 @@ class WindowStarts(unittest.TestCase): ("exec_if_edited", self.loop, "print-1", before), ("next_cycle", first, self.loop), ("run_cycle", on_ladder), - ("closed_cycle", first, OPUS_PROJECT, self.unfinished, pathlib.Path("/t/r"), "loop-claude", self.loop), + ("closed_cycle", first, "the cycle's task", OPUS_PROJECT, self.unfinished, pathlib.Path("/t/r"), "loop-claude", self.loop), ("check_routing", pathlib.Path("/t"), Rung("claude-opus-5-5", "medium"), self.loop), ("exec_if_edited", self.loop, "print-1", dataclasses.replace(first, unfinished_run=1)), ("next_cycle", second, self.loop), ("run_cycle", off_ladder), - ("closed_cycle", second, None, self.unfinished, pathlib.Path("/t/r"), "loop-claude", self.loop), + ("closed_cycle", second, "the cycle's task", None, self.unfinished, pathlib.Path("/t/r"), "loop-claude", self.loop), ("check_routing", pathlib.Path("/t"), Rung("my-model"), self.loop), ("exec_if_edited", self.loop, "print-1", dataclasses.replace(second, unfinished_run=2)), ("next_cycle", third, self.loop), diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index bca01233..74421fad 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -9,7 +9,6 @@ import shutil import subprocess import sys import tempfile -import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -24,6 +23,7 @@ from failure import Failure from review_rules.reviewer_context import reviewer_context from review_rules.review_passes import REVIEWERS from model_routing.ladder import Rung +from rung_replay.doubles import Together TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay" REFERENCE = Rung("claude-opus-5-5", "medium") @@ -306,21 +306,18 @@ class Main(unittest.TestCase): def test_replays_no_more_rounds_at_once_than_asked_on_any_rung(self): self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z") - self.limits["at_once"] = 1 + self.limits["at_once"] = 2 for argv, rungs in ((["stability", "claude-opus-5-5"], {REFERENCE, Rung("claude-opus-5-5", "low"), Rung("claude-sonnet-5-5", "high")}), (["stability", "claude-opus-5-5", "--omit-claude-md"], {REFERENCE})): with self.subTest(argv=argv): - running, most = [], {} + together = Together(2) def review(rung): - running.append(rung) - most[rung] = max(most.get(rung, 0), len(running)) - time.sleep(0.05) - running.remove(rung) + together(rung) return {"type": "result", "result": f"review on {rung.model} {rung.effort}"} code, _, err = self.run_main(argv, lambda rung: {"found": [0, 1]}, review=review) self.assertEqual(code, 0, err) - self.assertEqual(most, dict.fromkeys(rungs, 1)) + self.assertEqual(together.most, dict.fromkeys(rungs, 2)) def test_without_claude_md_replays_each_round_three_times_with_it_and_once_without_on_the_project_rung(self): finds = iter(([0, 1], [0], [0, 1], [1])) diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index aa6efc96..fd29f34c 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -1,6 +1,7 @@ import collections import contextlib import dataclasses +import functools import io import json import os @@ -319,7 +320,7 @@ class BranchHistory(unittest.TestCase): folder = configured(self, checkout) config = folder / "config.toml" config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) - found = archive.branch_history(str(checkout), folder.parents[1], BARE, git_repo.git) + found = archive.branch_history(str(checkout), folder.parents[1], BARE, functools.partial(git_repo.git, env=isolated_env())) assert isinstance(found, Failure), found self.assertEqual(found.reason, f"its chunks' items and later fixes are not counted: the project's config puts {folder}/todo.md elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far") @@ -365,7 +366,7 @@ class Archive(unittest.TestCase): env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)} self.ship_then_fix(home / "code" / "log", env) self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, str(home), "", git_repo.git) + found = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) self.assertEqual([(chunk.dollars["project"].keys(), chunk.fixed_later) for chunk in found.chunks], [({"log": 0}.keys(), 1)]) def test_reads_a_projects_round_titles_and_its_branchs_history_through_its_configs_templates(self): @@ -376,9 +377,9 @@ class Archive(unittest.TestCase): config = write_config(home, home / "code" / "log") / "config.toml" worker = [message(f"m{n}", "2026-10-14T09:00:00Z", call("Bash", command=f"git commit -m '{round_title.format(n)}'")) for n in (1, 2)] self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), worker) - bare = archive.measure_archive(self.root, str(home), "", git_repo.git) + bare = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\n') - templated = archive.measure_archive(self.root, str(home), "", git_repo.git) + templated = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) self.assertEqual([(chunk.rounds_past_first, chunk.fixed_later) for chunk in bare.chunks], [(0, 0)]) self.assertEqual([(chunk.rounds_past_first, chunk.fixed_later) for chunk in templated.chunks], [(1, 1)]) @@ -389,7 +390,7 @@ class Archive(unittest.TestCase): config = write_config(home, home / "code" / "log") / "config.toml" config.write_text(config.read_text() + 'commit-title = "PAY-{id}"\n') self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, str(home), "", git_repo.git) + found = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) self.assertEqual(found.chunks, []) self.assertEqual(len(found.unread), 1) self.assertRegex(found.unread[0], r"^log: none of its chunks is measured: .*`commit-title` is 'PAY-\{id\}'") @@ -403,7 +404,7 @@ class Archive(unittest.TestCase): def recording(*args, **options): made.append((args[0], options)) - return git_repo.git(*args, **options) + return git_repo.git(*args, **options, env=env) archive.measure_archive(self.root, str(home), "", recording) self.assertTrue(all(options.get("guarded") is True for _, options in made)) read = [options.get("timeout") for command, options in made if command in ("log", "ls-tree", "show", "diff", "blame")] @@ -416,7 +417,7 @@ class Archive(unittest.TestCase): (home / "code" / "log").mkdir(parents=True) subprocess.run(["git", "init", "-q"], cwd=home / "code" / "log", check=True, env=env, capture_output=True) self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, str(home), "", git_repo.git) + found = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) self.assertEqual(found.unread, ("log: no origin remote, and no main or master branch to take as the default branch",)) def test_names_each_project_whose_history_it_cannot_read(self): diff --git a/bin/rung_replay/doubles.py b/bin/rung_replay/doubles.py new file mode 100644 index 00000000..c4e62052 --- /dev/null +++ b/bin/rung_replay/doubles.py @@ -0,0 +1,26 @@ +"""Test doubles for what a replay runs at once.""" +import collections +import threading +import typing + + +class Together: + """What a fake replay calls to show how many replays run at once: each call returns once `parties` calls are inside it together, so it neither sleeps nor reads a clock.""" + + def __init__(self, parties: int) -> None: + # The timeout only ends a test whose replays never run `parties` at once: it breaks the barrier, which raises in every call. + self.barrier = threading.Barrier(parties, timeout=60) + self.lock = threading.Lock() + self.inside = 0 + # The most calls inside at once, by the key each call gave. + self.most: dict[typing.Hashable, int] = collections.defaultdict(int) + + def __call__(self, key: typing.Hashable) -> None: + with self.lock: + self.inside += 1 + self.most[key] = max(self.most[key], self.inside) + try: + self.barrier.wait() + finally: + with self.lock: + self.inside -= 1 diff --git a/bin/rung_replay/test_rung_replay.py b/bin/rung_replay/test_rung_replay.py index f4b276f1..d6e726de 100644 --- a/bin/rung_replay/test_rung_replay.py +++ b/bin/rung_replay/test_rung_replay.py @@ -5,7 +5,6 @@ import pathlib import subprocess import sys import tempfile -import time import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -18,6 +17,7 @@ from failure import Failure from claude_code.reply import Limited from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder import Rung +from rung_replay.doubles import Together LADDER = read_ladder(SHIPPED) REFERENCE = Rung("claude-opus-5-5", "medium") @@ -63,18 +63,15 @@ class Replayed(unittest.TestCase): def test_says_what_it_replays_on_each_rung_and_replays_no_more_cases_at_once_than_asked(self): high = Rung("claude-fable-5-2", "low") - said, running, most = [], [], {} + said, together = [], Together(2) def replay_one(case, rung): - running.append(case) - most[rung] = max(most.get(rung, 0), len(running)) - time.sleep(0.02) - running.remove(case) + together(rung) return {0} - replayed(["a", "b", "c"], REFERENCE, [MIDDLE], replay_one, lambda _, reply: sorted(reply), "verdicts", said.append, 1, [high]) - self.assertEqual(said, [f"replaying 3 verdicts on {REFERENCE}", f"replaying 3 verdicts on {high}", f"replaying 3 verdicts on {MIDDLE}"]) - self.assertEqual(most, {REFERENCE: 1, high: 1, MIDDLE: 1}) + replayed(["a", "b", "c", "d"], REFERENCE, [MIDDLE], replay_one, lambda _, reply: sorted(reply), "verdicts", said.append, 2, [high]) + self.assertEqual(said, [f"replaying 4 verdicts on {REFERENCE}", f"replaying 4 verdicts on {high}", f"replaying 4 verdicts on {MIDDLE}"]) + self.assertEqual(together.most, {REFERENCE: 2, high: 2, MIDDLE: 2}) def test_stops_at_a_usage_limit(self): limit = Limited(None, "limit") -- 2.52.0 From 04063e1bd8e0161328626a4b280d0a86ac4354be Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 14:08:11 +0100 Subject: [PATCH 13/14] Say in chunk_start's docstring that the route moved to chunk_driver --- bin/loop_claude/loop/chunk_start.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/loop_claude/loop/chunk_start.py b/bin/loop_claude/loop/chunk_start.py index 0a653980..e99fdf49 100644 --- a/bin/loop_claude/loop/chunk_start.py +++ b/bin/loop_claude/loop/chunk_start.py @@ -1,4 +1,4 @@ -"""How a cycle starts: the route it runs on, from the archive or the plan, and the facts chunk-preflight finds for a fresh chunk.""" +"""How loop-claude's cycle starts: the plan it fetches, the item it takes, and the facts chunk-preflight finds for a fresh chunk. The route is `chunk_driver.cycle_start`'s.""" from git_cli.git_repo import default_ref from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELEASES -- 2.52.0 From a7e129780593afa00a2905ff542ab0eb6101b99d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 14:08:16 +0100 Subject: [PATCH 14/14] Record the comprehension check: paired ruling better at 914b8dc2 against aedc5ed3, Mid A better, Inherited architect better --- docs/comprehension-history.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index a13498f3..35aafb66 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -4119,3 +4119,30 @@ Inherited architect, would restructure first: - Navigation: `bin/loop_state/paths.py:6` `Paths`: neither state nor loop-specific - Self-sufficiency: `bin/larv_review/plan.py:25` `scoring_run_due`: the module holds the scoring-run trigger and has no docstring - Locality: `bin/review_rules/review_passes.py:8` `PASS_AGENTS`: code constants that must match sentences in SKILL.md + +## 2026-11-19T13:08:12Z, PR #634 at 914b8dc2, against aedc5ed3 + +Ruling: better + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | better | better | better | same | better | +| Inherited architect | better | better | better | same | better | + +Mid A, decided by: + +- Navigation, Shape, Overall: `bin/do_epic/main.py:11` `next_cycle`: do-epic imports the shared `chunk_driver` instead of loop-claude's internals, so a do-epic routing symptom no longer leads into loop-claude's `main.py` +- Shape, Locality: `bin/chunk_driver/chunk_run.py:44` `closed_cycle`: takes the task as an argument, and do-epic runs on `ChunkRun` instead of a `LoopRun` filled with empty fields +- Navigation, Shape: `bin/chunk_driver/cycle_start.py:96` `cycle_of`: both entry points build a cycle through the same three steps, which the module docstring lists in order +- Navigation: `bin/forge/reviews.py:23` `review_decision`: one module reads a pull request's review state, where two tools each read part of it +- Navigation: `bin/atlassian/jira.py:1` module docstring: Jira search and transitions sit in the Atlassian package, not in the plan store +- Locality: `bin/wait_for/main.py:30` `main`: the clock is a visible parameter instead of a patched global + +Inherited architect, decided by: + +- Navigation, Locality, Shape, Overall: `bin/do_epic/main.py:410` `next_cycle`: calls the shared `project_routing`, `announced_route` and `cycle_of`, so how a cycle starts changes in one file, not in two kept in step +- Locality: `bin/do_epic/main.py:439` `chunk_work`: returns `EpicReopened` instead of handing chunks on from inside a getter +- Shape, Locality: `bin/chunk_driver/chunk_run.py:33` `ChunkRun`: holds only what do-epic needs; the `Run` protocol's use of `__dataclass_fields__` is clever but commented +- Navigation, Shape: `bin/chunk_driver/claims.py:1` module docstring: the lock and the chunk flags sit in one module named for that job, and `starting` yields a `Failure` instead of raising +- Locality, Navigation: `bin/forge/reviews.py:23` `review_decision`: all review-state reading in `forge/`, each field shape-checked; three similar names cost a docstring read each +- Locality: `bin/chunk_driver/project/model_choice.py:28` `overridden`: the model override is one function, where it was spelled out twice -- 2.52.0