From 3519922f01b901be426419f5e476be523542a84d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 4 Dec 2026 02:45:02 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1=20(2=20misread);=20read=20the?= =?UTF-8?q?=20scoring=20rule=20from=20the=20clone,=20hand=20windows=20XDG?= =?UTF-8?q?=5FDATA=5FHOME,=20retry=20the=20home=20check=20where=20nobody?= =?UTF-8?q?=20watches,=20tell=20an=20unreadable=20sign-in=20status=20and?= =?UTF-8?q?=20settings=20file=20apart,=20and=20bound=20the=20claude=20comm?= =?UTF-8?q?ands=20that=20build=20the=20home?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/agent_cycle/retry.py | 8 +++++ bin/build_epic/main.py | 5 ++- bin/build_epic/planning.py | 16 ++++----- bin/build_epic/test_main.py | 15 +++++--- bin/build_epic/test_planning.py | 30 ++++++---------- bin/build_release/loop/main.py | 3 +- bin/build_release/loop/test_chunk_windows.py | 2 +- bin/build_release/loop/test_main.py | 12 +++++++ bin/build_release/loop/usage.py | 7 ++-- bin/build_release/test_black_box.py | 2 +- bin/chunk_driver/claims.py | 6 ++-- bin/chunk_driver/test_claims.py | 8 ++--- bin/claude_home/home.py | 38 +++++++++++++------- bin/claude_home/test_home.py | 30 ++++++++++++++-- bin/loop_effects/effects.py | 8 +++-- bin/loop_effects/test_effects.py | 23 ++++++++++++ bin/loop_state/paths.py | 4 +-- bin/repo_checks/test_settings.py | 2 +- bin/self_update/main.py | 3 +- 19 files changed, 153 insertions(+), 69 deletions(-) diff --git a/bin/agent_cycle/retry.py b/bin/agent_cycle/retry.py index 25a5b775..cc0988f9 100644 --- a/bin/agent_cycle/retry.py +++ b/bin/agent_cycle/retry.py @@ -37,6 +37,14 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec effects.sleep(RETRY_DELAY) +def home_unready(effects: Effects, watched: bool) -> str | None: + """Why no claude can run in the loop's Claude home, which effects.claude_home builds, or None where one can. Where nobody watches, as in a chunk's window or a reload, a failure is retried as a failed worker run is, since `claude` may fail while Claude Code's updater repoints it.""" + if watched: + return effects.claude_home() + checked = retried("check of the loop's Claude home", lambda: Failure(reason) if (reason := effects.claude_home()) else None, effects) + return checked.reason if isinstance(checked, Stop) else None + + def limit_wait(limited: Limited, now: float) -> float: # The limit rejects every request until it resets, so wait for a known reset and poll rarely for an unknown one. if limited.resets_at is not None and limited.resets_at + PAST_RESET > now: diff --git a/bin/build_epic/main.py b/bin/build_epic/main.py index 39ca93d0..b446455c 100644 --- a/bin/build_epic/main.py +++ b/bin/build_epic/main.py @@ -27,6 +27,7 @@ from build_epic.backend.protocol import EpicIssue, EpicStore from build_epic.epic_record import EpicRecord from failure import Failure from agent_cycle.verdicts import Finished, TakenIn +from agent_cycle.retry import home_unready from atlassian.jira import ISSUE_KEY from build_epic.backend.jira import JiraEpic from claude_code.reply import Limited @@ -51,6 +52,8 @@ HELP = f"""usage: build-epic [--status | --dry-run] {finish.USAGE} Runs the chunks of one Jira epic, such as ABC-12, each in its own window of the tmux session epic-. +It runs every claude in the loop's Claude home, ~/.local/share/build-release/claude-home, which it builds first, under --dry-run too. +Until someone has signed in there, it stops and prints the command to sign in with. README.md → Install says what the home holds. Before it starts chunks, build-epic plans each open issue that has none of these labels: `repo:` for its repo, `build-epic-claude` for work of Claude's that changes no repo, `build-epic-human` for a task of yours. A label that `[label-repos]` in config.toml maps to a repo counts as that repo's. @@ -123,7 +126,7 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: if writes or closes: return epic_written(words[0], writes, paths, env, backend, stdin) # Before anything starts: a clone, a claude session or a tmux window. One stop names everything that is the person's to do. A dry run opens no window, but its planning runs claude. - if needs := [reason for reason in (None if dry_run_asked else tmux.unusable(effects.tmux, chunk_prompt.DRIVER), effects.claude_home()) if reason]: + if needs := [reason for reason in (None if dry_run_asked else tmux.unusable(effects.tmux, chunk_prompt.DRIVER), home_unready(effects, watched=chunk is None)) if reason]: return Stop(1, "\n".join(needs)) config = load(paths.home, env) if isinstance(config, Failure): diff --git a/bin/build_epic/planning.py b/bin/build_epic/planning.py index bda48dbb..5729ccaf 100644 --- a/bin/build_epic/planning.py +++ b/bin/build_epic/planning.py @@ -11,7 +11,6 @@ import pathlib import re from build_epic.config import BuildEpicConfig -from loop_state.paths import CLAUDE_HOME from loop_effects.effects import Effects, say from build_epic.backend.protocol import EpicIssue, EpicStore, no_scores from build_epic.epic_record import EpicRecord @@ -22,6 +21,7 @@ from plan.todo_table import Item from claude_code.reply import Limited from plan_store.jira_epic import number from model_routing.ladder_file import read_ladder, SHIPPED +from loop_state.paths import RELEASE_ROOT from model_routing.ladder import Rung from build_epic.scheduler import unblocks from plan_store.scoring import weighing_texts @@ -30,8 +30,8 @@ from plan_store.scoring import weighing_texts FORMULA = re.compile(r"^`Score = ([^`]+)`$", re.M) # An epic item has no release, and ranking wants every item of one epic in the same one. NO_RELEASE = (0, 0, 0) -# The rule every plan item is scored by, under the home folder, where each machine's setup keeps it. -RULE = f"{CLAUDE_HOME}/rules/todo-items.md" +# The rule every plan item is scored by, under the clone the setup ships in. +RULE = pathlib.Path("rules/todo-items.md") @dataclasses.dataclass(frozen=True) @@ -209,7 +209,7 @@ def scored(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Fai bare = [issue for issue in ours if not issue.scores] if not bare or len(ours) < 2: return issues, None - rung, language, rule, weighed = planning_rung(epic.config.repoless_model), epic.record.language(), scoring_rule(epic.home), weighing(epic, bare) + rung, language, rule, weighed = planning_rung(epic.config.repoless_model), epic.record.language(), scoring_rule(RELEASE_ROOT), weighing(epic, bare) if failed := next((each for each in (rung, language, rule, weighed) if isinstance(each, Failure)), None): return issues, failed assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(rule, str) and isinstance(weighed, Weighing) @@ -241,12 +241,12 @@ def scores_set(epic: Planned, issue: EpicIssue, answer: issue_scores.Scores, wei return ranked if isinstance(ranked, Failure) else epic.store.set_scores(issue.key, answer.scores, answer.moves, answer.comment) or held -def scoring_rule(home: pathlib.Path) -> str | Failure: - """The text every plan item is scored by, which says what L, E, I and S mean.""" +def scoring_rule(clone: pathlib.Path) -> str | Failure: + """The text every plan item is scored by, in clone, which says what L, E, I and S mean.""" try: - return (home / RULE).read_text(encoding="utf-8") + return (clone / RULE).read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: - return Failure(f"cannot read the scoring rule {home / RULE}, so no issue is scored: {failure}") + return Failure(f"cannot read the scoring rule {clone / RULE}, so no issue is scored: {failure}") def start_order(epic: Planned, issues: list[EpicIssue]) -> list[str] | Failure: diff --git a/bin/build_epic/test_main.py b/bin/build_epic/test_main.py index 1f83ff3c..d8b97048 100644 --- a/bin/build_epic/test_main.py +++ b/bin/build_epic/test_main.py @@ -14,7 +14,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from build_epic.config import BuildEpicConfig from build_epic.parking import CHUNK_PR -from build_epic import chunk_prompt, epic_run, main, planning +from build_epic import chunk_prompt, epic_run, main from chunk_driver.chunk_run import ChunkRun from project_config.doubles import configured from project_config.settings import Epic, Finish @@ -162,7 +162,7 @@ class TheCommand(BuildEpicTest): 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/build-release/build-epic/ABC-12"), "-e", "BUILD_RELEASE_WORKER_MODEL=m", "-e", "XDG_CONFIG_HOME=", "-e", "XDG_STATE_HOME=", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/build-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/build-release/build-epic/ABC-12"), "-e", "BUILD_RELEASE_WORKER_MODEL=m", "-e", "XDG_CONFIG_HOME=", "-e", "XDG_STATE_HOME=", "-e", "XDG_DATA_HOME=", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/build-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"]) @@ -203,6 +203,15 @@ class TheCommand(BuildEpicTest): self.assertIn("--chunk is how build-epic starts itself in a tmux window; run build-epic \n", err) self.assertEqual(fake.dms, ["build-epic --chunk ABC-21 ABC-12 stopped: --chunk is how build-epic starts itself in a tmux window; run build-epic "]) + def test_a_chunk_retries_a_failed_check_of_the_loops_claude_home_as_a_failed_worker_run_is(self) -> None: + fake = FakeEffects() + fake.home_unready = "could not build it" + code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, {"TMUX_PANE": "%1"}) + self.assertEqual(code, 1) + self.assertEqual(err.count("retrying the check of the loop's Claude home in a minute: could not build it\n"), 2) + self.assertEqual(fake.dms, ["build-epic --chunk ABC-21 ABC-12 stopped: the check of the loop's Claude home failed three times running: could not build it"]) + self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)]) + def test_a_chunk_of_an_issue_the_epic_lacks_stops(self) -> None: code, _, err = self.run_main(["--chunk", "ABC-99", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"}) self.assertEqual(code, 1) @@ -1477,8 +1486,6 @@ class TheDryRun(BuildEpicTest): self.assertEqual([what for seam, what in fake.calls if seam == "git" and "clone" in what], []) def test_prints_the_scores_it_would_write_and_the_order_the_issues_would_start_in(self) -> None: - (self.home / planning.RULE).parent.mkdir(parents=True, exist_ok=True) - (self.home / planning.RULE).write_text("L is how much the item changes.\n", encoding="utf-8") self.description = DESCRIPTION.replace("Ship the import.", "1. **Achieve:** Ship the import.") + "\n## Scoring\n`Score = V`\n" self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-claude")] answer = {"L": 2, "E": 1, "I": 2, "S": 3, "comment": "Scored to decide what starts first."} diff --git a/bin/build_epic/test_planning.py b/bin/build_epic/test_planning.py index c58bc538..004ec5de 100644 --- a/bin/build_epic/test_planning.py +++ b/bin/build_epic/test_planning.py @@ -21,6 +21,7 @@ from build_epic.config import load from build_epic.backend.fake import MemoryEpic from plan.todo_table import parse_moves from build_epic import planning +from loop_state.paths import RELEASE_ROOT RANKED = "## Goals\n1. **Achieve:** Ship the import.\n\n## Audience\nThe client's team.\n\n## Scoring\n`Score = V`\n" GOALS = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** Serve the API.\n\n## Audience\nIts callers.\n" @@ -54,11 +55,6 @@ class Planning(BuildEpicTest): issues, stopped = planning.planned(epic, read) return issues if stopped is None else stopped, store, out.getvalue() - def rule(self) -> None: - """Writes the rule every plan item is scored by.""" - (self.home / planning.RULE).parent.mkdir(parents=True, exist_ok=True) - (self.home / planning.RULE).write_text("L is how much the item changes.\n", encoding="utf-8") - def repo(self, name: str) -> None: """Checks out the repo called name, whose goals file voids code health and states one achieve goal.""" checkout = self.home / "code" / name @@ -378,7 +374,9 @@ class Planning(BuildEpicTest): self.assertEqual(self.plan(FakeEffects())[0], self.issues) def test_scores_each_bare_issue_whoever_filed_it_and_tells_its_team_without_ranking_a_persons(self) -> None: - self.rule() + # The person's own Claude home may hold an older release's rule, which the scoring doesn't read. + (self.home / ".claude/rules").mkdir(parents=True) + (self.home / ".claude/rules/todo-items.md").write_text("An older release's rule.\n", encoding="utf-8") self.description = RANKED self.issues = [scored("ABC-20", "epic 1 by 2", "build-epic-claude", by_loop=False), issue("ABC-21", "build-epic-claude")] # An earlier run made the folder the scoring runs in. @@ -392,12 +390,12 @@ class Planning(BuildEpicTest): self.assertEqual(out, "<1790000000> scoring ABC-21\n<1790000000> ABC-21 is scored L 2, E 1, I 2, S 3, Moves epic 1 by 9\n") self.assertEqual(planning.start_order(self.epic, found), ["ABC-21", "ABC-20"]) (asked,) = fake.made("claude") - for part in ("L is how much the item changes.", "Write the comment in English", "An item moves only these: `epic 1`.", "## Item ABC-21: Do ABC-21", "Labels: build-epic-claude"): + self.assertNotIn("An older release's rule.", asked[1]) + for part in ((RELEASE_ROOT / "rules/todo-items.md").read_text(encoding="utf-8"), "Write the comment in English", "An item moves only these: `epic 1`.", "## Item ABC-21: Do ABC-21", "Labels: build-epic-claude"): self.assertIn(part, asked[1]) self.assertIn("--json-schema", asked[0]) def test_scores_no_human_task_and_no_issue_that_is_the_only_one_to_start(self) -> None: - self.rule() self.description = RANKED self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-human")] fake = FakeEffects() @@ -407,7 +405,6 @@ class Planning(BuildEpicTest): def test_scores_no_issue_whose_work_has_landed(self) -> None: with (self.home / ".config/build-release/build-epic/config.toml").open("a", encoding="utf-8") as config: config.write('\njira-unblocking-statuses = ["Release Ready"]\n') - self.rule() self.description = RANKED self.issues = [issue("ABC-20", "build-epic-claude", status="release ready"), issue("ABC-21", "build-epic-claude"), scored("ABC-22", "epic 1 by 2", "build-epic-claude")] fake = FakeEffects(claude=[says(ANSWER)]) @@ -417,7 +414,6 @@ class Planning(BuildEpicTest): self.assertEqual(planning.start_order(self.epic, found), ["ABC-21", "ABC-22"]) def test_names_an_issue_whose_scoring_fails_and_scores_the_next(self) -> None: - self.rule() self.description = RANKED self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-claude"), issue("ABC-22", "build-epic-claude"), issue("ABC-23", "build-epic-claude")] fake = FakeEffects(claude=[says({"L": "big"}), says(ANSWER | {"moves": "epic 7 by 5"}), says(ANSWER | {"L": 99}), says(ANSWER)]) @@ -432,7 +428,6 @@ class Planning(BuildEpicTest): self.assertEqual(planning.start_order(self.epic, found), ["ABC-23"]) def test_names_each_issue_whose_goals_cannot_be_read_and_asks_claude_about_none(self) -> None: - self.rule() self.description = RANKED.replace("1. **Achieve:** ", "") self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-claude")] fake = FakeEffects() @@ -442,7 +437,6 @@ class Planning(BuildEpicTest): self.assertEqual(fake.made("claude"), []) def test_the_scoring_call_runs_in_the_epics_state_folder(self) -> None: - self.rule() self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-claude")] effects, folders = FakeEffects(claude=[says(ANSWER), says(ANSWER)]).effects(), [] @@ -455,7 +449,6 @@ class Planning(BuildEpicTest): planning.planned(epic, list(self.issues)) self.assertEqual(folders, [str(self.folder)] * 2) - self.rule() self.description = RANKED self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-claude")] fake = FakeEffects(claude=[subprocess.CompletedProcess([], 0, json.dumps(LIMIT), "")]) @@ -464,7 +457,6 @@ class Planning(BuildEpicTest): self.assertEqual((store.writes, len(fake.made("claude"))), ([], 1)) def test_names_a_score_the_tracker_refuses(self) -> None: - self.rule() self.description = RANKED self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-human"), scored("ABC-22", "epic 1 by 2", "build-epic-claude")] store = MemoryEpic("ABC-12", list(self.issues)) @@ -478,13 +470,12 @@ class Planning(BuildEpicTest): self.assertEqual((found, stopped, out.getvalue()), (self.issues, None, "<1790000000> scoring ABC-20\n<1790000000> ABC-20 is not scored: Jira answered 503\n")) def test_scores_no_issue_without_the_scoring_rule_or_the_epics_formula(self) -> None: + # A clone without the rule, here the test's home folder. + rule = planning.scoring_rule(self.home) + assert isinstance(rule, Failure), rule + self.assertIn(f"cannot read the scoring rule {self.home}/rules/todo-items.md, so no issue is scored: ", rule.reason) self.issues = [issue("ABC-20", "build-epic-claude"), issue("ABC-21", "build-epic-claude")] - self.description = RANKED fake = FakeEffects() - found, _, _ = self.plan(fake) - assert isinstance(found, Failure), found - self.assertIn(f"cannot read the scoring rule {self.home}/.claude/rules/todo-items.md, so no issue is scored: ", found.reason) - self.rule() self.description = "## Goals\n1. **Achieve:** Ship the import.\n\n## Audience\nThe client's team.\n\n## Scoring\n" found, _, _ = self.plan(fake) assert isinstance(found, Failure), found @@ -492,7 +483,6 @@ class Planning(BuildEpicTest): self.assertEqual(fake.made("claude"), []) def test_scores_a_sub_task_on_its_own_against_its_repos_goals_in_the_epics_language(self) -> None: - self.rule() self.repo("api") self.description = RANKED + "\n**Language:** Swedish\n" self.issues = [issue("ABC-20", "split-by-repo"), issue("ABC-30", "repo:api", parent="ABC-20"), scored("ABC-21", "epic 1 by 2", "build-epic-claude")] diff --git a/bin/build_release/loop/main.py b/bin/build_release/loop/main.py index ee168bf5..3f94ad8b 100644 --- a/bin/build_release/loop/main.py +++ b/bin/build_release/loop/main.py @@ -17,6 +17,7 @@ from loop_effects.effects import Effects, say from failure import Failure from agent_cycle.verdicts import Finished from build_release.loop.usage import HELP +from agent_cycle.retry import home_unready from chunk_driver.this_loop import Loop from loop_state.paths import Paths from transcript_archive.project_key import project_key @@ -72,7 +73,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if isinstance(loop_run, Stop): return loop_run # Before anything starts: a worktree, a claude session or a tmux window. One stop names everything that is the person's to do. - if needs := [reason for reason in (tmux.unusable(effects.tmux, fresh_prompt.DRIVER), effects.claude_home()) if reason]: + if needs := [reason for reason in (tmux.unusable(effects.tmux, fresh_prompt.DRIVER), home_unready(effects, watched=loop_run.chunk is None)) if reason]: return Stop(1, "\n".join(needs)) if loop_run.chunk is None: return windows_opened(loop_run, env, paths, launcher, effects, steps.start_chunks) diff --git a/bin/build_release/loop/test_chunk_windows.py b/bin/build_release/loop/test_chunk_windows.py index a0eb40bc..cff6257b 100644 --- a/bin/build_release/loop/test_chunk_windows.py +++ b/bin/build_release/loop/test_chunk_windows.py @@ -168,7 +168,7 @@ class StartChunks(unittest.TestCase): 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 build-release's own variables and the two XDG ones 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", "XDG_CONFIG_HOME=", "XDG_STATE_HOME="]) + self.assertEqual([word for word in first if "=" in word], ["BUILD_RELEASE_WORKER_MODEL=m", "XDG_CONFIG_HOME=", "XDG_STATE_HOME=", "XDG_DATA_HOME="]) 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) diff --git a/bin/build_release/loop/test_main.py b/bin/build_release/loop/test_main.py index 0d698f38..7e9d71e0 100644 --- a/bin/build_release/loop/test_main.py +++ b/bin/build_release/loop/test_main.py @@ -263,6 +263,18 @@ class WindowStarts(unittest.TestCase): 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 ")) self.assertEqual(self.asked, []) + def test_a_window_loop_retries_a_failed_check_of_the_loops_claude_home_as_a_failed_worker_run_is(self): + # Nobody watches a window, and a claude that Claude Code's updater repoints fails for a moment. + for answers, stop in ((["could not build it", None], Stop(1, "--chunk is how build-release starts itself in a tmux window; run build-release ")), (["could not build it"] * 3, Stop(1, "the check of the loop's Claude home failed three times running: could not build it"))): + with self.subTest(stop=stop): + fake = FakeEffects(git=["/r\n"]) + effects = dataclasses.replace(fake.effects(), claude_home=lambda: answers.pop(0)) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: + self.assertEqual(main.run_loop(["--chunk", "item-3", "do it"], {}, paths.paths_from(self.HOME, {}), pathlib.Path("/b/build-release"), CWD, effects, steps(self.fail)), stop) + self.assertEqual(answers, []) + self.assertIn(f"{STAMP} retrying the check of the loop's Claude home in a minute: could not build it\n", said.getvalue()) + self.assertIn(("sleep", 60), fake.calls) + def test_reads_the_chunk_a_window_loop_is_started_with(self): self.assertEqual(main.loop_run_from(["--chunk", "item-3", "do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "", chunk="item-3")) self.assertEqual(main.loop_run_from(["do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "")) diff --git a/bin/build_release/loop/usage.py b/bin/build_release/loop/usage.py index 4797dc01..fd1dac24 100644 --- a/bin/build_release/loop/usage.py +++ b/bin/build_release/loop/usage.py @@ -29,9 +29,10 @@ Words: the setup's CLAUDE.md → "Vocabulary". build-release runs every claude in the loop's Claude home, ~/.local/share/build-release/claude-home, which it builds from the clone it ships in before it starts anything. Until someone has signed in -there, it stops and prints the line that does so. README.md → Install says what the home holds. +there, it stops and prints the command to sign in with. README.md → Install says what the +home holds. -build-release needs tmux 3.2 or later, and checks that first too. Each chunk runs in +build-release needs tmux 3.2 or later, and checks that first as well. Each chunk runs in its own window of one tmux session per project, named loop-, such as loop-claude-config. 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 @@ -174,7 +175,7 @@ Exit 1, saying why, when: - no task is given - git cannot start or finds no checkout - tmux is missing or older than 3.2, the loop's Claude home cannot be built, or nobody is signed - in there + in there; a chunk's window checks the home three times, a minute apart, before it stops - --chunk is given outside a tmux window - a chunk's window cannot be started, as when the project's config cannot be read, or the tmux session runs another checkout's chunks diff --git a/bin/build_release/test_black_box.py b/bin/build_release/test_black_box.py index f7ea0e2a..82c693c3 100644 --- a/bin/build_release/test_black_box.py +++ b/bin/build_release/test_black_box.py @@ -843,7 +843,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", "BUILD_RELEASE_JUDGE_MODEL=judge-model", "-e", "BUILD_RELEASE_WORKER_MODEL=worker-model", "-e", "XDG_CONFIG_HOME=", "-e", "XDG_STATE_HOME=", "-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", "-e", "XDG_CONFIG_HOME=", "-e", "XDG_STATE_HOME=", "-e", "XDG_DATA_HOME=", "-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"], diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py index 181fd6b2..6f538d01 100644 --- a/bin/chunk_driver/claims.py +++ b/bin/chunk_driver/claims.py @@ -8,7 +8,7 @@ import pathlib import typing from failure import Failure -from loop_state.paths import Paths, XDG_CONFIG_HOME, XDG_STATE_HOME +from loop_state.paths import Paths, XDG_CONFIG_HOME, XDG_DATA_HOME, XDG_STATE_HOME from transcript_archive.project_key import project_key from agent_cycle import tmux @@ -22,9 +22,9 @@ OWN = "BUILD_RELEASE_" # A window gets the tmux server's environment, not the starting terminal's. With another XDG value than its starter's, a window would lock and write in other folders. So each is handed even where the starter lacks it, as empty: an empty value moves no folder. def handed(env: typing.Mapping[str, str]) -> dict[str, str]: - """The variables an entry point hands each window it starts: those of env that both entry points read, and the two that move the config folder and the state folder.""" + """The variables an entry point hands each window it starts: those of env that both entry points read, and the three that move the config folder, the state folder and the loop's Claude home.""" own = {name: value for name, value in env.items() if name.startswith(OWN)} - return {**own, XDG_CONFIG_HOME: env.get(XDG_CONFIG_HOME, ""), XDG_STATE_HOME: env.get(XDG_STATE_HOME, "")} + return {**own, **{name: env.get(name, "") for name in (XDG_CONFIG_HOME, XDG_STATE_HOME, XDG_DATA_HOME)}} @contextlib.contextmanager diff --git a/bin/chunk_driver/test_claims.py b/bin/chunk_driver/test_claims.py index 0c5f4076..13607821 100644 --- a/bin/chunk_driver/test_claims.py +++ b/bin/chunk_driver/test_claims.py @@ -10,12 +10,12 @@ from chunk_driver.claims import handed, LOCK, starting class Handed(unittest.TestCase): - def test_hands_a_window_the_setups_own_variables_and_the_two_that_move_its_folders(self) -> None: - env = {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state", "XDG_DATA_HOME": "/data", "PATH": "/bin"} - self.assertEqual(handed(env), {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state"}) + def test_hands_a_window_the_setups_own_variables_and_the_three_that_move_its_folders(self) -> None: + env = {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state", "XDG_DATA_HOME": "/data", "XDG_CACHE_HOME": "/cache", "PATH": "/bin"} + self.assertEqual(handed(env), {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state", "XDG_DATA_HOME": "/data"}) def test_hands_an_xdg_variable_the_starter_lacks_as_empty_so_the_tmux_servers_value_moves_no_folder(self) -> None: - self.assertEqual(handed({"PATH": "/bin", "XDG_STATE_HOME": "/state"}), {"XDG_CONFIG_HOME": "", "XDG_STATE_HOME": "/state"}) + self.assertEqual(handed({"PATH": "/bin", "XDG_STATE_HOME": "/state"}), {"XDG_CONFIG_HOME": "", "XDG_STATE_HOME": "/state", "XDG_DATA_HOME": ""}) class Starting(unittest.TestCase): diff --git a/bin/claude_home/home.py b/bin/claude_home/home.py index 25b27dcf..fb101d3f 100644 --- a/bin/claude_home/home.py +++ b/bin/claude_home/home.py @@ -15,7 +15,7 @@ from text_files.file_writes import replace_file # What the home links to in the clone: the instruction files Claude Code reads from its home. LINKED = ("CLAUDE.md", "agents", "rules", "skills") -# In a value of the clone's settings.json, the clone's folder. Every value that holds it is a shell command, such as a hook's. +# Stands for the clone's folder in the clone's settings.json. Every value that holds it is a shell command, such as a hook's. CLONE = "{clone}" # The file in the home that names the clone and the commit the home was built from. BUILT_FROM = "built-from" @@ -34,22 +34,31 @@ def unready(home: pathlib.Path, clone: pathlib.Path, claude: Claude, git: Git) - built = refreshed(home, clone, claude, git) if isinstance(built, Failure): return f"could not build the loop's Claude home, {home}: {built.reason}" - status = claude(["auth", "status"]).stdout - except OSError as failure: + status = claude(["auth", "status"]) + except (OSError, subprocess.TimeoutExpired) as failure: return f"could not build the loop's Claude home, {home}: {failure}" - if signed_in(status): + signed = signed_in(status.stdout) + if signed is None: + return f"could not ask claude who is signed in to the loop's Claude home, {home}: {printed(status)}" + if signed: return None - # /login is typed in a claude that runs in the home: lilleman chose it over a token file on 2026-12-03. + # /login is typed in a claude that runs in the home: docs/decisions.md → `Claude Code in a home of its own`. return f"nobody is signed in to the loop's Claude home; run `CLAUDE_CONFIG_DIR={shlex.quote(str(home))} claude` and type /login there, once" -def signed_in(status: str) -> bool: - """Whether `claude auth status` printed that someone is signed in, by a /login or by a token in the environment.""" +def signed_in(status: str) -> bool | None: + """Whether `claude auth status` printed that someone is signed in, by a /login or by a token in the environment; None where it printed no such answer.""" try: read = json.loads(status) except ValueError: - return False - return isinstance(read, dict) and read.get("loggedIn") is True + return None + logged_in = read.get("loggedIn") if isinstance(read, dict) else None + return logged_in if isinstance(logged_in, bool) else None + + +def printed(done: subprocess.CompletedProcess[str]) -> str: + """What a claude command printed, on stderr, else on stdout, on one line.""" + return " ".join((done.stderr or done.stdout).split()) or f"it printed nothing and exited {done.returncode}" def refreshed(home: pathlib.Path, clone: pathlib.Path, claude: Claude, git: Git) -> Failure | None: @@ -82,8 +91,14 @@ def settings_written(home: pathlib.Path, clone: pathlib.Path) -> Failure | None: """Writes the home's settings.json: the clone's, with the clone's folder in place of CLONE, and the model the home's file holds.""" settings = placed(json.loads((clone / "settings.json").read_text(encoding="utf-8")), shlex.quote(str(clone))) generated = home / "settings.json" + try: + old = json.loads(generated.read_text(encoding="utf-8")) if generated.is_file() else {} + except ValueError as failure: + return Failure(f"{generated} is not a JSON object: {failure}; delete it and run again") + if not isinstance(old, dict): + return Failure(f"{generated} is not a JSON object; delete it and run again") # Claude Code writes a /model pick into the home's file, so a refresh keeps it. - if generated.is_file() and "model" in (old := json.loads(generated.read_text(encoding="utf-8"))): + if "model" in old: settings["model"] = old["model"] return replace_file(generated, (json.dumps(settings, indent=2, sort_keys=True) + "\n").encode()) @@ -107,6 +122,5 @@ def plugins_installed(clone: pathlib.Path, claude: Claude) -> Failure | None: for command in commands + [["plugin", "install", plugin] for plugin in plugins]: done = claude(command) if done.returncode: - said = " ".join((done.stderr or done.stdout).split()) - return Failure(f"claude {' '.join(command)} failed: {said}") + return Failure(f"claude {' '.join(command)} failed: {printed(done)}") return None diff --git a/bin/claude_home/test_home.py b/bin/claude_home/test_home.py index a8194100..efb6436a 100644 --- a/bin/claude_home/test_home.py +++ b/bin/claude_home/test_home.py @@ -127,10 +127,26 @@ class Home(unittest.TestCase): self.assertEqual(self.unready(), f"nobody is signed in to the loop's Claude home; run `CLAUDE_CONFIG_DIR={self.home} claude` and type /login there, once") - def test_a_status_that_is_no_json_reads_as_signed_out(self) -> None: - self.status = "Not logged in" + def test_a_status_that_says_nobody_is_signed_in_or_out_quotes_what_claude_said(self) -> None: + for stdout, stderr, said in (("", "Error: the settings\nare broken\n", "Error: the settings are broken"), ("Not logged in\n", "", "Not logged in"), ('{"authMethod": "none"}', "", '{"authMethod": "none"}'), ("", "", "it printed nothing and exited 1")): + with self.subTest(said=said): + def claude(args: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.CompletedProcess(args, 1, stdout, stderr) if args == ["auth", "status"] else subprocess.CompletedProcess(args, 0, "", "") - self.assertIn("nobody is signed in", self.unready() or "") + reason = unready(self.home, self.clone, claude, lambda *args, cwd=None: "1a2b3c\n") + + self.assertEqual(reason, f"could not ask claude who is signed in to the loop's Claude home, {self.home}: {said}") + + def test_a_home_settings_file_that_is_no_json_object_stops_naming_the_file(self) -> None: + for written in ('{"model": "o', "3"): + with self.subTest(written=written): + self.home.mkdir(parents=True, exist_ok=True) + (self.home / "settings.json").write_text(written, encoding="utf-8") + + reason = self.unready() or "" + + self.assertTrue(reason.startswith(f"could not build the loop's Claude home, {self.home}: {self.home / 'settings.json'} is not a JSON object"), reason) + self.assertTrue(reason.endswith("; delete it and run again"), reason) def test_a_plugin_that_does_not_install_stops_and_the_next_run_tries_again(self) -> None: self.exits = {"lsp@other": 1} @@ -162,6 +178,14 @@ class Home(unittest.TestCase): self.assertEqual(reason, f"could not build the loop's Claude home, {self.home}: [Errno 2] No such file or directory: 'claude'") + def test_a_claude_that_is_stopped_after_its_time_stops(self) -> None: + def stalled(args: list[str]) -> subprocess.CompletedProcess[str]: + raise subprocess.TimeoutExpired(["claude", *args], 600) + + reason = unready(self.home, self.clone, stalled, lambda *args, cwd=None: "1a2b3c\n") + + self.assertEqual(reason, f"could not build the loop's Claude home, {self.home}: Command '['claude', 'plugin', 'marketplace', 'add', 'anthropics/official']' timed out after 600 seconds") + if __name__ == "__main__": unittest.main() diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index 2ecc5257..6a0f6ca3 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -30,6 +30,8 @@ from claude_home.home import unready PYTHON_TIMEOUT = 600 # Seconds a command of the forge's CLI may take, so a stalled one cannot hold the loop. FORGE_TIMEOUT = 60 +# Seconds each `claude` command that builds the loop's Claude home may take, as long as a Python script may, so a stalled plugin download cannot hold every loop that waits on the home's lock. +HOME_TIMEOUT = PYTHON_TIMEOUT class Streaming(typing.Protocol): @@ -118,14 +120,14 @@ class StreamingClaude: return self.proc.wait() -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: +def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS, forge_timeout: float = FORGE_TIMEOUT, home_timeout: float = HOME_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 in the loop's Claude home, with the release's tools first on its `PATH`. - 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. + 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` or `home_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=claude_environment(env, home), input=stdin, text=True), - claude_home=lambda: unready(claude_home(env, home), RELEASE_ROOT, lambda args: subprocess.run(["claude", *args], capture_output=True, env=claude_environment(env, home), stdin=subprocess.DEVNULL, text=True), git_repo.git), + claude_home=lambda: unready(claude_home(env, home), RELEASE_ROOT, lambda args: subprocess.run(["claude", *args], capture_output=True, env=claude_environment(env, home), stdin=subprocess.DEVNULL, text=True, timeout=home_timeout), git_repo.git), claude_on_terminal=claude_on_terminal, discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), dm=lambda text, directory: notify(text, directory, home, env, backends), diff --git a/bin/loop_effects/test_effects.py b/bin/loop_effects/test_effects.py index 03167e54..01240239 100644 --- a/bin/loop_effects/test_effects.py +++ b/bin/loop_effects/test_effects.py @@ -153,6 +153,29 @@ class ClaudeHomeEffect(unittest.TestCase): self.assertEqual(ran[-1], f"{built} auth status") self.assertIn(f"{built} plugin install code-review@claude-plugins-official", ran) + def test_a_plugin_that_does_not_install_stops_naming_the_command_and_what_claude_said(self): + with tempfile.TemporaryDirectory() as folder: + claude = pathlib.Path(folder, "claude") + claude.write_text('#!/bin/sh\nif [ "$*" = "plugin install code-review@claude-plugins-official" ]; then echo "no such plugin" >&2; exit 1; fi\n') + claude.chmod(0o755) + home = pathlib.Path(folder, "home") + + reason = system_effects(home, without_xdg_folders(os.environ) | {"PATH": f"{folder}:{os.environ['PATH']}"}).claude_home() + + self.assertEqual(reason, f"could not build the loop's Claude home, {home}/.local/share/build-release/claude-home: claude plugin install code-review@claude-plugins-official failed: no such plugin") + + def test_a_claude_that_outlasts_its_time_is_stopped_and_the_home_is_not_built(self): + with tempfile.TemporaryDirectory() as folder: + claude = pathlib.Path(folder, "claude") + claude.write_text("#!/bin/sh\nexec sleep 5\n") + claude.chmod(0o755) + home = pathlib.Path(folder, "home") + + reason = system_effects(home, without_xdg_folders(os.environ) | {"PATH": f"{folder}:{os.environ['PATH']}"}, home_timeout=0.2).claude_home() or "" + + self.assertTrue(reason.startswith(f"could not build the loop's Claude home, {home}/.local/share/build-release/claude-home: Command '['claude', 'plugin', "), reason) + self.assertTrue(reason.endswith("' timed out after 0.2 seconds"), reason) + class ForgeEffect(unittest.TestCase): def test_runs_the_forges_cli_in_the_checkout_it_is_given(self): diff --git a/bin/loop_state/paths.py b/bin/loop_state/paths.py index d96fed5a..7b1946a7 100644 --- a/bin/loop_state/paths.py +++ b/bin/loop_state/paths.py @@ -10,7 +10,7 @@ RELEASE_ROOT = pathlib.Path(__file__).resolve().parents[2] # Each folder below is named relative to the person's home folder. -# The person's own Claude home. No claude the loop starts runs there, and the setup doesn't read or write it: its name is for prose, and for the rule that keeps an agent out of its `.env`. +# The person's own Claude home. No claude the loop starts runs there, and neither entry point reads or writes it: its name is for prose and for rule-hook's rules that guard it. CLAUDE_HOME = ".claude" # The name of the setup's own folder, in the config home and in the state home. SETUP = "build-release" @@ -51,7 +51,7 @@ def state_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: def claude_home(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: """The loop's Claude home, which claude_home.home builds in the data folder: every claude the loop starts keeps its settings, plugins, sign-in and transcripts there.""" - # The data folder holds what the tools generate and can generate again, so it needs no backup. + # The data folder needs no backup: the tools build the home again, and what Claude Code keeps there is its own to restore, by a new /login. return xdg_folder(env.get(XDG_DATA_HOME), home / DATA_HOME) / SETUP / "claude-home" diff --git a/bin/repo_checks/test_settings.py b/bin/repo_checks/test_settings.py index 86c2543e..be1c9b55 100644 --- a/bin/repo_checks/test_settings.py +++ b/bin/repo_checks/test_settings.py @@ -36,4 +36,4 @@ class Settings(unittest.TestCase): self.assertTrue(enabled) for plugin in enabled: - self.assertRegex(self.settings["extraKnownMarketplaces"][plugin.split("@")[1]]["source"]["repo"], r"^[\w.-]+/[\w.-]+$", plugin) + self.assertRegex(self.settings["extraKnownMarketplaces"][plugin.split("@")[1]]["source"]["repo"], r"^[\w.-]+/[\w.-]+\Z", plugin) diff --git a/bin/self_update/main.py b/bin/self_update/main.py index 0304387d..16b88663 100644 --- a/bin/self_update/main.py +++ b/bin/self_update/main.py @@ -11,8 +11,7 @@ as a new step under Install. It refuses, exit 1, and leaves the clone as it was where a file the clone tracks has an uncommitted change the newest tag doesn't hold. Merge the change through the development clone and cut a release first. It also refuses where the newest tag doesn't hold the clone's commit, since -the move would drop work no release holds. Untracked files, such as Claude Code's sessions and -memory, stay as they are. +the move would drop work no release holds. Untracked files stay as they are. """ import sys