"""A project's settings, read from the one config that names its checkout: `~/.claude-projects//config.toml`. No path 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 re import tomllib from failure import Failure from project_config import templates 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 ~/' # A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's. ENV_FILE = "env-file" # The optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out. WAIT_FOR_APPROVAL = "wait-for-approval" # The optional text settings. `language` is the language the project's prose is written in, by its English name. The others are templates, as `templates` says. LANGUAGE = "language" COMMIT_TITLE = "commit-title" PULL_REQUEST_TITLE = "pull-request-title" BRANCH = "branch" OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, PULL_REQUEST_TITLE, WAIT_FOR_APPROVAL) OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials" @dataclasses.dataclass(frozen=True) class Unnamed(Failure): """No config names a checkout here: none names the one asked for, or git finds no checkout. A reader of titles takes them bare there, as in a third party's clone; a config that is faulty or cannot be read is a plain Failure.""" @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] # The config's `env-file`, or None where it sets none. env_file: pathlib.Path | None = None wait_for_approval: bool = False language: str = "English" commit_title: str = templates.TITLE pull_request_title: str = templates.TITLE branch: str = templates.BRANCH @property def texts(self) -> dict[str, str]: """Each text setting's value, by the name the config gives it.""" return {LANGUAGE: self.language, COMMIT_TITLE: self.commit_title, PULL_REQUEST_TITLE: self.pull_request_title, BRANCH: self.branch} @property def titles(self) -> templates.Titles: return templates.Titles(self.commit_title, self.pull_request_title) 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 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 Unnamed(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} env_file = anywhere(values.get(ENV_FILE), home) misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent)) waits = values.get(WAIT_FOR_APPROVAL, False) checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault} 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, *OPTIONAL)), *(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None), *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []), *([f"`{WAIT_FOR_APPROVAL}` is {waits!r}, not true or false"] if not isinstance(waits, bool) else []), *(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))), ] if faults: return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.") return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}) def language_fault(value: object) -> str | None: """Why value names no language; None where it does. Only words, since the name is quoted to every worker and reviewer as an instruction.""" named = isinstance(value, str) and re.fullmatch(r"[^\W\d_]+(?:[ -][^\W\d_]+)*", value) return None if named else 'not a language\'s English name in words of letters, such as "Swedish" or "Brazilian Portuguese"' def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool: """Whether path lies in one of places. Both sides are resolved, so a symlink can't lead a path out of the place it names.""" return any(path.resolve().is_relative_to(place.resolve()) for place in places) 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 env_files(home: pathlib.Path) -> list[pathlib.Path]: """Every config's env-file, read without the checks load makes, so a config that fails them still keeps its credentials guarded; a config that cannot be read names none.""" configs = [read(file, home) for file in sorted((home / PROJECTS).glob(f"*/{CONFIG}"))] return [path for config in configs if not isinstance(config, Failure) and (path := anywhere(config[1].get(ENV_FILE), 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