Keep configs in ~/.config/build-release/ and tool state in ~/.local/state/build-release/, under XDG_* where set
CI / tests (pull_request) Successful in 6m34s

This commit is contained in:
2026-12-03 18:56:28 +01:00
parent 20c83f861f
commit 1ca2c8efe0
142 changed files with 1095 additions and 933 deletions
+2 -2
View File
@@ -37,13 +37,13 @@ def chunk_facts(loop: Loop) -> str:
item = item_of(loop.window.name)
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root)
facts = fresh_prompt.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else fresh_prompt.preflight_facts(done.stdout.strip())
held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects)
held = held_beside(loop.window.name, loop.root, loop.paths, loop.env, loop.effects)
return facts + (fresh_prompt.held_by_others(held) if held else "")
def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure:
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. Where announce is True, as when a chunk starts, it says UNSEEN_RELEASES for such a plan, so the human reads it once per chunk, not every cycle."""
config = located(loop.root, loop.paths.home)
config = located(loop.root, loop.paths.home, loop.env)
if isinstance(config, Failure):
return config
if announce and config.tracked("plan") is None:
+11 -11
View File
@@ -100,9 +100,9 @@ def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | No
return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs))
def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | NoItem | Failure:
def next_plan(root: str, home: pathlib.Path, env: typing.Mapping[str, str], effects: Effects) -> NextChunk | NoItem | Failure:
"""The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it."""
config = located(root, home)
config = located(root, home, env)
if isinstance(config, Failure):
return config
# A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too.
@@ -116,18 +116,18 @@ 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 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)
config = located(loop_run.root, paths.home, env)
if isinstance(config, Failure):
return config
session = loop_session(loop_run.root, paths.home)
handed = {name: value for name, value in env.items() if name.startswith(HANDED)}
with starting(project_lock(loop_run.root, paths.home)) as unlocked:
with starting(project_lock(loop_run.root, paths.home, env)) as unlocked:
if unlocked:
return unlocked
windows = tmux.listed(session, effects.tmux)
if refused := refusal(session, windows, loop_run.root, effects.tmux):
return refused
chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects)
chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, env, effects)
if isinstance(chunks, AwaitedMerges):
return chunks
for chunk in chunks:
@@ -147,12 +147,12 @@ def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux)
return None
def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str] | AwaitedMerges:
def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> list[str] | AwaitedMerges:
"""The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. AwaitedMerges where no chunk runs or restarts and every item left awaits a person's merge."""
room = room_of(windows, loop_run.chunk, leaving, limit)
if not room.left:
return room.restart
plan = next_plan(loop_run.root, paths.home, effects)
plan = next_plan(loop_run.root, paths.home, env, effects)
if isinstance(plan, Failure):
# Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself.
say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects)
@@ -164,14 +164,14 @@ def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool
return room.restart + [chunk for chunk in picked if chunk not in room.stopped]
def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]:
def held_beside(chunk: str, root: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> list[int]:
"""The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it."""
wait_for_starts(root, paths.home)
wait_for_starts(root, paths.home, env)
others = [window.name for window in tmux.listed(loop_session(root, paths.home), effects.tmux) if window.name != chunk]
return sorted(held_items(others, project_key(root, paths.home), paths.claude_code_transcripts))
def wait_for_starts(root: str, home: pathlib.Path) -> None:
def wait_for_starts(root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> None:
"""Returns once no loop of the project is starting windows: start_chunks holds the lock file `claims.LOCK` names while it starts them. Where the lock cannot be taken, it returns at once."""
with starting(project_lock(root, home)):
with starting(project_lock(root, home, env)):
pass
+2 -2
View File
@@ -133,10 +133,10 @@ def handed_on(loop_run: LoopRun, loop: Loop, start: StartChunks) -> Stop:
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
"""The cycle loop_run runs next, from the premises, the records, the project's models and its routing ladder read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
premises = read_premises(loop.root, loop.paths.home)
premises = read_premises(loop.root, loop.paths.home, loop.env)
if isinstance(premises, Failure):
return Stop(1, premises.reason)
records = read_records(loop.root, loop.paths.home, loop.paths.claude_dir)
records = read_records(loop.root, loop.paths.home, loop.env, loop.paths.claude_dir)
if isinstance(records, Failure):
return Stop(1, records.reason)
routing = project_routing(loop, fresh_prompt.DRIVER)
+4 -3
View File
@@ -1,4 +1,5 @@
"""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…`."""
from collections.abc import Mapping
import pathlib
from routing_figures import archive
@@ -20,14 +21,14 @@ from text_files.utc_stamp import utc
def check_routing(root: pathlib.Path, rung: Rung, loop: Loop) -> Stop | None:
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. root is the archive's, and rung is the rung of the claude that puts the calls to the human."""
with archive.locked(root) as held:
new = new_calls(root, loop.paths, loop.effects) if held else []
new = new_calls(root, loop.paths, loop.env, loop.effects) if held else []
if isinstance(new, Failure):
say(f"routing figures: {new.reason}", loop.effects)
return None
return raise_calls(root, new, rung, loop) if new else None
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure:
def new_calls(root: pathlib.Path, paths: Paths, env: Mapping[str, str], effects: Effects) -> list[Call] | Failure:
"""Once due, measures and keeps the figures, and returns their calls not raised since the latest reset; none while not due."""
cycle = archive.cycles(root)
if isinstance(cycle, Failure):
@@ -39,7 +40,7 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
if isinstance(raised, Failure):
return raised
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)
measured = archive.measure_archive(root, str(paths.home), env, raised.since, effects.git)
if isinstance(measured, Failure):
return measured
# The shipped ladder, not the project's: the figures span every project.
+9 -9
View File
@@ -50,7 +50,7 @@ class RouteSources(unittest.TestCase):
unread = Failure("no git")
fake = FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread])
with contextlib.redirect_stderr(io.StringIO()) as stderr:
facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[1])))
facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[2], {})))
self.assertEqual((facts, held.plan), ("", plan_of(TODO)))
self.assertEqual([args for args in fake.made("git") if args[0] == "remote"], [["remote"]])
# An open session is no fresh chunk, so the human isn't told again of releases the plan cannot show.
@@ -79,7 +79,7 @@ class RouteSources(unittest.TestCase):
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
effects = dataclasses.replace(FakeEffects().effects(), git=git)
held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[1])))
held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[2], {})))
self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n")
def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_as_the_loops_forge_lists_them(self):
@@ -96,33 +96,33 @@ class RouteSources(unittest.TestCase):
folder = configured(self, pathlib.Path(root))
(folder / "config.toml").write_text((folder / "config.toml").read_text() + 'merge = "human"\n')
fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"] * 3)
held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[1])))
held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[2], {})))
self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")])
self.assertEqual(fake.made("forge")[0][:4], [root, "gh", "pr", "list"])
self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk")
window = chunk_windows.next_plan(root, folder.parents[1], dataclasses.replace(fake.effects(), git=git))
window = chunk_windows.next_plan(root, folder.parents[2], {}, dataclasses.replace(fake.effects(), git=git))
self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick")
stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[1]), dataclasses.replace(fake.effects(), git=git))
stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[2], {}), {}, dataclasses.replace(fake.effects(), git=git))
self.assertEqual(stopped, chunk_windows.AwaitedMerges(window.why), "so the loop starts no chunk, and says which pull requests it waits on")
def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self):
with tempfile.TemporaryDirectory() as root:
folder = configured(self, pathlib.Path(root))
loop = a_loop(FakeEffects(git=[*ON_MAIN] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
loop = a_loop(FakeEffects(git=[*ON_MAIN] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[2], {}))
config = folder / "config.toml"
tracked = a_loop(FakeEffects(git=[*ON_MAIN, *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
tracked = a_loop(FakeEffects(git=[*ON_MAIN, *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[2], {}))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_plan(tracked)
self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release")
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
(folder / "todo.md").write_text(TODO)
unread = Failure("no git")
standing = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
standing = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[2], {}))
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 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]))
quiet = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[2], {}))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_plan(quiet, announce=False)
self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts")
+13 -11
View File
@@ -99,14 +99,14 @@ class ChunkWindows(unittest.TestCase):
def test_tells_a_chunk_the_items_the_projects_other_live_chunks_hold(self):
with tempfile.TemporaryDirectory() as temp:
home = pathlib.Path(temp)
held = paths.paths_from(home)
held = paths.paths_from(home, {})
folder = held.claude_code_transcripts / "-r"
folder.mkdir(parents=True)
lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})]
(folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
# Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item.
fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n")
self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11])
self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, {}, fake.effects()), [8, 9, 10, 11])
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
@@ -118,13 +118,13 @@ class StartChunks(unittest.TestCase):
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.root = pathlib.Path(made.name, "r")
self.home = configured(self, self.root).parents[1]
self.home = configured(self, self.root).parents[2]
self.session = "loop-" + str(self.root).lstrip("/").replace("/", "-").replace(".", "-")
# Items 1 and 2 overlap, so 2 waits; 3 runs beside 1.
self.plan = plan_text("a.py", "a.py", "c.py")
def limit(self, chunks):
config = self.home / ".claude-projects" / self.root.name / "config.toml"
config = self.home / ".config/build-release" / self.root.name / "config.toml"
config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n")
def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None):
@@ -134,7 +134,7 @@ class StartChunks(unittest.TestCase):
ran = []
effects = dataclasses.replace(fake.effects(), git=self.git_reading(self.plan if plan is None else plan, ran))
with contextlib.redirect_stderr(io.StringIO()) as said:
started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home), env or {}, self.LAUNCHER, effects)
started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home, env or {}), env or {}, self.LAUNCHER, effects)
self.said = said.getvalue()
fetches = [args for args in ran if args[0] == "fetch"]
self.planned = len(fetches)
@@ -188,7 +188,7 @@ class StartChunks(unittest.TestCase):
def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self):
self.limit(2)
transcripts = paths.paths_from(self.home).claude_code_transcripts
transcripts = paths.paths_from(self.home, {}).claude_code_transcripts
folder = transcripts / "-r"
folder.mkdir(parents=True)
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
@@ -232,7 +232,7 @@ class StartChunks(unittest.TestCase):
def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self):
self.limit(2)
transcripts = paths.paths_from(self.home).claude_code_transcripts
transcripts = paths.paths_from(self.home, {}).claude_code_transcripts
folder = transcripts / "-r"
folder.mkdir(parents=True)
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
@@ -256,10 +256,11 @@ 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").mkdir(parents=True, exist_ok=True)
(self.home / ".local" / "state" / "build-release" / "claims").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)
self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/build-release/claims/"), started.reason)
def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self):
with self.assertRaisesRegex(OSError, "the plan's disk is gone"):
@@ -267,9 +268,10 @@ 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").mkdir(parents=True, exist_ok=True)
(self.home / ".local" / "state" / "build-release" / "claims").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])
self.assertEqual(chunk_windows.held_beside("item-7", str(self.root), paths.paths_from(self.home, {}), {}, fake.effects()), [9])
def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self):
with tempfile.TemporaryDirectory() as temp:
+9 -9
View File
@@ -129,7 +129,7 @@ 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/build-release"), CWD, fake.effects(), steps(start))
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME, env or {}), 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):
@@ -156,8 +156,8 @@ class WindowStarts(unittest.TestCase):
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"]))
self.assertEqual(asked, [(main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME), env, launcher, effects)])
main.run_loop(["do it"], env, paths.paths_from(self.HOME, {}), launcher, CWD, effects, steps(lambda *args: asked.append(args) or ["item-3"]))
self.assertEqual(asked, [(main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME, {}), env, launcher, effects)])
def test_a_window_loop_runs_its_chunk_in_its_own_session_and_window_and_hands_on_once_it_finished(self):
fake = FakeEffects(git=["/r\n"])
@@ -171,8 +171,8 @@ class WindowStarts(unittest.TestCase):
taken = steps(lambda *args: started.append(args) or [], fingerprint=lambda launcher: "", exec_if_edited=lambda *args: None, next_cycle=lambda *args: cycles.append(args) or cycle,
run_cycle=lambda cycle: concluded.pop(0), closed_cycle=lambda *args: closed.pop(0), check_routing=lambda *args: None)
with contextlib.redirect_stdout(io.StringIO()):
stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects, taken)
loop = this_loop.Loop(root="/r", session=session.session_named("A r 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)
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 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/build-release"), paths.paths_from(self.HOME)
effects, launcher, home = fake.effects(), pathlib.Path("/b/build-release"), paths.paths_from(self.HOME, env or {})
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}
@@ -246,7 +246,7 @@ 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/build-release"), 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):
@@ -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, "build-release"), 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):
@@ -325,7 +325,7 @@ class StopDms(unittest.TestCase):
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")
file = pathlib.Path("/h/.config/build-release/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; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run.")
+1 -1
View File
@@ -33,7 +33,7 @@ class RoutingCheck(unittest.TestCase):
self.home = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.home)
self.root = self.home / "archive"
self.paths = paths.paths_from(self.home)
self.paths = paths.paths_from(self.home, {})
self.session = session.session_named("A log build-release", self.paths.claude_code_transcripts)
def loop(self, fake):
+9 -8
View File
@@ -3,8 +3,9 @@ HELP = """Run a task as headless claude cycles; a judge interrupts only when a d
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
as goals-and-audience: a file, or a Jira epic's description. `project-config goals-and-audience`
premises. The goals file is the one the project's config, ~/.config/build-release/<key>/config.toml,
sets as goals-and-audience: a file, or a Jira epic's description. `project-config
goals-and-audience`
prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's
first worker prompt also quotes the premises. They, with code health (the setup's CLAUDE.md →
"Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the
@@ -78,9 +79,9 @@ 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 $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.
~/.local/state/build-release/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, build-release
@@ -110,7 +111,7 @@ characters to a file and see its path and the first 2,000 characters (BASH_MAX_O
bin/claude_code/output_limits.py).
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,
~/.config/build-release/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. BUILD_RELEASE_JUDGE_MODEL overrides
the model for the judge, BUILD_RELEASE_WORKER_MODEL for the worker and the session /talk opens; with
@@ -142,8 +143,8 @@ 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. build-release reads the
that keeps a routing-ladder.json in its config's folder, ~/.config/build-release/<key>/, runs on
that 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.
+15 -14
View File
@@ -325,13 +325,13 @@ class Checkout:
return self.home / ".claude.json"
def models_file(self):
return self.home / ".claude" / "loop-claude-models.json"
return self.home / ".config/build-release" / "models.json"
def transcripts(self):
return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl"))
def archive(self):
return pathlib.Path(self.env.get("BUILD_RELEASE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
return pathlib.Path(self.env.get("BUILD_RELEASE_TRANSCRIPTS", self.home / ".local/state/build-release" / "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."""
@@ -397,10 +397,10 @@ class Premises(unittest.TestCase):
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.strip(), f"cannot read {checkout.root}/README.md: Is a directory - no premises.")
(checkout.home / ".claude-projects" / "proj" / "config.toml").unlink()
(checkout.home / ".config/build-release" / "proj" / "config.toml").unlink()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.strip(), f"no config names the checkout {checkout.root}: write ~/.claude-projects/<key>/config.toml, as `project-config --help` shows - no premises.")
self.assertEqual(run.stderr.strip(), f"no config names the checkout {checkout.root}: write {checkout.home}/.config/build-release/<key>/config.toml, as `project-config --help` shows - no premises.")
(checkout.temp / "fake-bin" / "git").unlink()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
@@ -512,7 +512,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["BUILD_RELEASE_WORKER_MODEL"] = "claude-fable-5-2"
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
ladder = checkout.home / ".config/build-release" / "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)
run = checkout.run([worker(), judge(), worker(), judge(), worker()])
@@ -524,7 +524,7 @@ class Cycles(unittest.TestCase):
def test_says_where_the_projects_own_ladder_leaves_out_the_workers_model_and_says_nothing_on_the_shipped_one(self):
checkout = Checkout(self)
self.assertNotIn("own ladder", checkout.run([worker()]).stderr)
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
ladder = checkout.home / ".config/build-release" / "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; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run.\n", run.stderr)
@@ -533,7 +533,7 @@ class Cycles(unittest.TestCase):
def test_reads_the_projects_ladder_afresh_each_cycle_and_exits_1_once_it_holds_a_fault(self):
checkout = Checkout(self)
checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-fable-5-2"
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
ladder = checkout.home / ".config/build-release" / "proj" / "routing-ladder.json"
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "high"}]')
checkout.env["FAKE_CLAUDE_EDIT"] = str(ladder.parent)
run = checkout.run([worker(replace=["routing-ladder.json", '"high"}', '"high"},']), judge()])
@@ -672,7 +672,7 @@ class Cycles(unittest.TestCase):
checkout.archive().write_text("in the way")
run = checkout.run([worker(say="landed-it"), judge(finished=True, evidence="landed-it")])
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/loop-claude-transcripts/proj: Not a directory$")
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/build-release/transcripts/proj: Not a directory$")
self.assertEqual(run.stderr.count("could not archive the transcript"), 1)
session = argument(run.calls[0], "--session-id")
checkout.archive().unlink()
@@ -820,7 +820,7 @@ class Windows(unittest.TestCase):
checkout = Checkout(self)
checkout.commit_plan(BESIDE)
if parallel:
config = checkout.home / ".claude-projects" / "proj" / "config.toml"
config = checkout.home / ".config/build-release" / "proj" / "config.toml"
config.write_text(f"parallel-chunks = {parallel}\n" + config.read_text())
return checkout
@@ -944,11 +944,11 @@ class Interrupt(unittest.TestCase):
def test_sends_the_dm_through_the_notifier_and_env_file_the_config_names_and_no_credential_reaches_a_prompt_a_line_printed_or_a_file_written(self):
checkout = Checkout(self)
token = "tok-3f9a1c7e-sentinel"
env_file = checkout.home / ".claude-projects" / "proj.env"
env_file = checkout.home / ".config/build-release" / "proj.env"
env_file.write_text(f"MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN={token}\nMATTERMOST_RECIPIENT=lilleman\n")
env_file.chmod(0o600)
with (checkout.home / ".claude-projects" / "proj" / "config.toml").open("a") as config:
config.write('env-file = "~/.claude-projects/proj.env"\nnotifier = "mattermost"\n')
with (checkout.home / ".config/build-release" / "proj" / "config.toml").open("a") as config:
config.write('env-file = "~/.config/build-release/proj.env"\nnotifier = "mattermost"\n')
run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")])
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
self.assertIn("could not DM you: cannot reach https://127.0.0.1:1", run.stderr)
@@ -1054,7 +1054,7 @@ class Models(unittest.TestCase):
def test_keeps_the_models_file_mode_and_other_projects_when_saving(self):
checkout = Checkout(self)
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"]
checkout.models_file().parent.mkdir(parents=True)
checkout.models_file().parent.mkdir(parents=True, exist_ok=True)
checkout.models_file().write_text(json.dumps({"other": "model-x"}))
checkout.models_file().chmod(0o640)
def saved_elsewhere():
@@ -1092,7 +1092,8 @@ class Models(unittest.TestCase):
assert_not_root(self)
checkout = Checkout(self)
del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"]
checkout.models_file().parent.mkdir(parents=True, mode=0o500)
checkout.models_file().parent.mkdir(parents=True, exist_ok=True)
checkout.models_file().parent.chmod(0o500)
self.addCleanup(checkout.models_file().parent.chmod, 0o700)
run = checkout.run([worker()], terminal_input="custom-model\n")
self.assertEqual((run.code, run.calls), (1, []))