Files
claude-config/bin/claude_home/home.py
T

138 lines
7.0 KiB
Python

"""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, and the two folders those files name beside them. So a claude opens each file of the setup that they name in its own home: the setup's CLAUDE.md → "Vocabulary", "setup".
LINKED = ("CLAUDE.md", "agents", "bin", "principles", "rules", "skills")
# 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}"
# Stands for the reports folder, which holds every chunk's review folder, in the clone's settings.json. Every value that holds it is a path, so unlike CLONE it isn't shell-quoted.
REPORTS = "{reports}"
# What `unready` says first where nobody has signed in to the home yet.
SIGNED_OUT = "nobody is signed in to the loop's Claude home"
# The file in the home that names the clone, its commit and the reports folder 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, reports: pathlib.Path, claude: Claude, git: Git) -> str | None:
"""Builds the home from clone, or refreshes it where the clone's commit or the reports folder 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, reports, claude, git)
if isinstance(built, Failure):
return f"could not build the loop's Claude home, {home}: {built.reason}"
status = claude(["auth", "status"])
except (OSError, subprocess.TimeoutExpired) as failure:
return f"could not build the loop's Claude home, {home}: {failure}"
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: docs/decisions.md → `Claude Code in a home of its own`.
return f"{SIGNED_OUT}; run `CLAUDE_CONFIG_DIR={shlex.quote(str(home))} claude` and type /login there, once"
def only_signed_out(reason: str) -> bool:
"""Whether a reason `unready` gave is that nobody has signed in yet."""
return reason.startswith(SIGNED_OUT)
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 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, reports: 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()}, reports in {reports}\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, reports) 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, reports: pathlib.Path) -> Failure | None:
"""Writes the home's settings.json: the clone's, with the clone's folder in place of CLONE and the reports folder in place of REPORTS, and the model the home's file holds."""
settings = placed(json.loads((clone / "settings.json").read_text(encoding="utf-8")), {CLONE: shlex.quote(str(clone)), REPORTS: str(reports)})
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 "model" in old:
settings["model"] = old["model"]
return replace_file(generated, (json.dumps(settings, indent=2, sort_keys=True) + "\n").encode())
def placed(value: typing.Any, stand_for: dict[str, str]) -> typing.Any:
if isinstance(value, str):
for name, replacement in stand_for.items():
value = value.replace(name, replacement)
return value
if isinstance(value, list):
return [placed(each, stand_for) for each in value]
if isinstance(value, dict):
return {key: placed(each, stand_for) 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:
return Failure(f"claude {' '.join(command)} failed: {printed(done)}")
return None