Files
claude-config/bin/project_config/settings.py
T

242 lines
15 KiB
Python

"""A project's settings, read from the one config that names its checkout: `~/.claude-projects/<key>/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 decimal
import math
import pathlib
import re
import tomllib
import typing
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:<path>" for a path in the checkout, "folder:<path>" 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"
# An optional setting: the service that sends the loop's DMs to the human, one of NOTIFIERS. A project that names none gets no DMs, so a client's env file of Jira credentials is never read for a chat token.
NOTIFIER = "notifier"
Notifier = typing.Literal["mattermost", "slack"]
NOTIFIERS: tuple[Notifier, ...] = typing.get_args(Notifier)
# An 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"
# An optional boolean setting: whether the loop may run the project's language runtime, package manager, tests and task runner on the host, for a project with no container setup. False where left out.
TOOLING_ON_HOST = "tooling-on-host"
# An optional number setting: the comprehension score under which code health is very important. A legacy project, whose code scores low, may lower it.
READABILITY_FLOOR = "readability-floor"
# The floor where the config leaves it out, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
DEFAULT_FLOOR = decimal.Decimal("7.0")
# 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, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, WAIT_FOR_APPROVAL)
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
JIRA = "jira:"
EPIC_SPELLINGS = {
"goals-and-audience": '"jira:https://<site>/browse/<epic\'s key>" for goals and audience kept in a Jira Cloud epic\'s description',
"plan": '"jira:https://<site>/browse/<epic\'s key>" for a plan kept as a Jira Cloud epic\'s child issues',
}
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 Epic:
"""A Jira Cloud epic: site is its site's address, such as https://acme.atlassian.net, and key its issue key, such as ABC-12."""
site: str
key: str
@property
def spelling(self) -> str:
"""The epic as a config spells it."""
return f"{JIRA}{self.site}/browse/{self.key}"
@dataclasses.dataclass(frozen=True)
class ProjectConfig:
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except `plan` and `goals-and-audience` where they are kept in Jira."""
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
tooling_on_host: bool = False
readability_floor: decimal.Decimal = DEFAULT_FLOOR
language: str = "English"
commit_title: str = templates.TITLE
pull_request_title: str = templates.TITLE
branch: str = templates.BRANCH
# The epic whose child issues are the plan, where the config's `plan` names one.
epic: Epic | None = None
# The epic whose description holds the goals and audience, where the config's `goals-and-audience` names one.
goals_epic: Epic | None = None
# The config's `notifier`, or None where it names none.
notifier: Notifier | None = None
@property
def plan_file(self) -> pathlib.Path | None:
"""The plan's file; None where the plan is kept in Jira."""
return self.paths.get("plan")
@property
def plan_label(self) -> str:
"""What a message calls the plan: its path, or the epic as the config spells it."""
return self.epic.spelling if self.epic else str(self.paths["plan"])
@property
def places(self) -> dict[str, str]:
"""Where each of SETTINGS is kept, in SETTINGS' order: a path, or the epic as the config spells it."""
epics = {"plan": self.epic, "goals-and-audience": self.goals_epic}
return {name: epic.spelling if (epic := epics.get(name)) else str(self.paths[name]) for name in SETTINGS if epics.get(name) or name in self.paths}
@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.get(setting)
if path is None:
return None
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}/<key>/{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}
epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS}
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))
notifier = next((name for name in NOTIFIERS if name == values.get(NOTIFIER)), None)
waits = values.get(WAIT_FOR_APPROVAL, False)
on_host = values.get(TOOLING_ON_HOST, False)
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
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 and name not in EPIC_SPELLINGS),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira mustn't hold up.
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{NOTIFIER}` is {values[NOTIFIER]!r}, not {' or '.join(NOTIFIERS)}"] if NOTIFIER in values and values[NOTIFIER] not in NOTIFIERS else []),
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
*(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None 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]}.")
# faults names a floor the config misspells.
assert floor is not None
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier)
def epic_of(value: object) -> Epic | None:
"""The epic a setting's value spells; None where it spells none. Only https, so the credentials are never sent in the clear."""
spelt = isinstance(value, str) and re.fullmatch(rf"{JIRA}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/browse/([A-Z][A-Z0-9_]*-[0-9]+)", value)
return Epic(spelt.group(1), spelt.group(2)) if spelt else None
def floor_of(value: object) -> decimal.Decimal | None:
"""The floor value spells, an integer or a float from 1 to 10; None where it spells none. Not a string, nor a boolean, which Python counts as an integer, nor TOML's nan or inf."""
# An integer too large for a float makes math.isfinite raise, so only a float is checked.
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
return None
floor = decimal.Decimal(str(value))
return floor if 1 <= floor <= 10 else None
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