Run every claude the loop starts in a Claude home generated outside the clone
CI / tests (pull_request) Successful in 4m45s

This commit is contained in:
2026-12-04 01:07:03 +01:00
parent 2460b9e132
commit 0203a8e0b3
48 changed files with 703 additions and 369 deletions
View File
+112
View File
@@ -0,0 +1,112 @@
"""Builds the loop's Claude home: the folder every claude the loop starts reads in place of the person's own `~/.claude`.
The home lies outside the clone, so the clone stays a clean checkout. It holds links to the clone's LINKED files, a `settings.json` generated from the clone's, and what Claude Code itself keeps in its home: the plugins, the sign-in and the transcripts. docs/decisions.md → `Claude Code in a home of its own` says what loads from such a home.
"""
import collections.abc
import fcntl
import json
import pathlib
import shlex
import subprocess
import typing
from failure import Failure
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.
CLONE = "{clone}"
# The file in the home that names the clone and the commit the home was built from.
BUILT_FROM = "built-from"
# Runs `claude` with these arguments in the home.
Claude = collections.abc.Callable[[list[str]], subprocess.CompletedProcess[str]]
class Git(typing.Protocol):
def __call__(self, *args: str, cwd: str | None = None) -> str | Failure: ...
def unready(home: pathlib.Path, clone: pathlib.Path, claude: Claude, git: Git) -> str | None:
"""Builds the home from clone, or refreshes it where the clone's commit changed since. Then why a claude cannot run in the home yet, said for the person to act on; None where one can."""
try:
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:
return f"could not build the loop's Claude home, {home}: {failure}"
if signed_in(status):
return None
# /login is typed in a claude that runs in the home: lilleman chose it over a token file on 2026-12-03.
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."""
try:
read = json.loads(status)
except ValueError:
return False
return isinstance(read, dict) and read.get("loggedIn") is True
def refreshed(home: pathlib.Path, clone: pathlib.Path, claude: Claude, git: Git) -> Failure | None:
commit = git("rev-parse", "HEAD", cwd=str(clone))
if isinstance(commit, Failure):
return commit
built_from = f"{clone} at {commit.strip()}\n"
home.mkdir(parents=True, exist_ok=True)
# Several loops start at once after an update: one refreshes the home, and the others wait and find it done.
with open(home / ".refresh-lock", "w", encoding="utf-8") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
stamp = home / BUILT_FROM
if stamp.is_file() and stamp.read_text(encoding="utf-8") == built_from:
return None
# The stamp is written last, so a refresh that failed halfway runs again.
return linked(home, clone) or settings_written(home, clone) or plugins_installed(clone, claude) or replace_file(stamp, built_from.encode())
def linked(home: pathlib.Path, clone: pathlib.Path) -> Failure | None:
for name in LINKED:
link = home / name
# Only a link is replaced: a file or folder someone put there fails the build, and stays.
if link.is_symlink():
link.unlink()
link.symlink_to(clone / name)
return None
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"
# 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"))):
settings["model"] = old["model"]
return replace_file(generated, (json.dumps(settings, indent=2, sort_keys=True) + "\n").encode())
def placed(value: typing.Any, clone: str) -> typing.Any:
if isinstance(value, str):
return value.replace(CLONE, clone)
if isinstance(value, list):
return [placed(each, clone) for each in value]
if isinstance(value, dict):
return {key: placed(each, clone) for key, each in value.items()}
return value
def plugins_installed(clone: pathlib.Path, claude: Claude) -> Failure | None:
"""Installs every plugin the clone's settings.json enables, each marketplace first: `claude plugin install` finds a plugin only in a marketplace already added."""
settings = json.loads((clone / "settings.json").read_text(encoding="utf-8"))
plugins = sorted(plugin for plugin, enabled in settings.get("enabledPlugins", {}).items() if enabled)
marketplaces = sorted({plugin.split("@")[-1] for plugin in plugins})
commands = [["plugin", "marketplace", "add", settings["extraKnownMarketplaces"][name]["source"]["repo"]] for name in marketplaces]
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 None
+153
View File
@@ -0,0 +1,153 @@
import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from claude_home.home import unready
SETTINGS = {
"enabledPlugins": {"code-review@official": True, "frontend-design@official": False, "lsp@other": True},
"extraKnownMarketplaces": {"official": {"source": {"repo": "anthropics/official", "source": "github"}}, "other": {"source": {"repo": "someone/other", "source": "github"}}, "unused": {"source": {"repo": "someone/unused", "source": "github"}}},
"hooks": {"PreToolUse": [{"hooks": [{"command": "{clone}/bin/rule-hook", "type": "command"}]}]},
"tui": "fullscreen",
}
SIGNED_IN = json.dumps({"loggedIn": True, "authMethod": "claude.ai"})
SIGNED_OUT = json.dumps({"loggedIn": False, "authMethod": "none"})
class Home(unittest.TestCase):
def setUp(self) -> None:
self.temp = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
self.clone = self.temp / "the clone"
for folder in ("agents", "rules", "skills"):
(self.clone / folder).mkdir(parents=True)
(self.clone / "CLAUDE.md").write_text("# The setup's rules\n", encoding="utf-8")
(self.clone / "settings.json").write_text(json.dumps(SETTINGS), encoding="utf-8")
self.home = self.temp / "share" / "claude-home"
self.commit: str | Failure = "1a2b3c\n"
self.status = SIGNED_IN
# The exit code of each `claude plugin` command, by its last argument; 0 for one not named.
self.exits: dict[str, int] = {}
self.ran: list[list[str]] = []
def claude(self, args: list[str]) -> subprocess.CompletedProcess[str]:
self.ran.append(args)
if args == ["auth", "status"]:
return subprocess.CompletedProcess(args, 0 if self.status == SIGNED_IN else 1, self.status, "")
return subprocess.CompletedProcess(args, self.exits.get(args[-1], 0), "", f"no {args[-1]}\nin the marketplace\n")
def unready(self) -> str | None:
return unready(self.home, self.clone, self.claude, lambda *args, cwd=None: self.commit if (args, cwd) == (("rev-parse", "HEAD"), str(self.clone)) else Failure(f"unexpected git {args} in {cwd}"))
def settings(self) -> dict[str, object]:
read: dict[str, object] = json.loads((self.home / "settings.json").read_text(encoding="utf-8"))
return read
def test_a_new_home_links_the_clones_instruction_files(self) -> None:
self.assertIsNone(self.unready())
for name in ("CLAUDE.md", "agents", "rules", "skills"):
self.assertTrue((self.home / name).is_symlink(), name)
self.assertEqual((self.home / name).resolve(), (self.clone / name).resolve())
self.assertEqual((self.home / "CLAUDE.md").read_text(encoding="utf-8"), "# The setup's rules\n")
def test_the_generated_settings_name_the_clone_quoted_for_a_shell_and_leave_the_tracked_file_alone(self) -> None:
self.unready()
self.assertEqual(self.settings()["hooks"], {"PreToolUse": [{"hooks": [{"command": f"'{self.clone}'/bin/rule-hook", "type": "command"}]}]})
self.assertEqual(self.settings()["tui"], "fullscreen")
self.assertEqual(json.loads((self.clone / "settings.json").read_text(encoding="utf-8")), SETTINGS)
def test_it_adds_each_enabled_plugins_marketplace_then_installs_each_enabled_plugin(self) -> None:
self.unready()
self.assertEqual(self.ran, [
["plugin", "marketplace", "add", "anthropics/official"],
["plugin", "marketplace", "add", "someone/other"],
["plugin", "install", "code-review@official"],
["plugin", "install", "lsp@other"],
["auth", "status"],
])
def test_a_home_built_from_the_clones_commit_is_left_as_it_is(self) -> None:
self.unready()
(self.home / "settings.json").write_text('{"model": "opus", "tui": "inline"}', encoding="utf-8")
self.ran.clear()
self.assertIsNone(self.unready())
self.assertEqual(self.ran, [["auth", "status"]])
self.assertEqual(self.settings(), {"model": "opus", "tui": "inline"})
def test_a_new_commit_refreshes_the_home_and_keeps_the_model_claude_code_wrote(self) -> None:
self.unready()
(self.home / "settings.json").write_text('{"model": "opus", "tui": "inline"}', encoding="utf-8")
(self.clone / "settings.json").write_text(json.dumps({**SETTINGS, "tui": "compact"}), encoding="utf-8")
self.commit = "4d5e6f\n"
self.ran.clear()
self.assertIsNone(self.unready())
self.assertEqual(self.settings()["tui"], "compact")
self.assertEqual(self.settings()["model"], "opus")
self.assertIn(["plugin", "install", "lsp@other"], self.ran)
def test_a_clone_that_moved_refreshes_the_home(self) -> None:
self.unready()
moved = self.temp / "moved"
self.clone.rename(moved)
self.clone = moved
self.assertIsNone(self.unready())
self.assertEqual((self.home / "rules").resolve(), (moved / "rules").resolve())
def test_a_signed_out_home_says_how_to_sign_in(self) -> None:
self.status = SIGNED_OUT
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"
self.assertIn("nobody is signed in", self.unready() or "")
def test_a_plugin_that_does_not_install_stops_and_the_next_run_tries_again(self) -> None:
self.exits = {"lsp@other": 1}
self.assertEqual(self.unready(), f"could not build the loop's Claude home, {self.home}: claude plugin install lsp@other failed: no lsp@other in the marketplace")
self.exits = {}
self.ran.clear()
self.assertIsNone(self.unready())
self.assertIn(["plugin", "install", "lsp@other"], self.ran)
def test_a_clone_whose_commit_git_cannot_tell_stops(self) -> None:
self.commit = Failure("not a git repository")
self.assertEqual(self.unready(), f"could not build the loop's Claude home, {self.home}: not a git repository")
def test_a_file_in_a_links_place_stops(self) -> None:
(self.home / "rules").mkdir(parents=True)
(self.home / "rules" / "mine.md").write_text("", encoding="utf-8")
self.assertIn(f"could not build the loop's Claude home, {self.home}: ", self.unready() or "")
self.assertTrue((self.home / "rules" / "mine.md").exists())
def test_a_claude_that_cannot_start_stops(self) -> None:
def missing(args: list[str]) -> subprocess.CompletedProcess[str]:
raise FileNotFoundError(2, "No such file or directory", "claude")
reason = unready(self.home, self.clone, missing, lambda *args, cwd=None: "1a2b3c\n")
self.assertEqual(reason, f"could not build the loop's Claude home, {self.home}: [Errno 2] No such file or directory: 'claude'")
if __name__ == "__main__":
unittest.main()