"""A project's settings, read from the one config that names its checkout: `~/.claude-projects//config.toml`. No setting has a default, so that a client's project never runs on another project's files: a missing config or setting is a Failure that names it.""" import dataclasses import pathlib import tomllib from failure import Failure PROJECTS = ".claude-projects" CONFIG = "config.toml" # Every path a project sets, by its role. Three readers, seated as the human who writes the config, picked the spelling from four candidates. They picked role names over file names, which a client's project doesn't share. SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles") # They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default. SPELLING = '"checkout:" for a path in the checkout, "folder:" for one in the config\'s folder, or a path that starts with / or ~/' # Where a project keeps a file, for a tool that reads it at a commit: a path from the checkout's top, as git names it; or, outside the checkout, the file itself, which the tool reads as it stands, since the checkout's commits hold no version of it. Place = str | pathlib.Path @dataclasses.dataclass(frozen=True) class ProjectConfig: """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path.""" key: str folder: pathlib.Path top: pathlib.Path paths: dict[str, pathlib.Path] def tracked(self, setting: str) -> str | None: """setting's path from top, as git names a file in a commit; None where the config puts it outside the checkout, whose commits hold no version of it.""" path = self.paths[setting] return path.relative_to(self.top).as_posix() if path.is_relative_to(self.top) else None def place(self, setting: str) -> Place: return self.tracked(setting) or self.paths[setting] def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure: """The config that names main, the project's main checkout. top is the worktree that asks, and main itself outside a worktree. A `checkout:` path lands in top. A config that cannot be read fails every project, since it may be the one that names main.""" named: list[tuple[pathlib.Path, dict[str, object]]] = [] for file in sorted((home / PROJECTS).glob(f"*/{CONFIG}")): config = read(file, home) if isinstance(config, Failure): return config # Resolved on both sides, so a checkout reached through a symlink, or spelt with `..`, still finds its config. if config[0].resolve() == main.resolve(): named.append((file, config[1])) if not named: return Failure(f"no config names the checkout {main}: write ~/{PROJECTS}//{CONFIG}, as `project-config --help` shows") if len(named) > 1: return Failure(f"{' and '.join(str(file) for file, _ in named)} each name the checkout {main}; only one config may") file, values = named[0] paths = {name: placed(values[name], top, file.parent, home) for name in SETTINGS if name in values} faults = [ *(f"`{name}` is missing" for name in SETTINGS if name not in values), *(f"`{name}` is not a setting" for name in values if name not in SETTINGS), *(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None), ] if faults: return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}.") return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}) def held(folder: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure | None: """The config in folder, read as its project's main checkout reads it; None where folder is not a config's folder under home.""" # Matched on resolved paths, as git names a folder, so a config's folder reached through a symlink is still found. file = next((file for file in (home / PROJECTS).glob(f"*/{CONFIG}") if file.parent.resolve() == folder.resolve()), None) if file is None: return None config = read(file, home) return config if isinstance(config, Failure) else load(config[0], config[0], home) def read(file: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, dict[str, object]] | Failure: """The checkout a config names, as an absolute path, and its other values.""" try: values = tomllib.loads(file.read_text(encoding="utf-8")) except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as failure: return Failure(f"cannot read {file}: {failure}") checkout = anywhere(values.get("checkout"), home) if checkout is None: found = f"not {values['checkout']!r}" if "checkout" in values else "and is missing" return Failure(f'{file}: `checkout` names the project\'s main checkout as a path that starts with / or ~/, such as "~/code/acme-billing", {found}') return checkout, {name: value for name, value in values.items() if name != "checkout"} def placed(value: object, top: pathlib.Path, folder: pathlib.Path, home: pathlib.Path) -> pathlib.Path | None: """The path a setting's value spells, or None where it doesn't spell one. A prefixed path stays inside its place.""" if not isinstance(value, str): return None for prefix, place in (("checkout:", top), ("folder:", folder)): if value.startswith(prefix): inside = pathlib.PurePosixPath(value.removeprefix(prefix)) return None if inside.is_absolute() or ".." in inside.parts or not inside.parts else place / inside return anywhere(value, home) def anywhere(value: object, home: pathlib.Path) -> pathlib.Path | None: if isinstance(value, str) and value.startswith("~/"): return home / value.removeprefix("~/") return pathlib.Path(value) if isinstance(value, str) and value.startswith("/") else None