Run every claude the loop starts in a Claude home generated outside the clone
CI / tests (pull_request) Successful in 4m45s
CI / tests (pull_request) Successful in 4m45s
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user