Rename loop-claude to build-release, with no alias
This commit is contained in:
@@ -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 and do-epic (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: build-release 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). 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.
|
||||
"""
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""The escalation mark makes one escalation trigger step the worker up one rung, never two (docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`).
|
||||
|
||||
A worker whose run ends asking its driver, such as loop-claude, for a higher rung cites the trigger that fired, and the judge quotes the passage where it fired as the verdict's escalation. The mark, Route.escalated_at, is how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The session's transcript only grows, so the mark holds across cycles, and the archive's Worker: lines keep it for a rerun.
|
||||
A worker whose run ends asking its driver, such as build-release, for a higher rung cites the trigger that fired, and the judge quotes the passage where it fired as the verdict's escalation. The mark, Route.escalated_at, is how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The session's transcript only grows, so the mark holds across cycles, and the archive's Worker: lines keep it for a rerun.
|
||||
|
||||
- Stamp. stamped() writes on the judge's verdict how many entries the judge read.
|
||||
- Step. routing.next_route() steps the worker up on an escalation and moves the mark to moved_to(verdict).
|
||||
|
||||
@@ -19,7 +19,7 @@ def claude_args(rung: Rung, args: list[str]) -> list[str]:
|
||||
|
||||
|
||||
# CLAUDE_CODE_SANDBOXED, which Claude Code doesn't document, skips its trust dialog without writing ~/.claude.json:
|
||||
# docs/decisions.md → `loop-claude: every claude it opens on a terminal has CLAUDE_CODE_SANDBOXED set`.
|
||||
# docs/decisions.md → `build-release: every claude it opens on a terminal has CLAUDE_CODE_SANDBOXED set`.
|
||||
def hand_over(command: ClaudeCommand, effects: Effects) -> Failure | None:
|
||||
"""Runs claude on the terminal as command says, with CLAUDE_CODE_SANDBOXED=1 added to its environment; the failure is why claude could not start."""
|
||||
try:
|
||||
|
||||
@@ -96,9 +96,9 @@ class Reply:
|
||||
answered_before: str = dataclasses.field(metadata={"description": "With interrupt true, a [human] line from earlier in the chunk that answered the question the worker asks now, quoted verbatim, without elisions. Empty otherwise."})
|
||||
left_open: str = dataclasses.field(metadata={"description": "With answered_before set, the words of that line that leave open what the question asks, quoted verbatim; the question ends with them. Empty otherwise."})
|
||||
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."})
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it without typing anything.
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since build-release computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it without typing anything.
|
||||
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
|
||||
# Finds the answer that reverses a choice the worker took on its own recommendation. score-outcomes counts these answers per chunk: they are the counter-signal the 2026-11-08 entry of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…` stays valid by.
|
||||
# Finds the answer that reverses a choice the worker took on its own recommendation. score-outcomes counts these answers per chunk: they are the counter-signal the 2026-11-08 entry of docs/decisions.md → `build-release: a judge decides each interrupt and each quoted answer…` stays valid by.
|
||||
reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took on its own recommendation and recorded with its reason, quoted verbatim, without elisions. Empty where none does; a line that answers a question the worker left open doesn't override anything."})
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ def judge_schema(driver: str) -> dict[str, typing.Any]:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Rejected(Failure):
|
||||
"""A judge reply loop-claude rejected: reason says why, run holds the prompt and the reply, and cost is what the run cost in dollars, 0 where its reply records none."""
|
||||
"""A judge reply build-release rejected: reason says why, run holds the prompt and the reply, and cost is what the run cost in dollars, 0 where its reply records none."""
|
||||
run: JudgeRun
|
||||
cost: float = 0.0
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
The worker, and the session /talk opens, run on a Route (model_routing/route.py). A model off the ladder gets a route without an item, and it is never stepped.
|
||||
|
||||
- Start. The entry point finds the plan item that routes a fresh chunk, as loop_claude/routed_item.py does; first_route picks the worker's rung from its L, or the project's rung without an item.
|
||||
- Start. The entry point finds the plan item that routes a fresh chunk, as build_release/routed_item.py does; first_route picks the worker's rung from its L, or the project's rung without an item.
|
||||
- Rerun. kept decides whether a rerun resumes the route its archive last names.
|
||||
- Step-up. next_route raises the route after an unfinished verdict (unfinished_route), or an interrupt or a quoted answer that carries an escalation (escalated_route); escalation_cap bounds an escalation, and agent_cycle/escalation_mark.py states the escalation mark's rule. step_up names the change where it changes the worker line, which the archive records.
|
||||
- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model.
|
||||
@@ -43,7 +43,7 @@ JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
class Scored(typing.Protocol):
|
||||
"""What routes a chunk: a plan item under loop-claude, an epic's issue under do-epic."""
|
||||
"""What routes a chunk: a plan item under build-release, an epic's issue under do-epic."""
|
||||
@property
|
||||
def id(self) -> int:
|
||||
"""The number a Route keeps as its item."""
|
||||
|
||||
@@ -208,7 +208,7 @@ def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answer
|
||||
|
||||
|
||||
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
|
||||
"""Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1."""
|
||||
"""Archives a judge reply build-release rejected, so the archive shows what the judge returned before a retry or an exit 1."""
|
||||
if unkept := archived(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(cycle.judge), judge_cost=rejected.cost, judge_run=rejected.run), cycle.effects, rejected.run):
|
||||
return Stop(1, unkept.reason)
|
||||
return None
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `loop-claude: each verdict records the claude-config release and commit that ran it…`.
|
||||
"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `build-release: each verdict records the claude-config release and commit that ran it…`.
|
||||
|
||||
A stretch runs from the previous outcome that recorded a spend, or from the chunk's start, to the ruling. It counts the worker's main thread, each subagent and the judge run that ruled, each message once. Dollars are left to be derived from the model and the tokens, at the prices recorded beside them.
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,7 @@ QUOTED_ANSWERS_PER_CYCLE = 3
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TypedAnswer:
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
|
||||
"""The human's answer to an interrupt, typed at build-release's terminal."""
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
|
||||
@@ -30,12 +30,12 @@ class Interrupts(unittest.TestCase):
|
||||
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"})
|
||||
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), Rung("m", "high"), str(self.transcript), {"BUILD_RELEASE_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())
|
||||
answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, "build-release", effects or fake.effects())
|
||||
self.bells = said.getvalue().count(tmux.BELL)
|
||||
return answer, said.getvalue().replace(tmux.BELL, "")
|
||||
|
||||
@@ -162,7 +162,7 @@ class Interrupts(unittest.TestCase):
|
||||
|
||||
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(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun build-release 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):
|
||||
@@ -170,7 +170,7 @@ class Interrupts(unittest.TestCase):
|
||||
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?"])
|
||||
self.assertEqual(fake.dms, [f"build-release 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."])
|
||||
@@ -222,7 +222,7 @@ class Interrupts(unittest.TestCase):
|
||||
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"}])
|
||||
self.assertEqual(fake.terminal_environments, [{"BUILD_RELEASE_WORKER_RUNG": "m at high effort", "CLAUDE_CODE_SANDBOXED": "1"}])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -107,27 +107,27 @@ 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", "", "the project's decisions", "the plan or a comment", 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, "build-release"), 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):
|
||||
def test_drops_an_escalation_quote_that_only_build_releases_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", "", "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())
|
||||
verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 1, "build-release"), 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", "", "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())
|
||||
verdict = judge.judge_once("/r", judge.Brief("Do it.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 1, "build-release"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects())
|
||||
self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2))
|
||||
|
||||
def test_takes_the_task_as_evidence_where_the_tail_it_shows_cuts_off_the_workers_first_prompt_but_no_quote_across_the_join(self):
|
||||
entries = [human("Do the next chunk. " + "x" * judge.JUDGE_PROMPT_CHARS), assistant({"type": "text", "text": "Merged."})]
|
||||
def judged_on(evidence):
|
||||
return judge.judge_once("/r", judge.Brief("Do the next chunk.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 0, "loop-claude"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence=evidence)] * 3).effects())
|
||||
return judge.judge_once("/r", judge.Brief("Do the next chunk.", "## Goals", "", "the project's decisions", "the plan or a comment", kinds(*entries), 0, "build-release"), Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence=evidence)] * 3).effects())
|
||||
self.assertEqual(judged_on("Do the next chunk."), Unfinished("Do the next chunk.", entries_read=2))
|
||||
self.assertEqual(judged_on("Do the next chunk. ... Merged."), Unfinished("Do the next chunk. ... Merged.", entries_read=2))
|
||||
self.assertIsInstance(judged_on("Do the next release."), Failure)
|
||||
|
||||
@@ -130,7 +130,7 @@ Worker: {OFF_LADDER}
|
||||
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"}])
|
||||
self.assertEqual(fake.worker_environments, [{"BUILD_RELEASE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "BUILD_RELEASE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "BUILD_RELEASE_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")):
|
||||
@@ -159,7 +159,7 @@ Worker: {OFF_LADDER}
|
||||
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")
|
||||
self.assertEqual(fake.terminal_environments[0]["BUILD_RELEASE_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)
|
||||
|
||||
@@ -14,12 +14,12 @@ from agent_cycle.doubles import WINDOW
|
||||
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")):
|
||||
("tmux 3.1c", "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"),
|
||||
("tmux 2.9a", "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 2.9a"),
|
||||
("", "build-release 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, "build-release"), reason)
|
||||
self.assertEqual(fake.tmux_calls, [["-V"]])
|
||||
|
||||
def test_names_the_session_for_the_project(self):
|
||||
@@ -39,14 +39,14 @@ class TmuxCommands(unittest.TestCase):
|
||||
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.assertIsNone(tmux.start_window(window, "/r", {"BUILD_RELEASE_X": "1"}, ["/b/build-release", "--chunk", "item-7", "ship it;"], True, True, fake.tmux))
|
||||
self.assertIsNone(tmux.start_window(window, "/r", {}, ["/b/build-release"], 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\;"],
|
||||
["new-session", "-d", "-s", "loop-proj", "-n", "item-7", "-c", "/r", "-e", "BUILD_RELEASE_X=1", "-P", "-F", "#{window_id}", "--", "/b/build-release", "--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"],
|
||||
["new-window", "-d", "-t", "=loop-proj:", "-n", "item-7", "-c", "/r", "-P", "-F", "#{window_id}", "--", "/b/build-release"],
|
||||
["set-option", "-w", "-t", "@9", "@chunk-root", "/r"],
|
||||
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
|
||||
])
|
||||
|
||||
@@ -52,7 +52,7 @@ 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."""
|
||||
"""Runs a worker whose claude prints events and holds shells `held`; returns the claude, what build-release said and the record's text."""
|
||||
clock = [NOW]
|
||||
streamed = Streamed(0, *events, clock=clock, held=held)
|
||||
fake = FakeEffects(streams=[streamed])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The tmux commands an entry point runs: each chunk's loop runs in its own window of one tmux session, which loop-claude names for the project and do-epic for the epic (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
"""The tmux commands an entry point runs: each chunk's loop runs in its own window of one tmux session, which build-release names for the project and do-epic for the epic (docs/decisions.md → `build-release: each chunk runs in its own tmux window`)."""
|
||||
import dataclasses
|
||||
import re
|
||||
import subprocess
|
||||
@@ -16,12 +16,12 @@ WAITS = " ?"
|
||||
BELL = "\a"
|
||||
# What follows a window's name while its chunk is parked, before what its pull request waits on, as in `ABC-34 awaits an approval`. A parked chunk takes no running slot (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
|
||||
PARKED = " awaits "
|
||||
# What a session's name opens with: LOOP for a project's chunks under loop-claude, EPIC for an epic's chunks under do-epic.
|
||||
# What a session's name opens with: LOOP for a project's chunks under build-release, EPIC for an epic's chunks under do-epic.
|
||||
LOOP = "loop"
|
||||
EPIC = "epic"
|
||||
# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name.
|
||||
OWNER = "@loop-root"
|
||||
# The window option that names the folder a window's chunk works in, so that loop-claude and every do-epic see the chunks a do-epic runs in a checkout.
|
||||
# The window option that names the folder a window's chunk works in, so that build-release and every do-epic see the chunks a do-epic runs in a checkout.
|
||||
ROOT = "@chunk-root"
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], comman
|
||||
return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}")
|
||||
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
|
||||
marked = run(["set-option", "-t", f"={window.session}:", OWNER, cwd]) if first and owned else None
|
||||
# A failure leaves the window unseen by loop-claude and by another epic's do-epic, which then may start a chunk beside it; the window still runs.
|
||||
# A failure leaves the window unseen by build-release and by another epic's do-epic, which then may start a chunk beside it; the window still runs.
|
||||
run(["set-option", "-w", "-t", done.stdout.strip(), ROOT, cwd])
|
||||
# By the ID, since a window of the same name may still be closing. A failed remain-on-exit doesn't matter: a loop that fails before it is set closes its window, and its stop is still sent as a DM.
|
||||
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
|
||||
|
||||
@@ -14,7 +14,7 @@ from agent_cycle.stuck_workers import Watch
|
||||
PRINTED_TOOL_INPUT = 160
|
||||
# Seconds between reads of the machine's memory while too little of it is available to start a worker.
|
||||
MEMORY_POLL = 60
|
||||
# The auto-compact window, in tokens, handed to the worker's claude in the environment variable AUTO_COMPACT_WINDOW names. Claude Code compacts before the window fills, at about 170k: docs/decisions.md → `loop-claude: the worker's claude compacts its context before it fills a 200k window`.
|
||||
# The auto-compact window, in tokens, handed to the worker's claude in the environment variable AUTO_COMPACT_WINDOW names. Claude Code compacts before the window fills, at about 170k: docs/decisions.md → `build-release: the worker's claude compacts its context before it fills a 200k window`.
|
||||
AUTO_COMPACT_WINDOW = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
|
||||
COMPACT_WINDOW = 200_000
|
||||
|
||||
@@ -76,7 +76,7 @@ def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure
|
||||
|
||||
|
||||
def worker_args(session: Session, worker: Rung, prompt: str, resume: bool) -> list[str]:
|
||||
# --session-id creates the session under the id loop-claude keeps; --resume continues that session.
|
||||
# --session-id creates the session under the id build-release keeps; --resume continues that session.
|
||||
start = ["--resume", str(session.id)] if resume else ["--name", session.name, "--session-id", str(session.id)]
|
||||
# -p fails without --verbose under stream-json.
|
||||
return [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""A worker's prompts: those the entry point driving the cycle words, and those that resume a worker with an answer to its question.
|
||||
|
||||
An entry point is a tool that drives cycles, such as loop-claude. It words the prompts of its own workflow and names the files of its project. WorkerPrompts holds those, so the cycle doesn't import an entry point to word a prompt.
|
||||
An entry point is a tool that drives cycles, such as build-release. It words the prompts of its own workflow and names the files of its project. WorkerPrompts holds those, so the cycle doesn't import an entry point to word a prompt.
|
||||
"""
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
@@ -7,7 +7,7 @@ LAUNCHER = pathlib.Path(__file__).resolve()
|
||||
sys.path.insert(0, str(LAUNCHER.parent))
|
||||
|
||||
from loop_effects import effects
|
||||
from loop_claude.loop import main
|
||||
from build_release.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(pathlib.Path.home(), os.environ)))
|
||||
@@ -0,0 +1,4 @@
|
||||
"""build-release: 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: 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/. build-release'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.
|
||||
"""
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The plan items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as the plan scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
|
||||
"""The plan items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as the plan scores them (docs/decisions.md → `routing: build-release reads the items a chunk takes`)."""
|
||||
import re
|
||||
|
||||
from claude_code.entries import AssistantTurn, Entry, Text
|
||||
@@ -25,7 +25,7 @@ def taken_in(entries: list[Entry], plan: Plan | Failure) -> TakenIn:
|
||||
|
||||
|
||||
def named(entries: list[Entry]) -> tuple[int, ...]:
|
||||
"""The IDs on the worker's latest Chunk items: line, each once, in its order; empty where it wrote none. Only the worker's own text counts: a loop-claude prompt quotes the line's example, and a tool call may write the label into a file."""
|
||||
"""The IDs on the worker's latest Chunk items: line, each once, in its order; empty where it wrote none. Only the worker's own text counts: a build-release prompt quotes the line's example, and a tool call may write the label into a file."""
|
||||
lines = [line for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, Text) for line in part.text.splitlines()]
|
||||
for line in reversed(lines):
|
||||
if found := LINE.match(plain(line)):
|
||||
@@ -1,15 +1,15 @@
|
||||
"""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."""
|
||||
"""What build-release 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 build_release.chunk.chunk_items import CHUNK_ITEMS
|
||||
from chunk_driver.drivers import BUILD_RELEASE
|
||||
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`).
|
||||
# build-release'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 = BUILD_RELEASE
|
||||
# chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: build-release 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 (the setup\'s CLAUDE.md → "Shared goal") unless the goals file voids it'
|
||||
@@ -36,7 +36,7 @@ def recount(route: Route) -> str:
|
||||
|
||||
def preflight_facts(printed: str) -> str:
|
||||
"""What chunk-preflight printed, for the worker to take as found."""
|
||||
return f"loop-claude ran `chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}"
|
||||
return f"build-release ran `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:
|
||||
@@ -46,7 +46,7 @@ def held_by_others(items: list[int]) -> str:
|
||||
|
||||
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 `chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
|
||||
return f"build-release could not run `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)
|
||||
+2
-2
@@ -5,10 +5,10 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from loop_claude.chunk import chunk_items
|
||||
from build_release.chunk import chunk_items
|
||||
from claude_code import entries
|
||||
from failure import Failure
|
||||
from loop_claude.chunk import fresh_prompt
|
||||
from build_release.chunk import fresh_prompt
|
||||
from plan_store.todo_md import plan_of
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
+5
-5
@@ -4,24 +4,24 @@ 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 build_release.chunk import fresh_prompt
|
||||
from build_release.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."""
|
||||
"""build-release'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)
|
||||
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\nbuild-release 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)
|
||||
self.assertNotIn("build-release 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)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Test doubles for loop-claude's suites: the shipped ladder's opus project, a plan and its release standing."""
|
||||
"""Test doubles for build-release'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
|
||||
@@ -1,17 +1,17 @@
|
||||
"""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."""
|
||||
"""How build-release'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
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.chunk import fresh_prompt
|
||||
from loop_claude.loop.chunk_windows import held_beside, item_of
|
||||
from build_release.chunk import fresh_prompt
|
||||
from build_release.loop.chunk_windows import held_beside, item_of
|
||||
from chunk_preflight.main import ITEM
|
||||
from plan.todo_table import Item
|
||||
from project_config.main import located
|
||||
from chunk_driver.this_loop import Loop
|
||||
from plan_store.plans import Plan
|
||||
from loop_claude.routed_item import routed_item
|
||||
from build_release.routed_item import routed_item
|
||||
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.
|
||||
@@ -54,7 +54,7 @@ def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure:
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk: the one its window is named for, or else release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
# It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
|
||||
# It prints the reason itself, through effects, like the other build-release functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
else:
|
||||
@@ -1,4 +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`)."""
|
||||
"""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 → `build-release: each chunk runs in its own tmux window`)."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
@@ -6,12 +6,12 @@ import typing
|
||||
|
||||
from touch_predictions.beside import Beside, chunks_beside
|
||||
from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_session, project_lock, starting
|
||||
from loop_claude.chunk import chunk_items
|
||||
from build_release.chunk import chunk_items
|
||||
from git_cli.git_repo import default_ref
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from build_release.loop.reload import LoopRun
|
||||
from release_plan.next_chunk import NextChunk, NoItem, planned
|
||||
from plan.touches import overlaps, predicted, Touches
|
||||
from loop_state.paths import Paths
|
||||
@@ -39,7 +39,7 @@ def item_of(chunk: str) -> int | None:
|
||||
|
||||
def chunk_session(key: str, chunk: str, claude_code_transcripts: pathlib.Path) -> Session:
|
||||
"""The worker's session for a chunk. A rerun finds a chunk left open by this name. "A " is the human's cue in the session picker that the session is the loop's."""
|
||||
return session_named(f"A {key} loop-claude {chunk}", claude_code_transcripts)
|
||||
return session_named(f"A {key} build-release {chunk}", claude_code_transcripts)
|
||||
|
||||
|
||||
def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]:
|
||||
@@ -67,7 +67,7 @@ class Room:
|
||||
|
||||
|
||||
def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: int) -> Room:
|
||||
"""The room windows leave under limit. own is the chunk of the loop that asks, None for the human's loop-claude <task>. leaving is True where own's chunk finished: its window no longer counts as running, and no stopped chunk starts again, since only a loop that isn't leaving, such as the human's loop-claude <task>, restarts one."""
|
||||
"""The room windows leave under limit. own is the chunk of the loop that asks, None for the human's build-release <task>. leaving is True where own's chunk finished: its window no longer counts as running, and no stopped chunk starts again, since only a loop that isn't leaving, such as the human's build-release <task>, restarts one."""
|
||||
running = [window.name for window in windows if not window.dead and not (leaving and window.name == own)]
|
||||
# Below 0 where the config lowered parallel-chunks while more chunks ran.
|
||||
room = max(limit - len(running), 0)
|
||||
@@ -115,7 +115,7 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | No
|
||||
|
||||
|
||||
def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | AwaitedMerges | Failure:
|
||||
"""Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. AwaitedMerges where chunks_to_start returns it. A Failure says why no chunk may start, or why one could not; those before it run."""
|
||||
"""Starts a build-release in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started build-release. AwaitedMerges where chunks_to_start returns it. A Failure says why no chunk may start, or why one could not; those before it run."""
|
||||
config = located(loop_run.root, paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
@@ -143,7 +143,7 @@ def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux)
|
||||
if windows and (owned := tmux.owner(session, run)) != root:
|
||||
return Failure(f"the tmux session {session} runs the chunks of {owned or 'another checkout'}, whose key maps to the same session name; rename one of the two checkouts' folders")
|
||||
if theirs := epic_chunks(root, run):
|
||||
return Failure(f"do-epic runs chunks in {root}: {', '.join(f'{placed.window.name} of {placed.session}' for placed in theirs)}; loop-claude doesn't start a chunk there until those chunks finish")
|
||||
return Failure(f"do-epic runs chunks in {root}: {', '.join(f'{placed.window.name} of {placed.session}' for placed in theirs)}; build-release doesn't start a chunk there until those chunks finish")
|
||||
return None
|
||||
|
||||
|
||||
@@ -4,19 +4,19 @@ 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_windows import AwaitedMerges, chunk_session, item_of, start_chunks
|
||||
from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.loop.checkout import checkout_root
|
||||
from build_release.loop.chunk_windows import AwaitedMerges, chunk_session, item_of, start_chunks
|
||||
from build_release.loop.routing_check import check_routing
|
||||
from build_release.loop.checkout import checkout_root
|
||||
from chunk_driver.claims import CHUNK_FLAG, loop_session
|
||||
from loop_claude.chunk import chunk_items, fresh_prompt
|
||||
from loop_claude.loop.chunk_start import chunk_start, plan_item, scored_plan
|
||||
from build_release.chunk import chunk_items, fresh_prompt
|
||||
from build_release.loop.chunk_start import chunk_start, plan_item, scored_plan
|
||||
from chunk_driver.chunk_run import closed_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 build_release.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.loop.usage import HELP
|
||||
from build_release.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
|
||||
@@ -57,13 +57,13 @@ def exit_code(run: typing.Callable[[], Stop], cwd: pathlib.Path, effects: Effect
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
except Exception as crash:
|
||||
tell(f"loop-claude in {cwd} crashed: {crash!r}", effects)
|
||||
tell(f"build-release in {cwd} crashed: {crash!r}", effects)
|
||||
raise
|
||||
if stop.reason:
|
||||
say(stop.reason, effects, stdout=not stop.code)
|
||||
# Every stop with a reason, but the help, is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help. Ctrl-C stops without a reason. So does the loop that started the project's windows once it attaches or prints how to, and a loop whose chunk finished once it started the next chunks, since the project's chunks go on.
|
||||
if stop.reason not in ("", HELP):
|
||||
tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects)
|
||||
tell(f"build-release in {cwd} stopped: {stop.reason}", effects)
|
||||
return stop.code
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
return windows_opened(loop_run, env, paths, launcher, effects, steps.start_chunks)
|
||||
pane = env.get("TMUX_PANE")
|
||||
if not pane:
|
||||
return Stop(1, f"{CHUNK_FLAG} is how loop-claude starts itself in a tmux window; run loop-claude <task>")
|
||||
return Stop(1, f"{CHUNK_FLAG} is how build-release starts itself in a tmux window; run build-release <task>")
|
||||
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)
|
||||
@@ -105,7 +105,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
|
||||
|
||||
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."""
|
||||
"""What the build-release 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, AwaitedMerges):
|
||||
return Stop(0, started.why)
|
||||
@@ -154,7 +154,7 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
|
||||
|
||||
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
|
||||
"""What a cycle says of a project that runs on a ladder of its own, so that a file left in place after its reason passed doesn't go unseen, nor one that leaves out the project's model, whose work the ladder then doesn't route."""
|
||||
routes = f" {model} is not on it, so the worker runs on {model} unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run." if unrouted else ""
|
||||
routes = f" {model} is not on it, so the worker runs on {model} unrouted; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run." if unrouted else ""
|
||||
return f"routing on the project's own ladder, {file}.{routes}"
|
||||
|
||||
|
||||
@@ -168,5 +168,5 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task, "", chunk=chunk)
|
||||
loop_run = decode_handed(argv[1]) if len(argv) == 2 else None
|
||||
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 <task>. Handed: {' '.join(argv[1:])}")
|
||||
return Stop(1, f"the edited build-release cannot read the state the running one handed it, likely because the edit changed that handover; rerun build-release <task>. Handed: {' '.join(argv[1:])}")
|
||||
return loop_run
|
||||
@@ -25,7 +25,7 @@ class LoopRun:
|
||||
route: Route | None = None
|
||||
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
|
||||
unfinished_run: int = 0
|
||||
# The chunk this loop runs in its tmux window, as chunk_windows names it: `item-372`, or `no-item`. None for the loop-claude the human started, which starts the windows; a loop started before chunks ran in windows reloads with None too, and so starts the project's windows; its open claude session, named for its slot, is left in the session picker (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window, …`).
|
||||
# The chunk this loop runs in its tmux window, as chunk_windows names it: `item-372`, or `no-item`. None for the build-release the human started, which starts the windows; a loop started before chunks ran in windows reloads with None too, and so starts the project's windows; its open claude session, named for its slot, is left in the session picker (docs/decisions.md → `build-release: each chunk runs in its own tmux window, …`).
|
||||
chunk: str | None = None
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ def fingerprint(launcher: pathlib.Path) -> str:
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
# A loop runs unattended for hours, often on its own checkout: reloading puts each edit to loop-claude to use without the human rerunning it.
|
||||
# A loop runs unattended for hours, often on its own checkout: reloading puts each edit to build-release to use without the human rerunning it.
|
||||
def exec_if_edited(loop: Loop, baseline: str, loop_run: LoopRun) -> Stop | None:
|
||||
if fingerprint(loop.launcher) == baseline:
|
||||
return None
|
||||
@@ -104,5 +104,5 @@ def exec_if_edited(loop: Loop, baseline: str, loop_run: LoopRun) -> Stop | None:
|
||||
try:
|
||||
loop.effects.execv(sys.executable, [sys.executable, str(loop.launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
|
||||
except OSError as failure:
|
||||
return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude <task>")
|
||||
return Stop(1, f"could not reload build-release: {failure.strerror}; rerun build-release <task>")
|
||||
return None
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing: loop-claude measures review rounds…`."""
|
||||
"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing: build-release measures review rounds…`."""
|
||||
import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
@@ -38,7 +38,7 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
|
||||
raised = state.raised(root)
|
||||
if isinstance(raised, Failure):
|
||||
return raised
|
||||
say(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", effects, stdout=True)
|
||||
say(f"\n=== cycle {cycle} across build-release's archive: measuring the routing figures ===", effects, stdout=True)
|
||||
measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
@@ -56,13 +56,13 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
|
||||
def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
bullets = "".join(f"- {call.sentence()}\n" for call in new)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
|
||||
question = f"build-release's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
|
||||
say(f"\n{question}", loop.effects)
|
||||
tell(f"loop-claude in {loop.root} asks:\n\n{question}", loop.effects)
|
||||
tell(f"build-release in {loop.root} asks:\n\n{question}", loop.effects)
|
||||
if not loop.effects.on_terminal():
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", loop.effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and don't change anything until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as the setup's CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
prompt = f"Put these calls for a routing change from build-release's figures to the human, and don't change anything until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as the setup's CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects)
|
||||
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}")
|
||||
+7
-7
@@ -9,13 +9,13 @@ import unittest
|
||||
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, chunk_windows, reload
|
||||
from build_release.loop import chunk_start, chunk_windows, reload
|
||||
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 build_release.chunk import fresh_prompt
|
||||
from build_release.doubles import NO_CUT, TODO
|
||||
from loop_state import paths
|
||||
from plan_store.todo_md import plan_of
|
||||
from claude_code import session
|
||||
@@ -43,7 +43,7 @@ class RouteSources(unittest.TestCase):
|
||||
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"))
|
||||
opened = session.session_named("A proj build-release", pathlib.Path(root, "projects"))
|
||||
transcript = pathlib.Path(root, "projects", "-fake", f"{opened.id}.jsonl")
|
||||
transcript.parent.mkdir(parents=True)
|
||||
transcript.write_text("{}\n")
|
||||
@@ -121,7 +121,7 @@ class RouteSources(unittest.TestCase):
|
||||
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")
|
||||
self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review build-release cannot call due is never skipped silently")
|
||||
quiet = a_loop(FakeEffects(git=[*ON_MAIN, 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)
|
||||
@@ -135,7 +135,7 @@ class RouteSources(unittest.TestCase):
|
||||
|
||||
class ChunkFacts(unittest.TestCase):
|
||||
# The launcher beside which chunk_start finds /b/chunk-preflight.
|
||||
LAUNCHER = pathlib.Path("/b/loop-claude")
|
||||
LAUNCHER = pathlib.Path("/b/build-release")
|
||||
|
||||
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
|
||||
fake = FakeEffects(python=[ran("- A fact.\n")])
|
||||
@@ -170,7 +170,7 @@ class ChunkFacts(unittest.TestCase):
|
||||
|
||||
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"))
|
||||
opened = session.session_named("A proj build-release", 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))
|
||||
+11
-11
@@ -11,12 +11,12 @@ import unittest
|
||||
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 build_release.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 build_release.loop import main
|
||||
from release_plan import next_chunk
|
||||
from loop_state import paths
|
||||
from agent_cycle import tmux
|
||||
@@ -112,7 +112,7 @@ class ChunkWindows(unittest.TestCase):
|
||||
|
||||
class StartChunks(unittest.TestCase):
|
||||
"""start_chunks: the windows a loop opens for the chunks that may start now."""
|
||||
LAUNCHER = pathlib.Path("/b/loop-claude")
|
||||
LAUNCHER = pathlib.Path("/b/build-release")
|
||||
|
||||
def setUp(self):
|
||||
made = tempfile.TemporaryDirectory()
|
||||
@@ -163,12 +163,12 @@ class StartChunks(unittest.TestCase):
|
||||
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.start(fake, env={"BUILD_RELEASE_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"])
|
||||
# Only build-release'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], ["BUILD_RELEASE_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)
|
||||
@@ -183,7 +183,7 @@ class StartChunks(unittest.TestCase):
|
||||
|
||||
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.start(fake), Failure(f"do-epic runs chunks in {self.root}: ABC-34 of epic-ABC-12; build-release 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):
|
||||
@@ -215,7 +215,7 @@ class StartChunks(unittest.TestCase):
|
||||
# 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):
|
||||
def test_the_humans_build_release_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)
|
||||
@@ -256,7 +256,7 @@ class StartChunks(unittest.TestCase):
|
||||
|
||||
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("")
|
||||
(self.home / ".local" / "state" / "build-release").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)
|
||||
@@ -267,7 +267,7 @@ class StartChunks(unittest.TestCase):
|
||||
|
||||
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("")
|
||||
(self.home / ".local" / "state" / "build-release").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])
|
||||
|
||||
@@ -275,7 +275,7 @@ class StartChunks(unittest.TestCase):
|
||||
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")
|
||||
self.assertEqual(opened.name, "A proj build-release 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)"})]
|
||||
@@ -11,11 +11,11 @@ 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_windows, main, reload, usage
|
||||
from build_release.loop import chunk_windows, main, reload, usage
|
||||
from loop_effects.doubles import CWD, FakeEffects, ran, STAMP
|
||||
from failure import Failure
|
||||
from agent_cycle.verdicts import Finished, Unfinished
|
||||
from loop_claude.doubles import OPUS_PROJECT
|
||||
from build_release.doubles import OPUS_PROJECT
|
||||
from loop_state import paths
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
@@ -29,7 +29,7 @@ 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 <task>. Handed: {' '.join(handed)}"))
|
||||
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited build-release cannot read the state the running one handed it, likely because the edit changed that handover; rerun build-release <task>. 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)
|
||||
@@ -102,10 +102,10 @@ class LoopRuns(unittest.TestCase):
|
||||
|
||||
def test_stops_when_the_reload_cannot_start_python(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
launcher = pathlib.Path(root, "loop-claude")
|
||||
launcher = pathlib.Path(root, "build-release")
|
||||
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 <task>"))
|
||||
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 build-release: No such file or directory; rerun build-release <task>"))
|
||||
|
||||
|
||||
def steps(start_chunks, **others):
|
||||
@@ -117,7 +117,7 @@ def steps(start_chunks, **others):
|
||||
|
||||
|
||||
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."""
|
||||
"""The build-release 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")):
|
||||
@@ -129,12 +129,12 @@ class WindowStarts(unittest.TestCase):
|
||||
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))
|
||||
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/build-release"), CWD, fake.effects(), steps(start))
|
||||
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(self.run_loop(["do it"], fake), (Stop(1, "build-release 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):
|
||||
@@ -153,7 +153,7 @@ 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")
|
||||
effects, env, launcher = fake.effects(), {"BUILD_RELEASE_X": "1"}, pathlib.Path("/b/build-release")
|
||||
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"]))
|
||||
@@ -162,7 +162,7 @@ class WindowStarts(unittest.TestCase):
|
||||
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")
|
||||
launcher = pathlib.Path("/b/build-release")
|
||||
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))
|
||||
@@ -172,7 +172,7 @@ class WindowStarts(unittest.TestCase):
|
||||
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)
|
||||
loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release 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(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)])
|
||||
@@ -180,7 +180,7 @@ class WindowStarts(unittest.TestCase):
|
||||
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)
|
||||
effects, launcher, home = fake.effects(), pathlib.Path("/b/build-release"), 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}
|
||||
@@ -189,27 +189,27 @@ class WindowStarts(unittest.TestCase):
|
||||
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)
|
||||
self.loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release 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"}
|
||||
env = {"TMUX_PANE": "%4", "BUILD_RELEASE_TRANSCRIPTS": "/t"}
|
||||
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))
|
||||
self.assertEqual(calls, [
|
||||
("fingerprint", pathlib.Path("/b/loop-claude")),
|
||||
("fingerprint", pathlib.Path("/b/build-release")),
|
||||
("exec_if_edited", self.loop, "print-1", before),
|
||||
("next_cycle", first, self.loop),
|
||||
("run_cycle", on_ladder),
|
||||
("closed_cycle", first, "the cycle's task", 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"), "build-release", 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, "the cycle's task", 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"), "build-release", 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),
|
||||
@@ -246,12 +246,12 @@ class WindowStarts(unittest.TestCase):
|
||||
fake = FakeEffects(git=["/r\n"])
|
||||
effects = dataclasses.replace(fake.effects(), tmux_on_terminal=lambda args: 1)
|
||||
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"]))
|
||||
stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/build-release"), 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):
|
||||
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 <task>"))
|
||||
self.assertEqual(self.run_loop(["--chunk", "item-3", "do it"], fake)[0], Stop(1, "--chunk is how build-release starts itself in a tmux window; run build-release <task>"))
|
||||
self.assertEqual(self.asked, [])
|
||||
|
||||
def test_reads_the_chunk_a_window_loop_is_started_with(self):
|
||||
@@ -264,7 +264,7 @@ class WindowStarts(unittest.TestCase):
|
||||
(Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan")),
|
||||
(chunk_windows.AwaitedMerges("#7 awaits a merge."), "", Stop(0, "the chunk finished; #7 awaits a merge."))):
|
||||
with self.subTest(started=started), contextlib.redirect_stdout(io.StringIO()) as printed:
|
||||
loop, asked = a_loop(FakeEffects().effects(), env={"LOOP_CLAUDE_X": "1"}), []
|
||||
loop, asked = a_loop(FakeEffects().effects(), env={"BUILD_RELEASE_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(asked, [(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)])
|
||||
@@ -273,7 +273,7 @@ class WindowStarts(unittest.TestCase):
|
||||
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())
|
||||
code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "build-release"), CWD, fake.effects())
|
||||
return code, said.getvalue()
|
||||
|
||||
def exit_code(self, run, fake):
|
||||
@@ -287,7 +287,7 @@ class StopDms(unittest.TestCase):
|
||||
def test_dms_the_reason_of_a_stop_with_exit_2_such_as_a_chunk_left_unfinished_too_often(self):
|
||||
fake = FakeEffects()
|
||||
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"])
|
||||
self.assertEqual(fake.dms, [f"build-release 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()
|
||||
@@ -303,13 +303,13 @@ class StopDms(unittest.TestCase):
|
||||
fake = FakeEffects()
|
||||
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')"])
|
||||
self.assertEqual(fake.dms, [f"build-release 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 <task>. Handed: 3"])
|
||||
self.assertEqual(fake.dms, [f"build-release in {CWD} stopped: the edited build-release cannot read the state the running one handed it, likely because the edit changed that handover; rerun build-release <task>. 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")])
|
||||
@@ -327,7 +327,7 @@ 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.")
|
||||
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; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
+3
-3
@@ -17,7 +17,7 @@ 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 build_release.loop import routing_check
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code import session
|
||||
from agent_cycle.stop import Stop
|
||||
@@ -34,7 +34,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
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)
|
||||
self.session = session.session_named("A log build-release", self.paths.claude_code_transcripts)
|
||||
|
||||
def loop(self, fake):
|
||||
"""The loop in /code/log."""
|
||||
@@ -148,7 +148,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", 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)
|
||||
self.assertTrue(sent.startswith(f"build-release in {self.loop(fake).root} asks:\n\nbuild-release's routing figures call for a routing change:\n- {new[0].sentence()}\n"), sent)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -8,7 +8,7 @@ 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 build_release.loop import main, usage
|
||||
from loop_effects.effects import PYTHON_TIMEOUT
|
||||
from chunk_driver.project import records
|
||||
from claude_code import reply
|
||||
@@ -60,22 +60,22 @@ class ExitContract(unittest.TestCase):
|
||||
("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", "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"),
|
||||
("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"),
|
||||
("build_release/loop/checkout.py", "checkout_root", "1", "found.reason", git),
|
||||
("build_release/loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
|
||||
("build_release/loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how build-release starts itself", "--chunk is given outside a tmux window"),
|
||||
("build_release/loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
|
||||
("build_release/loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
|
||||
("build_release/loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"),
|
||||
("build_release/loop/main.py", "next_cycle", "1", "premises.reason", premises_),
|
||||
("build_release/loop/main.py", "next_cycle", "1", "records.reason", unreadable),
|
||||
("build_release/loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
|
||||
("build_release/loop/main.py", "loop_run_from", "1", 'f"the edited build-release cannot read the state', "a reload cannot read the state the running script handed it"),
|
||||
("build_release/loop/reload.py", "exec_if_edited", "1", "f'could not reload build-release:", "python cannot start for a reload"),
|
||||
("build_release/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_")):
|
||||
for path in sorted(path for package in ("agent_cycle", "chunk_driver", "build_release") 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)]
|
||||
@@ -1,6 +1,6 @@
|
||||
HELP = """Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
usage: loop-claude <task>
|
||||
usage: build-release <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose goals file has ## Goals and ## Audience, the
|
||||
premises. The goals file is the one the project's config, ~/.claude-projects/<key>/config.toml, sets
|
||||
@@ -16,7 +16,7 @@ finished. A chunk stays unfinished until each answer the human typed in it that
|
||||
need is recorded: the premises or the records hold it, or the transcript shows the worker writing it
|
||||
into the premises, AGENTS.md, docs/decisions.md, the plan or a comment. A choice the worker made
|
||||
that the premises or the records settle is not asked about. When the worker asks a question they
|
||||
answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A quote
|
||||
answer, the judge quotes the answer, build-release prints it, and the worker resumes with it. A quote
|
||||
they do not hold word for word is dropped, and the question goes to the human. So does a question
|
||||
asked again after its answer. A question the human answered earlier in the chunk goes back to the
|
||||
worker with that answer, unless the question quotes the words of the answer that leave it open. The
|
||||
@@ -26,11 +26,11 @@ remaining. The next chunk starts a fresh session. Cycles continue until an exit
|
||||
either of which stops that one chunk.
|
||||
Words: the setup's CLAUDE.md → "Vocabulary".
|
||||
|
||||
loop-claude needs tmux 3.2 or later, and checks it before it starts anything. Each chunk runs in its
|
||||
build-release needs tmux 3.2 or later, and checks it before it starts anything. Each chunk runs in its
|
||||
own window of one tmux session per project, named loop-<key>, such as loop-claude-config. <key> is
|
||||
the checkout's path relative to ~/code, or to / outside it, with a dash for each character other
|
||||
than a letter, a digit, _ or -. The tmux session's @loop-root option names its checkout, and a
|
||||
checkout whose key maps to a tmux session another checkout runs is refused. loop-claude <task>
|
||||
checkout whose key maps to a tmux session another checkout runs is refused. build-release <task>
|
||||
starts the chunks that may start now, then attaches to the tmux session, or switches to it inside
|
||||
tmux; detaching leaves the chunks running. Off a terminal it prints the command that attaches. Where
|
||||
no chunk may start, it says so, and the task starts in no new window. At most parallel-chunks chunks
|
||||
@@ -40,17 +40,17 @@ before it nor an item another chunk holds (touch-predictions --help). A window i
|
||||
its chunk starts from, as item-372; a chunk without a plan item, such as planning a release or its
|
||||
release review, runs alone in the window no-item.
|
||||
|
||||
Each window runs a loop-claude for that one chunk, started with --chunk <window>, which nobody
|
||||
Each window runs a build-release for that one chunk, started with --chunk <window>, which nobody
|
||||
types. As a chunk finishes, its loop starts each chunk that may start then, with the task it ran
|
||||
itself, and exits, which closes its window. A loop that stops, by Ctrl-C, an exit below or a
|
||||
failure, keeps its window, with its last lines, and its chunk keeps its items; the next loop-claude
|
||||
failure, keeps its window, with its last lines, and its chunk keeps its items; the next build-release
|
||||
<task> starts it again before any other. To stop every chunk, press Ctrl-C in each window. A chunk's
|
||||
claude session is named "A <key> loop-claude <window>", so a rerun resumes a chunk left open, and is
|
||||
claude session is named "A <key> build-release <window>", so a rerun resumes a chunk left open, and is
|
||||
deleted when the chunk finishes. A fresh worker is told the items the project's other chunks hold,
|
||||
running or stopped: each one's own and those on its latest `Chunk items:` line, and leaves them out.
|
||||
|
||||
A question only the human can answer is an interrupt (bin/agent_cycle/interrupt.py).
|
||||
loop-claude prints the question in the chunk's window and rings its bell. Until it is answered the
|
||||
build-release prints the question in the chunk's window and rings its bell. Until it is answered the
|
||||
window's name ends in " ?", as in "item-372 ?", which tmux's status bar shows. The human answers it
|
||||
there:
|
||||
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
||||
@@ -60,46 +60,46 @@ there:
|
||||
- Enter alone: stops the loop.
|
||||
A release ready to cut opens that claude session on the terminal at once, since only the human may
|
||||
cut it. While claude is open, Ctrl-C reaches it alone, and the loop goes on. Where the project's
|
||||
config sets notifier, loop-claude also sends the human each question, naming its tmux window as
|
||||
config sets notifier, build-release also sends the human each question, naming its tmux window as
|
||||
<session>:<window>, each release ready to cut and each stop as a DM, as bin/notify sends it. Four
|
||||
stops are left out: Ctrl-C, printing this help, the loop-claude that started the windows once it
|
||||
stops are left out: Ctrl-C, printing this help, the build-release that started the windows once it
|
||||
attaches or prints how to, and a loop whose chunk finished once it started the next chunks. A DM
|
||||
that fails is said on stderr, and the loop goes on. Where no answer has come 10 minutes before the
|
||||
worker's hour-long prompt cache expires, and the worker's context holds at least 60k tokens,
|
||||
loop-claude compacts the worker's session with `claude -p /compact` and keeps waiting, so the resume
|
||||
build-release compacts the worker's session with `claude -p /compact` and keeps waiting, so the resume
|
||||
doesn't write the whole context again.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree, adding
|
||||
As a chunk starts, before it is routed, build-release runs bin/chunk-preflight --worktree, adding
|
||||
--item <ID> in a window named for an item, and quotes what it prints in the first prompt
|
||||
(preflight_facts in bin/loop_claude/chunk/fresh_prompt.py); chunk-preflight --help says what it
|
||||
(preflight_facts in bin/build_release/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.
|
||||
|
||||
At every interrupt, and as every cycle ends, Ctrl-C and a failure included, the claude session's
|
||||
transcript is copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
transcript is copied into a folder per chunk under $BUILD_RELEASE_TRANSCRIPTS/<key> (default root
|
||||
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
||||
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
||||
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
||||
|
||||
A worker's claude can print its final result and then keep waiting on a background shell that
|
||||
never ends. Every 5 minutes without output from that claude after its final result, loop-claude
|
||||
never ends. Every 5 minutes without output from that claude after its final result, build-release
|
||||
stops each of its shells and what runs below them, unless a shell has written output in the last 3
|
||||
minutes, runs chunk-pr or run-heavy, or holds a heavy slot. It prints each stop and appends it, with
|
||||
the UTC time, to lingering-workers.md at the project's folder in that archive
|
||||
(bin/agent_cycle/lingering_workers.py).
|
||||
|
||||
A worker can also stall before its result, on a command that hangs. Every 5 minutes without output
|
||||
from its claude, loop-claude looks for a shell that may be stuck: one that used no CPU since the
|
||||
from its claude, build-release looks for a shell that may be stuck: one that used no CPU since the
|
||||
last check and wrote no output for 3 minutes, or one that has run over 4 hours. A shell that runs
|
||||
chunk-pr or run-heavy doesn't count, but one that holds a heavy slot can. Where such a shell is
|
||||
found, a headless claude on the project's rung reads every shell's command, processes and output.
|
||||
The headless claude judges the worker working, waiting on a person or stuck, and names the process
|
||||
the worker waits on. It judges a shell again only after the shell used CPU and went idle once more.
|
||||
loop-claude prints the verdict and the shells that showed a sign, and appends them to
|
||||
build-release prints the verdict and the shells that showed a sign, and appends them to
|
||||
stuck-workers.md beside lingering-workers.md. It doesn't kill anything yet
|
||||
(bin/agent_cycle/stuck_workers.py).
|
||||
|
||||
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is
|
||||
Before each worker starts, build-release waits until at least a quarter of the machine's memory is
|
||||
available (bin/machine_load/memory.py).
|
||||
|
||||
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
|
||||
@@ -108,11 +108,11 @@ compacts its context at about 170k tokens. They also save a Bash result of more
|
||||
characters to a file and see its path and the first 2,000 characters (BASH_MAX_OUTPUT_LENGTH,
|
||||
bin/claude_code/output_limits.py).
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
Every claude build-release starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the session /talk opens and the judge on another rung, a model at an effort. A project without an
|
||||
entry, as on its first run, is asked for one on the terminal. LOOP_CLAUDE_JUDGE_MODEL overrides
|
||||
the model for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with
|
||||
entry, as on its first run, is asked for one on the terminal. BUILD_RELEASE_JUDGE_MODEL overrides
|
||||
the model for the judge, BUILD_RELEASE_WORKER_MODEL for the worker and the session /talk opens; with
|
||||
both set, nothing is asked.
|
||||
|
||||
The routing ladder is a list of rungs, least competent first, each a model at an effort. Where the
|
||||
@@ -124,7 +124,7 @@ 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/chunk/fresh_prompt.py, bin/chunk_driver/prompts.py and
|
||||
bin/build_release/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
|
||||
@@ -142,7 +142,7 @@ or max:
|
||||
It holds one model of each family, such as opus, since the Agent tool launches a subagent or a
|
||||
review by its family's name. This setup ships one, bin/model_routing/routing-ladder.json. A project
|
||||
that keeps a routing-ladder.json in its config's folder, ~/.claude-projects/<key>/, runs on that
|
||||
ladder instead, whole: write there every rung the project may run on. loop-claude reads the
|
||||
ladder instead, whole: write there every rung the project may run on. build-release reads the
|
||||
project's ladder as each cycle starts, says on stderr where the project runs on its own, and never
|
||||
commits the file. subagent-rung and rule-hook read the same ladder; the routing figures,
|
||||
judge-replay and review-replay, which span every project, read the shipped one.
|
||||
@@ -157,12 +157,12 @@ routing-calls-raised.md beside the figures, kept in routing-state.json, and not
|
||||
terminal, the calls are said on stderr, the loop goes on, and they are raised again at the next
|
||||
measurement.
|
||||
|
||||
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
A change to bin/build-release or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
build-release --help succeeds: the loop reloads into the edited script.
|
||||
|
||||
Under merge = "human", where no chunk runs and every item left awaits a person's merge, loop-claude
|
||||
Under merge = "human", where no chunk runs and every item left awaits a person's merge, build-release
|
||||
doesn't start a chunk: it names those pull requests, in a DM too, and exits 0. Its window closes,
|
||||
so the next loop-claude <task> reads the plan again.
|
||||
so the next build-release <task> reads the plan again.
|
||||
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
@@ -204,5 +204,5 @@ Exit 2, when the human is needed to go on:
|
||||
- the claude opened for /talk, or for a release ready to cut, ends without
|
||||
anything typed
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning loop-claude <task> starts the chunks that may start, a stopped one first, and each
|
||||
Rerunning build-release <task> starts the chunks that may start, a stopped one first, and each
|
||||
resumes its claude session where it is open."""
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The plan item that routes a fresh chunk of loop-claude's: agent_cycle/routing.py's first_route picks the worker's rung from its L."""
|
||||
"""The plan item that routes a fresh chunk of build-release's: agent_cycle/routing.py's first_route picks the worker's rung from its L."""
|
||||
from release_plan.release_standing import chunk_item, LastCut, Next
|
||||
from failure import Failure
|
||||
from plan.todo_table import Item, NoItemsTable
|
||||
@@ -49,7 +49,7 @@ else:
|
||||
"""
|
||||
|
||||
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
|
||||
# or none left, is Ctrl-C to loop-claude, which otherwise loops forever.
|
||||
# or none left, is Ctrl-C to build-release, which otherwise loops forever.
|
||||
FAKE_CLAUDE = """#!{python}
|
||||
import json, os, pathlib, signal, sys, time
|
||||
|
||||
@@ -120,7 +120,7 @@ elif role == "judge":
|
||||
print(step.get("stderr", ""), file=sys.stderr)
|
||||
else:
|
||||
if step.get("ctrl_c"):
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too. kill returns once the signal is pending in loop-claude, before this process exits and loop-claude stops waiting for it.
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground, build-release too. kill returns once the signal is pending in build-release, before this process exits and build-release stops waiting for it.
|
||||
os.kill(os.getppid(), signal.SIGINT)
|
||||
if "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
@@ -131,10 +131,10 @@ if step.get("vanish"):
|
||||
sys.exit(step.get("exit", 0))
|
||||
"""
|
||||
|
||||
# Records every start of loop-claude and turns its retry waits into log lines.
|
||||
# Records every start of build-release and turns its retry waits into log lines.
|
||||
SITECUSTOMIZE = """import json, os, sys, time
|
||||
|
||||
if os.path.basename(sys.argv[0]) == "loop-claude":
|
||||
if os.path.basename(sys.argv[0]) == "build-release":
|
||||
def record(event):
|
||||
with open(os.environ["LOOP_TEST_LOG"], "a") as log:
|
||||
log.write(json.dumps(event) + "\\n")
|
||||
@@ -161,7 +161,7 @@ TAKEN_IN_AT_L_4 = CHEAP + "| 9 | 0.1.0 | | **Do more.** | 4 | 1 | 2 | 5 | 2 | 1
|
||||
TAKEN_IN_AT_E_PLUS_I_6 = CHEAP + "| 9 | 0.1.0 | | **Do more.** | 2 | 3 | 3 | 6 | 2 | 1 by 9 | 20 |\n"
|
||||
|
||||
|
||||
# Waits for the interrupt's prompt before typing the answer, since loop-claude drops what was typed before it.
|
||||
# Waits for the interrupt's prompt before typing the answer, since build-release drops what was typed before it.
|
||||
ANSWERING = ("Answer (", lambda: None)
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ class Run:
|
||||
code: int
|
||||
sleeps: list
|
||||
starts: list
|
||||
# stderr and stdout are without the local time that opens each message loop-claude prints, and stderr without the bell an interrupt rings; raw_stderr and raw_stdout keep them.
|
||||
# stderr and stdout are without the local time that opens each message build-release prints, and stderr without the bell an interrupt rings; raw_stderr and raw_stdout keep them.
|
||||
stderr: str
|
||||
stdout: str
|
||||
# Each tmux command run, as its arguments.
|
||||
@@ -201,7 +201,7 @@ class Run:
|
||||
|
||||
|
||||
class Checkout:
|
||||
"""A temporary HOME with a git checkout at ~/code/proj, where loop-claude runs against the fake claude."""
|
||||
"""A temporary HOME with a git checkout at ~/code/proj, where build-release runs against the fake claude."""
|
||||
|
||||
def __init__(self, test):
|
||||
self.test = test
|
||||
@@ -213,7 +213,7 @@ class Checkout:
|
||||
self.root.mkdir(parents=True)
|
||||
(self.root / "README.md").write_text(PREMISES)
|
||||
write_config(self.home, self.root)
|
||||
self.script = BIN / "loop-claude"
|
||||
self.script = BIN / "build-release"
|
||||
self.env = isolated_env()
|
||||
fake = self.temp / "fake-bin"
|
||||
fake.mkdir()
|
||||
@@ -238,8 +238,8 @@ class Checkout:
|
||||
"GIT_CONFIG_GLOBAL": os.devnull,
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
"HOME": str(self.home),
|
||||
"LOOP_CLAUDE_JUDGE_MODEL": "judge-model",
|
||||
"LOOP_CLAUDE_WORKER_MODEL": "worker-model",
|
||||
"BUILD_RELEASE_JUDGE_MODEL": "judge-model",
|
||||
"BUILD_RELEASE_WORKER_MODEL": "worker-model",
|
||||
"LOOP_TEST_LOG": str(self.temp / "starts.jsonl"),
|
||||
"PATH": str(fake),
|
||||
"PYTHONPATH": str(site),
|
||||
@@ -256,7 +256,7 @@ class Checkout:
|
||||
self.git("commit", "--quiet", "-m", "plan")
|
||||
|
||||
def run(self, steps, argv=None, cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early="", chunk="no-item"):
|
||||
"""Runs loop-claude with argv, or without one as the loop of the window `chunk`, on TASK. Off a terminal, a window's loop whose chunk finished is run again while steps remain, as the window it starts for the next chunk would."""
|
||||
"""Runs build-release with argv, or without one as the loop of the window `chunk`, on TASK. Off a terminal, a window's loop whose chunk finished is run again while steps remain, as the window it starts for the next chunk would."""
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG", "FAKE_TMUX_LOG"):
|
||||
pathlib.Path(self.env[name]).unlink(missing_ok=True)
|
||||
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
|
||||
@@ -331,7 +331,7 @@ class Checkout:
|
||||
return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl"))
|
||||
|
||||
def archive(self):
|
||||
return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
|
||||
return pathlib.Path(self.env.get("BUILD_RELEASE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
|
||||
|
||||
def archived(self):
|
||||
"""Each archived transcript's outcomes, with every UTC stamp replaced by <UTC> and every setup version by <config>, after checking the copy is named by its content hash."""
|
||||
@@ -364,7 +364,7 @@ def argument(call, flag):
|
||||
class Premises(unittest.TestCase):
|
||||
def test_refuses_to_start_without_a_task_a_checkout_or_premises(self):
|
||||
checkout = Checkout(self)
|
||||
for argv, code, said in (([], 1, "usage: loop-claude <task>"), (["--help"], 0, "usage: loop-claude <task>"), (["-h"], 0, "usage: loop-claude <task>")):
|
||||
for argv, code, said in (([], 1, "usage: build-release <task>"), (["--help"], 0, "usage: build-release <task>"), (["-h"], 0, "usage: build-release <task>")):
|
||||
with self.subTest(argv=argv):
|
||||
run = checkout.run([], argv=argv)
|
||||
self.assertEqual(run.code, code)
|
||||
@@ -433,7 +433,7 @@ class Premises(unittest.TestCase):
|
||||
write_config(checkout.home, root)
|
||||
checkout.git("init", "--quiet", str(root))
|
||||
run = checkout.run([worker()], cwd=root)
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude no-item")
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} build-release no-item")
|
||||
|
||||
|
||||
class Cycles(unittest.TestCase):
|
||||
@@ -453,7 +453,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"])
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
session = argument(workers[0], "--session-id")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude no-item")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj build-release no-item")
|
||||
self.assertEqual(argument(workers[1], "--resume"), session)
|
||||
self.assertIsNone(argument(workers[1], "--session-id"))
|
||||
self.assertIsNone(argument(workers[1], "--name"))
|
||||
@@ -484,7 +484,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_routes_the_worker_by_its_items_l_and_steps_it_up_within_the_chunk(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TAKEN_IN_AT_L_4)
|
||||
run = checkout.run([
|
||||
worker(say="one"), judge(evidence="one"),
|
||||
@@ -503,7 +503,7 @@ class Cycles(unittest.TestCase):
|
||||
("claude-sonnet-5-5", "high"),
|
||||
])
|
||||
self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)})
|
||||
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2.", argument(workers[0], "-p"))
|
||||
self.assertIn("build-release runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2.", argument(workers[0], "-p"))
|
||||
self.assertIn("on one line, as in `Chunk items: ", argument(workers[0], "-p"))
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
@@ -511,7 +511,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_routes_on_the_ladder_the_projects_config_folder_holds_in_place_of_the_shipped_one(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-fable-5-2"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-fable-5-2"
|
||||
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
|
||||
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "max"}]')
|
||||
checkout.commit_plan(CHEAP)
|
||||
@@ -527,12 +527,12 @@ class Cycles(unittest.TestCase):
|
||||
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
|
||||
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}]')
|
||||
run = checkout.run([worker()])
|
||||
self.assertIn(f"routing on the project's own ladder, {ladder}. worker-model is not on it, so the worker runs on worker-model unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run.\n", run.stderr)
|
||||
self.assertIn(f"routing on the project's own ladder, {ladder}. worker-model is not on it, so the worker runs on worker-model unrouted; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run.\n", run.stderr)
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("worker-model", None))
|
||||
|
||||
def test_reads_the_projects_ladder_afresh_each_cycle_and_exits_1_once_it_holds_a_fault(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-fable-5-2"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-fable-5-2"
|
||||
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
|
||||
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "high"}]')
|
||||
checkout.env["FAKE_CLAUDE_EDIT"] = str(ladder.parent)
|
||||
@@ -543,7 +543,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
origin = checkout.temp / "origin.git"
|
||||
checkout.git("init", "--quiet", "--bare", "--initial-branch=main", str(origin))
|
||||
checkout.git("symbolic-ref", "HEAD", "refs/heads/main")
|
||||
@@ -567,7 +567,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TODO)
|
||||
run = checkout.run([
|
||||
worker(say="Stability round 2: a 🔴. Trigger 3 fired; I ask for a higher rung."), judge(evidence="I ask for a higher rung.", escalation="Stability round 2: a 🔴."),
|
||||
@@ -589,7 +589,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TODO)
|
||||
cited = "Stability round 2: a 🔴."
|
||||
run = checkout.run([
|
||||
@@ -607,7 +607,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_on_it_and_its_judge_on_the_models_highest(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = checkout.env["BUILD_RELEASE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([worker(say="one"), judge(finished=True, evidence="one"), worker(say="next chunk")])
|
||||
self.assertEqual(run.code, 130)
|
||||
@@ -620,7 +620,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_routes_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in_and_keeps_the_judge_on_the_models_highest(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = checkout.env["BUILD_RELEASE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TAKEN_IN_AT_E_PLUS_I_6)
|
||||
run = checkout.run([
|
||||
worker(say="one\nChunk items: 4, 9"), judge(evidence="one"),
|
||||
@@ -638,7 +638,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TODO)
|
||||
run = checkout.run([worker(), judge(), worker(), judge()])
|
||||
self.assertEqual(run.code, 130)
|
||||
@@ -655,9 +655,9 @@ class Cycles(unittest.TestCase):
|
||||
session = argument(first.calls[0], "--session-id")
|
||||
transcript = checkout.transcripts()[0]
|
||||
kept, archived = transcript.read_bytes(), checkout.archived()
|
||||
self.assertEqual(argument(first.calls[0], "--name"), "A proj loop-claude no-item")
|
||||
self.assertEqual(argument(first.calls[0], "--name"), "A proj build-release no-item")
|
||||
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")], chunk="item-2")
|
||||
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude item-2")
|
||||
self.assertEqual(argument(second.calls[0], "--name"), "A proj build-release item-2")
|
||||
self.assertNotIn(session, [argument(call, "--session-id") or argument(call, "--resume") for call in second.calls if call["role"] == "worker"])
|
||||
self.assertNotIn("first chunk", second.calls[1]["stdin"])
|
||||
self.assertEqual(transcript.read_bytes(), kept)
|
||||
@@ -785,7 +785,7 @@ class Cycles(unittest.TestCase):
|
||||
run = checkout.run(six + [worker()])
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"] * 6))
|
||||
self.assertIn("the judge ruled it unfinished 6 cycles running", run.stderr.strip().splitlines()[-1])
|
||||
self.assertIn("rerun loop-claude to give it 6 more cycles", run.stderr.strip().splitlines()[-1])
|
||||
self.assertIn("rerun build-release to give it 6 more cycles", run.stderr.strip().splitlines()[-1])
|
||||
stops = [outcome for outcome in checkout.archived().values() if "Stopped: " in outcome]
|
||||
self.assertEqual(len(stops), 1)
|
||||
self.assertIn(f"\n\nWorker: {OFF_LADDER}\n", stops[0])
|
||||
@@ -794,7 +794,7 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_archives_the_stop_on_the_route_the_sixth_verdict_stepped_to_and_a_rerun_resumes_there(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([step for _ in range(6) for step in (worker(), judge())] + [worker()])
|
||||
self.assertEqual(run.code, 2)
|
||||
@@ -836,7 +836,7 @@ class Windows(unittest.TestCase):
|
||||
["-V"],
|
||||
["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"],
|
||||
["list-windows", "-a", "-F", "#{session_name}\t#{window_name}\t#{pane_dead}\t#{window_id}\t#{@chunk-root}"],
|
||||
["new-session", "-d", "-s", "loop-proj", "-n", "item-4", "-c", str(checkout.root), "-e", "LOOP_CLAUDE_JUDGE_MODEL=judge-model", "-e", "LOOP_CLAUDE_WORKER_MODEL=worker-model", "-P", "-F", "#{window_id}", "--", str(checkout.script), "--chunk", "item-4", "ship it"],
|
||||
["new-session", "-d", "-s", "loop-proj", "-n", "item-4", "-c", str(checkout.root), "-e", "BUILD_RELEASE_JUDGE_MODEL=judge-model", "-e", "BUILD_RELEASE_WORKER_MODEL=worker-model", "-P", "-F", "#{window_id}", "--", str(checkout.script), "--chunk", "item-4", "ship it"],
|
||||
["set-option", "-t", "=loop-proj:", "@loop-root", str(checkout.root)],
|
||||
["set-option", "-w", "-t", "@7", "@chunk-root", str(checkout.root)],
|
||||
["set-option", "-w", "-t", "@7", "remain-on-exit", "failed"],
|
||||
@@ -890,7 +890,7 @@ class Windows(unittest.TestCase):
|
||||
|
||||
def test_tells_a_fresh_worker_the_items_the_other_running_chunks_hold_and_starts_from_its_windows_item(self):
|
||||
checkout = self.checkout(parallel=2)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
|
||||
run = checkout.run([worker()], chunk="item-9")
|
||||
prompt = argument(run.calls[0], "-p")
|
||||
@@ -902,10 +902,10 @@ class Windows(unittest.TestCase):
|
||||
checkout = self.checkout()
|
||||
checkout.env["FAKE_TMUX_VERSION"] = "tmux 3.1c"
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual((run.code, run.stderr, run.tmux), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c\n", [["-V"]]))
|
||||
self.assertEqual((run.code, run.stderr, run.tmux), (1, "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c\n", [["-V"]]))
|
||||
(pathlib.Path(checkout.env["PATH"]) / "tmux").unlink()
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual((run.code, run.stderr), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux\n"))
|
||||
self.assertEqual((run.code, run.stderr), (1, "build-release runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux\n"))
|
||||
|
||||
def test_marks_the_window_while_an_interrupt_waits_and_rings_its_bell(self):
|
||||
checkout = self.checkout()
|
||||
@@ -920,14 +920,14 @@ class Windows(unittest.TestCase):
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_TRANSCRIPTS"] = str(checkout.temp / "deep" / "archive")
|
||||
checkout.env["BUILD_RELEASE_TRANSCRIPTS"] = str(checkout.temp / "deep" / "archive")
|
||||
steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run(steps)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun build-release on a terminal"])
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun build-release on a terminal\n\nWorker: {OFF_LADDER}\n")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} transcript: ")
|
||||
@@ -936,7 +936,7 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
self.assertEqual(argument(run.calls[0], "--resume"), session)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun build-release on a terminal")
|
||||
run = checkout.run([worker(transcript=False), steps[1]])
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
@@ -1023,20 +1023,20 @@ class Models(unittest.TestCase):
|
||||
|
||||
def test_asks_a_project_without_a_model_on_the_terminal_and_saves_the_answer(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"]
|
||||
self.catalog(checkout)
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": "<model>"}} into {checkout.models_file()}, but stdin or stdout is not a terminal; rerun loop-claude on a terminal')
|
||||
self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": "<model>"}} into {checkout.models_file()}, but stdin or stdout is not a terminal; rerun build-release on a terminal')
|
||||
|
||||
run = checkout.run([worker()], terminal_input="\x04")
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to pick proj's model, but the input ended")
|
||||
|
||||
checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "judge-model"
|
||||
checkout.env["BUILD_RELEASE_JUDGE_MODEL"] = "judge-model"
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"]
|
||||
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"]
|
||||
run = checkout.run([worker(), judge()], terminal_input="\n9\n2\n")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertIn("proj runs on model-b", run.stderr)
|
||||
@@ -1047,13 +1047,13 @@ class Models(unittest.TestCase):
|
||||
self.assertEqual(json.loads(checkout.models_file().read_text()), {"proj": "model-b"})
|
||||
self.assertEqual(stat.S_IMODE(checkout.models_file().stat().st_mode), 0o600)
|
||||
|
||||
checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "judge-model"
|
||||
checkout.env["BUILD_RELEASE_JUDGE_MODEL"] = "judge-model"
|
||||
run = checkout.run([worker(), judge()])
|
||||
self.assertEqual([argument(call, "--model") for call in run.calls], ["model-b", "judge-model", "model-b"])
|
||||
|
||||
def test_keeps_the_models_file_mode_and_other_projects_when_saving(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"]
|
||||
checkout.models_file().parent.mkdir(parents=True)
|
||||
checkout.models_file().write_text(json.dumps({"other": "model-x"}))
|
||||
checkout.models_file().chmod(0o640)
|
||||
@@ -1077,7 +1077,7 @@ class Models(unittest.TestCase):
|
||||
|
||||
def test_offers_no_catalog_whose_models_are_not_a_list(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"]
|
||||
self.catalog(checkout)
|
||||
catalog = checkout.home / ".claude" / "cache" / "model-catalog" / "new.json"
|
||||
for shape in ({"catalog": {"config": {"models": []}}}, {"catalog": None}, {"catalog": {"config": []}}, {"catalog": {"config": {"models": "x"}}}):
|
||||
@@ -1091,7 +1091,7 @@ class Models(unittest.TestCase):
|
||||
def test_exits_1_when_the_models_file_cannot_be_written(self):
|
||||
assert_not_root(self)
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"]
|
||||
checkout.models_file().parent.mkdir(parents=True, mode=0o500)
|
||||
self.addCleanup(checkout.models_file().parent.chmod, 0o700)
|
||||
run = checkout.run([worker()], terminal_input="custom-model\n")
|
||||
@@ -1104,12 +1104,12 @@ class Reload(unittest.TestCase):
|
||||
checkout = Checkout(self)
|
||||
copy = checkout.temp / "bin"
|
||||
shutil.copytree(BIN, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*"))
|
||||
checkout.script = copy / "loop-claude"
|
||||
checkout.script = copy / "build-release"
|
||||
checkout.env["FAKE_CLAUDE_EDIT"] = str(copy)
|
||||
run = checkout.run([
|
||||
worker(append=["loop-claude", "\ndef\n"]), judge(),
|
||||
worker(replace=["loop-claude", "\ndef\n", "\n# edited\n"]), judge(),
|
||||
worker(append=["loop_claude/nested/edited.py", "# edited\n"]), judge(),
|
||||
worker(append=["build-release", "\ndef\n"]), judge(),
|
||||
worker(replace=["build-release", "\ndef\n", "\n# edited\n"]), judge(),
|
||||
worker(append=["build_release/nested/edited.py", "# edited\n"]), judge(),
|
||||
worker(append=["records/file_writes.py", "# edited\n"]), judge(),
|
||||
worker(),
|
||||
])
|
||||
@@ -1141,7 +1141,7 @@ class Reload(unittest.TestCase):
|
||||
|
||||
run = checkout.run([], argv=["--reloaded", "{}"])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn("rerun loop-claude <task>", run.stderr)
|
||||
self.assertIn("rerun build-release <task>", run.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -7,14 +7,14 @@ 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
|
||||
import build_release.routed_item
|
||||
from build_release.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)
|
||||
"""build_release.routed_item.routed_item for the plan a todo.md's text holds."""
|
||||
return build_release.routed_item.routed_item(plan_of(todo), cut)
|
||||
|
||||
|
||||
class RoutedItem(unittest.TestCase):
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What the entry points that drive chunks share: loop-claude and do-epic.
|
||||
"""What the entry points that drive chunks share: build-release 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.
|
||||
"""
|
||||
|
||||
@@ -17,7 +17,7 @@ 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."""
|
||||
"""What closing a cycle reads and replaces in an entry point's run of one chunk. ChunkRun below is one; build-release'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]]
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""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.
|
||||
"""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 build-release runs.
|
||||
|
||||
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.
|
||||
"""
|
||||
@@ -13,13 +13,13 @@ from loop_state.paths import STATE_FOLDER
|
||||
from agent_cycle import tmux
|
||||
|
||||
# Under the home folder, a folder per project key holds LOCK.
|
||||
CLAIMS = f"{STATE_FOLDER}/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.
|
||||
CLAIMS = f"{STATE_FOLDER}/build-release"
|
||||
# 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 build-release 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.
|
||||
# The flag that tells the entry point in a window its chunk, as `--chunk item-372` for build-release 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_"
|
||||
HANDED = "BUILD_RELEASE_"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
@@ -53,12 +53,12 @@ def project_lock(root: str, home: pathlib.Path) -> pathlib.Path:
|
||||
|
||||
|
||||
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."""
|
||||
"""The tmux session that holds the windows of build-release'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."""
|
||||
"""The windows of build-release'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 []
|
||||
|
||||
@@ -1,3 +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"
|
||||
BUILD_RELEASE = "build-release"
|
||||
DO_EPIC = "do-epic"
|
||||
|
||||
@@ -19,8 +19,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"
|
||||
JUDGE_MODEL = "BUILD_RELEASE_JUDGE_MODEL"
|
||||
WORKER_MODEL = "BUILD_RELEASE_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"
|
||||
|
||||
@@ -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 entry points, loop-claude and do-epic, 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 entry points, build-release and do-epic, and the replay tools read it."""
|
||||
try:
|
||||
with open(saved, encoding="utf-8") as handle:
|
||||
models = json.load(handle)
|
||||
|
||||
@@ -12,7 +12,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from failure import Failure
|
||||
from loop_effects.doubles import FakeEffects
|
||||
from chunk_driver.drivers import LOOP_CLAUDE
|
||||
from chunk_driver.drivers import BUILD_RELEASE
|
||||
from chunk_driver.project import model_choice
|
||||
from loop_state.paths import paths_from
|
||||
from text_files.file_writes import replace_file
|
||||
@@ -22,8 +22,8 @@ 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"))
|
||||
self.assertEqual(model_choice.overridden({"BUILD_RELEASE_JUDGE_MODEL": "j", "BUILD_RELEASE_WORKER_MODEL": ""}, "saved"), model_choice.Models("j", "saved"))
|
||||
self.assertEqual(model_choice.overridden({"BUILD_RELEASE_JUDGE_MODEL": "j", "BUILD_RELEASE_WORKER_MODEL": "w"}, "saved"), model_choice.Models("j", "w"))
|
||||
|
||||
|
||||
class ModelsOfARun(unittest.TestCase):
|
||||
@@ -36,39 +36,39 @@ class ModelsOfARun(unittest.TestCase):
|
||||
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"))
|
||||
env = {"BUILD_RELEASE_JUDGE_MODEL": "j", "BUILD_RELEASE_WORKER_MODEL": "w"}
|
||||
self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, env, BUILD_RELEASE, 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(model_choice.get_or_ask_models("proj", self.paths, {"BUILD_RELEASE_JUDGE_MODEL": "j"}, BUILD_RELEASE, fake.effects()), model_choice.Models("j", "saved"))
|
||||
self.assertEqual(model_choice.get_or_ask_models("proj", self.paths, {"BUILD_RELEASE_WORKER_MODEL": "w"}, BUILD_RELEASE, 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())
|
||||
models = model_choice.get_or_ask_models("proj", self.paths, {"BUILD_RELEASE_JUDGE_MODEL": "j"}, BUILD_RELEASE, 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())
|
||||
stop = model_choice.get_or_ask_models("proj", self.paths, {}, BUILD_RELEASE, fake.effects())
|
||||
assert isinstance(stop, Stop)
|
||||
self.assertEqual(stop.code, 2)
|
||||
self.assertIn(f"pick proj's model, or merge {{\"proj\": \"<model>\"}} into {self.paths.models_file}", stop.reason)
|
||||
self.assertIn(LOOP_CLAUDE, stop.reason)
|
||||
self.assertIn(BUILD_RELEASE, 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())
|
||||
stop = model_choice.get_or_ask_models("proj", self.paths, {}, BUILD_RELEASE, FakeEffects().effects())
|
||||
self.assertEqual(stop, Stop(1, f"could not read {self.paths.models_file}: not an object mapping projects to model names"))
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ class SavingAModel(unittest.TestCase):
|
||||
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(model_choice.get_or_ask_model("proj", self.paths, BUILD_RELEASE, fake.effects()), Stop(1, f"could not save the model in {self.paths.models_file}: could not save"))
|
||||
self.assertEqual(held, [True])
|
||||
|
||||
|
||||
@@ -155,10 +155,10 @@ class ModelPrompt(unittest.TestCase):
|
||||
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(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), BUILD_RELEASE, 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"))
|
||||
self.assertEqual(model_choice.ask_for_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), BUILD_RELEASE, fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""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."""
|
||||
"""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 build-release does in bin/build_release/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
|
||||
|
||||
@@ -70,7 +70,7 @@ def shared_launches(choice: ReviewChoice, route: Route, project: ProjectRung) ->
|
||||
|
||||
|
||||
def taken_in_launches(choice: ReviewChoice) -> list[str]:
|
||||
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since loop-claude reads a taken-in item's E + I only as the cycle ends, and routes on it from the next cycle. None where no higher E + I picks a higher rung.
|
||||
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since build-release reads a taken-in item's E + I only as the cycle ends, and routes on it from the next cycle. None where no higher E + I picks a higher rung.
|
||||
|
||||
For a worker on the project's rung, routed by an item of E + I 6, it reads: `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 `<rung>` from 7 and `<rung>` from 8.`
|
||||
"""
|
||||
@@ -93,7 +93,7 @@ def escalation(driver: str, route: Route, project: ProjectRung | None) -> list[s
|
||||
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
|
||||
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
|
||||
|
||||
For a worker one rung above the project's, routed by item 3 of L 3, they read: `When an escalation trigger in the setup's `CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `<rung>`, one rung above yours, and on each further trigger one rung higher, up to `<rung>`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `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 `<rung>`.`
|
||||
For a worker one rung above the project's, routed by item 3 of L 3, they read: `When an escalation trigger in the setup's `CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `<rung>`, one rung above yours, and on each further trigger one rung higher, up to `<rung>`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking build-release 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 `<rung>`.`
|
||||
"""
|
||||
if project is None or route.rung not in project.ladder.rungs[:-1]:
|
||||
return []
|
||||
@@ -154,5 +154,5 @@ 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."""
|
||||
"""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 build-release'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)
|
||||
|
||||
@@ -75,7 +75,7 @@ class ProjectRouting(unittest.TestCase):
|
||||
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))
|
||||
self.assertEqual(self.routing(env={"BUILD_RELEASE_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()
|
||||
|
||||
@@ -10,8 +10,8 @@ from agent_cycle.tmux import Window
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Loop:
|
||||
"""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.
|
||||
"""What stays the same while an entry point drives one chunk in one process. build-release builds it once per process, so a reload builds it afresh; do-epic builds one per chunk."""
|
||||
# The checkout the loop runs in. build-release'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 entry point's script, beside which chunk-preflight lies; an edit of loop-claude's reloads its loop.
|
||||
# The entry point's script, beside which chunk-preflight lies; an edit of build-release's reloads its loop.
|
||||
launcher: pathlib.Path
|
||||
effects: Effects
|
||||
|
||||
@@ -4,10 +4,10 @@ usage: chunk-preflight [--worktree] [--item <ID>]
|
||||
|
||||
Run it inside a project checkout. It fetches origin, when the checkout has that remote, and takes
|
||||
origin's default branch, or else the local main or master. Without --worktree, it still fetches,
|
||||
but it doesn't make a worktree or a branch, and doesn't run any tool in one. loop-claude runs it
|
||||
but it doesn't make a worktree or a branch, and doesn't run any tool in one. build-release runs it
|
||||
with --worktree at the checkout root before each chunk's first worker, before it routes the chunk,
|
||||
and quotes what it prints in the worker's prompt. It leaves the checkout as it is, and reads
|
||||
todo.md as the default branch holds it, the plan loop-claude routes on. Where the project's config
|
||||
todo.md as the default branch holds it, the plan build-release routes on. Where the project's config
|
||||
puts todo.md or CHANGELOG.md outside the checkout, it reads that file as it stands. Such a plan
|
||||
no longer names a release whose last item has shipped, so chunk-preflight doesn't see that release,
|
||||
and prints that the release reviews and the cuts are the human's to call. It prints:
|
||||
@@ -27,8 +27,8 @@ and prints that the release reviews and the cuts are the human's to call. It pri
|
||||
formatter setting (`rustfmt.toml` `hard_tabs`, Prettier `useTabs`, Biome `indentStyle`) sets the
|
||||
indent, one line naming the technical principles' hard-tabs default and the two ways out. It
|
||||
reports only, and never fails the run;
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with its L
|
||||
and E + I; with --item <ID>, the plan item of that ID instead, which loop-claude names in a window
|
||||
- the next release and its first item that does not wait, the item build-release routes on, with its L
|
||||
and E + I; with --item <ID>, the plan item of that ID instead, which build-release names in a window
|
||||
named for an item. An item waits while it is marked question, while an item still in todo.md
|
||||
blocks it, or while it awaits such a merge. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z
|
||||
that todo.md has named at that cut or since, less a release its ## Renamed section marks renamed.
|
||||
|
||||
@@ -96,7 +96,7 @@ class Repo:
|
||||
(self.fake / name).write_text(script)
|
||||
(self.fake / name).chmod(0o755)
|
||||
(self.fake / "git").symlink_to(shutil.which("git"))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(self.fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")}
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(self.fake), "BUILD_RELEASE_TRANSCRIPTS": str(self.temp / "archive")}
|
||||
self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
|
||||
self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root))
|
||||
write_config(self.temp / "home", self.root)
|
||||
@@ -163,7 +163,7 @@ elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]:
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(f"- The worktree {repo.temp}/proj-item-2, on the branch item-2, is left from pull request #11, which has merged: run `chunk-pr clean` in it as this chunk's first step.\n", done.stdout)
|
||||
self.assertNotIn("proj-item-3, on the branch", done.stdout, "an open pull request leaves no worktree to clean")
|
||||
self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.", done.stdout)
|
||||
self.assertIn("No plan item: every item of release 0.2.0 in origin/main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #12 https://github.com/o/r/pull/12, which finishes item 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run build-release again.", done.stdout)
|
||||
(repo.fake / "gh").write_text("#!/bin/sh\necho 'not logged in' >&2\nexit 1\n")
|
||||
unread = repo.preflight()
|
||||
self.assertIn("- The pull requests that await a person's merge cannot be read, so no item is passed over for one: gh pr list: not logged in\n", unread.stdout)
|
||||
|
||||
@@ -34,7 +34,7 @@ class HumanTurn(UserText):
|
||||
|
||||
|
||||
class LoopPrompt(UserText):
|
||||
"""What loop-claude told the worker in a -p prompt."""
|
||||
"""What build-release told the worker in a -p prompt."""
|
||||
|
||||
|
||||
class InjectedText(UserText):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The environment variables that cut what one tool result adds to a claude's context: the Bash ceiling loop-claude hands the worker's claude, and the Read limit that review-replay tests for it. Their values: docs/decisions.md → `loop-claude: the worker's claude saves a Bash result of more than 6,000 characters to a file, and rule-hook refuses a Read of a session transcript`.
|
||||
"""The environment variables that cut what one tool result adds to a claude's context: the Bash ceiling build-release hands the worker's claude, and the Read limit that review-replay tests for it. Their values: docs/decisions.md → `build-release: the worker's claude saves a Bash result of more than 6,000 characters to a file, and rule-hook refuses a Read of a session transcript`.
|
||||
|
||||
A subagent inherits both variables, so the ceiling reaches every reviewer the worker launches."""
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""One `claude -p --output-format stream-json` run, as loop-claude's judge and the replays start it."""
|
||||
"""One `claude -p --output-format stream-json` run, as build-release's judge and the replays start it."""
|
||||
import dataclasses
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
@@ -11,7 +11,7 @@ JUDGED_TOOL_INPUT = 400
|
||||
|
||||
|
||||
class Typed(typing.NamedTuple):
|
||||
"""A -p prompt of loop-claude's that carries an answer the human typed: loop-claude's words, and that answer."""
|
||||
"""A -p prompt of build-release's that carries an answer the human typed: build-release's words, and that answer."""
|
||||
loop_words: str
|
||||
answer: str
|
||||
|
||||
@@ -50,7 +50,7 @@ def human_turns(entries: list[Entry]) -> int:
|
||||
|
||||
|
||||
def render(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | None]) -> str:
|
||||
"""The transcript as the judge reads it. typed_answer splits the answer the human typed out of a -p prompt of loop-claude's, so that answer reads as the human's, like one typed in claude."""
|
||||
"""The transcript as the judge reads it. typed_answer splits the answer the human typed out of a -p prompt of build-release's, so that answer reads as the human's, like one typed in claude."""
|
||||
lines = []
|
||||
for entry in entries:
|
||||
if isinstance(entry, AssistantTurn):
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
usage: command-patterns [<version>] [--calls <file>]
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. It reads loop-claude's archive of the
|
||||
Run it inside a project checkout or one of its worktrees. It reads build-release's archive of the
|
||||
project, as reading-cost does, and takes each chunk that finished in the release's window: after
|
||||
the tag before v<version> and up to v<version>'s own tag, by their tag dates. Without <version>, it
|
||||
takes the chunks finished since the highest v* tag, the release not yet cut. It reads the worker's
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Gzip each file of loop-claude's archive and the review folders that no tool changes any more, keeping all of them.
|
||||
"""Gzip each file of build-release's archive and the review folders that no tool changes any more, keeping all of them.
|
||||
|
||||
usage: compress-archives
|
||||
|
||||
It gzips each file that last changed over 30 days ago: in loop-claude's archive,
|
||||
$LOOP_CLAUDE_TRANSCRIPTS (default ~/.claude/loop-claude-transcripts), each transcript, *.jsonl;
|
||||
It gzips each file that last changed over 30 days ago: in build-release's archive,
|
||||
$BUILD_RELEASE_TRANSCRIPTS (default ~/.claude/loop-claude-transcripts), each transcript, *.jsonl;
|
||||
in the review folders, ~/.local/state/larv-review, every file but a lock, *.lock. A file's last change is the later
|
||||
of its mtime and ctime, so a copied or unpacked file counts from when it landed.
|
||||
|
||||
@@ -24,7 +24,7 @@ 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`.
|
||||
# Why 30 days: docs/decisions.md → `archives: gzip each transcript in build-release's archive and each file in the review folders 30 days after it last changed, keeping all of them`.
|
||||
AGE_DAYS = 30
|
||||
|
||||
|
||||
|
||||
@@ -101,10 +101,10 @@ class Main(unittest.TestCase):
|
||||
root = mock.Mock(**{"rglob.return_value": [packed, link, gone, kept]})
|
||||
self.assertEqual(main.old_files(root, "*.jsonl", NOW), [kept])
|
||||
|
||||
def test_reads_the_archive_where_loop_claude_transcripts_puts_it(self):
|
||||
def test_reads_the_archive_where_build_release_transcripts_puts_it(self):
|
||||
moved = self.home / "elsewhere"
|
||||
(self.home / ".claude" / "loop-claude-transcripts").rename(moved)
|
||||
code, _, err = self.run_main(env={"LOOP_CLAUDE_TRANSCRIPTS": str(moved)})
|
||||
code, _, err = self.run_main(env={"BUILD_RELEASE_TRANSCRIPTS": str(moved)})
|
||||
self.assertEqual((code, err), (0, ""))
|
||||
self.assertTrue((moved / "proj" / "c1" / "a.jsonl.gz").is_file())
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ alone. Name the commits the fix's chunk merged, including the one that finished
|
||||
under ## Unreleased in CHANGELOG.md become the release's. Each commit must be on origin's main and not in the tag. Merge
|
||||
commits are left out, and so are the commits a merge of main brought into the range. todo.md must name the release and
|
||||
file no item under it; a patch skips the release review. Cut it as soon as the fix merges: until then chunk-preflight calls
|
||||
the patch's release review due, and loop-claude would run it. It refuses without changing anything where any of that
|
||||
the patch's release review due, and build-release would run it. It refuses without changing anything where any of that
|
||||
doesn't hold, and on a GitHub origin, whose rebase merge would drop the tag from main's history.
|
||||
1. It says on stderr which commits the release ships.
|
||||
2. In a worktree of its own at the tag, it applies each commit's changes, except to CHANGELOG.md, todo.md,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""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."""
|
||||
"""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 build-release'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
|
||||
|
||||
@@ -79,5 +79,5 @@ def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Fa
|
||||
|
||||
|
||||
def real(checkout: pathlib.Path) -> pathlib.Path:
|
||||
"""The checkout as loop-claude names it, which is as git does: through no symlink or `..`. Each keys the checkout's lock and its chunks by that path, so a project config that spells it another way hides neither from the other."""
|
||||
"""The checkout as build-release names it, which is as git does: through no symlink or `..`. Each keys the checkout's lock and its chunks by that path, so a project config that spells it another way hides neither from the other."""
|
||||
return checkout.resolve()
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
"""The do-epic command (docs/decisions.md → `do-epic: drives one Jira epic …`).
|
||||
|
||||
`do-epic <EPIC-KEY>` first plans the epic's open issues (`planning`): each that no label places is split by repo or gets its pick, and the scored issues do-epic filed are re-ranked. Then it moves each parent whose sub-tasks a person filed, where those sub-tasks have landed or are done (`parent_moves`). Then it starts each of the epic's chunks that may start now, each in a window of the epic's tmux session, as `scheduler` picks them, and puts that session on the terminal. Each window runs `do-epic --chunk <ISSUE-KEY> <EPIC-KEY>`: the cycles of one issue's chunk, run by the code that runs loop-claude's (`agent_cycle`), until the judge rules it finished. Then it starts the chunks that may start now, and its window closes. The window of a human's task runs no cycle: it waits until the task no longer holds up an issue (`human_tasks`), then does the same.
|
||||
`do-epic <EPIC-KEY>` first plans the epic's open issues (`planning`): each that no label places is split by repo or gets its pick, and the scored issues do-epic filed are re-ranked. Then it moves each parent whose sub-tasks a person filed, where those sub-tasks have landed or are done (`parent_moves`). Then it starts each of the epic's chunks that may start now, each in a window of the epic's tmux session, as `scheduler` picks them, and puts that session on the terminal. Each window runs `do-epic --chunk <ISSUE-KEY> <EPIC-KEY>`: the cycles of one issue's chunk, run by the code that runs build-release's (`agent_cycle`), until the judge rules it finished. Then it starts the chunks that may start now, and its window closes. The window of a human's task runs no cycle: it waits until the task no longer holds up an issue (`human_tasks`), then does the same.
|
||||
|
||||
After each cycle of a chunk in a repo, the window reads what the chunk's pull request waits on (`gates`). While that is a gate only time or a person passes, the chunk is parked (`parked`): the window frees its running slot and polls the forge, and the chunk's next cycle starts once the worker has something to do and a slot is free. `do-epic <EPIC-KEY> --status` prints what each open issue does."""
|
||||
import dataclasses
|
||||
@@ -62,7 +62,7 @@ An open issue labelled `repo:<name>` or `do-epic-claude` runs as a chunk once no
|
||||
The issues start in order of score, highest first, whatever their order on the board. An issue it could not score starts after the others. As its chunk starts, an issue is assigned in Jira to the account do-epic works as, unless someone else holds it. Where config.toml names a start transition or a sprint board, the issue is also moved by that transition and joins that board's active sprint.
|
||||
A `do-epic-human` issue that blocks another gets a window too. The window DMs you once, then waits without taking a place until you close the issue in Jira.
|
||||
As many run at once as the epic's description allows with a line such as `**Max parallel chunks:** 2`, one where it has none.
|
||||
A repo takes as many chunks as its `parallel-chunks`, and none while loop-claude runs chunks in it.
|
||||
A repo takes as many chunks as its `parallel-chunks`, and none while build-release runs chunks in it.
|
||||
A chunk whose worker ends its run while its pull request waits on its checks, an approval or a new review
|
||||
is parked: it frees its place for the next chunk, and its window's name says what it awaits. Its worker goes
|
||||
on once the checks pass, the approval comes or a reviewer comments, and a place is free; until one is, the
|
||||
@@ -74,7 +74,7 @@ A repo that is missing isn't cloned. Planning then stops there, so its writes ar
|
||||
{findings.HELP}
|
||||
{finish.HELP}
|
||||
The Jira site and its credentials are set in ~/.claude-projects/do-epic/config.toml."""
|
||||
# Under the home folder, where a chunk's cycles are archived, a folder per epic. It is not loop-claude's archive, since that archive's readers, such as judge-replay and the routing figures, read loop-claude's prompts.
|
||||
# Under the home folder, where a chunk's cycles are archived, a folder per epic. It is not build-release's archive, since that archive's readers, such as judge-replay and the routing figures, read build-release's prompts.
|
||||
ARCHIVE = f"{CLAUDE_HOME}/do-epic-transcripts"
|
||||
# The flag that prints what each open issue does.
|
||||
STATUS_FLAG = "--status"
|
||||
@@ -102,7 +102,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
|
||||
raise
|
||||
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.
|
||||
# A chunk's stop is DMed, as build-release's is, so a chunk left overnight never ends unseen.
|
||||
if stop.reason and argv[:1] == [CHUNK_FLAG]:
|
||||
tell(f"do-epic {' '.join(argv)} stopped: {stop.reason}", effects)
|
||||
return stop.code
|
||||
@@ -538,7 +538,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."""
|
||||
"""The models of a chunk without a repo: `repoless-model`, unless the environment names another for the run, as it may for build-release."""
|
||||
return overridden(epic.env, epic.config.repoless_model)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""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_driver.claims.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 build-release 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 build-release 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
|
||||
@@ -57,8 +57,8 @@ class RepoRoom:
|
||||
limit: int
|
||||
# How many chunks of any epic run there.
|
||||
running: int
|
||||
# Whether a loop-claude runs chunks there.
|
||||
loop_claude: bool
|
||||
# Whether a build-release runs chunks there.
|
||||
build_release: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -163,8 +163,8 @@ def turn_of(issue: EpicIssue, pick: Pick | None | Failure, blocking: list[str],
|
||||
|
||||
def refusal(repo: str, room: RepoRoom) -> str | None:
|
||||
"""Why the repo takes no further chunk; None where it takes one."""
|
||||
if room.loop_claude:
|
||||
return f"loop-claude runs chunks in {repo}"
|
||||
if room.build_release:
|
||||
return f"build-release runs chunks in {repo}"
|
||||
if room.running >= room.limit:
|
||||
return f"{repo} runs as many chunks as its `{PARALLEL_CHUNKS}` allows: {room.limit}"
|
||||
return None
|
||||
|
||||
+10
-10
@@ -141,12 +141,12 @@ class TheCommand(DoEpicTest):
|
||||
|
||||
def test_starts_the_chunks_and_says_why_each_other_issue_waits(self) -> None:
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
code, out, _ = self.run_main(["ABC-12"], fake, {"LOOP_CLAUDE_WORKER_MODEL": "m"})
|
||||
code, out, _ = self.run_main(["ABC-12"], fake, {"BUILD_RELEASE_WORKER_MODEL": "m"})
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("started ABC-21 in the tmux session epic-ABC-12\n", out)
|
||||
self.assertIn("ABC-20 waits: it is a human's task\n", out)
|
||||
started = [args for args in fake.tmux_calls if args[0] == "new-session"]
|
||||
self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "LOOP_CLAUDE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]])
|
||||
self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "BUILD_RELEASE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]])
|
||||
# The session is no checkout's, so nothing marks it as one's.
|
||||
self.assertNotIn(tmux.OWNER, [args[3] for args in fake.tmux_calls if args[0] == "set-option"])
|
||||
|
||||
@@ -228,8 +228,8 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest):
|
||||
self.assertEqual(cycle.project.rung.model, "claude-opus-5-5")
|
||||
self.assertEqual(cycle.route, Route(cycle.project.worker_rung(3), 21, 3, 5))
|
||||
self.assertEqual(cycle.judge.model, "claude-opus-5-5")
|
||||
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")
|
||||
self.assertEqual(self.cycle({"BUILD_RELEASE_WORKER_MODEL": "off-the-ladder"}).route, Route(Rung("off-the-ladder")))
|
||||
self.assertEqual(self.cycle({"BUILD_RELEASE_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)
|
||||
@@ -241,7 +241,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest):
|
||||
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:
|
||||
def test_works_in_the_epics_folder_and_archives_apart_from_build_release(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", ""))
|
||||
|
||||
@@ -275,7 +275,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest):
|
||||
|
||||
|
||||
UNREAD = [Failure("no git")] * 20
|
||||
MODELS = {"LOOP_CLAUDE_JUDGE_MODEL": "claude-opus-5-5", "LOOP_CLAUDE_WORKER_MODEL": "claude-opus-5-5", "TMUX_PANE": "%1"}
|
||||
MODELS = {"BUILD_RELEASE_JUDGE_MODEL": "claude-opus-5-5", "BUILD_RELEASE_WORKER_MODEL": "claude-opus-5-5", "TMUX_PANE": "%1"}
|
||||
|
||||
|
||||
class TheHumansRun(DoEpicTest):
|
||||
@@ -351,7 +351,7 @@ class TheHumansRun(DoEpicTest):
|
||||
clones = [what for seam, what in fake.calls if seam == "git" and "clone" in what]
|
||||
self.assertEqual([what[what.index("--") + 1:] for what in clones], [["git@host.example:team/web", str(self.home / "code/web")]])
|
||||
|
||||
def test_names_a_checkout_as_loop_claude_does_whatever_way_its_config_spells_it(self) -> None:
|
||||
def test_names_a_checkout_as_build_release_does_whatever_way_its_config_spells_it(self) -> None:
|
||||
real = self.home / "code" / "api"
|
||||
real.mkdir(parents=True)
|
||||
(self.home / "work").mkdir()
|
||||
@@ -428,7 +428,7 @@ class AChunksRun(DoEpicTest):
|
||||
judged_with = [" ".join(what[0]) + (what[1] or "") for seam, what in fake.calls if seam == "claude"]
|
||||
self.assertEqual((len(prompts), len(judged_with)), (3, 3))
|
||||
for text in (*prompts, *judged_with, *fake.dms, *[str(what) for seam, what in fake.calls if seam == "input"]):
|
||||
self.assertNotIn("loop-claude", text)
|
||||
self.assertNotIn("build-release", text)
|
||||
self.assertNotIn("None", text)
|
||||
self.assertIn(" do-epic runs you on claude-", prompts[1])
|
||||
self.assertIn("The human answered your question at do-epic's terminal:\nUse B.", prompts[2])
|
||||
@@ -699,7 +699,7 @@ class AChunksRun(DoEpicTest):
|
||||
|
||||
|
||||
class WhatAWorkerJudgeAndHumanRead(DoEpicTest):
|
||||
def test_every_prompt_names_do_epic_and_never_loop_claude(self) -> None:
|
||||
def test_every_prompt_names_do_epic_and_never_build_release(self) -> None:
|
||||
cycle = ACycleOfAChunkWithoutARepo.cycle(self) # type: ignore[arg-type]
|
||||
prompts = cycle.prompts
|
||||
texts = [
|
||||
@@ -710,7 +710,7 @@ class WhatAWorkerJudgeAndHumanRead(DoEpicTest):
|
||||
str(judge.judge_schema(prompts.driver)),
|
||||
]
|
||||
for text in texts:
|
||||
self.assertNotIn("loop-claude", text)
|
||||
self.assertNotIn("build-release", text)
|
||||
self.assertIn(f"do-epic runs you on {cycle.route.rung}, routed by the issue's L of 3. Where a sentence below names item 21, it means the issue.", texts[0])
|
||||
self.assertRegex(texts[0], r"it means the issue\.( \S|\n\n)")
|
||||
self.assertNotIn("Chunk items:", texts[1])
|
||||
|
||||
@@ -155,14 +155,14 @@ class WhichIssuesAreChunks(unittest.TestCase):
|
||||
|
||||
|
||||
class RoomInARepo(unittest.TestCase):
|
||||
def test_a_repo_with_room_and_no_loop_claude_takes_a_chunk(self) -> None:
|
||||
self.assertIsNone(refusal("api", RepoRoom(limit=2, running=1, loop_claude=False)))
|
||||
def test_a_repo_with_room_and_no_build_release_takes_a_chunk(self) -> None:
|
||||
self.assertIsNone(refusal("api", RepoRoom(limit=2, running=1, build_release=False)))
|
||||
|
||||
def test_a_full_repo_takes_none(self) -> None:
|
||||
self.assertEqual(refusal("api", RepoRoom(limit=2, running=2, loop_claude=False)), "api runs as many chunks as its `parallel-chunks` allows: 2")
|
||||
self.assertEqual(refusal("api", RepoRoom(limit=2, running=2, build_release=False)), "api runs as many chunks as its `parallel-chunks` allows: 2")
|
||||
|
||||
def test_a_repo_loop_claude_runs_chunks_in_takes_none(self) -> None:
|
||||
self.assertEqual(refusal("api", RepoRoom(limit=2, running=0, loop_claude=True)), "loop-claude runs chunks in api")
|
||||
def test_a_repo_build_release_runs_chunks_in_takes_none(self) -> None:
|
||||
self.assertEqual(refusal("api", RepoRoom(limit=2, running=0, build_release=True)), "build-release runs chunks in api")
|
||||
|
||||
|
||||
class Tmux:
|
||||
@@ -210,7 +210,7 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
"""An epic whose repos are checked out under the home folder, each with its `parallel-chunks`."""
|
||||
def locate(name: str) -> tuple[pathlib.Path, int] | Failure:
|
||||
return (self.home / "code" / name, limits[name]) if name in limits else Failure(f"no project config names {name}")
|
||||
return Epic("ABC-12", cap, locate, self.home, pathlib.Path("/bin/do-epic"), {"LOOP_CLAUDE_X": "1", "OTHER": "2"}, {}, self.order)
|
||||
return Epic("ABC-12", cap, locate, self.home, pathlib.Path("/bin/do-epic"), {"BUILD_RELEASE_X": "1", "OTHER": "2"}, {}, self.order)
|
||||
|
||||
def start(self, epic: Epic, issues: list[EpicIssue], run: Tmux, own: str | None = None) -> Started:
|
||||
found = start_chunks(epic, issues, False, own, run)
|
||||
@@ -223,7 +223,7 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
self.assertEqual(found, Started(["ABC-20", "ABC-21"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2")]))
|
||||
self.assertEqual(run.started(), [("epic-ABC-12", "ABC-20", f"{CHUNK_FLAG} ABC-20 ABC-12"), ("epic-ABC-12", "ABC-21", f"{CHUNK_FLAG} ABC-21 ABC-12")])
|
||||
self.assertEqual([args[args.index("-c") + 1] for args in run.calls if args[0] in ("new-session", "new-window")], [str(self.home / "code/api"), str(self.home / ".local/state/do-epic/ABC-12")])
|
||||
self.assertIn("LOOP_CLAUDE_X=1", run.calls[[args[0] for args in run.calls].index("new-session")])
|
||||
self.assertIn("BUILD_RELEASE_X=1", run.calls[[args[0] for args in run.calls].index("new-session")])
|
||||
self.assertNotIn("OTHER=2", run.calls[[args[0] for args in run.calls].index("new-session")])
|
||||
|
||||
def parked(self, issue_key: str, on: str = "an approval") -> None:
|
||||
@@ -325,7 +325,7 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
cases = {
|
||||
"the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 1": (self.epic(1, api=2), Tmux(parked, ("epic-ABC-12", "ABC-21", False, str(self.home / "code/web")))),
|
||||
"api runs as many chunks as its `parallel-chunks` allows: 1": (self.epic(2, api=1), Tmux(parked, ("epic-XYZ-1", "XYZ-5", False, str(self.home / "code/api")))),
|
||||
"loop-claude runs chunks in api": (self.epic(2, api=1), Tmux(parked, ("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})),
|
||||
"build-release runs chunks in api": (self.epic(2, api=1), Tmux(parked, ("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})),
|
||||
"no project config names api": (self.epic(2), Tmux(parked)),
|
||||
}
|
||||
for reason, (epic, run) in cases.items():
|
||||
@@ -346,14 +346,14 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
def test_a_chunk_its_repo_refuses_takes_no_slot_of_the_epics_cap(self) -> None:
|
||||
run = Tmux(("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})
|
||||
found = self.start(self.epic(1, api=1, web=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:web")], run)
|
||||
self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-20", "loop-claude runs chunks in api")]))
|
||||
self.assertEqual(found, Started(["ABC-21"], [Waits("ABC-20", "build-release runs chunks in api")]))
|
||||
|
||||
def test_never_starts_in_a_repo_loop_claude_runs_chunks_in(self) -> None:
|
||||
def test_never_starts_in_a_repo_build_release_runs_chunks_in(self) -> None:
|
||||
run = Tmux(("loop-api", "item-3", False, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})
|
||||
found = self.start(self.epic(3, api=2), [issue("ABC-20", "repo:api")], run)
|
||||
self.assertEqual(found, Started([], [Waits("ABC-20", "loop-claude runs chunks in api")]))
|
||||
self.assertEqual(found, Started([], [Waits("ABC-20", "build-release runs chunks in api")]))
|
||||
|
||||
def test_a_stopped_loop_claude_window_keeps_no_repo(self) -> None:
|
||||
def test_a_stopped_build_release_window_keeps_no_repo(self) -> None:
|
||||
run = Tmux(("loop-api", "item-3", True, str(self.home / "code/api")), owners={"loop-api": str(self.home / "code/api")})
|
||||
self.assertEqual(self.start(self.epic(3, api=2), [issue("ABC-20", "repo:api")], run).started, ["ABC-20"])
|
||||
|
||||
@@ -371,7 +371,7 @@ class StartingAnEpicsChunks(unittest.TestCase):
|
||||
found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api")], run, own="ABC-20")
|
||||
self.assertEqual(found, Started(["ABC-22"], [Waits("ABC-21", "its window stopped; run `do-epic ABC-12` to start it again")]))
|
||||
|
||||
def test_holds_each_repos_starting_lock_that_loop_claude_holds(self) -> None:
|
||||
def test_holds_each_repos_starting_lock_that_build_release_holds(self) -> None:
|
||||
self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], Tmux())
|
||||
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())
|
||||
|
||||
@@ -4,15 +4,15 @@ 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 chunk_driver.drivers import BUILD_RELEASE
|
||||
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 task is quotable as the evidence, and 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(LOOP_CLAUDE)
|
||||
heading = transcript_heading(BUILD_RELEASE)
|
||||
task, 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, LOOP_CLAUDE)}"), escalation_mark.after_mark(entries, 0), before_task, tuple(human_answers(entries, typed_answer)), task.removesuffix("\n\n"))
|
||||
return Grounds(shown.removesuffix(f"\n\n{judge_rules(ANSWER_DESTINATIONS, BUILD_RELEASE)}"), escalation_mark.after_mark(entries, 0), before_task, tuple(human_answers(entries, typed_answer)), task.removesuffix("\n\n"))
|
||||
|
||||
+10
-10
@@ -1,17 +1,17 @@
|
||||
"""Replay loop-claude's judge on archived verdicts, to find the lowest rung that returns them: docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
"""Replay build-release's judge on archived verdicts, to find the lowest rung that returns them: docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
|
||||
usage: judge-replay <model> [--offline]
|
||||
|
||||
<model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the
|
||||
verdicts archived for the projects that ~/.claude/loop-claude-models.json runs on it: the latest
|
||||
15 of each kind, finished, unfinished, interrupt and quoted answer. Where the archive kept the judge's own
|
||||
prompt (docs/decisions.md → `loop-claude: the archive keeps the raw transcript and each judge run, …`), the
|
||||
prompt (docs/decisions.md → `build-release: the archive keeps the raw transcript and each judge run, …`), the
|
||||
replay hands the judge that prompt, which holds what the judge read then. For a verdict from before the
|
||||
archive kept it, the replay builds the prompt from the transcript copy beside the verdict, with the task,
|
||||
premises and records each project holds now.
|
||||
|
||||
It first replays every verdict on the reference judge: the model at xhigh effort, the rung the
|
||||
judge ran on before loop-claude routed it. A verdict the reference judge returns another kind on
|
||||
judge ran on before build-release routed it. A verdict the reference judge returns another kind on
|
||||
may rest, where its prompt was rebuilt, on records or judge rules that have changed since; where the archived prompt was
|
||||
replayed, the judge's own variance is the cause. Either way no rung is held to it. It
|
||||
then replays the rest on each rung above the model's cheapest that a chunk's E + I raises a
|
||||
@@ -27,8 +27,8 @@ JUDGE_REPLAYED in bin/agent_cycle/routing.py, which routes that model's judge. j
|
||||
keeps the judge to its own model's rungs; a rung above them that misses no interrupt is the
|
||||
evidence to let the judge climb onto it.
|
||||
|
||||
It keeps each run and the report it prints in loop-claude's archive, in
|
||||
replays/judge-replay-<model>-<UTC stamp>/ under ~/.claude/loop-claude-transcripts or $LOOP_CLAUDE_TRANSCRIPTS.
|
||||
It keeps each run and the report it prints in build-release's archive, in
|
||||
replays/judge-replay-<model>-<UTC stamp>/ under ~/.claude/loop-claude-transcripts or $BUILD_RELEASE_TRANSCRIPTS.
|
||||
A run's .jsonl file starts with a line holding claude's arguments, working directory, prompt, exit code and
|
||||
stderr, then holds claude's stream-json output; result.md holds the report.
|
||||
|
||||
@@ -70,7 +70,7 @@ 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 chunk_driver.drivers import BUILD_RELEASE
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from chunk_driver.project.premises import read_premises
|
||||
from chunk_driver.project.records import read_records, RECORDS_NAMED
|
||||
@@ -81,7 +81,7 @@ TOOL = "judge-replay"
|
||||
USAGE = f"{TOOL} <model> [--offline]; <model> is a model on the routing ladder"
|
||||
OFFLINE = "--offline"
|
||||
PER_KIND = 15
|
||||
# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it.
|
||||
# The effort settings.json gave every judge before build-release routed it; the archived verdicts came from it.
|
||||
REFERENCE_EFFORT = "xhigh"
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
if isinstance(cases, Failure):
|
||||
return failed(TOOL, cases.reason)
|
||||
if not cases:
|
||||
return failed(TOOL, f"no archived verdicts of projects on {project.rung.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
|
||||
return failed(TOOL, f"no archived verdicts of projects on {project.rung.model} in {archive_root(home, env)}; run build-release on a project on that model first")
|
||||
if OFFLINE in argv:
|
||||
return offline(project.rung.model, cases, archive_root(home, env), effects)
|
||||
cases = sample(cases, PER_KIND)
|
||||
@@ -166,7 +166,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, LOOP_CLAUDE, effects))
|
||||
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, BUILD_RELEASE, 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_HOME)
|
||||
if isinstance(premises, Failure):
|
||||
@@ -174,5 +174,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=LOOP_CLAUDE), 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=BUILD_RELEASE), rung, effects))
|
||||
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
|
||||
|
||||
@@ -20,7 +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 chunk_driver.drivers import BUILD_RELEASE
|
||||
from judge_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from model_routing.ladder import Rung
|
||||
@@ -256,19 +256,19 @@ class Main(unittest.TestCase):
|
||||
self.assertIn("replaying 8 verdicts on ", err)
|
||||
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):
|
||||
def test_the_prompt_and_the_reply_schema_of_a_rebuilt_run_name_build_release_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.assertIn("what build-release told it on [loop] lines, latest last:\n", prompt)
|
||||
self.assertEqual(prompt.count("said Verdict: "), 1)
|
||||
self.assertIn("loop-claude", schema)
|
||||
self.assertIn("build-release", 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"
|
||||
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 build-release told it on [loop] lines, latest last:\nsaid Verdict: finished\n\nOLD rules"
|
||||
(kept / "judge").mkdir()
|
||||
(kept / "judge" / "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json").write_text(json.dumps({"prompt": prompt, "reply": {"type": "result"}}))
|
||||
(kept / "t0.outcomes.md").write_text("Task: Do it.\n\n2026-10-14T10:00:00Z Verdict: finished\n\nJudge: j\nJudge run: judge/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json\nWorker: x\n")
|
||||
@@ -277,8 +277,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], [])
|
||||
# The reply's schema names build-release to the judge of either prompt.
|
||||
self.assertEqual([schema for schema in self.schemas if "build-release" 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])
|
||||
@@ -375,7 +375,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(LOOP_CLAUDE)}Worker chose option B.\n[human] Use Postgres.\n\n{judge_rules(ANSWER_DESTINATIONS, LOOP_CLAUDE)}"
|
||||
PROMPT = f"HEAD: Ship fast.\n\n{TASK_HEADING}Do it.\n\n{transcript_heading(BUILD_RELEASE)}Worker chose option B.\n[human] Use Postgres.\n\n{judge_rules(ANSWER_DESTINATIONS, BUILD_RELEASE)}"
|
||||
ENTRIES = [AssistantTurn(parts=(Text("Worker chose option B."),)), HumanTurn(text="Use Postgres."), LoopPrompt(text="Keep going.")]
|
||||
|
||||
def judged(self, prompt=PROMPT, **fields):
|
||||
@@ -389,7 +389,7 @@ class JudgeArchivedRuns(unittest.TestCase):
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, forge=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
|
||||
return (grounds if isinstance(grounds, Failure) else judge_archived("/code/p", prompt, grounds, len(self.ENTRIES), REFERENCE, BUILD_RELEASE, effects)), cwds
|
||||
|
||||
def test_runs_in_the_projects_folder_and_stamps_the_verdict_with_the_entries_read(self):
|
||||
verdict, cwds = self.judged()
|
||||
@@ -404,7 +404,7 @@ class JudgeArchivedRuns(unittest.TestCase):
|
||||
self.assertIsInstance(self.judged(evidence="Do it. ... Use Postgres.")[0], Unfinished)
|
||||
|
||||
def test_splits_the_prompt_into_the_premises_the_task_and_the_transcript_at_the_first_heading_of_each(self):
|
||||
heading = transcript_heading(LOOP_CLAUDE)
|
||||
heading = transcript_heading(BUILD_RELEASE)
|
||||
again = self.PROMPT.replace("Worker chose option B.", f"Worker chose option B. {heading}Again.", 1)
|
||||
for prompt in (self.PROMPT, again):
|
||||
grounds = grounds_of(prompt, self.ENTRIES)
|
||||
@@ -420,11 +420,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, LOOP_CLAUDE))[0], Rejected)
|
||||
self.assertIsInstance(self.judged(evidence=judge_rules(ANSWER_DESTINATIONS, BUILD_RELEASE))[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(LOOP_CLAUDE)}Worker chose", 1)
|
||||
quoting = self.PROMPT.replace("Worker chose", f"Quoted: {transcript_heading(BUILD_RELEASE)}Worker chose", 1)
|
||||
self.assertIsInstance(self.judged(quoting, evidence="Quoted:")[0], Unfinished)
|
||||
|
||||
def test_splits_the_prompt_at_the_first_task_heading(self):
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
"""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: 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.
|
||||
"""
|
||||
@@ -25,7 +25,7 @@ from forge.commands import Run, runner
|
||||
from machine_load.slots import slot_folder
|
||||
from loop_state.paths import with_release_tools
|
||||
|
||||
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
|
||||
# Seconds before a Python script build-release runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
|
||||
PYTHON_TIMEOUT = 600
|
||||
# Seconds a command of the forge's CLI may take, so a stalled one cannot hold the loop.
|
||||
FORGE_TIMEOUT = 60
|
||||
@@ -118,7 +118,7 @@ class StreamingClaude:
|
||||
def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS, forge_timeout: float = FORGE_TIMEOUT) -> Effects:
|
||||
"""The effects on this machine: the configs of its DM are under home, and tmux and the one-shot headless claude run in env, while a streaming claude and one on a terminal run in this process's environment plus what their caller adds. Every claude starts with the release's tools first on its `PATH`.
|
||||
|
||||
A test hands in `backends` that don't send anything, in place of the notifiers loop-claude's DM goes through. It hands in a short `forge_timeout`, so a command that outlasts it ends quickly.
|
||||
A test hands in `backends` that don't send anything, in place of the notifiers build-release's DM goes through. It hands in a short `forge_timeout`, so a command that outlasts it ends quickly.
|
||||
"""
|
||||
return Effects(
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, env=with_release_tools(env), input=stdin, text=True),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Where loop-claude keeps its files (paths.py), which the tools that replay its runs read too.
|
||||
"""Where build-release keeps its files (paths.py), which the tools that replay its runs read too.
|
||||
|
||||
It doesn't import anything from loop_claude/.
|
||||
It doesn't import anything from build_release/.
|
||||
"""
|
||||
|
||||
@@ -85,7 +85,7 @@ def medians(runs: list[RunScores]) -> dict[str, Score]:
|
||||
|
||||
|
||||
def tracked_places(places: list[Place], tracked: list[str]) -> tuple[list[Place], list[Place]]:
|
||||
"""Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones."""
|
||||
"""Entries written before paths were written from the repository's root shorten a path once they have named its folder: `cycle/run.py` after `bin/build_release/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones."""
|
||||
found = []
|
||||
dropped = []
|
||||
before = ""
|
||||
|
||||
@@ -30,7 +30,7 @@ class Rung:
|
||||
"""The rung in the Agent tool's words. The tool takes a family name, such as opus, and runs that family's latest model, which is the model each rung names."""
|
||||
return f"model {self.family()}, effort {self.effort}"
|
||||
|
||||
# loop-claude hands a rung to rule-hook in environment variables in this spelling, so parse must keep reading it.
|
||||
# build-release hands a rung to rule-hook in environment variables in this spelling, so parse must keep reading it.
|
||||
def __str__(self) -> str:
|
||||
return f"{self.model} at {self.effort} effort" if self.effort else self.model
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ class Price:
|
||||
return self.input * 2
|
||||
|
||||
|
||||
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06, and Fable 5.2's on 2026-11-03), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Keep each price current with that list: the prices are archived as the ones in force.
|
||||
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06, and Fable 5.2's on 2026-11-03), with Opus 5.5's cache prices from `docs/decisions.md` → `build-release: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Keep each price current with that list: the prices are archived as the ones in force.
|
||||
PRICES = {
|
||||
# Archived chunks that ran on Fable 5.1 are still priced from here.
|
||||
"claude-fable-5-1": Price(10, 0.25, 50),
|
||||
|
||||
@@ -79,7 +79,7 @@ class Route:
|
||||
return WorkerLine(json.dumps({name: value for name, value in fields.items() if value}))
|
||||
|
||||
|
||||
# The Route fields a worker line holds beside the rung's model and effort. A human reads the line in the archive, so it is flatter than the JSON a reload hands over (loop_claude/loop/reload.py) and leaves out zeros. It leaves out unfinished, so a rerun restarts that count.
|
||||
# The Route fields a worker line holds beside the rung's model and effort. A human reads the line in the archive, so it is flatter than the JSON a reload hands over (build_release/loop/reload.py) and leaves out zeros. It leaves out unfinished, so a rerun restarts that count.
|
||||
WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if field.name not in ("rung", "unfinished"))
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ def route_from(worker: str) -> Route | None:
|
||||
|
||||
|
||||
def route_of(fields: object) -> Route | None:
|
||||
"""The route these fields of a worker line name, with an unfinished count of 0; None for fields Route.worker_line could not have written. A reload decodes its route through it too (loop_claude/loop/reload.py), so Route has one decoder."""
|
||||
"""The route these fields of a worker line name, with an unfinished count of 0; None for fields Route.worker_line could not have written. A reload decodes its route through it too (build_release/loop/reload.py), so Route has one decoder."""
|
||||
if not isinstance(fields, dict) or not fields.keys() <= {"model", "effort", *WORKER_LINE_FIELDS}:
|
||||
return None
|
||||
if not isinstance(fields.get("model"), str) or not isinstance(fields.get("effort", ""), str):
|
||||
|
||||
@@ -14,12 +14,12 @@ class Environment(unittest.TestCase):
|
||||
WORKER = Rung("claude-sonnet-5-5", "high")
|
||||
|
||||
def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self):
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "0")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "6")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"BUILD_RELEASE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "BUILD_RELEASE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "BUILD_RELEASE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["BUILD_RELEASE_ESCAPE_AND_IMPACT"], "0")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["BUILD_RELEASE_ESCAPE_AND_IMPACT"], "6")
|
||||
|
||||
def test_a_project_off_the_ladder_is_handed_an_empty_rung_so_none_is_inherited(self):
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"BUILD_RELEASE_PROJECT_RUNG": "", "BUILD_RELEASE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "BUILD_RELEASE_ESCAPE_AND_IMPACT": "0"})
|
||||
|
||||
def test_handed_reads_back_what_environment_named(self):
|
||||
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), LADDER), (self.PROJECT, self.WORKER, 5))
|
||||
@@ -32,13 +32,13 @@ class Environment(unittest.TestCase):
|
||||
def test_tells_whether_both_rungs_are_named_before_any_ladder_is_read(self):
|
||||
self.assertTrue(hands_rungs(environment(self.PROJECT, Route(self.WORKER))))
|
||||
self.assertFalse(hands_rungs(environment(None, Route(self.WORKER))))
|
||||
self.assertFalse(hands_rungs({"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort"}))
|
||||
self.assertFalse(hands_rungs({"BUILD_RELEASE_PROJECT_RUNG": "claude-opus-5-5 at medium effort"}))
|
||||
self.assertFalse(hands_rungs({}))
|
||||
|
||||
def test_a_missing_or_unknown_rung_reads_as_none_and_a_missing_or_unknown_e_plus_i_as_0(self):
|
||||
self.assertEqual(handed({}, LADDER), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}, LADDER), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}, LADDER), (None, None, 0))
|
||||
self.assertEqual(handed({"BUILD_RELEASE_WORKER_RUNG": "claude-haiku-5-5 bogus"}, LADDER), (None, None, 0))
|
||||
self.assertEqual(handed({"BUILD_RELEASE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}, LADDER), (None, None, 0))
|
||||
for bogus in ("", "five", "-1", "5.0", "²"):
|
||||
with self.subTest(bogus=bogus):
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus}, LADDER)[2], 0)
|
||||
self.assertEqual(handed({"BUILD_RELEASE_ESCAPE_AND_IMPACT": bogus}, LADDER)[2], 0)
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
"""The rungs and the E + I loop-claude hands a worker's claude in its environment, from which rule-hook works out the rung of each review launch: docs/decisions.md → `routing:`.
|
||||
"""The rungs and the E + I build-release hands a worker's claude in its environment, from which rule-hook works out the rung of each review launch: docs/decisions.md → `routing:`.
|
||||
|
||||
loop-claude sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch."""
|
||||
build-release sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch."""
|
||||
import typing
|
||||
|
||||
from model_routing.ladder import Ladder, ProjectRung, Rung
|
||||
from model_routing.route import Route
|
||||
|
||||
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
|
||||
WORKER_RUNG = "LOOP_CLAUDE_WORKER_RUNG"
|
||||
PROJECT_RUNG = "BUILD_RELEASE_PROJECT_RUNG"
|
||||
WORKER_RUNG = "BUILD_RELEASE_WORKER_RUNG"
|
||||
# The E + I the chunk's reviews are routed on, from which review_rung works out each review's rung.
|
||||
ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT"
|
||||
ESCAPE_AND_IMPACT = "BUILD_RELEASE_ESCAPE_AND_IMPACT"
|
||||
|
||||
|
||||
def environment(project: ProjectRung | None, route: Route) -> dict[str, str]:
|
||||
@@ -18,12 +18,12 @@ def environment(project: ProjectRung | None, route: Route) -> dict[str, str]:
|
||||
|
||||
|
||||
def hands_rungs(environ: typing.Mapping[str, str]) -> bool:
|
||||
"""Whether the environment names a project's and a worker's rung, as loop-claude sets them for a project on its ladder. Where it names neither, no review launch is checked, so the caller skips reading the project's ladder."""
|
||||
"""Whether the environment names a project's and a worker's rung, as build-release sets them for a project on its ladder. Where it names neither, no review launch is checked, so the caller skips reading the project's ladder."""
|
||||
return bool(environ.get(PROJECT_RUNG) and environ.get(WORKER_RUNG))
|
||||
|
||||
|
||||
def handed(environ: typing.Mapping[str, str], ladder: Ladder) -> tuple[ProjectRung | None, Rung | None, int]:
|
||||
"""The project's rung and the worker's rung, each None when unset or not on ladder, and the reviews' E + I, 0 when unset or not a whole number. ladder is the project's. An older loop-claude hands no E + I, and 0 steps no review up."""
|
||||
"""The project's rung and the worker's rung, each None when unset or not on ladder, and the reviews' E + I, 0 when unset or not a whole number. ladder is the project's. An older build-release hands no E + I, and 0 steps no review up."""
|
||||
escape_and_impact = environ.get(ESCAPE_AND_IMPACT, "")
|
||||
project = on_the_ladder(environ.get(PROJECT_RUNG), ladder)
|
||||
return ProjectRung(ladder, project) if project else None, on_the_ladder(environ.get(WORKER_RUNG), ladder), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
|
||||
|
||||
@@ -10,7 +10,7 @@ from rest_client import json_request
|
||||
from rest_client.env_file import read_env
|
||||
|
||||
KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT")
|
||||
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
|
||||
# Seconds each connect and each read may wait, so an unreachable server holds build-release's interrupt only briefly.
|
||||
TIMEOUT = 10
|
||||
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ def sender_of(project: ProjectConfig, backends: typing.Mapping[Notifier, Backend
|
||||
def notify(text: str, directory: str | None, home: pathlib.Path, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Failure | None:
|
||||
"""Sends text through the notifier of the project whose checkout holds directory.
|
||||
|
||||
The DM is skipped where the config names no notifier, since the project hasn't asked for DMs. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no notifier to ask."""
|
||||
The DM is skipped where the config names no notifier, since the project hasn't asked for DMs. It is skipped too where no config can be read: build-release has stopped with that reason, and without a config there is no notifier to ask."""
|
||||
project = located(directory, home)
|
||||
if isinstance(project, Failure) or project.notifier is None:
|
||||
return None
|
||||
|
||||
@@ -12,7 +12,7 @@ from rest_client.env_file import read_env
|
||||
KEYS = ("SLACK_TOKEN", "SLACK_RECIPIENT")
|
||||
# Slack's one host for every workspace.
|
||||
API = "https://slack.com/api"
|
||||
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
|
||||
# Seconds each connect and each read may wait, so an unreachable server holds build-release's interrupt only briefly.
|
||||
TIMEOUT = 10
|
||||
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ class Notify(Project):
|
||||
self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("slack", slack)))
|
||||
self.assertEqual(slack.requests, [SLACK_POST])
|
||||
|
||||
def test_loop_claudes_dm_goes_through_the_notifier_for_the_project_holding_the_current_directory(self):
|
||||
def test_build_releases_dm_goes_through_the_notifier_for_the_project_holding_the_current_directory(self):
|
||||
self.name_notifier("slack", SLACK_KEYS)
|
||||
slack = Slack({"ok": True})
|
||||
with contextlib.chdir(self.checkout):
|
||||
@@ -90,7 +90,7 @@ class Notify(Project):
|
||||
self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("mattermost", server)))
|
||||
self.assertEqual(server.requests, [])
|
||||
|
||||
def test_skips_the_notice_where_no_config_names_the_checkout_since_loop_claude_stops_on_that_itself(self):
|
||||
def test_skips_the_notice_where_no_config_names_the_checkout_since_build_release_stops_on_that_itself(self):
|
||||
other = self.home / "code" / "other"
|
||||
other.mkdir()
|
||||
subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env())
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Reads the goals file, for the ranking and for loop-claude's premises: its ## Goals and ## Audience sections, each goal's number and mark, and what each goal weighs."""
|
||||
"""Reads the goals file, for the ranking and for build-release's premises: its ## Goals and ## Audience sections, each goal's number and mark, and what each goal weighs."""
|
||||
|
||||
import decimal
|
||||
import re
|
||||
|
||||
@@ -94,7 +94,7 @@ them beside the principles and the standards, and the team's rule wins where the
|
||||
prints one path a line. Left out, the reviewers read no such file. It is printed with the others only
|
||||
where it is set.
|
||||
|
||||
`notifier` is an optional setting, "mattermost" or "slack": the service that sends loop-claude's DMs and
|
||||
`notifier` is an optional setting, "mattermost" or "slack": the service that sends build-release's DMs and
|
||||
`notify`'s messages to the human. Setting it requires `env-file`, which holds that service's keys;
|
||||
`notify --help` names them. Left out, the project gets no DMs. It is printed with the others only where it
|
||||
is set.
|
||||
@@ -134,7 +134,7 @@ ranking, and a scoring run with a mean under it asks for a floor item. A legacy
|
||||
scores low, may lower it. Left out, it is 7.0.
|
||||
|
||||
`parallel-chunks` is an optional setting, a whole number of 1 or more: the most chunks of the project
|
||||
loop-claude runs at once, each in its own tmux window. Left out, it is 1.
|
||||
build-release runs at once, each in its own tmux window. Left out, it is 1.
|
||||
|
||||
`project-config tooling-on-host`, `project-config readability-floor` and `project-config parallel-chunks`
|
||||
print their values; the full listing shows each only where the config changes it from what it is when
|
||||
|
||||
@@ -44,7 +44,7 @@ TOOLING_ON_HOST = "tooling-on-host"
|
||||
READABILITY_FLOOR = "readability-floor"
|
||||
# The floor where the config leaves it out, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
|
||||
DEFAULT_FLOOR = decimal.Decimal("7.0")
|
||||
# The most chunks of the project loop-claude runs at once, each in its own tmux window; 1 where left out. Three readers seated as the README's audience picked the spelling 2-1 over concurrent-chunks.
|
||||
# The most chunks of the project build-release runs at once, each in its own tmux window; 1 where left out. Three readers seated as the README's audience picked the spelling 2-1 over concurrent-chunks.
|
||||
PARALLEL_CHUNKS = "parallel-chunks"
|
||||
# The optional text settings. `language` is the language the project's prose is written in, by its English name. The others are templates, as `templates` says.
|
||||
LANGUAGE = "language"
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
ranks, by a formula over R, S, A, G and W and a | Goal | W | table that weighs every goal, W
|
||||
being the heaviest cited goal's weight; ranking it says to reshape it.
|
||||
- ## Renamed is optional: one line `- 0.2.1 renamed to 0.3.0` per renamed release. chunk-preflight,
|
||||
loop-claude and larv-review skip the line's first release, and ignore the second, which is for the
|
||||
build-release and larv-review skip the line's first release, and ignore the second, which is for the
|
||||
reader. No item may sit under a marked release, and a line goes once a tag at or past its first
|
||||
release is cut. A release whose items all moved elsewhere without a line reads as finished.
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Measure each chunk loop-claude finished, append the figures to a project's record, and say whether they rise.
|
||||
"""Measure each chunk build-release finished, append the figures to a project's record, and say whether they rise.
|
||||
|
||||
usage: reading-cost [--reset] [record]
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. record defaults to the
|
||||
docs/reading-cost.md the project's config names, created when missing. It reads loop-claude's archive of the project,
|
||||
$LOOP_CLAUDE_TRANSCRIPTS/<key> (default ~/.claude/loop-claude-transcripts), <key> being the
|
||||
docs/reading-cost.md the project's config names, created when missing. It reads build-release's archive of the project,
|
||||
$BUILD_RELEASE_TRANSCRIPTS/<key> (default ~/.claude/loop-claude-transcripts), <key> being the
|
||||
checkout's path relative to ~/code, or to / outside it. For each finished chunk the record does not
|
||||
yet hold, it measures what the worker and its subagents read before the worker's first commit: their
|
||||
new input tokens (uncached and cache-written; cache reads excluded), and how often they opened or
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The next chunk's pick: the plan's items weighed against the last cut, with the item the next chunk takes first, or why there is none, as chunk-preflight states it and loop-claude starts chunks by it."""
|
||||
"""The next chunk's pick: the plan's items weighed against the last cut, with the item the next chunk takes first, or why there is none, as chunk-preflight states it and build-release starts chunks by it."""
|
||||
import dataclasses
|
||||
|
||||
from release_plan.release_standing import Cut, dated_cut, LastCut, picked, ReadyToCut, ReviewDue, standing_of, Unknown, Unplanned
|
||||
@@ -115,4 +115,4 @@ def merge_stop(pulls: dict[str, list[int]]) -> str:
|
||||
if not pulls:
|
||||
return ""
|
||||
named = "; ".join(f"{pull}, which finishes item{'s' if len(ids) > 1 else ''} {listed([str(item_id) for item_id in ids], 'and')}" for pull, ids in pulls.items())
|
||||
return f" Under `merge = \"human\"`, these pull requests await a person's merge: {named}. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again."
|
||||
return f" Under `merge = \"human\"`, these pull requests await a person's merge: {named}. The working loop stops here. Once a person has merged one, or turned one back into a draft, run build-release again."
|
||||
|
||||
@@ -16,7 +16,7 @@ from project_config import templates
|
||||
|
||||
# The version a branch with no v* tag and no dated CHANGELOG.md heading counts as cut: below every release, 0.0.0 included, so that every release todo.md names comes after it.
|
||||
BEFORE_FIRST_RELEASE = (-1, 0, 0)
|
||||
# What chunk-preflight and loop-claude say where the plan is outside the checkout, since no commit holds an earlier plan: `docs/decisions.md` → "project config: a tool that reads a file's commits …".
|
||||
# What chunk-preflight and build-release say where the plan is outside the checkout, since no commit holds an earlier plan: `docs/decisions.md` → "project config: a tool that reads a file's commits …".
|
||||
UNSEEN_RELEASES = "The plan is outside the checkout, where no commit holds it, so a release whose last item has shipped is not seen: the plan no longer names it, and the release after it reads as next. Until the last release of all, no release review is called due and no release is called ready to cut: both are the human's to call."
|
||||
|
||||
|
||||
|
||||
@@ -543,7 +543,7 @@ class AwaitingMerge(unittest.TestCase):
|
||||
items = [dataclasses.replace(item, awaits_merge="#8 https://github.com/o/r/pull/8" if item.id in (2, 3) else item.awaits_merge) for item in held.plan.items]
|
||||
items[3] = dataclasses.replace(items[3], exempt="question")
|
||||
none = next_chunk.planned(Plan(items), held.cut, "main", "item-{id}")
|
||||
self.assertEqual(none.why, "every item of release 0.1.0 in main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #7 https://github.com/o/r/pull/7, which finishes item 1; #8 https://github.com/o/r/pull/8, which finishes items 2 and 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run loop-claude again.")
|
||||
self.assertEqual(none.why, "every item of release 0.1.0 in main's todo.md waits. Under `merge = \"human\"`, these pull requests await a person's merge: #7 https://github.com/o/r/pull/7, which finishes item 1; #8 https://github.com/o/r/pull/8, which finishes items 2 and 3. The working loop stops here. Once a person has merged one, or turned one back into a draft, run build-release again.")
|
||||
self.assertTrue(none.awaits_merge)
|
||||
later = dataclasses.replace(items[0], id=9, release=(0, 2, 0), awaits_merge="#10 https://github.com/o/r/pull/10")
|
||||
self.assertEqual(next_chunk.awaited_merges([*items, later], (0, 1, 0)), {"#7 https://github.com/o/r/pull/7": [1], "#8 https://github.com/o/r/pull/8": [2, 3]}, "a pull request that finishes only a later release's items doesn't count")
|
||||
|
||||
@@ -23,8 +23,8 @@ def unsorted_imports(source: str) -> list[int]:
|
||||
|
||||
class ImportOrder(unittest.TestCase):
|
||||
def test_each_python_file_sorts_its_imports_by_their_first_binding(self):
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
self.assertIn("bin/loop-claude", listed)
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/build-release"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
self.assertIn("bin/build-release", listed)
|
||||
for name in listed:
|
||||
with self.subTest(name):
|
||||
self.assertEqual(unsorted_imports((ROOT / name).read_text(encoding="utf-8")), [])
|
||||
|
||||
@@ -62,7 +62,7 @@ def part_cycles(bin_folder: pathlib.Path) -> dict[str, list[str]]:
|
||||
|
||||
|
||||
# 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")
|
||||
DRIVERS = ("do_epic", "build_release")
|
||||
|
||||
|
||||
def driver_imports(bin_folder: pathlib.Path, drivers: tuple[str, ...]) -> list[str]:
|
||||
|
||||
@@ -8,9 +8,9 @@ from repo_checks import ROOT
|
||||
BY_ITS_FOLDER = re.compile(r"(?:~|\$HOME)/\.claude/bin/[\w.<>-]+(?![\w.<>/-])")
|
||||
# The plan, the changelog and the records: their text names a tool as it was spelled when the line was written, and nobody rewrites it.
|
||||
HISTORY = ("CHANGELOG.md", "docs/", "todo.md")
|
||||
# The lines a person runs in their own shell or a crontab, which lack the tools: only `loop-claude` is linked onto their `PATH`.
|
||||
# The lines a person runs in their own shell or a crontab, which lack the tools: only `build-release` is linked onto their `PATH`.
|
||||
BY_HAND = {
|
||||
"README.md": {"$HOME/.claude/bin/compress-archives", "~/.claude/bin/<tool>", "~/.claude/bin/loop-claude", "~/.claude/bin/notify", "~/.claude/bin/project-config"},
|
||||
"README.md": {"$HOME/.claude/bin/compress-archives", "~/.claude/bin/<tool>", "~/.claude/bin/build-release", "~/.claude/bin/notify", "~/.claude/bin/project-config"},
|
||||
"presentation/README.md": {"~/.claude/bin/run-heavy"},
|
||||
"presentation/build-pdf.py": {"~/.claude/bin/run-heavy"},
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ instruction files off in its settings and opens the prompt with what the hook ha
|
||||
closes it with the header's line on the project principles.
|
||||
|
||||
--bash-ceiling and --read-limit run the same comparison for two limits on what one tool result adds to a
|
||||
claude's context, which a subagent inherits (bin/claude_code/output_limits.py). loop-claude hands the worker's
|
||||
claude's context, which a subagent inherits (bin/claude_code/output_limits.py). build-release hands the worker's
|
||||
claude the Bash ceiling, and doesn't hand it the Read limit yet. The replay with --bash-ceiling starts under
|
||||
BASH_MAX_OUTPUT_LENGTH=6000, which saves a Bash result of more than 6,000 characters to a file and hands the
|
||||
reviewer its path and the first 2,000 characters. The replay with --read-limit starts under
|
||||
@@ -56,9 +56,9 @@ unchanged replay missed. The tool doesn't count what the replays read: each run'
|
||||
result, is in the archive. It refuses to run where its own environment already holds the variable, since the
|
||||
replays as archived would inherit it.
|
||||
|
||||
It keeps each run, a reviewer's tool calls included, and the report it prints in loop-claude's archive, in
|
||||
It keeps each run, a reviewer's tool calls included, and the report it prints in build-release's archive, in
|
||||
replays/review-replay-<pass>-<model>[-<flag without its leading dashes>]-<UTC stamp>/ under ~/.claude/loop-claude-transcripts
|
||||
or $LOOP_CLAUDE_TRANSCRIPTS. A run's .jsonl file starts with a line holding claude's arguments, working
|
||||
or $BUILD_RELEASE_TRANSCRIPTS. A run's .jsonl file starts with a line holding claude's arguments, working
|
||||
directory, prompt, exit code and stderr, then holds claude's stream-json output; result.md holds the report.
|
||||
|
||||
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Reads the chunks of every project in loop-claude's archive, and keeps the routing figures at the archive's root for the human to read."""
|
||||
"""Reads the chunks of every project in build-release's archive, and keeps the routing figures at the archive's root for the human to read."""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import fcntl
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing: loop-claude measures review rounds…`."""
|
||||
"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing: build-release measures review rounds…`."""
|
||||
import collections
|
||||
import dataclasses
|
||||
import statistics
|
||||
|
||||
@@ -13,7 +13,7 @@ def render(ladder: Ladder, figures: Figures, found: list[Call], at: str, cycle:
|
||||
"""The figures as markdown, for the human to read. ladder orders the rungs, and since is the latest reset's stamp, empty for none."""
|
||||
sections = [
|
||||
"# Routing figures",
|
||||
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
|
||||
f"Measured {at}, at cycle {cycle} across build-release's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
|
||||
"## Calls for a routing change",
|
||||
bullets([call.sentence() for call in found]) or "None.",
|
||||
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", dollars_table(figures, dimension))],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""What loop-claude keeps at the archive's root between measurements: docs/decisions.md → `routing: loop-claude measures review rounds…`.
|
||||
"""What build-release keeps at the archive's root between measurements: docs/decisions.md → `routing: build-release measures review rounds…`.
|
||||
|
||||
STATE holds, as fields loop-claude reads back, the cycle it last measured at and each call it raised. RAISED lists the raised calls for the human to read. A chunk appends a reset to RAISED by hand, as docs/decisions.md → "Working rules" says, and loop-claude reads the resets from there."""
|
||||
STATE holds, as fields build-release reads back, the cycle it last measured at and each call it raised. RAISED lists the raised calls for the human to read. A chunk appends a reset to RAISED by hand, as docs/decisions.md → "Working rules" says, and build-release reads the resets from there."""
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
@@ -274,7 +274,7 @@ class Calls(unittest.TestCase):
|
||||
def test_renders_each_dimension_largest_first_and_the_calls(self):
|
||||
chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0)
|
||||
text = render(LADDER, totals([chunk]), [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
|
||||
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across build-release's archive, from 1 finished chunk.", text)
|
||||
self.assertIn("## Calls for a routing change\n\n- Explore subagents' reports took more of the worker's context than their searches would have.\n", text)
|
||||
self.assertIn("## Dollars by project", text)
|
||||
self.assertIn("| b | $1,234.50 |\n| a | $2.50 |", text)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Refuse an Agent or Skill call that launches a review below the rung it needs, worked out on the project's ladder from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
|
||||
"""Refuse an Agent or Skill call that launches a review below the rung it needs, worked out on the project's ladder from the rungs and the E + I build-release hands its worker: docs/decisions.md → `routing:`."""
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
@@ -26,7 +26,7 @@ SECURITY_SKILLS = {"claude-security", "security-review"}
|
||||
|
||||
|
||||
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
|
||||
"""The breach of an Agent call that launches a review below its rung; none where loop-claude handed no rungs."""
|
||||
"""The breach of an Agent call that launches a review below its rung; none where build-release handed no rungs."""
|
||||
kind = review_kind(call.given)
|
||||
if kind is None or not hands_rungs(environ):
|
||||
return []
|
||||
@@ -45,12 +45,12 @@ def reviewer_breaches(call: Call, environ: typing.Mapping[str, str], home: str)
|
||||
|
||||
|
||||
def unread(ladder: Failure, cwd: str) -> Breach:
|
||||
"""The breach of a review launched where loop-claude handed rungs and the project's ladder cannot be read, so nothing tells which rung the review needs."""
|
||||
"""The breach of a review launched where build-release handed rungs and the project's ladder cannot be read, so nothing tells which rung the review needs."""
|
||||
return Breach("reviewer-rung", f"the rung this review needs cannot be worked out: {ladder.reason}", cwd)
|
||||
|
||||
|
||||
def skill_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
|
||||
"""The breach of a Skill call that runs the security pass below the project's rung; none where loop-claude handed no rungs.
|
||||
"""The breach of a Skill call that runs the security pass below the project's rung; none where build-release handed no rungs.
|
||||
|
||||
The skill runs on its caller's rung. A subagent launched as the security pass was held to the project's rung by reviewer_breaches. The worker's own rung is known, so its call is refused only below the project's rung. Any other subagent's rung is unknown, so its call is refused."""
|
||||
skill = text(call.given, "skill").lstrip("/").rsplit(":", 1)[-1]
|
||||
|
||||
@@ -47,7 +47,7 @@ RULES: dict[RuleName, Rule] = {
|
||||
),
|
||||
# A marker would let the credentials into the transcript all the same, so no marker waives it.
|
||||
"env-file-read": Rule(
|
||||
"an agent never reads ~/.claude/.env or a project's env-file, the file of credentials the project's config names, since a value the agent reads lands in its transcript, which loop-claude archives and the backups copy; it leaves a tool that needs a credential to read the file itself, gets the file's path from `project-config env-file`, and spells the path another way, such as \"the .env in ~/.claude\", in a command that must mention it without reading it, such as a commit's title, and searches only a folder without it",
|
||||
"an agent never reads ~/.claude/.env or a project's env-file, the file of credentials the project's config names, since a value the agent reads lands in its transcript, which build-release archives and the backups copy; it leaves a tool that needs a credential to read the file itself, gets the file's path from `project-config env-file`, and spells the path another way, such as \"the .env in ~/.claude\", in a command that must mention it without reading it, such as a commit's title, and searches only a folder without it",
|
||||
"against ~/.claude/.env and the env-file of every config under ~/.claude-projects: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it; and a Bash command that runs `ag`, `grep -r` or `rg` over a folder holding one, or over the directory `cd` left the command in where it names no folder, unless the tool skips the file: `ag` and `rg` skip a hidden file, one below a hidden folder of the search and one a checkout ignores, and `rg` one that none of its globs matches",
|
||||
overridable=False,
|
||||
),
|
||||
@@ -77,8 +77,8 @@ RULES: dict[RuleName, Rule] = {
|
||||
),
|
||||
# A rung is not a judgment call, and the refusal names the arguments to pass, so no marker waives it.
|
||||
"reviewer-rung": Rule(
|
||||
"a reviewer, a comprehension seat or the security pass runs on the rung loop-claude names for it: for a seat or the security pass the project's rung, and for a reviewer the highest of the project's rung, the worker's and the one the chunk's item's E + I picks, or the project's rung where the branch changes only Markdown no agent follows, so a worker below the project's rung cannot hand a review to its own cheaper model. The rungs rank as on the project's routing ladder, and the review is refused while that ladder cannot be read",
|
||||
"an Agent call, in a claude loop-claude started, whose subagent type is an agent under agents/, or whose prompt opens with seat-prompts.md's opening sentence or the one larv-review's Security section sets; and a `security-review` or `claude-security` Skill call in such a claude, which runs on its caller's rung, unless the caller is a subagent whose prompt opens with that sentence",
|
||||
"a reviewer, a comprehension seat or the security pass runs on the rung build-release names for it: for a seat or the security pass the project's rung, and for a reviewer the highest of the project's rung, the worker's and the one the chunk's item's E + I picks, or the project's rung where the branch changes only Markdown no agent follows, so a worker below the project's rung cannot hand a review to its own cheaper model. The rungs rank as on the project's routing ladder, and the review is refused while that ladder cannot be read",
|
||||
"an Agent call, in a claude build-release started, whose subagent type is an agent under agents/, or whose prompt opens with seat-prompts.md's opening sentence or the one larv-review's Security section sets; and a `security-review` or `claude-security` Skill call in such a claude, which runs on its caller's rung, unless the caller is a subagent whose prompt opens with that sentence",
|
||||
overridable=False,
|
||||
),
|
||||
# The cap holds with no ask, so no marker waives it.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user