| # | |
| # Licensed to the Apache Software Foundation (ASF) under one | |
| # or more contributor license agreements. See the NOTICE file | |
| # distributed with this work for additional information | |
| # regarding copyright ownership. The ASF licenses this file | |
| # to you under the Apache License, Version 2.0 (the | |
| # "License"); you may not use this file except in compliance | |
| # with the License. You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, | |
| # software distributed under the License is distributed on an | |
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| # KIND, either express or implied. See the License for the | |
| # specific language governing permissions and limitations | |
| # under the License. | |
| """ | |
| ``vetted-op-git``: the git operations a sandboxed agent cannot run, as closed shapes. | |
| Three things a sandboxed session routinely cannot do, and used to hand to the | |
| user as a command to paste: | |
| * **Push over SSH.** The sandbox routes network through an HTTP proxy, so an | |
| SSH transport gets no TCP at all, and a hardware key's touch prompt cannot | |
| reach the user from inside it. | |
| * **Write a linked worktree's administrative directory.** Harnesses keep | |
| ``.git/worktrees/<name>/`` read-only for worktrees the session did not | |
| create, so moving such a worktree to a rebased commit fails half-way. | |
| * **Add or remove a linked worktree**, for the same reason. | |
| Each operation here is one of those, with every parameter validated and every | |
| target bounded by the approved policy's ``[git]`` table. The entry point runs | |
| outside the sandbox and stays behind the harness's confirmation (``ask``), like | |
| ``vetted-op``: it removes the copy and paste, not the human decision. | |
| What makes running git outside the sandbox safe here, beyond the closed shapes: | |
| * **The pre-push checks run in the sandbox, not here.** A push never runs a | |
| hook. Whatever a ``pre-push`` hook would run — ``.git/hooks/pre-push``, or a | |
| hook manager reading its configuration from the working tree — is code the | |
| agent can write, and running it here would run that code outside the | |
| sandbox; the harness confirmation shows the push, not the code the hook | |
| would execute. The caller runs the same checks inside the sandbox first | |
| (for prek: ``prek run --hook-stage pre-push --from-ref <base> --to-ref | |
| <branch>``), fixes what they report, and only then pushes. The checks still | |
| run; they just run where working-tree code belongs. | |
| * **No repository code runs.** Every operation switches hooks off | |
| (``core.hooksPath=/dev/null``, plus ``--no-verify`` on the push), so neither | |
| a ``pre-push`` nor a ``post-checkout`` hook can run code from the working | |
| tree. | |
| * **No repository configuration steers git.** A key that makes git run a | |
| program, rewrite a URL, or pick credentials (``core.sshCommand``, | |
| ``url.*.insteadOf``, ``filter.*``, ``core.fsmonitor``, ``include.path``, …) | |
| can be planted in a repository's own config by anything that writes it. The | |
| operation refuses to run when the local or worktree config holds any key | |
| outside a short list of inert ones (`SAFE_LOCAL_KEY`). Global and system | |
| configuration are the user's own and stay in effect, so an SSH wrapper or a | |
| signing setup there keeps working. | |
| * **No environment steers git.** Every ``GIT_*`` variable is dropped, and | |
| ``HOME`` comes from the password database, so the global configuration read | |
| is the account's own. | |
| * **What is re-checked cannot change in between.** The configuration check | |
| runs again right before the command that acts, and the keys that could start | |
| a program in that window are pinned on the command line (`PINNED_CONFIG`, | |
| ``core.sshCommand`` set to the user's global value, the signing and | |
| verification settings (`SIGNING_KEYS`) set to the user's own, hooks off where | |
| they are not wanted). Attributes come from the empty tree, so no ``.gitattributes`` | |
| can switch on a filter. ``GIT_ALLOW_PROTOCOL`` limits transports whatever | |
| the configuration says. Validated directories are opened without following | |
| a symlink and git runs inside them by descriptor, so a directory swapped for | |
| a symlink after the checks cannot redirect it. Git itself still finds a | |
| repository's ``.git`` by name; its identity is re-checked, by name, right | |
| before the acting command, and a linked worktree's validated git directory | |
| is passed explicitly (``--git-dir``, ``--work-tree=.``) so its agent-writable | |
| ``.git`` file is never read again. That the git directory cannot be swapped | |
| in the moment between rests, like the next point, on the harness protecting | |
| it. A rewrite | |
| such as ``url.*.insteadOf`` cannot be | |
| pinned away; that it cannot appear while the confirmed command runs rests on | |
| the harness keeping ``.git/config`` write-protected, as Claude Code's sandbox | |
| does. | |
| * **The destination is not addressable.** A push goes to a URL built from the | |
| policy's repository names, never to a remote the repository configures. | |
| Protected branches are refused whatever the policy says, and the upstream | |
| repository accepts only branches matching the policy's globs. | |
| * **Nothing is lost silently.** A push always uses ``--force-with-lease`` with | |
| the full SHA the caller expects the remote branch to have (or ``new``), and | |
| a worktree moves with ``reset --keep`` only when it has no local changes; | |
| the previous commit is printed and stays in the reflog. | |
| """ | |
| import argparse | |
| import dataclasses | |
| import fnmatch | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import stat | |
| import subprocess | |
| import sys | |
| import tomllib | |
| import unicodedata | |
| from collections.abc import Callable, Sequence | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from . import layers, policy_source | |
| from .config import ( | |
| OPERATOR_GIT_FILE, | |
| Config, | |
| ConfigError, | |
| _expand_home, | |
| account_home, | |
| approved_dir, | |
| describe, | |
| load, | |
| ) | |
| from .layers import main_worktree | |
| from .safe_read import TamperedPath, read_regular_file | |
| EXIT_OK = 0 | |
| EXIT_USAGE = 2 | |
| EXIT_POLICY = 3 | |
| EXIT_COMMAND = 4 | |
| PROG = "vetted-op-git" | |
| #: A full object name. Short SHAs are refused: they can become ambiguous, and | |
| #: the caller always has the full one from `git rev-parse` or the forge. | |
| _SHA = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$") | |
| #: A branch name, before `git check-ref-format --branch` has its say. | |
| _BRANCH = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/+-]{0,199}$") | |
| #: The last component of a new worktree's path. | |
| _WORKTREE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,99}$") | |
| #: `owner/name`, as in `config._REPO`. | |
| _REPO = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,100}/[A-Za-z0-9][A-Za-z0-9._-]{0,100}$") | |
| _HOST = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$") | |
| #: A remote name: no `/` or `:`, so it can neither nest nor read as a URL. | |
| _REMOTE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") | |
| #: Paths one `git-stage` call may name, at most. | |
| MAX_STAGE_PATHS = 500 | |
| #: Longest commit message `git-commit` accepts, in characters. | |
| MAX_COMMIT_MESSAGE = 20000 | |
| #: Branches no operation pushes to, whatever the policy adds or grants. | |
| DEFAULT_PROTECTED = ( | |
| "main", | |
| "master", | |
| "trunk", | |
| "develop", | |
| "gh-pages", | |
| "release", | |
| "release/*", | |
| "release-*", | |
| "v*-test", | |
| "v*-stable", | |
| "*-stable", | |
| "asf-site", | |
| ) | |
| #: Repository-scope configuration keys that cannot make git run a program, | |
| #: pick a credential, change a destination or transform file contents. Every | |
| #: other key at `local` or `worktree` scope makes an operation refuse. | |
| SAFE_LOCAL_KEY = re.compile( | |
| r"""^(?: | |
| core\.(?:repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode | |
| |symlinks|autocrlf|eol|safecrlf|quotepath|abbrev|commitgraph|untrackedcache | |
| |splitindex|multipackindex|sparsecheckout|sparsecheckoutcone|checkstat|trustctime) | |
| | extensions\.(?:worktreeconfig|objectformat|refstorage|preciousobjects|partialclone|noop) | |
| # A remote name without `:` or `/`: git applies the settings of a remote named exactly | |
| # like the URL a push goes to, so a URL-shaped name could redirect it. | |
| | remote\.[A-Za-z0-9._-]+\.(?:url|pushurl|fetch|tagopt|prune|prunetags|promisor|partialclonefilter | |
| |mirror|skipdefaultupdate|skipfetchall|gh-resolved) | |
| | branch\.[^\x00]+\.(?:remote|pushremote|merge|rebase|description|vscode-merge-base) | |
| | user\.(?:name|email) | |
| | (?:pull|fetch)\.(?:rebase|ff|prune|prunetags|parallel|writecommitgraph) | |
| | push\.(?:default|autosetupremote|followtags) | |
| | rerere\.(?:enabled|autoupdate) | |
| | gc\.(?:auto|autopacklimit|autodetach|reflogexpire|reflogexpireunreachable|prunexpire|worktreepruneexpire) | |
| | maintenance\.(?:auto|strategy|repo) | |
| | index\.(?:version|threads|skiphash) | |
| | feature\.(?:manyfiles|experimental) | |
| | color\.[a-z.]+ | |
| | advice\.[a-z]+ | |
| | (?:commit|tag)\.gpgsign | |
| | init\.defaultbranch | |
| | merge\.conflictstyle | |
| | diff\.(?:renames|algorithm|colormoved) | |
| | log\.(?:date|decorate|follow) | |
| | status\.(?:showuntrackedfiles|submodulesummary) | |
| # Read by the `gh stack` extension (AGENTS.md recommends it for stacked pull | |
| # requests), which writes it to the repository; git itself never reads it. | |
| | gh-stack\.remote | |
| )$""", | |
| re.VERBOSE, | |
| ) | |
| class GitRefused(ValueError): | |
| """A parameter or the repository state that the operation does not accept.""" | |
| class GitFailed(RuntimeError): | |
| """A git command that ran and failed.""" | |
| def __init__(self, argv: Sequence[str], returncode: int, stderr: str, stdout: str = "") -> None: | |
| command = " ".join(a for a in argv if a != "-c" and "=" not in a) | |
| super().__init__(f"{command} exited {returncode}") | |
| self.returncode = returncode | |
| self.stderr = stderr | |
| #: A hook may explain its failure on stdout; it is shown with stderr. | |
| self.stdout = stdout | |
| @dataclass(frozen=True) | |
| class GitPolicy: | |
| """The validated ``[git]`` table of the policy.""" | |
| #: Main checkouts (their top-level directories) the operations may act on, | |
| #: together with the linked worktrees that share their ``.git``. | |
| checkouts: tuple[Path, ...] | |
| upstream_repo: str | |
| fork_repo: str | None = None | |
| #: Globs of the branches a push may create or move on the upstream | |
| #: repository. Empty: no push to upstream at all. | |
| upstream_push: tuple[str, ...] = () | |
| protected: tuple[str, ...] = DEFAULT_PROTECTED | |
| #: Directories new linked worktrees may be created in (directly). | |
| worktree_roots: tuple[Path, ...] = () | |
| host: str = "github.com" | |
| transport: str = "ssh" | |
| #: The policy's workspace: commit messages, path lists and pull-request | |
| #: texts are read from files there only (see `ops.read_body`). | |
| workspace: Path | None = None | |
| #: The remote-tracking namespace `git-fetch` writes upstream branches to. | |
| upstream_remote: str = "upstream" | |
| #: The upstream branch a pull request opened by `git-pr-create` targets. | |
| pr_base: str = "main" | |
| #: Paths `git-switch` treats as steering the harness, beyond `HARNESS_PATHS`. | |
| harness_paths: tuple[str, ...] = () | |
| #: Never-publish terms `git-pr-create` lets through for this repository, | |
| #: from `PUBLISHABLE_TERMS` only: a site repository whose pull requests add | |
| #: records that are public by the time they are opened. | |
| published_terms: tuple[str, ...] = () | |
| #: Relative path prefixes the `published_terms` exemption is bound to: it | |
| #: applies only to a branch whose every changed file lies under one of them. | |
| published_paths: tuple[str, ...] = () | |
| #: `"skip"`: a records site's own hooks may be recorded as skipped by | |
| #: `vetted-op-checks` (they need the checkout's git directory, which the | |
| #: sandbox cannot read); the site's CI runs them on the pull request. | |
| site_hooks: str | None = None | |
| def push_url(self, repo: str) -> str: | |
| if self.transport == "https": | |
| return f"https://{self.host}/{repo}.git" | |
| return f"git@{self.host}:{repo}.git" | |
| #: The never-publish terms a policy may let through in `git-pr-create`'s text | |
| #: (``[git] published_terms``): only a published record's identifier. A policy | |
| #: that names one is for a repository whose pull requests carry records already | |
| #: public (the project's security records site), never for its source repository. | |
| PUBLISHABLE_TERMS = frozenset({"CVE id", "CVE"}) | |
| _GLOB_CHARS = frozenset("*?[]{}\\") | |
| def _published_path(raw: str) -> str: | |
| """A relative, glob-free path prefix, without ``.``/``..`` parts, normalised without its trailing ``/``.""" | |
| path = raw.strip().rstrip("/") | |
| parts = path.split("/") | |
| if ( | |
| not path | |
| or path.startswith("/") | |
| or any(part in ("", ".", "..") for part in parts) | |
| or any(c in _GLOB_CHARS or unicodedata.category(c).startswith("C") for c in path) | |
| ): | |
| raise ConfigError( | |
| f"[git] published_paths entries must be relative path prefixes without globs or '..', got {raw!r}" | |
| ) | |
| return path | |
| def _under(path: str, prefixes: Sequence[str]) -> bool: | |
| return any(path == prefix or path.startswith(prefix + "/") for prefix in prefixes) | |
| #: The forge's compare of the pull request's base and head: every changed file | |
| #: and the head commit it compared. A renamed or copied file contributes its old | |
| #: path too, so moving a file out of a path outside `published_paths` counts as | |
| #: changing that path. | |
| _COMPARE_JQ = ( | |
| "{files: [.files[]? | .filename, (.previous_filename // empty)], " | |
| "head: (.commits | last | .sha), total: .files | length}" | |
| ) | |
| #: GitHub's compare lists at most this many files; a longer list is incomplete. | |
| _COMPARE_FILE_LIMIT = 300 | |
| def _published_paths_only(git: Git, policy: GitPolicy, worktree: Path, branch: str) -> None: | |
| """Refuse unless every file the branch changes against ``pr_base`` is under ``published_paths``. | |
| The forge answers, for the branch as pushed to the fork, and its head must | |
| be the local branch's: the exemption follows what the pull request will | |
| show, never a ref the agent can move. | |
| """ | |
| assert policy.fork_repo is not None | |
| local = git.run(worktree, "rev-parse", "--verify", f"refs/heads/{branch}^{{commit}}").strip() | |
| fork_owner = policy.fork_repo.split("/", 1)[0] | |
| argv = [ | |
| "gh", "api", "--hostname", policy.host, "--method", "GET", | |
| f"repos/{policy.upstream_repo}/compare/{policy.pr_base}...{fork_owner}:{branch}", | |
| "--jq", _COMPARE_JQ, | |
| ] # fmt: skip | |
| completed = git.gh_runner(argv, clean_env(), "") | |
| if completed.returncode != 0: | |
| raise GitFailed(argv, completed.returncode, completed.stderr or "", completed.stdout or "") | |
| try: | |
| answer = json.loads(completed.stdout) | |
| except json.JSONDecodeError: | |
| raise GitRefused("the forge's compare of the branch is not JSON") from None | |
| files = answer.get("files") if isinstance(answer, dict) else None | |
| if not isinstance(files, list) or not files or not all(isinstance(f, str) for f in files): | |
| raise GitRefused( | |
| "the forge lists no changed file for the branch; the published_terms exemption needs them" | |
| ) | |
| if answer.get("head") != local: | |
| raise GitRefused( | |
| f"the fork's {branch} is not at the local branch's {local}; push it first, then open the pull request" | |
| ) | |
| if len(files) >= _COMPARE_FILE_LIMIT: | |
| raise GitRefused("the branch changes too many files for the forge to list them all") | |
| outside = sorted(f for f in files if not _under(f, policy.published_paths)) | |
| if outside: | |
| raise GitRefused( | |
| "the published_terms exemption covers only branches that change files under " | |
| f"{', '.join(policy.published_paths)}; this one also changes {', '.join(outside[:5])}" | |
| ) | |
| def _absolute_real_dir(raw: object, key: str) -> Path: | |
| if not isinstance(raw, str) or not raw or not _expand_home(raw).is_absolute(): | |
| raise ConfigError(f"[git] {key} entries must be absolute paths (or start with ~/), got {raw!r}") | |
| path = Path(os.path.abspath(_expand_home(raw))) | |
| if str(path) != os.path.realpath(path): | |
| raise ConfigError( | |
| f"[git] {key} entry {raw!r} must be an absolute path with no symlink on it " | |
| f"(its real location is {os.path.realpath(path)!r})" | |
| ) | |
| return path | |
| def _str_list(table: dict[str, object], key: str) -> list[str]: | |
| value = table.get(key, []) | |
| if not isinstance(value, list) or not all(isinstance(v, str) and v for v in value): | |
| raise ConfigError(f"[git] {key} must be a list of non-empty strings") | |
| return list(value) | |
| #: Each operator's own ``[git]`` values live in `OPERATOR_GIT_FILE`, one table | |
| #: per upstream repository (``["apache/airflow"]``), in the approved-policy | |
| #: directory: outside every repository and every sandbox-writable root, so only | |
| #: the operator puts them there, and a shared, committed policy never has to | |
| #: name one person's paths. | |
| #: | |
| #: What an operator's table may set: where their clones, worktrees and fork are, | |
| #: and how they reach the forge. The project-wide keys (``upstream_push``, | |
| #: ``pr_base``, ``host``) stay in the shared policy, and ``protected`` only adds | |
| #: branches to the policy's list. | |
| OPERATOR_KEYS = frozenset( | |
| {"checkouts", "fork", "worktree_roots", "upstream_remote", "transport", "protected"} | |
| ) | |
| def operator_git_path() -> Path: | |
| return approved_dir() / OPERATOR_GIT_FILE | |
| def operator_git_table(upstream_repo: str) -> dict[str, object] | None: | |
| """The operator's table for ``upstream_repo``, or None when they declare none.""" | |
| path = operator_git_path() | |
| try: | |
| data = read_regular_file(path) | |
| except TamperedPath as exc: | |
| raise ConfigError(str(exc)) from None | |
| if data is None: | |
| return None | |
| try: | |
| raw = tomllib.loads(data.decode("utf-8")) | |
| except (UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: | |
| raise ConfigError(f"{path} is not valid TOML: {exc}") from None | |
| table = raw.get(upstream_repo) | |
| if table is None: | |
| return None | |
| if not isinstance(table, dict): | |
| raise ConfigError(f'{path}: ["{upstream_repo}"] must be a table') | |
| unknown = sorted(set(table) - OPERATOR_KEYS) | |
| if unknown: | |
| raise ConfigError( | |
| f'{path}: ["{upstream_repo}"] may not set {", ".join(unknown)}; ' | |
| "those are the project's, in the shared policy's [git] table" | |
| ) | |
| return table | |
| def _operator() -> policy_source.Operator: | |
| """The operator's own files, for `policy_source` (see its ``Operator``). | |
| ``operator_git_path()`` is read through this module's namespace, so a test — | |
| or an adopter — that points `approved_dir` at another directory authorises | |
| against that directory's table too. | |
| """ | |
| return policy_source.Operator(table=operator_git_path(), home=account_home()) | |
| def policy_from_checkout(raw: Path) -> Path: | |
| """The directory ``--policy-from`` names, refused unless it is a checkout the operator listed. | |
| The read dispatcher runs outside the sandbox without a prompt, so a free | |
| choice of directory would let an agent probe the host for directories and | |
| approved policies, or read through another project's policy unseen. Only a | |
| ``checkouts`` entry of the operator's own `OPERATOR_GIT_FILE` (which only | |
| they write) is accepted, and the check runs before anything on disk is | |
| looked at, so an unlisted path learns nothing about the file system. | |
| The rule itself lives in `policy_source.policy_from_checkout`, which | |
| `agent-guard` runs too: a guard that checked a different directory than the | |
| one the write reaches would report the wrong PR as clean. | |
| """ | |
| return policy_source.policy_from_checkout(raw, _operator()) | |
| def check_policy_from_upstream(config: Config, base: Path) -> None: | |
| """Refuse a policy found in ``base`` whose upstream's operator table does not list ``base``.""" | |
| policy_source.check_upstream_checkout(config.upstream_repo, base, _operator()) | |
| def load_source(policy_from: Path | None) -> policy_source.Source: | |
| """The policy a write entry point acts on, once its directory is settled. | |
| ``policy_from`` is a directory `policy_from_checkout` has already accepted, or | |
| ``None`` for the working directory. What is read here is what `config.load` | |
| then approves and validates — and what `agent-guard` checked the target | |
| repository of independently. Both use the same discovery rules. | |
| Parsing waits for `load`, after its approval check, where it always was. | |
| """ | |
| if policy_from is None: | |
| return policy_source.read_policy(Path.cwd(), layers.personal_layers) | |
| return policy_source.read_policy(policy_from, layers.personal_layers, authorized=policy_from) | |
| def operator_git_draft(upstream_repo: str, base: Path | None = None) -> str: | |
| """A ready-to-save ``["<upstream>"]`` table for the operator file, for a refusal to show. | |
| Filled from what is known without running anything: the main checkout of | |
| the working directory and the upstream's repository name. The fork stays a | |
| placeholder, since it is the operator's, not the repository's. Only keys in | |
| `OPERATOR_KEYS` appear, so the draft is always one the file accepts. | |
| """ | |
| here = (base or Path.cwd()).resolve() | |
| checkout = main_worktree(here) or here | |
| name = upstream_repo.split("/", 1)[-1] if "/" in upstream_repo else checkout.name | |
| roots = Path(os.path.realpath(checkout.parent)) / f"{checkout.name}-worktrees" | |
| path = operator_git_path() | |
| return "\n".join( | |
| [ | |
| "", | |
| f"Add your own values: append this table to {path}", | |
| "(create the worktree_roots directory first; no symlink may be on its path),", | |
| "with your fork filled in. Only you can write that file:", | |
| "", | |
| f'["{upstream_repo}"]', | |
| f'checkouts = ["{checkout}"]', | |
| f'fork = "<your-github-login>/{name}"', | |
| f'worktree_roots = ["{roots}"]', | |
| 'upstream_remote = "upstream"', | |
| ] | |
| ) | |
| def _git_table(config: Config, base: Path | None = None) -> dict[str, object]: | |
| """The shared policy's ``[git]`` table with the operator's own values over it.""" | |
| project = config.git | |
| if project is not None and not isinstance(project, dict): | |
| raise ConfigError("[git] must be a table") | |
| operator = operator_git_table(config.upstream_repo) | |
| if project is None and operator is None: | |
| raise ConfigError( | |
| f"no [git] values for {config.upstream_repo}: the policy has no [git] table and " | |
| f'{operator_git_path()} has no ["{config.upstream_repo}"] table, so no git operation may run' | |
| + operator_git_draft(config.upstream_repo, base) | |
| ) | |
| merged = dict(project or {}) | |
| if operator is not None: | |
| protected = _str_list(merged, "protected") + _str_list(operator, "protected") | |
| merged.update(operator) | |
| merged["protected"] = protected | |
| return merged | |
| def describe_git(config: Config, policy: GitPolicy) -> str: | |
| """The effective ``[git]`` values, each with the file it came from.""" | |
| operator = operator_git_table(config.upstream_repo) or {} | |
| project = config.git if isinstance(config.git, dict) else {} | |
| def source(key: str) -> str: | |
| if key in operator: | |
| return str(operator_git_path()) | |
| return "policy" if key in project else "default" | |
| values: list[tuple[str, object]] = [ | |
| ("checkouts", [str(p) for p in policy.checkouts]), | |
| ("fork", policy.fork_repo), | |
| ("worktree_roots", [str(p) for p in policy.worktree_roots]), | |
| ("upstream_remote", policy.upstream_remote), | |
| ("transport", policy.transport), | |
| ("host", policy.host), | |
| ("upstream_push", list(policy.upstream_push)), | |
| ("pr_base", policy.pr_base), | |
| ("harness_paths", list(policy.harness_paths)), | |
| ("published_terms", list(policy.published_terms)), | |
| ("published_paths", list(policy.published_paths)), | |
| ("site_hooks", policy.site_hooks), | |
| ] | |
| lines = ["[git] (effective)"] | |
| lines += [f" {key} = {value!r} # {source(key)}" for key, value in values] | |
| extra = [p for p in policy.protected if p not in DEFAULT_PROTECTED] | |
| origins = [ | |
| s for s, table in ((str(operator_git_path()), operator), ("policy", project)) if "protected" in table | |
| ] | |
| lines.append(f" protected += {extra!r} # {', '.join(origins) or 'default'}") | |
| return "\n".join(lines) | |
| def _owned_private_dir(path: Path, key: str) -> Path: | |
| """Refuse a directory another account owns or may write: worktrees there hold | |
| unpublished work and are where git later runs outside the sandbox.""" | |
| try: | |
| st = os.stat(path) | |
| except FileNotFoundError: | |
| raise ConfigError(f"[git] {key} entry {str(path)!r} does not exist") from None | |
| if not stat.S_ISDIR(st.st_mode): | |
| raise ConfigError(f"[git] {key} entry {str(path)!r} is not a directory") | |
| if st.st_uid != os.getuid(): | |
| raise ConfigError(f"[git] {key} entry {str(path)!r} is not owned by you") | |
| if st.st_mode & (stat.S_IWGRP | stat.S_IWOTH): | |
| raise ConfigError(f"[git] {key} entry {str(path)!r} is writable by others (chmod go-w it)") | |
| return path | |
| def git_policy(config: Config, base: Path | None = None) -> GitPolicy: | |
| """Validate the ``[git]`` values; without any, every operation refuses. | |
| ``base`` is the directory the policy was discovered from, for the draft a | |
| refusal shows (default: the working directory). | |
| """ | |
| table = _git_table(config, base) | |
| checkouts = tuple(_absolute_real_dir(raw, "checkouts") for raw in _str_list(table, "checkouts")) | |
| if not checkouts: | |
| raise ConfigError( | |
| "[git] checkouts must name at least one main checkout" | |
| + operator_git_draft(config.upstream_repo, base) | |
| ) | |
| fork = table.get("fork") | |
| if fork is not None and (not isinstance(fork, str) or not _REPO.fullmatch(fork)): | |
| raise ConfigError(f"[git] fork must be an 'owner/name' string, got {fork!r}") | |
| host = table.get("host", "github.com") | |
| if not isinstance(host, str) or not _HOST.fullmatch(host): | |
| raise ConfigError(f"[git] host must be a host name, got {host!r}") | |
| transport = table.get("transport", "ssh") | |
| if not isinstance(transport, str) or transport not in ("ssh", "https"): | |
| raise ConfigError(f"[git] transport must be 'ssh' or 'https', got {transport!r}") | |
| upstream_remote = table.get("upstream_remote", "upstream") | |
| if not isinstance(upstream_remote, str) or not _REMOTE_NAME.fullmatch(upstream_remote): | |
| raise ConfigError(f"[git] upstream_remote must be a plain remote name, got {upstream_remote!r}") | |
| pr_base = table.get("pr_base", "main") | |
| if not isinstance(pr_base, str) or not _BRANCH.fullmatch(pr_base): | |
| raise ConfigError(f"[git] pr_base must be a branch name, got {pr_base!r}") | |
| published_terms = _str_list(table, "published_terms") | |
| published_paths = [_published_path(raw) for raw in _str_list(table, "published_paths")] | |
| if published_terms and not published_paths: | |
| raise ConfigError( | |
| "[git] published_terms needs published_paths: the records directories the exemption is bound to" | |
| ) | |
| if published_paths and not published_terms: | |
| raise ConfigError("[git] published_paths applies only with published_terms") | |
| site_hooks = table.get("site_hooks") | |
| if site_hooks is not None: | |
| if not isinstance(site_hooks, str) or site_hooks != "skip": | |
| raise ConfigError(f'[git] site_hooks may only be "skip", got {site_hooks!r}') | |
| if not published_paths: | |
| raise ConfigError( | |
| "[git] site_hooks applies only in a records-site policy, one that sets published_paths" | |
| ) | |
| unknown_terms = sorted(set(published_terms) - PUBLISHABLE_TERMS) | |
| if unknown_terms: | |
| raise ConfigError( | |
| f"[git] published_terms may name only {', '.join(sorted(PUBLISHABLE_TERMS))}, " | |
| f"got {', '.join(unknown_terms)}" | |
| ) | |
| return GitPolicy( | |
| checkouts=checkouts, | |
| upstream_repo=config.upstream_repo, | |
| fork_repo=fork, | |
| upstream_push=tuple(_str_list(table, "upstream_push")), | |
| protected=DEFAULT_PROTECTED + tuple(_str_list(table, "protected")), | |
| worktree_roots=tuple( | |
| _owned_private_dir(_absolute_real_dir(raw, "worktree_roots"), "worktree_roots") | |
| for raw in _str_list(table, "worktree_roots") | |
| ), | |
| host=host, | |
| transport=transport, | |
| workspace=config.workspace, | |
| upstream_remote=upstream_remote, | |
| pr_base=pr_base, | |
| harness_paths=tuple(path.removeprefix("./").strip("/") for path in _str_list(table, "harness_paths")), | |
| published_terms=tuple(published_terms), | |
| published_paths=tuple(published_paths), | |
| site_hooks=site_hooks, | |
| ) | |
| # --- running git ----------------------------------------------------------- | |
| def clean_env(environ: dict[str, str] | None = None) -> dict[str, str]: | |
| """The caller's environment, minus everything that would let it reconfigure git. | |
| Every ``GIT_*`` variable is dropped (``GIT_DIR``, ``GIT_SSH_COMMAND``, | |
| ``GIT_CONFIG_GLOBAL``, ``GIT_CONFIG_PARAMETERS``, …), and the global | |
| configuration is pinned to the account's own: ``HOME`` comes from the | |
| password database, never from the caller, and ``XDG_CONFIG_HOME`` is | |
| dropped, so a configuration written somewhere the agent can write is never | |
| read as the user's global one. What remains (``PATH``, ``SSH_AUTH_SOCK``, | |
| ``GNUPGHOME``, …) is what the user's own git and ssh setup needs. | |
| """ | |
| source = os.environ if environ is None else environ | |
| env = {k: v for k, v in source.items() if not k.startswith("GIT_") and k != "XDG_CONFIG_HOME"} | |
| env["HOME"] = str(account_home()) | |
| env["GIT_TERMINAL_PROMPT"] = "0" | |
| return env | |
| #: Runs ``argv`` with ``env``, in the directory open as ``cwd_fd`` when one is given. | |
| Runner = Callable[[list[str], dict[str, str], "int | None"], "subprocess.CompletedProcess[str]"] | |
| #: Runs ``gh`` (``argv``) with ``env``, feeding ``stdin``. | |
| GhRunner = Callable[[list[str], dict[str, str], str], "subprocess.CompletedProcess[str]"] | |
| def _default_gh_runner(argv: list[str], env: dict[str, str], stdin: str) -> subprocess.CompletedProcess[str]: | |
| return subprocess.run(argv, check=False, capture_output=True, text=True, env=env, input=stdin) | |
| def _default_runner( | |
| argv: list[str], env: dict[str, str], cwd_fd: int | None | |
| ) -> subprocess.CompletedProcess[str]: | |
| if cwd_fd is None: | |
| return subprocess.run(argv, check=False, capture_output=True, text=True, env=env) | |
| return subprocess.run( | |
| argv, | |
| check=False, | |
| capture_output=True, | |
| text=True, | |
| env=env, | |
| pass_fds=(cwd_fd,), | |
| preexec_fn=lambda: os.fchdir(cwd_fd), | |
| ) | |
| def open_dir(path: Path) -> int: | |
| """Open ``path`` as a directory, refusing a symlink at any component. | |
| Walked one component at a time from ``/`` with ``O_NOFOLLOW``, so the | |
| descriptor is the directory the name led to when it was checked. Git then | |
| runs *in* that descriptor rather than at the name, and swapping a directory | |
| on the path for a symlink afterwards (the agent can write inside a | |
| checkout) cannot send git somewhere else. | |
| """ | |
| flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | |
| fd = os.open("/", os.O_RDONLY | os.O_DIRECTORY) | |
| try: | |
| for part in path.parts[1:]: | |
| child = os.open(part, flags, dir_fd=fd) | |
| os.close(fd) | |
| fd = child | |
| except OSError as exc: | |
| os.close(fd) | |
| raise GitRefused( | |
| f"{str(path)!r} is not a directory reachable without a symlink: {exc.strerror}" | |
| ) from None | |
| return fd | |
| #: Pinned on every call, so a key the repository's configuration gains between | |
| #: `check_repository_config` and the command cannot take effect: no file-system | |
| #: monitor program, no automatic gc or maintenance (their hooks are commands), | |
| #: and only network transports (a local path would run that repository's | |
| #: receive-pack and hooks here). The same pins as the local tracker's git. | |
| PINNED_CONFIG = ( | |
| "core.fsmonitor=false", | |
| "gc.auto=0", | |
| "maintenance.auto=false", | |
| "protocol.allow=never", | |
| # The commit-graph file is in the agent-writable `.git` and git trusts the | |
| # parents it lists: the graph checks must read the commit objects instead. | |
| "core.commitGraph=false", | |
| ) | |
| #: The settings that pick the program that signs or verifies a commit, the key | |
| #: it signs with, and whom a signature is trusted from (see `Git.signing_pins`). | |
| SIGNING_KEYS = ( | |
| "gpg.format", | |
| "gpg.program", | |
| "gpg.openpgp.program", | |
| "gpg.ssh.program", | |
| "gpg.x509.program", | |
| "gpg.ssh.allowedSignersFile", | |
| "gpg.ssh.defaultKeyCommand", | |
| "gpg.ssh.revocationFile", | |
| "gpg.minTrustLevel", | |
| "user.signingKey", | |
| ) | |
| #: The first git that honours ``GIT_ATTR_SOURCE``. | |
| MIN_GIT_VERSION = (2, 42) | |
| #: The empty tree, per object format: attributes are read from it, so no | |
| #: `.gitattributes` in the working tree can switch on a filter or driver. | |
| EMPTY_TREE = { | |
| "sha1": "4b825dc642cb6eb9a060e54bf8d69288fbee4904", | |
| "sha256": "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321", | |
| } | |
| @dataclass | |
| class Git: | |
| """Runs git with the pins above; injectable for tests.""" | |
| runner: Runner = field(default=_default_runner) | |
| #: Runs ``gh`` for `git-pr-create`; injectable for tests. | |
| gh_runner: GhRunner = field(default=_default_gh_runner) | |
| #: Transports a push may use. Tests add ``file``; production cannot. | |
| protocols: tuple[str, ...] = ("https", "ssh") | |
| #: The user's global ``core.sshCommand`` (or plain ``ssh``), pinned on every | |
| #: call so the repository's configuration cannot replace it. | |
| _ssh_command: str | None = field(default=None, repr=False) | |
| #: The user's signing and verification settings, pinned on every call (see `signing_pins`). | |
| _signing_pins: list[str] | None = field(default=None, repr=False) | |
| #: Set once the object format is known (see `check_repository_config`). | |
| attr_source: str | None = None | |
| #: The repository's object format (`sha1` or `sha256`), set with `attr_source`. | |
| object_format: str = "sha1" | |
| #: Validated directories, open (see `open_dir`); git runs in these, never at the name. | |
| anchors: dict[Path, int] = field(default_factory=dict) | |
| #: Validated working tree -> its git directory. Git gets these explicitly | |
| #: (``--git-dir``, ``--work-tree=.``) and never reads the ``.git`` file of a | |
| #: linked worktree again: that file is in the tree the agent can write. | |
| git_dirs: dict[Path, Path] = field(default_factory=dict) | |
| def anchor(self, path: Path, fd: int | None = None) -> int: | |
| """Return the open descriptor for ``path``, opening it on first use. | |
| Takes ownership of a passed ``fd``: it is kept until `close`, or closed | |
| at once when ``path`` already has a descriptor. | |
| """ | |
| if path in self.anchors: | |
| if fd is not None and fd != self.anchors[path]: | |
| os.close(fd) | |
| else: | |
| self.anchors[path] = open_dir(path) if fd is None else fd | |
| return self.anchors[path] | |
| def close(self) -> None: | |
| for fd in self.anchors.values(): | |
| os.close(fd) | |
| self.anchors.clear() | |
| def check_version(self) -> None: | |
| """Refuse a git older than `MIN_GIT_VERSION`, which ignores ``GIT_ATTR_SOURCE``.""" | |
| found = self.runner(["git", "version"], clean_env(), None) | |
| match = re.search(r"(\d+)\.(\d+)", found.stdout or "") | |
| version = (int(match.group(1)), int(match.group(2))) if match else (0, 0) | |
| if found.returncode != 0 or version < MIN_GIT_VERSION: | |
| raise GitRefused( | |
| f"git {'.'.join(map(str, MIN_GIT_VERSION))} or later is required (found " | |
| f"{(found.stdout or '').strip() or 'none'}): an older git ignores GIT_ATTR_SOURCE, so a " | |
| ".gitattributes could switch on a filter outside the sandbox" | |
| ) | |
| def ssh_command(self) -> str: | |
| if self._ssh_command is None: | |
| argv = ["git", "config", "--global", "--get", "core.sshCommand"] | |
| found = self.runner(argv, clean_env(), None) | |
| value = found.stdout.strip() if found.returncode == 0 else "" | |
| self._ssh_command = value if value and "\n" not in value else "ssh" | |
| return self._ssh_command | |
| def signs_commits(self) -> bool: | |
| """Whether the user's own configuration signs commits (``commit.gpgsign``).""" | |
| argv = ["git", "-C", "/", "config", "--bool", "--get", "commit.gpgsign"] | |
| found = self.runner(argv, clean_env(), None) | |
| return found.returncode == 0 and found.stdout.strip() == "true" | |
| def _user_config(self, key: str) -> str | None: | |
| """``key`` from the user's own (system and global) configuration, never a repository's.""" | |
| found = self.runner(["git", "-C", "/", "config", "--get", key], clean_env(), None) | |
| value = found.stdout.strip() if found.returncode == 0 else "" | |
| return value if value and "\n" not in value else None | |
| def signing_pins(self) -> list[str]: | |
| """The signing and verification settings, pinned to the user's own values on every call. | |
| Signing a commit and checking a signature (``%G?``) start a program and | |
| read a list of trusted signers. The repository-config check refuses a | |
| repository that sets any of these, but it cannot cover the moment | |
| between that check and the command, so the command carries the user's | |
| values itself: a key the repository gains in between cannot name | |
| another program or another allowed-signers file. A key the user leaves | |
| unset is pinned to git's default, so the repository cannot set it | |
| either; an unset allowed-signers file is pinned to an empty one. | |
| """ | |
| if self._signing_pins is None: | |
| values = {key: self._user_config(key) for key in SIGNING_KEYS} | |
| program = values["gpg.program"] or "gpg" | |
| defaults = { | |
| "gpg.format": "openpgp", | |
| "gpg.program": program, | |
| "gpg.openpgp.program": program, | |
| "gpg.ssh.program": "ssh-keygen", | |
| "gpg.x509.program": "gpgsm", | |
| "gpg.ssh.allowedSignersFile": os.devnull, | |
| } | |
| self._signing_pins = [ | |
| f"{key}={values[key] or defaults[key]}" | |
| for key in SIGNING_KEYS | |
| if values[key] is not None or key in defaults | |
| ] | |
| return self._signing_pins | |
| def argv(self, directory: Path, *args: str, hooks: bool = False) -> list[str]: | |
| """A git command in ``directory``, with hooks switched off unless ``hooks``. | |
| An anchored directory is entered by descriptor (see `open_dir`), so the | |
| argv names it only when it is not anchored (dry runs print the name). | |
| """ | |
| pins = [*PINNED_CONFIG, *(f"protocol.{p}.allow=always" for p in self.protocols)] | |
| pins.append(f"core.sshCommand={self.ssh_command()}") | |
| pins.extend(self.signing_pins()) | |
| if not hooks: | |
| pins.append("core.hooksPath=/dev/null") | |
| where = [] if directory in self.anchors else ["-C", str(directory)] | |
| if directory in self.git_dirs: | |
| where += [f"--git-dir={self.git_dirs[directory]}", "--work-tree=."] | |
| return ["git", *(arg for pin in pins for arg in ("-c", pin)), *where, *args] | |
| def _env(self) -> dict[str, str]: | |
| env = clean_env() | |
| # Overrides every protocol.* setting, the repository's included. | |
| env["GIT_ALLOW_PROTOCOL"] = ":".join(self.protocols) | |
| # Replace refs live in the agent-writable `.git`: honoured, they would let | |
| # the graph checks (ancestry, merges, commit counts) see a history other | |
| # than the one a push sends. Grafts likewise: none is read (the file is | |
| # also refused up front in `check_repository_config`, with a clearer message). | |
| env["GIT_NO_REPLACE_OBJECTS"] = "1" | |
| env["GIT_GRAFT_FILE"] = os.devnull | |
| if self.attr_source is not None: | |
| env["GIT_ATTR_SOURCE"] = self.attr_source | |
| return env | |
| def _call( | |
| self, directory: Path, *args: str, hooks: bool = False | |
| ) -> tuple[list[str], subprocess.CompletedProcess[str]]: | |
| argv = self.argv(directory, *args, hooks=hooks) | |
| return argv, self.runner(argv, self._env(), self.anchors.get(directory)) | |
| def run(self, directory: Path, *args: str, hooks: bool = False) -> str: | |
| argv, completed = self._call(directory, *args, hooks=hooks) | |
| if completed.returncode != 0: | |
| raise GitFailed(argv, completed.returncode, completed.stderr or "", completed.stdout or "") | |
| return completed.stdout | |
| def run_bytes(self, directory: Path, *args: str, stdin: str = "") -> bytes: | |
| """Like `run`, for output that is not text (object contents), with ``stdin`` fed to git.""" | |
| argv = self.argv(directory, *args) | |
| cwd_fd = self.anchors.get(directory) | |
| completed = subprocess.run( | |
| argv, | |
| check=False, | |
| capture_output=True, | |
| input=stdin.encode(), | |
| env=self._env(), | |
| pass_fds=(cwd_fd,) if cwd_fd is not None else (), | |
| preexec_fn=(lambda: os.fchdir(cwd_fd)) if cwd_fd is not None else None, | |
| ) | |
| if completed.returncode != 0: | |
| raise GitFailed(argv, completed.returncode, completed.stderr.decode("utf-8", "replace")) | |
| return completed.stdout | |
| def ok(self, directory: Path, *args: str) -> bool: | |
| return self._call(directory, *args)[1].returncode == 0 | |
| # --- validation ------------------------------------------------------------ | |
| def _param(raw: str, name: str) -> str: | |
| if not raw or raw.startswith("-") or "\x00" in raw or "\n" in raw: | |
| raise GitRefused(f"parameter {name!r} may not be empty, start with '-' or span lines: {raw!r}") | |
| return raw | |
| def sha(raw: str, name: str) -> str: | |
| if not _SHA.fullmatch(_param(raw, name)): | |
| raise GitRefused(f"{name} must be a full lowercase commit SHA, got {raw!r}") | |
| return raw | |
| def branch_name(git: Git, directory: Path, raw: str, name: str) -> str: | |
| _param(raw, name) | |
| if not _BRANCH.fullmatch(raw) or ".." in raw or raw.endswith((".lock", "/", ".")): | |
| raise GitRefused(f"{name} is not an acceptable branch name: {raw!r}") | |
| if not git.ok(directory, "check-ref-format", "--branch", raw): | |
| raise GitRefused(f"{name} is not a valid branch name: {raw!r}") | |
| return raw | |
| def is_protected(branch: str, policy: GitPolicy) -> bool: | |
| return any(fnmatch.fnmatchcase(branch, glob) for glob in policy.protected) | |
| def current_branch(git: Git, worktree: Worktree) -> str: | |
| """The branch checked out in ``worktree``, its exact name without ``refs/heads/``. | |
| Never ``symbolic-ref --short``: with a tag of the same name it answers | |
| ``heads/main``, which no protected-branch glob matches. | |
| """ | |
| if not git.ok(worktree.path, "symbolic-ref", "--quiet", "HEAD"): | |
| raise GitRefused(f"{str(worktree.path)!r} has a detached HEAD; check out a branch first") | |
| ref = git.run(worktree.path, "symbolic-ref", "HEAD").strip() | |
| if not ref.startswith("refs/heads/"): | |
| raise GitRefused(f"HEAD of {str(worktree.path)!r} points at {ref!r}, not a local branch") | |
| # Validated like a branch parameter: a ref named `refs/heads/-x` is valid | |
| # git, and the name may reach a command line (`git-rebase` passes it). | |
| return branch_name(git, worktree.path, ref.removeprefix("refs/heads/"), "the checked-out branch") | |
| def _absolute(raw: str, name: str) -> Path: | |
| expanded = _expand_home(_param(raw, name)) | |
| if not expanded.is_absolute(): | |
| raise GitRefused(f"{name} must be an absolute path (or start with ~/), got {raw!r}") | |
| return Path(os.path.abspath(expanded)) | |
| def _real_dir(raw: str, name: str) -> Path: | |
| path = _absolute(raw, name) | |
| if str(path) != os.path.realpath(path): | |
| raise GitRefused(f"{name} {raw!r} has a symlink on its path; name its real location") | |
| return path | |
| @dataclass(frozen=True) | |
| class Worktree: | |
| """A working tree of one of the policy's checkouts.""" | |
| path: Path | |
| checkout: Path | |
| #: (device, inode) of the checkout's `.git` directory when it was validated. | |
| git_dir_id: tuple[int, int] = (0, 0) | |
| #: The worktree's own git directory: `.git` for the main checkout, the | |
| #: registered `.git/worktrees/<name>` for a linked one. | |
| git_dir: Path = Path("/nonexistent") | |
| @property | |
| def linked(self) -> bool: | |
| return self.path != self.checkout | |
| def resolve_worktree(git: Git, raw: str, policy: GitPolicy, name: str = "worktree") -> Worktree: | |
| """The working tree at ``raw``, if it is a policy checkout or one of its linked worktrees.""" | |
| path = _real_dir(raw, name) | |
| if not path.is_dir(): | |
| raise GitRefused(f"{name} {str(path)!r} is not a directory") | |
| git.anchor(path) | |
| lines = git.run(path, "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir") | |
| top, common = (Path(os.path.realpath(line)) for line in lines.splitlines()[:2]) | |
| if top != path: | |
| raise GitRefused(f"{name} {str(path)!r} is not the top of a working tree (that is {str(top)!r})") | |
| for checkout in policy.checkouts: | |
| if common == checkout / ".git" and (checkout / ".git").is_dir(): | |
| git.anchor(checkout) | |
| worktree = Worktree(path=path, checkout=checkout, git_dir_id=git_dir_identity(checkout)) | |
| worktree = _check_registered(git, worktree, name) | |
| git.git_dirs[path] = worktree.git_dir | |
| git.git_dirs.setdefault(checkout, checkout / ".git") | |
| return worktree | |
| allowed = ", ".join(str(c) for c in policy.checkouts) | |
| raise GitRefused(f"{name} {str(path)!r} does not belong to a checkout the policy names ({allowed})") | |
| def git_dir_identity(checkout: Path) -> tuple[int, int]: | |
| """The checkout's `.git`, looked up by name now, with no symlink anywhere on the way. | |
| Looked up afresh each time rather than through an anchor, so a directory | |
| swapped anywhere on the path since the last look shows as a different one. | |
| """ | |
| fd = open_dir(checkout) | |
| try: | |
| found = os.stat(".git", dir_fd=fd, follow_symlinks=False) | |
| except OSError as exc: | |
| raise GitRefused(f"cannot read {str(checkout / '.git')!r}: {exc.strerror}") from None | |
| finally: | |
| os.close(fd) | |
| if not stat.S_ISDIR(found.st_mode): | |
| raise GitRefused(f"{str(checkout / '.git')!r} is not a directory") | |
| return (found.st_dev, found.st_ino) | |
| def _check_registered(git: Git, worktree: Worktree, name: str) -> Worktree: | |
| """A linked worktree must be one git registered for this path, not a copy pointing at `.git`.""" | |
| git_dir = Path(os.path.realpath(git.run(worktree.path, "rev-parse", "--absolute-git-dir").strip())) | |
| main = worktree.checkout / ".git" | |
| if not worktree.linked: | |
| if git_dir != main: | |
| raise GitRefused(f"{name} {str(worktree.path)!r} does not use {str(main)!r} as its git directory") | |
| return dataclasses.replace(worktree, git_dir=main) | |
| if git_dir.parent != main / "worktrees": | |
| raise GitRefused( | |
| f"{name} {str(worktree.path)!r} is not a linked worktree registered with {str(main)!r}" | |
| ) | |
| try: | |
| registered = (git_dir / "gitdir").read_text().strip() | |
| except OSError: | |
| registered = "" | |
| if Path(os.path.realpath(registered)) != worktree.path / ".git": | |
| raise GitRefused(f"{name} {str(worktree.path)!r} is not where git registered {git_dir.name!r}") | |
| return dataclasses.replace(worktree, git_dir=git_dir) | |
| def parse_config_scopes(output: str) -> list[tuple[str, str]]: | |
| """``git config --list --show-scope --name-only -z`` output as (scope, key) pairs.""" | |
| items = [item for item in output.split("\x00") if item] | |
| pairs: list[tuple[str, str]] = [] | |
| pending: str | None = None | |
| for item in items: | |
| if "\t" in item: | |
| scope, key = item.split("\t", 1) | |
| pairs.append((scope, key)) | |
| elif pending is None: | |
| pending = item | |
| else: | |
| pairs.append((pending, item)) | |
| pending = None | |
| return pairs | |
| def check_repository_config(git: Git, worktree: Worktree) -> None: | |
| """Refuse a repository whose own configuration holds a key outside `SAFE_LOCAL_KEY`. | |
| Checked in every working tree an operation runs git in (a linked worktree | |
| has its own ``config.worktree``), and again right before the command that | |
| acts, so a key added after the first check is still caught; what cannot | |
| be re-checked in between is pinned by `PINNED_CONFIG`. | |
| """ | |
| git.check_version() | |
| if git_dir_identity(worktree.checkout) != worktree.git_dir_id: | |
| raise GitRefused(f"{str(worktree.checkout / '.git')!r} changed since it was validated") | |
| # A linked worktree's common directory comes from its `commondir` file, which | |
| # can be rewritten after `resolve_worktree` looked: ask git again, through the | |
| # same pinned git directory the command will use, and require the same answer. | |
| lines = git.run( | |
| worktree.path, "rev-parse", "--path-format=absolute", "--git-common-dir", "--absolute-git-dir" | |
| ) | |
| common, git_dir = (Path(os.path.realpath(line)) for line in lines.splitlines()[:2]) | |
| if common != worktree.checkout / ".git": | |
| raise GitRefused( | |
| f"the common git directory of {str(worktree.path)!r} is now {str(common)!r}, " | |
| f"not {str(worktree.checkout / '.git')!r}" | |
| ) | |
| if git_dir != worktree.git_dir: | |
| raise GitRefused(f"the git directory of {str(worktree.path)!r} changed since it was validated") | |
| if os.path.lexists(worktree.checkout / ".git" / "info" / "grafts"): | |
| raise GitRefused( | |
| f"{str(worktree.checkout / '.git' / 'info' / 'grafts')!r} exists; grafts rewrite the history " | |
| "git reports, so the checks here could pass on a history other than the one a push sends. " | |
| "Remove the file (or convert it with `git replace --convert-graft-file`) and retry" | |
| ) | |
| for directory in dict.fromkeys((worktree.path, worktree.checkout)): | |
| _check_config_in(git, directory) | |
| object_format = git.run(worktree.path, "rev-parse", "--show-object-format").strip() | |
| if object_format not in EMPTY_TREE: | |
| raise GitRefused(f"unsupported object format {object_format!r}") | |
| git.attr_source = EMPTY_TREE[object_format] | |
| git.object_format = object_format | |
| def _check_config_in(git: Git, directory: Path) -> None: | |
| output = git.run(directory, "config", "--list", "--show-scope", "--name-only", "--includes", "-z") | |
| unsafe = sorted( | |
| { | |
| key | |
| for scope, key in parse_config_scopes(output) | |
| # `command` scope is this module's own `-c` pins; `GIT_CONFIG_*` is dropped. | |
| if scope in ("local", "worktree") and not SAFE_LOCAL_KEY.fullmatch(key.lower()) | |
| } | |
| ) | |
| if unsafe: | |
| raise GitRefused( | |
| f"the repository configuration of {str(directory)!r} sets {', '.join(unsafe)}; " | |
| "git runs outside the sandbox here, so only inert repository settings are accepted. " | |
| "Move those settings to your global git configuration, or remove them, and retry" | |
| ) | |
| def resolve_commit(git: Git, directory: Path, commit: str, name: str) -> str: | |
| if not git.ok(directory, "cat-file", "-e", f"{commit}^{{commit}}"): | |
| raise GitRefused(f"{name} {commit} is not a commit in this repository") | |
| return commit | |
| # --- operations ------------------------------------------------------------ | |
| @dataclass(frozen=True) | |
| class GitOp: | |
| name: str | |
| params: tuple[str, ...] | |
| summary: str | |
| run: Callable[[Git, GitPolicy, dict[str, str], bool], str] | |
| def _refuse_empty_branch(git: Git, worktree: Worktree, commit: str, local: str) -> None: | |
| """The agent-guard `empty-rebase` rule, for the push this dispatcher runs. | |
| Moving an existing branch to a commit with nothing over a default branch | |
| (a rebase that dropped every commit) closes the pull request it heads and | |
| revokes maintainers' push access to it. The bases are the remotes' default | |
| branches (`refs/remotes/*/HEAD`); with none known, nothing is refused, as | |
| in the guard. There is no override: closing a pull request is not a push. | |
| """ | |
| heads = git.run(worktree.path, "for-each-ref", "--format=%(symref)", "refs/remotes/*/HEAD") | |
| for base in sorted({line for line in heads.splitlines() if line}): | |
| if git.run(worktree.path, "rev-list", "--count", f"{base}..{commit}").strip() == "0": | |
| raise GitRefused( | |
| f"{local!r} has no commits over {base.removeprefix('refs/remotes/')}; force-pushing it " | |
| "would empty the branch, which closes a pull request it heads. Check the rebase result" | |
| ) | |
| def push_branch(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Push a local branch's commit to the fork or upstream, with a lease on the expected SHA.""" | |
| worktree = resolve_worktree(git, p["checkout"], policy, "checkout") | |
| check_repository_config(git, worktree) | |
| local = branch_name(git, worktree.path, p["branch"], "branch") | |
| remote_branch = branch_name(git, worktree.path, p["remote_branch"], "remote_branch") | |
| if is_protected(remote_branch, policy): | |
| raise GitRefused(f"{remote_branch!r} is a protected branch; no operation pushes to it") | |
| target = _param(p["target"], "target") | |
| if target == "fork": | |
| if policy.fork_repo is None: | |
| raise GitRefused("the policy names no [git] fork, so nothing may be pushed to one") | |
| repo = policy.fork_repo | |
| elif target == "upstream": | |
| if not any(fnmatch.fnmatchcase(remote_branch, glob) for glob in policy.upstream_push): | |
| raise GitRefused( | |
| f"{remote_branch!r} matches no [git] upstream_push glob " | |
| f"({', '.join(policy.upstream_push) or 'none declared'}), so it may not be pushed upstream" | |
| ) | |
| repo = policy.upstream_repo | |
| else: | |
| raise GitRefused(f"target must be 'fork' or 'upstream', got {target!r}") | |
| expected = p["expected"] | |
| lease = "" if expected == "new" else sha(expected, "expected") | |
| if not git.ok(worktree.path, "show-ref", "--verify", "--quiet", f"refs/heads/{local}"): | |
| raise GitRefused(f"there is no local branch {local!r}") | |
| commit = git.run(worktree.path, "rev-parse", "--verify", f"refs/heads/{local}^{{commit}}").strip() | |
| if lease: | |
| _refuse_empty_branch(git, worktree, commit, local) | |
| args = [ | |
| "push", | |
| # The pre-push checks run in the sandbox before this call (see the module | |
| # docstring): a hook here would run working-tree code outside it. | |
| "--no-verify", | |
| # Only the one ref: `push.followTags` would also publish reachable tags. | |
| "--no-follow-tags", | |
| "--porcelain", | |
| f"--force-with-lease=refs/heads/{remote_branch}:{lease}", | |
| policy.push_url(repo), | |
| f"{commit}:refs/heads/{remote_branch}", | |
| ] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| check_repository_config(git, worktree) | |
| git.run(worktree.path, *args) | |
| was = "created" if not lease else f"was {lease}" | |
| return f"pushed {commit} to {repo} {remote_branch} ({was})" | |
| #: The merged pull requests `git-delete-fork-branch` reads, as a JSON list. | |
| _MERGED_PRS_JQ = ( | |
| "[.[] | select(.merged_at != null) | {number: .number, head_repo: .head.repo.full_name, " | |
| "head_ref: .head.ref, head_sha: .head.sha}]" | |
| ) | |
| def delete_fork_branch(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Delete a branch on the user's fork once the pull request it headed has merged. | |
| The cleanup after a merge. Only the policy's fork, never a protected | |
| branch, and only a branch the forge reports as the head of a merged pull | |
| request against the upstream repository, at exactly ``expected``: a squash | |
| or rebase merge leaves no trace of the branch in the base's history, so the | |
| forge's word is the check. The deletion is leased on ``expected``, so a | |
| branch pushed to since the merge is never removed. | |
| """ | |
| if policy.fork_repo is None: | |
| raise GitRefused("the policy names no [git] fork, so no branch can be deleted from one") | |
| worktree = resolve_worktree(git, p["checkout"], policy, "checkout") | |
| check_repository_config(git, worktree) | |
| branch = branch_name(git, worktree.path, p["branch"], "branch") | |
| if is_protected(branch, policy): | |
| raise GitRefused(f"{branch!r} is a protected branch; it is never deleted") | |
| expected = sha(p["expected"], "expected") | |
| fork_owner = policy.fork_repo.split("/", 1)[0] | |
| args = [ | |
| "push", | |
| "--no-verify", | |
| "--porcelain", | |
| f"--force-with-lease=refs/heads/{branch}:{expected}", | |
| policy.push_url(policy.fork_repo), | |
| f":refs/heads/{branch}", | |
| ] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| argv = [ | |
| "gh", | |
| "api", | |
| "--hostname", | |
| policy.host, | |
| "--method", | |
| "GET", | |
| f"repos/{policy.upstream_repo}/pulls", | |
| "-f", | |
| f"head={fork_owner}:{branch}", | |
| "-f", | |
| "state=closed", | |
| "-f", | |
| "per_page=100", | |
| "--jq", | |
| _MERGED_PRS_JQ, | |
| ] | |
| completed = git.gh_runner(argv, clean_env(), "") | |
| if completed.returncode != 0: | |
| raise GitFailed(argv, completed.returncode, completed.stderr or "", completed.stdout or "") | |
| try: | |
| merged = json.loads(completed.stdout) | |
| except json.JSONDecodeError: | |
| raise GitRefused("the forge's answer about merged pull requests is not JSON") from None | |
| matching = [ | |
| pr | |
| for pr in (merged if isinstance(merged, list) else []) | |
| if isinstance(pr, dict) | |
| and str(pr.get("head_repo") or "").casefold() == policy.fork_repo.casefold() | |
| and pr.get("head_ref") == branch | |
| and pr.get("head_sha") == expected | |
| ] | |
| if not matching: | |
| raise GitRefused( | |
| f"no merged pull request against {policy.upstream_repo} had {policy.fork_repo} {branch} at " | |
| f"{expected} as its head; only a merged pull request's branch is deleted, at the commit that merged" | |
| ) | |
| check_repository_config(git, worktree) | |
| git.run(worktree.path, *args) | |
| return ( | |
| f"deleted {policy.fork_repo} {branch} (was {expected}, head of merged #{matching[0].get('number')})" | |
| ) | |
| #: A pull request number, as GitHub assigns them. | |
| _PR_NUMBER = re.compile(r"^[1-9][0-9]{0,9}$") | |
| #: What `git-push-pr-head` reads about the pull request, as one JSON object. | |
| _PR_HEAD_JQ = ( | |
| "{state: .state, maintainer_can_modify: .maintainer_can_modify, base_repo: .base.repo.full_name, " | |
| "head_repo: .head.repo.full_name, head_ref: .head.ref, head_sha: .head.sha}" | |
| ) | |
| def _pull_request_head(git: Git, policy: GitPolicy, number: str) -> dict[str, object]: | |
| """The head of upstream pull request ``number``, read from the forge, never from the caller.""" | |
| argv = [ | |
| "gh", | |
| "api", | |
| "--hostname", | |
| policy.host, | |
| f"repos/{policy.upstream_repo}/pulls/{number}", | |
| "--jq", | |
| _PR_HEAD_JQ, | |
| ] | |
| completed = git.gh_runner(argv, clean_env(), "") | |
| if completed.returncode != 0: | |
| raise GitFailed(argv, completed.returncode, completed.stderr or "", completed.stdout or "") | |
| try: | |
| head = json.loads(completed.stdout) | |
| except json.JSONDecodeError: | |
| raise GitRefused(f"pull request #{number}: the forge's answer is not JSON") from None | |
| if not isinstance(head, dict): | |
| raise GitRefused(f"pull request #{number}: the forge's answer is not an object") | |
| return head | |
| #: Commits one `git-push-pr-head` may add on top of the pull request's head. | |
| MAX_FIXUP_COMMITS = 10 | |
| def push_pr_head(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Fast-forward an open upstream pull request's head branch to a local branch's commit. | |
| The maintainer-fixup push, to a repository the policy does not name: the | |
| contributor's fork. Three things keep that destination bounded. The caller | |
| names it (``head_repo``, ``head_branch``), so the confirmation the user | |
| approves shows where the commits go, and the forge must report that same | |
| head for pull request ``number``: open, against the upstream repository, | |
| still at ``expected``, with maintainer edits allowed (or, on the upstream | |
| repository itself, an ``upstream_push`` branch). And only a fixup goes: at | |
| most `MAX_FIXUP_COMMITS` commits on top of ``expected``, none of them a | |
| merge, so no other local history can be carried along. The push is a | |
| fast-forward under a lease on ``expected``, so it adds commits to the | |
| contributor's branch and never rewrites or drops theirs. | |
| """ | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| local = branch_name(git, worktree.path, p["branch"], "branch") | |
| number = _param(p["number"], "number") | |
| if not _PR_NUMBER.fullmatch(number): | |
| raise GitRefused(f"number must be a pull request number, got {number!r}") | |
| named_repo = _param(p["head_repo"], "head_repo") | |
| if not _REPO.fullmatch(named_repo): | |
| raise GitRefused(f"head_repo must be 'owner/name', got {named_repo!r}") | |
| named_branch = branch_name(git, worktree.path, p["head_branch"], "head_branch") | |
| expected = sha(p["expected"], "expected") | |
| if not git.ok(worktree.path, "show-ref", "--verify", "--quiet", f"refs/heads/{local}"): | |
| raise GitRefused(f"there is no local branch {local!r}") | |
| commit = git.run(worktree.path, "rev-parse", "--verify", f"refs/heads/{local}^{{commit}}").strip() | |
| resolve_commit(git, worktree.path, expected, "expected") | |
| if commit == expected: | |
| raise GitRefused(f"{local!r} is still at the pull request's head {expected}; commit the fixup first") | |
| if not git.ok(worktree.path, "merge-base", "--is-ancestor", expected, commit): | |
| raise GitRefused( | |
| f"{local!r} does not build on the pull request's head {expected}; a fixup adds commits on top " | |
| "of the contributor's and never rewrites them" | |
| ) | |
| # One kind of merge may go along: upstream's pr_base merged in | |
| # (`git-merge-upstream`), its other parent on the pr_base fetched here. | |
| # Upstream's own commits are then public history, not part of the fixup. | |
| merges = git.run(worktree.path, "rev-list", "--merges", f"{expected}..{commit}").split() | |
| upstream_tip = _fetch_base(git, worktree, policy) if merges else None | |
| excluded = [f"^{upstream_tip}"] if upstream_tip else [] | |
| for merge in merges: | |
| others = git.run(worktree.path, "rev-list", "--parents", "-n", "1", merge).split()[2:] | |
| if ( | |
| not upstream_tip | |
| or len(others) != 1 | |
| or not git.ok(worktree.path, "merge-base", "--is-ancestor", others[0], upstream_tip) | |
| ): | |
| raise GitRefused( | |
| f"{local!r} has a merge commit ({merge}) on top of the pull request's head that does not " | |
| f"merge {policy.upstream_repo} {policy.pr_base}; a fixup is plain commits, or upstream " | |
| "merged in, so no other branch's history goes with it" | |
| ) | |
| added = git.run(worktree.path, "rev-list", "--count", f"{expected}..{commit}", *excluded).strip() | |
| if int(added) > MAX_FIXUP_COMMITS: | |
| raise GitRefused( | |
| f"{local!r} adds {added} commits on top of the pull request's head; a fixup adds at most " | |
| f"{MAX_FIXUP_COMMITS}" | |
| ) | |
| head = _pull_request_head(git, policy, number) | |
| # GitHub repository names are case-insensitive; the forge answers in its own casing. | |
| if str(head.get("base_repo") or "").casefold() != policy.upstream_repo.casefold(): | |
| raise GitRefused(f"pull request #{number} is not against {policy.upstream_repo}") | |
| if head.get("state") != "open": | |
| raise GitRefused(f"pull request #{number} is {head.get('state')!r}, not open") | |
| if head.get("head_sha") != expected: | |
| raise GitRefused( | |
| f"pull request #{number}'s head is now {head.get('head_sha')}, not {expected}; " | |
| "fetch it again and rebuild the fixup on it" | |
| ) | |
| repo = head.get("head_repo") | |
| if not isinstance(repo, str) or not _REPO.fullmatch(repo): | |
| raise GitRefused(f"pull request #{number} has no head repository (was its fork deleted?)") | |
| remote_branch = branch_name(git, worktree.path, str(head.get("head_ref") or ""), "the head branch") | |
| if (repo.casefold(), remote_branch) != (named_repo.casefold(), named_branch): | |
| raise GitRefused( | |
| f"pull request #{number}'s head is {repo} {remote_branch}, not {named_repo} {named_branch}; " | |
| "name the head the forge reports" | |
| ) | |
| if is_protected(remote_branch, policy): | |
| raise GitRefused(f"{remote_branch!r} is a protected branch; no operation pushes to it") | |
| if repo.casefold() == policy.upstream_repo.casefold(): | |
| if not any(fnmatch.fnmatchcase(remote_branch, glob) for glob in policy.upstream_push): | |
| raise GitRefused( | |
| f"{remote_branch!r} matches no [git] upstream_push glob " | |
| f"({', '.join(policy.upstream_push) or 'none declared'}), so it may not be pushed upstream" | |
| ) | |
| elif head.get("maintainer_can_modify") is not True: | |
| raise GitRefused( | |
| f"the author of pull request #{number} does not allow edits from maintainers, " | |
| f"so nothing may be pushed to {repo} {remote_branch}" | |
| ) | |
| args = [ | |
| "push", | |
| # The pre-push checks run in the sandbox before this call (see the module docstring). | |
| "--no-verify", | |
| "--no-follow-tags", | |
| "--porcelain", | |
| f"--force-with-lease=refs/heads/{remote_branch}:{expected}", | |
| policy.push_url(repo), | |
| f"{commit}:refs/heads/{remote_branch}", | |
| ] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| check_repository_config(git, worktree) | |
| git.run(worktree.path, *args) | |
| return f"pushed {commit} to {repo} {remote_branch}, the head of #{number} (was {expected})" | |
| def worktree_sync(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Move a clean linked worktree's branch to a commit (``reset --keep``).""" | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| if not worktree.linked: | |
| raise GitRefused("worktree-sync moves linked worktrees only; this is the main checkout") | |
| check_repository_config(git, worktree) | |
| commit = resolve_commit(git, worktree.path, sha(p["commit"], "commit"), "commit") | |
| branch = current_branch(git, worktree) | |
| if git.run(worktree.path, "status", "--porcelain", "--untracked-files=no").strip(): | |
| raise GitRefused(f"{str(worktree.path)!r} has uncommitted changes; commit or set them aside first") | |
| previous = git.run(worktree.path, "rev-parse", "HEAD").strip() | |
| args = ["reset", "--keep", commit] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| check_repository_config(git, worktree) | |
| git.run(worktree.path, *args) | |
| return f"moved {branch} in {worktree.path} from {previous} to {commit}" | |
| #: Pinned on a rebase on top of `PINNED_CONFIG`: no recorded conflict | |
| #: resolution is replayed (`rerere` would write content no check passed), no | |
| #: stash is made or popped, no other branch is moved, and no editor is started. | |
| REBASE_CONFIG = ( | |
| "rerere.enabled=false", | |
| "rerere.autoUpdate=false", | |
| "rebase.autoStash=false", | |
| "rebase.autoSquash=false", | |
| "rebase.updateRefs=false", | |
| "core.editor=false", | |
| "sequence.editor=false", | |
| ) | |
| #: Pinned on a merge, for the same reasons as `REBASE_CONFIG`: no recorded | |
| #: resolution, no stash, no editor, and no merge log built from commit text. | |
| MERGE_CONFIG = ( | |
| "rerere.enabled=false", | |
| "rerere.autoUpdate=false", | |
| "merge.autoStash=false", | |
| "merge.log=false", | |
| "core.editor=false", | |
| ) | |
| #: Pinned on a cherry-pick, for the same reasons as `REBASE_CONFIG`. | |
| CHERRY_PICK_CONFIG = ( | |
| "rerere.enabled=false", | |
| "rerere.autoUpdate=false", | |
| "core.editor=false", | |
| "sequence.editor=false", | |
| ) | |
| def require_signed(git: Git, worktree: Worktree, revisions: str | Sequence[str], operation: str) -> None: | |
| """Refuse to re-sign a commit that does not already carry the user's good signature. | |
| An operation that replays commits (a rebase, a cherry-pick, a merge) signs | |
| what it writes with the user's key, outside the sandbox. Inside it, the | |
| agent can make commits of its own, unsigned and with content the sandboxed | |
| checks never saw; replaying those here would put the user's signature on | |
| them. So when the user signs commits, every replayed commit must already | |
| verify (``%G?`` is ``G``) against their global configuration: one made | |
| through `git-commit`, or one they signed themselves. Verifying runs here, | |
| outside the sandbox, because the allowed-signers file and keyring are | |
| out of its reach. When the user does not sign, nothing is signed here | |
| either, and there is no signature to protect. | |
| """ | |
| if not git.signs_commits(): | |
| return | |
| spec = [revisions] if isinstance(revisions, str) else list(revisions) | |
| output = git.run(worktree.path, "log", "--format=%H %G?", *spec) | |
| unsigned = [fields[0] for fields in (line.split() for line in output.splitlines()) if fields[1:] != ["G"]] | |
| if unsigned: | |
| shown = ", ".join(unsigned[:10]) + (" …" if len(unsigned) > 10 else "") | |
| raise GitRefused( | |
| f"the {operation} would sign commits that carry no good signature of yours: {shown}. Commit through " | |
| "git-commit, or sign those commits yourself, and retry. Signatures are checked against your global " | |
| "gpg configuration (for ssh signing, gpg.ssh.allowedSignersFile)" | |
| ) | |
| def _fetch_base(git: Git, worktree: Worktree, policy: GitPolicy) -> str: | |
| """Fetch the policy's ``pr_base`` from the upstream URL and return the commit it fetched. | |
| The commit comes from this fetch's own output, not from the remote-tracking | |
| ref afterwards: that ref is in the repository, which a sandboxed `git fetch` | |
| from a URL the repository configures can also write. | |
| """ | |
| ref = f"refs/remotes/{policy.upstream_remote}/{policy.pr_base}" | |
| output = git.run( | |
| worktree.path, | |
| "fetch", | |
| "--porcelain", | |
| # Without it an up-to-date ref is left out of the porcelain output. | |
| "--verbose", | |
| "--no-tags", | |
| "--no-recurse-submodules", | |
| "--no-write-fetch-head", | |
| policy.push_url(policy.upstream_repo), | |
| f"+refs/heads/{policy.pr_base}:{ref}", | |
| ) | |
| for line in output.splitlines(): | |
| fields = line.split() | |
| if len(fields) == 4 and fields[3] == ref and _SHA.fullmatch(fields[2]): | |
| return fields[2] | |
| raise GitRefused(f"fetching {policy.upstream_repo} {policy.pr_base} reported no commit for {ref}") | |
| def rebase_onto(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Rebase a clean topic branch onto an upstream commit; on a conflict, abort and report it. | |
| The rebase re-creates each commit, so it signs them per the user's global | |
| configuration, which the sandbox cannot reach. Nothing in it is decided by | |
| hand: git replays each commit already on the branch onto a commit of the | |
| upstream ``pr_base`` (fetched here, from the policy's URL), merging the | |
| two sides only where that needs no decision. A conflict is never resolved | |
| out here; the rebase is aborted, the branch is left where it was, and the | |
| conflicting paths are named, to be resolved in the sandbox and committed | |
| through `git-commit`. | |
| """ | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| onto = sha(p["onto"], "onto") | |
| expected = sha(p["expected"], "expected") | |
| branch = current_branch(git, worktree) | |
| if is_protected(branch, policy): | |
| raise GitRefused(f"{branch!r} is a protected branch; only a topic branch is rebased") | |
| previous = git.run(worktree.path, "rev-parse", "HEAD").strip() | |
| if previous != expected: | |
| raise GitRefused( | |
| f"{branch!r} is at {previous}, not the expected {expected}; it moved since the rebase was " | |
| "approved, so look at it again" | |
| ) | |
| if git.run(worktree.path, "status", "--porcelain", "--untracked-files=no").strip(): | |
| raise GitRefused(f"{str(worktree.path)!r} has uncommitted changes; commit or set them aside first") | |
| pins = [arg for pin in REBASE_CONFIG for arg in ("-c", pin)] | |
| args = [ | |
| *pins, | |
| "rebase", | |
| "--no-autosquash", | |
| "--no-autostash", | |
| "--no-update-refs", | |
| "--no-rerere-autoupdate", | |
| "--empty=drop", | |
| "--end-of-options", | |
| onto, | |
| # Named, so the rebase acts on this branch even if HEAD is switched in between. | |
| branch, | |
| ] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| base = _fetch_base(git, worktree, policy) | |
| resolve_commit(git, worktree.path, onto, "onto") | |
| if not git.ok(worktree.path, "merge-base", "--is-ancestor", onto, base): | |
| raise GitRefused( | |
| f"onto {onto} is not on {policy.upstream_repo} {policy.pr_base} (fetched just now at {base}); " | |
| f"rebase onto a commit of {policy.pr_base}" | |
| ) | |
| if git.ok(worktree.path, "merge-base", "--is-ancestor", onto, previous): | |
| return f"{branch} in {worktree.path} already contains {onto}; nothing to rebase" | |
| if git.run(worktree.path, "rev-list", "--count", f"{onto}..{previous}").strip() == "0": | |
| raise GitRefused(f"{branch!r} has no commits over {onto}; a rebase would leave it empty") | |
| if git.run(worktree.path, "rev-list", "--merges", "--count", f"{onto}..{previous}").strip() != "0": | |
| raise GitRefused( | |
| f"{branch!r} has merge commits over {onto}; a rebase would flatten them and could drop what " | |
| "they resolved. Rebase it in the sandbox instead" | |
| ) | |
| check_repository_config(git, worktree) | |
| # After the last configuration check; verifying runs with the user's own | |
| # signing settings pinned (`Git.signing_pins`). | |
| require_signed(git, worktree, f"{onto}..{previous}", "rebase") | |
| argv, completed = git._call(worktree.path, *args) | |
| if completed.returncode != 0: | |
| conflicts = git._call(worktree.path, "diff", "--name-only", "--diff-filter=U", "-z")[1].stdout or "" | |
| aborted = git._call(worktree.path, "rebase", "--abort")[1].returncode == 0 | |
| paths = [path for path in conflicts.split("\0") if path] | |
| shown = ", ".join(paths[:20]) + (" …" if len(paths) > 20 else "") if paths else "none reported" | |
| state = ( | |
| f"the rebase was aborted and {branch} is still at {previous}" | |
| if aborted | |
| else f"`git rebase --abort` failed too; {str(worktree.path)!r} is mid-rebase" | |
| ) | |
| raise GitFailed( | |
| argv, | |
| completed.returncode, | |
| f"{completed.stderr or ''}conflicting paths: {shown}; {state}. Resolve the conflict in the " | |
| "sandbox and commit it with git-commit\n", | |
| completed.stdout or "", | |
| ) | |
| rebased = git.run(worktree.path, "rev-parse", "--verify", f"refs/heads/{branch}").strip() | |
| # The checks above saw `expected`; the rebase replayed whatever the branch | |
| # held when it started. If something moved it in between, put back what the | |
| # rebase started from and refuse: those commits were never approved. | |
| started = git.run(worktree.path, "rev-parse", "--verify", "ORIG_HEAD").strip() | |
| if started != expected: | |
| git.run(worktree.path, "reset", "--keep", started) | |
| raise GitRefused( | |
| f"{branch!r} moved to {started} while the rebase was starting, not the approved {expected}; " | |
| f"it is back at {started}, unrebased. Look at it again" | |
| ) | |
| count = git.run(worktree.path, "rev-list", "--count", f"{onto}..{rebased}").strip() | |
| return f"rebased {branch} in {worktree.path} onto {onto}: {previous} -> {rebased} ({count} commits)" | |
| def cherry_pick(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Replay one commit onto a clean topic branch; on a conflict, abort and report it. | |
| The way to finish a rebase that conflicted: start a branch on the upstream | |
| base, then replay the commits one at a time, resolving the one that | |
| conflicts in the sandbox and committing it through `git-commit`. The new | |
| commit is signed per the user's configuration, so when the user signs, | |
| the commit replayed must already carry their good signature: one of their | |
| own, never one the agent made unsigned in the sandbox. A merge commit is | |
| refused, since a pick of it needs a decision about its parents. | |
| """ | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| commit = sha(p["commit"], "commit") | |
| expected = sha(p["expected"], "expected") | |
| branch = current_branch(git, worktree) | |
| if is_protected(branch, policy): | |
| raise GitRefused(f"{branch!r} is a protected branch; commits are replayed onto a topic branch only") | |
| previous = git.run(worktree.path, "rev-parse", "HEAD").strip() | |
| if previous != expected: | |
| raise GitRefused( | |
| f"{branch!r} is at {previous}, not the expected {expected}; it moved since the cherry-pick was " | |
| "approved, so look at it again" | |
| ) | |
| if git.run(worktree.path, "status", "--porcelain", "--untracked-files=no").strip(): | |
| raise GitRefused(f"{str(worktree.path)!r} has uncommitted changes; commit or set them aside first") | |
| resolve_commit(git, worktree.path, commit, "commit") | |
| parents = git.run(worktree.path, "rev-list", "--parents", "-n", "1", commit).split()[1:] | |
| if len(parents) != 1: | |
| raise GitRefused( | |
| f"{commit} is {'a merge' if parents else 'a root'} commit; only a plain commit is replayed" | |
| ) | |
| if git.ok(worktree.path, "merge-base", "--is-ancestor", commit, previous): | |
| return f"{branch} in {worktree.path} already contains {commit}; nothing to replay" | |
| pins = [arg for pin in CHERRY_PICK_CONFIG for arg in ("-c", pin)] | |
| args = [ | |
| *pins, | |
| "cherry-pick", | |
| "--no-edit", | |
| "--no-rerere-autoupdate", | |
| "--allow-empty", | |
| "--end-of-options", | |
| commit, | |
| ] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| check_repository_config(git, worktree) | |
| require_signed(git, worktree, f"{commit}^!", "cherry-pick") | |
| argv, completed = git._call(worktree.path, *args) | |
| if completed.returncode != 0: | |
| conflicts = git._call(worktree.path, "diff", "--name-only", "--diff-filter=U", "-z")[1].stdout or "" | |
| aborted = git._call(worktree.path, "cherry-pick", "--abort")[1].returncode == 0 | |
| paths = [path for path in conflicts.split("\0") if path] | |
| shown = ", ".join(paths[:20]) + (" …" if len(paths) > 20 else "") if paths else "none reported" | |
| state = ( | |
| f"the cherry-pick was aborted and {branch} is still at {previous}" | |
| if aborted | |
| else f"`git cherry-pick --abort` failed too; {str(worktree.path)!r} is mid-cherry-pick" | |
| ) | |
| raise GitFailed( | |
| argv, | |
| completed.returncode, | |
| f"{completed.stderr or ''}conflicting paths: {shown}; {state}. Make the change in the sandbox " | |
| "and commit it with git-commit\n", | |
| completed.stdout or "", | |
| ) | |
| picked = git.run(worktree.path, "rev-parse", "HEAD").strip() | |
| landed = git.run(worktree.path, "rev-list", "--parents", "-n", "1", picked).split()[1:] | |
| now = git.run(worktree.path, "symbolic-ref", "--quiet", "HEAD").strip() | |
| if landed != [expected] or now != f"refs/heads/{branch}": | |
| git.run(worktree.path, "reset", "--keep", landed[0]) | |
| raise GitRefused( | |
| f"the cherry-pick landed on {now or 'a detached HEAD'} at {landed[0]}, not on {branch!r} at the " | |
| f"approved {expected}; it was taken back off. Look at the branch again" | |
| ) | |
| return f"replayed {commit} onto {branch} in {worktree.path}: {previous} -> {picked}" | |
| def merge_upstream(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Merge an upstream ``pr_base`` commit into a clean topic branch; on a conflict, abort and report it. | |
| For a branch whose history must not be rewritten (a contributor's pull | |
| request), where a rebase would. The merge commit is signed per the user's | |
| configuration, so the same rule as for a rebase holds: when the user | |
| signs, the commits the merge vouches for must already carry their | |
| signature. On the user's own branch (``pr`` is ``none``) that is every | |
| commit not on upstream. On a pull request's branch (``pr`` is its number) | |
| the contributor's commits are theirs, already published, and never carry | |
| the user's signature, so only the commits on top of the head the forge | |
| reports for that pull request are checked. The message is fixed, the | |
| other parent must be on the upstream ``pr_base`` fetched here, and a | |
| conflict is never resolved out here. | |
| """ | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| onto = sha(p["onto"], "onto") | |
| expected = sha(p["expected"], "expected") | |
| pr = _param(p["pr"], "pr") | |
| if pr != "none" and not _PR_NUMBER.fullmatch(pr): | |
| raise GitRefused(f"pr must be a pull request number, or 'none' for your own branch; got {pr!r}") | |
| branch = current_branch(git, worktree) | |
| if is_protected(branch, policy): | |
| raise GitRefused(f"{branch!r} is a protected branch; upstream is merged into a topic branch only") | |
| previous = git.run(worktree.path, "rev-parse", "HEAD").strip() | |
| if previous != expected: | |
| raise GitRefused( | |
| f"{branch!r} is at {previous}, not the expected {expected}; it moved since the merge was " | |
| "approved, so look at it again" | |
| ) | |
| if git.run(worktree.path, "status", "--porcelain", "--untracked-files=no").strip(): | |
| raise GitRefused(f"{str(worktree.path)!r} has uncommitted changes; commit or set them aside first") | |
| message = f"Merge {policy.upstream_repo} {policy.pr_base} into {branch}" | |
| pins = [arg for pin in MERGE_CONFIG for arg in ("-c", pin)] | |
| args = [ | |
| *pins, | |
| "merge", | |
| "--no-ff", | |
| "--no-edit", | |
| "--no-autostash", | |
| "--no-rerere-autoupdate", | |
| "--no-verify", | |
| "-m", | |
| message, | |
| "--end-of-options", | |
| onto, | |
| ] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| base = _fetch_base(git, worktree, policy) | |
| resolve_commit(git, worktree.path, onto, "onto") | |
| if not git.ok(worktree.path, "merge-base", "--is-ancestor", onto, base): | |
| raise GitRefused( | |
| f"onto {onto} is not on {policy.upstream_repo} {policy.pr_base} (fetched just now at {base}); " | |
| f"merge a commit of {policy.pr_base}" | |
| ) | |
| if git.ok(worktree.path, "merge-base", "--is-ancestor", onto, previous): | |
| return f"{branch} in {worktree.path} already contains {onto}; nothing to merge" | |
| # The commits the merge commit vouches for: the branch's own, not upstream's, | |
| # and on a pull request's branch not the contributor's either. | |
| vouched = [f"{onto}..{previous}"] | |
| if pr != "none": | |
| head = _pull_request_head(git, policy, pr) | |
| if str(head.get("base_repo") or "").casefold() != policy.upstream_repo.casefold(): | |
| raise GitRefused(f"pull request #{pr} is not against {policy.upstream_repo}") | |
| if head.get("state") != "open": | |
| raise GitRefused(f"pull request #{pr} is {head.get('state')!r}, not open") | |
| head_sha = head.get("head_sha") | |
| if not isinstance(head_sha, str) or not _SHA.fullmatch(head_sha): | |
| raise GitRefused(f"pull request #{pr}: the forge reports no head commit") | |
| if not git.ok(worktree.path, "cat-file", "-e", f"{head_sha}^{{commit}}") or not git.ok( | |
| worktree.path, "merge-base", "--is-ancestor", head_sha, previous | |
| ): | |
| raise GitRefused( | |
| f"{branch!r} does not build on pull request #{pr}'s head {head_sha}; fetch the pull request " | |
| "and build on its head" | |
| ) | |
| vouched.append(f"^{head_sha}") | |
| check_repository_config(git, worktree) | |
| require_signed(git, worktree, vouched, "merge") | |
| argv, completed = git._call(worktree.path, *args) | |
| if completed.returncode != 0: | |
| conflicts = git._call(worktree.path, "diff", "--name-only", "--diff-filter=U", "-z")[1].stdout or "" | |
| aborted = git._call(worktree.path, "merge", "--abort")[1].returncode == 0 | |
| paths = [path for path in conflicts.split("\0") if path] | |
| shown = ", ".join(paths[:20]) + (" …" if len(paths) > 20 else "") if paths else "none reported" | |
| state = ( | |
| f"the merge was aborted and {branch} is still at {previous}" | |
| if aborted | |
| else f"`git merge --abort` failed too; {str(worktree.path)!r} is mid-merge" | |
| ) | |
| raise GitFailed( | |
| argv, | |
| completed.returncode, | |
| f"{completed.stderr or ''}conflicting paths: {shown}; {state}. Resolve the conflict in the " | |
| "sandbox and commit it with git-commit\n", | |
| completed.stdout or "", | |
| ) | |
| merged = git.run(worktree.path, "rev-parse", "HEAD").strip() | |
| # A merge acts on whatever HEAD is when it starts. If the branch or its tip | |
| # changed after the checks, take the merge back off and refuse. | |
| parents = git.run(worktree.path, "rev-list", "--parents", "-n", "1", merged).split()[1:] | |
| now = git.run(worktree.path, "symbolic-ref", "--quiet", "HEAD").strip() | |
| if parents != [expected, onto] or now != f"refs/heads/{branch}": | |
| git.run(worktree.path, "reset", "--keep", parents[0]) | |
| raise GitRefused( | |
| f"the merge landed on {now or 'a detached HEAD'} at {parents[0]}, not on {branch!r} at the approved " | |
| f"{expected}; it was taken back off. Look at the branch again" | |
| ) | |
| return f"merged {policy.upstream_repo} {policy.pr_base} {onto} into {branch} in {worktree.path}: {previous} -> {merged}" | |
| #: Tracked paths that steer an agent harness or this dispatcher: settings, | |
| #: hooks, skills, agents, MCP servers, plugin manifests and the vetted-ops | |
| #: policy. Harnesses keep them read-only in the sandbox because what they say | |
| #: runs outside it, which is also why a branch switch inside the sandbox fails | |
| #: half-way. `git-switch` writes them, so it only ever writes a version that | |
| #: came from upstream. A project adds its own with `[git] harness_paths`. | |
| HARNESS_PATHS = ( | |
| ".claude", | |
| ".agents", | |
| ".codex", | |
| ".gemini", | |
| ".github/skills", | |
| ".mcp.json", | |
| ".claude-plugin", | |
| ".apache-magpie-overrides/tools/vetted-ops", | |
| ".apache-magpie-local/tools/vetted-ops", | |
| # A Subversion working copy's personal layer; a tree can carry `.svn` as plain files. | |
| ".svn/apache-magpie/tools/vetted-ops", | |
| ) | |
| def _path_key(path: str) -> str: | |
| """``path`` as a case-insensitive, normalising file system sees it. | |
| On such a file system (macOS by default) a tracked `.Claude/settings.json` | |
| is written to `.claude/settings.json`, and HFS+ also drops Unicode format | |
| characters, so a byte-exact comparison would miss both. | |
| """ | |
| composed = unicodedata.normalize("NFC", path) | |
| return "".join(c for c in composed if unicodedata.category(c) != "Cf").casefold() | |
| def is_harness_path(path: str, extra: Sequence[str] = ()) -> bool: | |
| """Whether ``path`` is, is inside, or stands in for a directory of a harness path, at any depth. | |
| Any depth, because harnesses also read nested `.claude/` directories. And | |
| an ancestor counts (a tracked `.github` or `.apache-magpie-overrides/tools` | |
| entry), because a symlink there would redirect every harness path below it. | |
| ``extra`` are the policy's `harness_paths`. | |
| """ | |
| keys = [_path_key(h) for h in (*HARNESS_PATHS, *extra)] | |
| parts = _path_key(path).split("/") | |
| for start in range(len(parts)): | |
| tail = "/".join(parts[start:]) | |
| if any(tail == h or tail.startswith(f"{h}/") or h.startswith(f"{tail}/") for h in keys): | |
| return True | |
| return False | |
| def _upstream_base(git: Git, policy: GitPolicy, worktree: Worktree, fetch: bool = True) -> str | None: | |
| """The upstream ``pr_base`` commit, asked of the policy's URL now, with its objects present. | |
| Never a local ref: `refs/remotes/...` lives in the agent-writable `.git`, | |
| so a ref there could name a commit of the agent's own as "upstream". The | |
| objects behind the answer are then read through `_VerifiedObjects`, so a | |
| forged object stored under that name is caught too. Without ``fetch`` (a | |
| dry run) a commit not yet in the repository is None. | |
| """ | |
| url = policy.push_url(policy.upstream_repo) | |
| ref = f"refs/heads/{policy.pr_base}" | |
| # The URL is built from the policy and starts with a scheme or `git@`, never `-`. | |
| lines = git.run(worktree.path, "ls-remote", url, ref).splitlines() | |
| found = [line.split("\t", 1)[0] for line in lines if line.endswith(f"\t{ref}")] | |
| if len(found) != 1 or not _SHA.fullmatch(found[0]): | |
| raise GitRefused(f"{policy.upstream_repo} has no branch {policy.pr_base!r} to check against") | |
| base = found[0] | |
| if not git.ok(worktree.path, "cat-file", "-e", f"{base}^{{commit}}"): | |
| if not fetch: | |
| return None | |
| git.run( | |
| worktree.path, "fetch", "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", url, ref | |
| ) | |
| if not git.ok(worktree.path, "cat-file", "-e", f"{base}^{{commit}}"): | |
| raise GitRefused( | |
| f"upstream {policy.pr_base} ({base}) is missing or damaged in the repository even after fetching " | |
| "it: it moved meanwhile (retry), or the object store has been tampered with" | |
| ) | |
| return base | |
| #: Tree entry modes `git-switch` writes as files: regular, executable, symlink. | |
| _FILE_MODES = ("100644", "100755", "120000") | |
| #: Every mode a well-formed tree uses; `git fsck` flags any other spelling. | |
| _TREE_MODES = ("40000", *_FILE_MODES, "160000") | |
| #: Commits read to confirm the fork point is upstream's, at most. | |
| MAX_ANCESTRY = 200_000 | |
| class _VerifiedObjects: | |
| """Objects read from the repository and re-hashed before they are believed. | |
| The object store is in the agent-writable `.git`, and git does not re-hash | |
| what it reads, so a loose object holding other content under a name would | |
| be taken as genuine. Every object here is hashed again and must match the | |
| name it was asked for, so a walk that starts from a commit name obtained | |
| from the forge reads only content the forge's history really holds. | |
| """ | |
| def __init__(self, git: Git, directory: Path) -> None: | |
| self.git = git | |
| self.directory = directory | |
| self.cache: dict[str, tuple[str, bytes]] = {} | |
| def read(self, oids: Sequence[str]) -> None: | |
| wanted = [oid for oid in dict.fromkeys(oids) if oid not in self.cache] | |
| if not wanted: | |
| return | |
| output = self.git.run_bytes( | |
| self.directory, "cat-file", "--batch", stdin="".join(f"{o}\n" for o in wanted) | |
| ) | |
| at = 0 | |
| for oid in wanted: | |
| end = output.index(b"\n", at) | |
| header = output[at:end].decode("ascii", "replace").split() | |
| if len(header) != 3 or header[0] != oid: | |
| raise GitRefused(f"object {oid} is missing from the repository") | |
| kind, size = header[1], int(header[2]) | |
| body = output[end + 1 : end + 1 + size] | |
| at = end + 1 + size + 1 | |
| digest = hashlib.new(self.git.object_format, f"{kind} {size}\0".encode() + body).hexdigest() | |
| if digest != oid: | |
| raise GitRefused( | |
| f"object {oid} in the repository holds other content (it hashes to {digest}); " | |
| "the object store has been tampered with" | |
| ) | |
| self.cache[oid] = (kind, body) | |
| def get(self, oid: str, kind: str) -> bytes: | |
| self.read([oid]) | |
| found, body = self.cache[oid] | |
| if found != kind: | |
| raise GitRefused(f"object {oid} is a {found}, not a {kind}") | |
| return body | |
| def _commit_lines(self, oid: str) -> list[list[str]]: | |
| head = self.get(oid, "commit").split(b"\n\n", 1)[0].decode("utf-8", "replace") | |
| return [line.split(" ", 1) for line in head.split("\n") if " " in line] | |
| def parents(self, oid: str) -> list[str]: | |
| return [value for key, value in self._commit_lines(oid) if key == "parent" and _SHA.fullmatch(value)] | |
| def is_ancestor(self, ancestor: str, of: str, hint: Sequence[str] = ()) -> bool: | |
| """Whether ``ancestor`` is reachable from ``of`` through verified parent links. | |
| ``hint`` (commits git lists in between) is only read ahead in one batch; | |
| nothing in it is believed until a verified parent link reaches it. | |
| """ | |
| self.read([of, *hint]) | |
| seen = {of} | |
| frontier = [of] | |
| while frontier: | |
| if ancestor in seen: | |
| return True | |
| if len(seen) > MAX_ANCESTRY: | |
| raise GitRefused(f"{of} is more than {MAX_ANCESTRY} commits from {ancestor}; switch by hand") | |
| self.read(frontier) | |
| nxt = [p for oid in frontier for p in self.parents(oid) if p not in seen] | |
| seen.update(nxt) | |
| frontier = list(dict.fromkeys(nxt)) | |
| return ancestor in seen | |
| def harness_entries(self, commit: str, extra: Sequence[str]) -> dict[str, tuple[str, str]]: | |
| """Every harness path in ``commit``'s tree, as ``{path: (mode, oid)}``, walked through verified trees.""" | |
| trees = [value for key, value in self._commit_lines(commit) if key == "tree"] | |
| if len(trees) != 1 or not _SHA.fullmatch(trees[0]): | |
| raise GitRefused(f"commit {commit} has no single tree line") | |
| width = 32 if self.git.object_format == "sha256" else 20 | |
| entries: dict[str, tuple[str, str]] = {} | |
| level = [("", trees[0])] | |
| while level: | |
| self.read([oid for _, oid in level]) | |
| below: list[tuple[str, str]] = [] | |
| for prefix, oid in level: | |
| raw = self.get(oid, "tree") | |
| at = 0 | |
| while at < len(raw): | |
| space = raw.index(b" ", at) | |
| nul = raw.index(b"\0", space) | |
| mode = raw[at:space].decode("ascii", "replace") | |
| name = raw[space + 1 : nul].decode("utf-8", "surrogateescape") | |
| child = raw[nul + 1 : nul + 1 + width].hex() | |
| at = nul + 1 + width | |
| # Git's own walker accepts other spellings of a mode (`040000`); refusing | |
| # them keeps this walk and the checkout reading the same tree. | |
| if mode not in _TREE_MODES or name in ("", ".", "..") or "/" in name: | |
| raise GitRefused(f"tree {oid} has a malformed entry {mode} {name!r}") | |
| path = f"{prefix}{name}" | |
| if mode == "40000": | |
| below.append((f"{path}/", child)) | |
| elif is_harness_path(path, extra): | |
| entries[path] = (mode, child) | |
| level = below | |
| return entries | |
| def _plain_directories(root: Path, parts: Sequence[str]) -> bool: | |
| """Whether every directory on ``parts`` under ``root`` exists; a symlink on the way fails closed.""" | |
| here = root | |
| for part in parts: | |
| here = here / part | |
| try: | |
| st = os.lstat(here) | |
| except FileNotFoundError: | |
| return False | |
| if not stat.S_ISDIR(st.st_mode): | |
| raise GitRefused(f"{str(here.relative_to(root))!r} is not a plain directory") | |
| return True | |
| def _restore_written( | |
| worktree: Worktree, entries: dict[str, tuple[str, str]], objects: _VerifiedObjects | |
| ) -> list[str]: | |
| """Re-hash each harness file the switch wrote, and put back verified content where it differs. | |
| Git read those files from the same object store, and something could have | |
| changed an object between the walk and the checkout; this is the check that | |
| what is on disk is what was verified. A missing file whose directory exists | |
| is written too; a missing directory is a sparse checkout and is left alone. | |
| """ | |
| restored = [] | |
| for path, (mode, oid) in sorted(entries.items()): | |
| if mode not in _FILE_MODES: | |
| continue | |
| content = objects.get(oid, "blob") | |
| parts = Path(path).parts | |
| if not _plain_directories(worktree.path, parts[:-1]): | |
| continue # not written: a sparse checkout | |
| dir_fd = open_dir((worktree.path / path).parent) | |
| name = parts[-1] | |
| try: | |
| try: | |
| st: os.stat_result | None = os.stat(name, dir_fd=dir_fd, follow_symlinks=False) | |
| except FileNotFoundError: | |
| st = None | |
| ok = False | |
| if st is not None and mode == "120000": | |
| ok = stat.S_ISLNK(st.st_mode) and os.readlink(name, dir_fd=dir_fd).encode() == content | |
| elif st is not None and stat.S_ISREG(st.st_mode): | |
| fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=dir_fd) | |
| with os.fdopen(fd, "rb") as handle: | |
| ok = stat.S_ISREG(os.fstat(handle.fileno()).st_mode) and handle.read() == content | |
| if ok: | |
| continue | |
| temp = f".{name}.vetted-op-git-{os.urandom(8).hex()}" | |
| if mode == "120000": | |
| os.symlink(content, temp, dir_fd=dir_fd) | |
| else: | |
| # Owner-only: git tracks only the executable bit, and these files | |
| # (settings, hooks, the policy) are nobody else's to read. | |
| fd = os.open( | |
| temp, | |
| os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, | |
| 0o700 if mode == "100755" else 0o600, | |
| dir_fd=dir_fd, | |
| ) | |
| with os.fdopen(fd, "wb") as handle: | |
| handle.write(content) | |
| os.replace(temp, name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) | |
| restored.append(path) | |
| finally: | |
| os.close(dir_fd) | |
| return restored | |
| def _index_harness_entries(git: Git, worktree: Worktree, extra: Sequence[str]) -> dict[str, tuple[str, str]]: | |
| """The harness entries of the index the checkout just wrote, as ``{path: (mode, oid)}``.""" | |
| entries = {} | |
| for record in git.run(worktree.path, "ls-files", "--stage", "-z").split("\0"): | |
| if not record: | |
| continue | |
| info, _, path = record.partition("\t") | |
| mode, oid, _stage = info.split(" ") | |
| if is_harness_path(path, extra): | |
| entries[path] = (mode, oid) | |
| return entries | |
| def _checked_out_elsewhere(git: Git, worktree: Worktree, branch: str) -> str | None: | |
| """The other working tree that has ``branch`` checked out, if any.""" | |
| current = None | |
| for line in git.run(worktree.path, "worktree", "list", "--porcelain").splitlines(): | |
| if line.startswith("worktree "): | |
| current = line[len("worktree ") :] | |
| elif ( | |
| line == f"branch refs/heads/{branch}" | |
| and current is not None | |
| and os.path.realpath(current) != str(worktree.path) | |
| ): | |
| return current | |
| return None | |
| def switch_branch(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Switch a clean working tree to an existing local branch. | |
| Inside the sandbox a switch fails half-way: the harness keeps its files | |
| (`HARNESS_PATHS`, plus the policy's `harness_paths`) read-only, so git | |
| updates everything else, leaves those behind and reports them as local | |
| changes. Out here it can write them, and that is the risk: a branch whose | |
| own commits change `.claude/settings.json` or a hook would be installed by | |
| a confirmation that shows only a branch name. So the branch's harness | |
| files must be upstream's from where the branch left it: any branch that | |
| did not change them itself switches, however old. | |
| - The upstream commit is asked of the policy's URL during this call, so a | |
| local ref the agent moved cannot stand in for it. | |
| - The fork point must be reached from it through verified parent links, | |
| and both trees are walked through `_VerifiedObjects`, so a forged | |
| object or a forged history in the agent-writable `.git` is refused. | |
| - After the checkout, the index's harness entries must be the verified | |
| ones, and every harness file on disk is hashed again; any that differs | |
| is replaced with the verified content. | |
| The files written are those of the commit checked here, whatever the | |
| branch name points at later. | |
| """ | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| branch = branch_name(git, worktree.path, p["branch"], "branch") | |
| if not git.ok(worktree.path, "show-ref", "--verify", "--quiet", f"refs/heads/{branch}"): | |
| raise GitRefused(f"there is no local branch {branch!r}; git-switch never creates one") | |
| elsewhere = _checked_out_elsewhere(git, worktree, branch) | |
| if elsewhere: | |
| raise GitRefused( | |
| f"{branch!r} is checked out in {elsewhere}; a branch is checked out in one place only" | |
| ) | |
| target = git.run(worktree.path, "rev-parse", "--verify", f"refs/heads/{branch}^{{commit}}").strip() | |
| if git.run(worktree.path, "status", "--porcelain", "--untracked-files=no").strip(): | |
| raise GitRefused(f"{str(worktree.path)!r} has uncommitted changes; commit or set them aside first") | |
| args = ["switch", "--detach", "--no-recurse-submodules", target] | |
| base = _upstream_base(git, policy, worktree, fetch=not dry_run) | |
| if base is None: | |
| return " ".join(git.argv(worktree.path, *args)) + f" # after fetching {policy.pr_base}" | |
| merge_base = git._call(worktree.path, "merge-base", target, base)[1] | |
| if merge_base.returncode != 0: | |
| raise GitRefused(f"{branch!r} shares no history with upstream {policy.pr_base}") | |
| fork_point = merge_base.stdout.strip() | |
| objects = _VerifiedObjects(git, worktree.path) | |
| between = git.run(worktree.path, "rev-list", f"{base}", f"^{fork_point}").split() | |
| if not objects.is_ancestor(fork_point, base, between): | |
| raise GitRefused( | |
| f"{fork_point}, where git says {branch!r} left {policy.pr_base}, is not in upstream's history; " | |
| "the repository's history has been tampered with" | |
| ) | |
| expected = objects.harness_entries(fork_point, policy.harness_paths) | |
| found = objects.harness_entries(target, policy.harness_paths) | |
| own = sorted(path for path in expected.keys() | found.keys() if expected.get(path) != found.get(path)) | |
| if own: | |
| shown = ", ".join(own[:10]) + (" …" if len(own) > 10 else "") | |
| raise GitRefused( | |
| f"{branch!r} changes {shown} in its own commits; those files steer the agent harness " | |
| "outside the sandbox, so only you may switch to it" | |
| ) | |
| # Read now, so the restore below needs nothing from the store after the checkout. | |
| objects.read([oid for mode, oid in found.values() if mode in _FILE_MODES]) | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| check_repository_config(git, worktree) | |
| previous = git.run(worktree.path, "rev-parse", "--abbrev-ref", "HEAD").strip() | |
| git.run(worktree.path, *args) | |
| try: | |
| written = _index_harness_entries(git, worktree, policy.harness_paths) | |
| if written != found: | |
| extra_paths = sorted(set(written) - set(found)) | |
| raise GitRefused( | |
| "the checkout wrote harness entries other than the verified ones" | |
| + (f" ({', '.join(extra_paths[:10])})" if extra_paths else "") | |
| ) | |
| restored = _restore_written(worktree, found, objects) | |
| except (GitRefused, OSError) as exc: | |
| raise GitRefused( | |
| f"checked out {target} in {worktree.path} with a detached HEAD, but its harness files could not " | |
| f"be verified ({exc}); check them by hand before running anything there" | |
| ) from None | |
| note = f"; put back the verified content of {', '.join(restored)}" if restored else "" | |
| git.run(worktree.path, "symbolic-ref", "HEAD", f"refs/heads/{branch}") | |
| # Attached only to the commit that was checked: a branch moved meanwhile leaves HEAD detached there. | |
| if git.run(worktree.path, "rev-parse", "--verify", "HEAD^{commit}").strip() != target: | |
| git.run(worktree.path, "update-ref", "--no-deref", "HEAD", target) | |
| return ( | |
| f"checked out {target} in {worktree.path} (from {previous}) with a detached HEAD: " | |
| f"{branch} moved during the switch, so it was not attached{note}" | |
| ) | |
| return f"switched {worktree.path} from {previous} to {branch} at {target}{note}" | |
| def switch_create(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Create a branch at the upstream ``pr_base`` and switch a clean working tree to it. | |
| The start of a new change in the main checkout, which a sandboxed | |
| ``git switch -c`` cannot finish: the new branch starts where upstream is | |
| now, asked of the policy's URL during this call, never where a local ref | |
| says. Its harness files are then upstream's, so `switch_branch`, which | |
| does the switch, finds nothing of the branch's own to refuse; every check | |
| it makes still runs. A new branch that could not be switched to is | |
| deleted again. | |
| """ | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| branch = branch_name(git, worktree.path, p["branch"], "branch") | |
| if is_protected(branch, policy): | |
| raise GitRefused(f"{branch!r} is a protected branch; a new topic branch is created only") | |
| if git.ok(worktree.path, "show-ref", "--verify", "--quiet", f"refs/heads/{branch}"): | |
| raise GitRefused(f"branch {branch!r} already exists; switch to it with git-switch") | |
| if git.run(worktree.path, "status", "--porcelain", "--untracked-files=no").strip(): | |
| raise GitRefused(f"{str(worktree.path)!r} has uncommitted changes; commit or set them aside first") | |
| if dry_run: | |
| create = git.argv( | |
| worktree.path, "branch", "--no-track", branch, f"<{policy.pr_base} from the policy URL>" | |
| ) | |
| return " ".join(create) + "; then git-switch " + branch | |
| base = _upstream_base(git, policy, worktree, fetch=True) | |
| if base is None: | |
| raise GitRefused(f"upstream {policy.pr_base} could not be read from the policy's URL") | |
| check_repository_config(git, worktree) | |
| # Created only if absent (the zero old value), so an existing branch is never moved. | |
| git.run(worktree.path, "update-ref", f"refs/heads/{branch}", base, "0" * len(base)) | |
| try: | |
| switched = switch_branch(git, policy, {"worktree": p["worktree"], "branch": branch}, False) | |
| except GitRefused, GitFailed: | |
| git._call(worktree.path, "update-ref", "-d", f"refs/heads/{branch}", base) | |
| raise | |
| return f"created {branch} at upstream {policy.pr_base} {base}; {switched}" | |
| def worktree_add(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Create a linked worktree on a new branch, inside a policy worktree root.""" | |
| checkout = resolve_worktree(git, p["checkout"], policy, "checkout") | |
| if checkout.linked: | |
| raise GitRefused("checkout must be the main checkout, not a linked worktree") | |
| check_repository_config(git, checkout) | |
| path = _absolute(p["path"], "path") | |
| if not _WORKTREE_NAME.fullmatch(path.name): | |
| raise GitRefused(f"the new worktree's directory name is not acceptable: {path.name!r}") | |
| if not any( | |
| path.parent == root and str(root) == os.path.realpath(path.parent) for root in policy.worktree_roots | |
| ): | |
| roots = ", ".join(str(r) for r in policy.worktree_roots) or "none declared" | |
| raise GitRefused(f"{str(path)!r} is not directly inside a [git] worktree_roots directory ({roots})") | |
| if os.path.lexists(path): | |
| raise GitRefused(f"{str(path)!r} already exists") | |
| branch = branch_name(git, checkout.path, p["branch"], "branch") | |
| if git.ok(checkout.path, "show-ref", "--verify", "--quiet", f"refs/heads/{branch}"): | |
| raise GitRefused(f"branch {branch!r} already exists; worktree-add creates a new one") | |
| start = resolve_commit(git, checkout.path, sha(p["start"], "start"), "start") | |
| if dry_run: | |
| return " ".join(git.argv(checkout.path, "worktree", "add", "-b", branch, str(path), start)) | |
| check_repository_config(git, checkout) | |
| # Created through the root's descriptor and entered by descriptor, then | |
| # added as `.`: a root swapped for a symlink after the checks above still | |
| # cannot make git write anywhere but this new, empty directory. (Git names | |
| # its administrative directory after the path given, so it is `-` here.) | |
| root_fd = open_dir(path.parent) | |
| try: | |
| os.mkdir(path.name, 0o777, dir_fd=root_fd) | |
| new_fd = os.open(path.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd) | |
| git.anchor(path, new_fd) | |
| try: | |
| git.run( | |
| path, f"--git-dir={checkout.checkout / '.git'}", "worktree", "add", "-b", branch, ".", start | |
| ) | |
| except GitFailed: | |
| os.rmdir(path.name, dir_fd=root_fd) | |
| raise | |
| finally: | |
| os.close(root_fd) | |
| return f"created {path} on new branch {branch} at {start}" | |
| def worktree_remove(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Remove a linked worktree that has no changes (never ``--force``).""" | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| if not worktree.linked: | |
| raise GitRefused("worktree-remove removes linked worktrees only; this is the main checkout") | |
| check_repository_config(git, worktree) | |
| args = ["worktree", "remove", str(worktree.path)] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.checkout, *args)) | |
| # Without --force git itself refuses a worktree with modified or untracked files. | |
| check_repository_config(git, worktree) | |
| git.run(worktree.checkout, *args) | |
| return f"removed {worktree.path}" | |
| def _workspace_text(policy: GitPolicy, value: str, what: str) -> str: | |
| """A UTF-8 text file read from the policy's workspace (see `ops.read_body`).""" | |
| from .ops import ParamError, read_body | |
| if policy.workspace is None: | |
| raise GitRefused(f"the policy names no workspace, so no {what} file can be read") | |
| try: | |
| data = read_body(_param(value, what), workspace=policy.workspace) | |
| except ParamError as exc: | |
| raise GitRefused(str(exc)) from None | |
| try: | |
| text = data.decode("utf-8") | |
| except UnicodeDecodeError: | |
| raise GitRefused(f"the {what} file is not UTF-8 text") from None | |
| if "\x00" in text: | |
| raise GitRefused(f"the {what} file holds a NUL character") | |
| return text | |
| def _stage_paths(worktree: Worktree, text: str) -> list[str]: | |
| """The paths of a `git-stage` list: relative, inside the worktree, one per line.""" | |
| paths = [line for line in (raw.strip() for raw in text.splitlines()) if line] | |
| if not paths: | |
| raise GitRefused("the path list is empty") | |
| if len(paths) > MAX_STAGE_PATHS: | |
| raise GitRefused(f"the path list names {len(paths)} paths; at most {MAX_STAGE_PATHS} per call") | |
| for path in paths: | |
| parts = Path(path).parts | |
| if path.startswith(("-", "/", ":")) or ".." in parts or ".git" in parts: | |
| raise GitRefused( | |
| f"{path!r} is not a plain relative path inside the worktree " | |
| "(no leading '-', '/' or ':', no '..', nothing under .git)" | |
| ) | |
| resolved = os.path.abspath(worktree.path / path) | |
| if os.path.commonpath([str(worktree.path), resolved]) != str(worktree.path): | |
| raise GitRefused(f"{path!r} resolves outside {str(worktree.path)!r}") | |
| return paths | |
| def stage_paths(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Stage exactly the paths listed in a workspace file (``git add`` with literal pathspecs).""" | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| paths = _stage_paths(worktree, _workspace_text(policy, p["paths_file"], "paths_file")) | |
| # Literal pathspecs: no glob or `:(magic)` in a listed path widens what is staged. | |
| # Attributes come from the empty tree (`check_repository_config`), so no | |
| # `.gitattributes` in the working tree can switch on a clean filter. | |
| args = ["--literal-pathspecs", "add", "--", *paths] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| check_repository_config(git, worktree) | |
| git.run(worktree.path, *args) | |
| return f"staged {len(paths)} path(s) in {worktree.path}" | |
| def _require_checked(git: Git, policy: GitPolicy, worktree: Worktree) -> None: | |
| """Refuse a staged change whose content the sandboxed checks did not pass. | |
| `vetted-op-checks` records, per path, the content it checked; every staged | |
| path must be in that record with the same content. The record sits in the | |
| workspace, which sandboxed commands can write, so this keeps an agent | |
| honest the way CI does; it is not a proof against one forging it. | |
| """ | |
| from .checks import DELETED, SITE_HOOKS_SKIPPED, stamp_path | |
| from .checks import PROG as CHECKS | |
| assert policy.workspace is not None # the message file was read from it | |
| hint = f"run `{CHECKS} {worktree.path} <workspace>/<paths_file>` in the sandbox, then stage again" | |
| path = stamp_path(policy.workspace, worktree.path) | |
| try: | |
| data = read_regular_file(path) | |
| except (OSError, TamperedPath) as exc: | |
| raise GitRefused(f"the checks record {str(path)!r} cannot be read ({exc}): {hint}") from None | |
| if data is None: | |
| raise GitRefused(f"no checks were recorded for {str(worktree.path)!r}: {hint}") | |
| try: | |
| record = json.loads(data.decode("utf-8")) | |
| except UnicodeDecodeError, json.JSONDecodeError: | |
| raise GitRefused(f"the checks record {str(path)!r} is not valid JSON: {hint}") from None | |
| files = record.get("files") if isinstance(record, dict) else None | |
| if not isinstance(files, dict): | |
| raise GitRefused(f"the checks record {str(path)!r} lists no files: {hint}") | |
| if record.get("checks") == SITE_HOOKS_SKIPPED and policy.site_hooks != "skip": | |
| raise GitRefused( | |
| "the checks record says the site's hooks were skipped, and this policy does not allow that " | |
| '([git] site_hooks = "skip", in a records-site policy only); run the checks with the hooks instead' | |
| ) | |
| staged = [ | |
| p | |
| for p in git.run(worktree.path, "diff", "--cached", "--name-only", "--no-renames", "-z").split("\0") | |
| if p | |
| ] | |
| unchecked = [] | |
| for staged_path in staged: | |
| entry = git.run(worktree.path, "--literal-pathspecs", "ls-files", "--stage", "-z", "--", staged_path) | |
| blob = entry.split()[1] if entry.strip("\0").strip() else DELETED | |
| if files.get(staged_path) != blob: | |
| unchecked.append(staged_path) | |
| if unchecked: | |
| shown = ", ".join(unchecked[:10]) + (" …" if len(unchecked) > 10 else "") | |
| raise GitRefused(f"the checks did not pass these staged paths as they are now: {shown}; {hint}") | |
| def commit_staged(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Commit what is staged, with a message from a workspace file, signed per the user's own config.""" | |
| worktree = resolve_worktree(git, p["worktree"], policy) | |
| check_repository_config(git, worktree) | |
| message = _workspace_text(policy, p["message_file"], "message_file").strip() | |
| if not message: | |
| raise GitRefused("the commit message is empty") | |
| if len(message) > MAX_COMMIT_MESSAGE: | |
| raise GitRefused(f"the commit message is longer than {MAX_COMMIT_MESSAGE} characters") | |
| branch = current_branch(git, worktree) | |
| if is_protected(branch, policy): | |
| raise GitRefused(f"{branch!r} is a protected branch; commit on a topic branch") | |
| if git.ok(worktree.path, "diff", "--cached", "--quiet"): | |
| raise GitRefused("nothing is staged; stage the change first (git-stage)") | |
| _require_checked(git, policy, worktree) | |
| # No hook runs (`core.hooksPath=/dev/null`, `--no-verify`): the pre-commit | |
| # checks are working-tree code, so `vetted-op-checks` runs them in the | |
| # sandbox before this call, and `_require_checked` refuses a staged change | |
| # they did not pass. Signing follows the user's global git configuration, | |
| # which is theirs; the repository's cannot change it. | |
| args = ["commit", "--no-verify", "--cleanup=strip", "-m", message] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args[:-1], "<message from message_file>")) | |
| check_repository_config(git, worktree) | |
| git.run(worktree.path, *args) | |
| commit = git.run(worktree.path, "rev-parse", "HEAD").strip() | |
| return f"committed {commit} on {branch} in {worktree.path}" | |
| def fetch_upstream(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Fetch one upstream branch into ``refs/remotes/<upstream_remote>/<branch>``.""" | |
| worktree = resolve_worktree(git, p["checkout"], policy, "checkout") | |
| check_repository_config(git, worktree) | |
| branch = branch_name(git, worktree.path, p["branch"], "branch") | |
| # The URL comes from the policy, never from a remote the repository configures. | |
| ref = f"refs/remotes/{policy.upstream_remote}/{branch}" | |
| args = [ | |
| "fetch", | |
| "--no-tags", | |
| "--no-recurse-submodules", | |
| "--no-write-fetch-head", | |
| policy.push_url(policy.upstream_repo), | |
| f"+refs/heads/{branch}:{ref}", | |
| ] | |
| if dry_run: | |
| return " ".join(git.argv(worktree.path, *args)) | |
| check_repository_config(git, worktree) | |
| git.run(worktree.path, *args) | |
| head = git.run(worktree.path, "rev-parse", ref).strip() | |
| return f"fetched {policy.upstream_repo} {branch} into {ref} at {head}" | |
| def _strip_framework_identifiers(text: str) -> str: | |
| """``text`` with each exact framework name (``FRAMEWORK_IDENTIFIERS``) replaced by a space. | |
| Whole names only, case-sensitive, longest first: ``cve-tool`` is not cut out of | |
| ``cve-tool-x``, nor ``cve-allocate`` out of ``xcve-allocate``. The same rule as the | |
| publication guard's ``stripFrameworkIdentifiers``. | |
| """ | |
| from .forbidden_terms import FRAMEWORK_IDENTIFIERS | |
| for name in sorted(FRAMEWORK_IDENTIFIERS, key=len, reverse=True): | |
| text = re.sub(rf"(?<![A-Za-z0-9_:-]){re.escape(name)}(?![A-Za-z0-9_-])", " ", text) | |
| return text | |
| def _forbidden_hits(text: str, *, framework: bool = False) -> list[str]: | |
| """The labels of the never-publish terms in ``text``. | |
| With ``framework`` (the policy's upstream is the framework repository itself) the | |
| framework's own skill and tool names are cut out first, so they cannot trip a term by | |
| themselves; ``ALWAYS_SCANNED_TERMS`` (a CVE id, security-fix framing) are still matched | |
| on the text as written. | |
| """ | |
| from .forbidden_terms import ALWAYS_SCANNED_TERMS, DEFAULT_TERMS | |
| scanned = _strip_framework_identifiers(text) if framework else text | |
| return [ | |
| label | |
| for label, pattern in DEFAULT_TERMS | |
| if re.search(pattern, text if label in ALWAYS_SCANNED_TERMS else scanned, re.IGNORECASE) | |
| ] | |
| def pr_create(git: Git, policy: GitPolicy, p: dict[str, str], dry_run: bool) -> str: | |
| """Open a pull request from ``<fork>:<branch>`` against the policy's ``pr_base`` upstream.""" | |
| if policy.fork_repo is None: | |
| raise GitRefused("the policy names no [git] fork, so no pull request can be opened from one") | |
| worktree = resolve_worktree(git, p["checkout"], policy, "checkout") | |
| check_repository_config(git, worktree) | |
| branch = branch_name(git, worktree.path, p["branch"], "branch") | |
| if is_protected(branch, policy): | |
| raise GitRefused(f"{branch!r} is a protected branch; open pull requests from a topic branch") | |
| # The title travels on the command line, not in a file, so the confirmation | |
| # the user approves shows exactly the title that will be published. | |
| title = _param(p["title"], "title").strip() | |
| if not title or len(title) > 256 or any(unicodedata.category(c).startswith("C") for c in title): | |
| raise GitRefused("the title must be one line of 1 to 256 printable characters") | |
| body = _workspace_text(policy, p["body_file"], "body_file") | |
| # A pull request is public. The same terms the publication guard refuses in | |
| # any public text are refused here, so a security detail cannot reach the | |
| # upstream repository through a file the guard does not read. A policy for a | |
| # repository of published records lets the record's identifier through | |
| # (`published_terms`, from `PUBLISHABLE_TERMS` only), and only for a branch | |
| # that changes nothing outside `published_paths`; every other term stays. | |
| # On the framework repository itself, its own skill and tool names (`generate-cve-json`) | |
| # may be named: the target is the approved policy's upstream, never the text. | |
| from .forbidden_terms import FRAMEWORK_REPO | |
| framework = policy.upstream_repo.lower() == FRAMEWORK_REPO | |
| found = set(_forbidden_hits(title, framework=framework) + _forbidden_hits(body, framework=framework)) | |
| hits = sorted(found - set(policy.published_terms)) | |
| if hits: | |
| raise GitRefused( | |
| "the pull request text contains terms that are never published before disclosure: " | |
| f"{', '.join(hits)}; describe the change in neutral functional terms" | |
| ) | |
| exempted = sorted(found & set(policy.published_terms)) | |
| if exempted and not dry_run: | |
| try: | |
| _published_paths_only(git, policy, worktree.path, branch) | |
| except GitRefused as exc: | |
| raise GitRefused( | |
| "the pull request text contains terms that are never published before disclosure: " | |
| f"{', '.join(exempted)}, and the policy's exemption does not apply: {exc}" | |
| ) from None | |
| head = f"{policy.fork_repo.split('/', 1)[0]}:{branch}" | |
| argv = [ | |
| "gh", | |
| "api", | |
| "--hostname", | |
| policy.host, | |
| "--method", | |
| "POST", | |
| f"repos/{policy.upstream_repo}/pulls", | |
| "-f", | |
| f"head={head}", | |
| "-f", | |
| f"base={policy.pr_base}", | |
| "-f", | |
| f"title={title}", | |
| "-F", | |
| "body=@-", | |
| "--jq", | |
| ".html_url", | |
| ] | |
| if dry_run: | |
| return " ".join([*argv[:-4], "-F", "body=@<body_file>", *argv[-2:]]) | |
| completed = git.gh_runner(argv, clean_env(), body) | |
| if completed.returncode != 0: | |
| raise GitFailed(argv[:7], completed.returncode, completed.stderr or "", completed.stdout or "") | |
| return f"opened {completed.stdout.strip()} ({head} -> {policy.upstream_repo} {policy.pr_base})" | |
| OPS: dict[str, GitOp] = { | |
| op.name: op | |
| for op in ( | |
| GitOp( | |
| "git-push-branch", | |
| ("checkout", "branch", "target", "remote_branch", "expected"), | |
| "push local <branch> to <remote_branch> of the fork or upstream; <expected> is the " | |
| "remote branch's current full SHA, or 'new'. No hook runs: run the pre-push checks " | |
| "in the sandbox first", | |
| push_branch, | |
| ), | |
| GitOp( | |
| "git-delete-fork-branch", | |
| ("checkout", "branch", "expected"), | |
| "delete <branch> on the policy's fork once the forge reports it as the head of a merged pull " | |
| "request against upstream at exactly <expected>; never a protected branch, leased on <expected>", | |
| delete_fork_branch, | |
| ), | |
| GitOp( | |
| "git-push-pr-head", | |
| ("worktree", "branch", "number", "head_repo", "head_branch", "expected"), | |
| "fast-forward <head_branch> of <head_repo>, the head of upstream pull request <number>, " | |
| "from <expected> (its full SHA) to local <branch>: refused unless the forge reports that " | |
| "head, a fork allows maintainer edits, and <branch> adds at most " | |
| f"{MAX_FIXUP_COMMITS} non-merge commits. No hook runs: run the pre-push checks in the " | |
| "sandbox first", | |
| push_pr_head, | |
| ), | |
| GitOp( | |
| "git-worktree-sync", | |
| ("worktree", "commit"), | |
| "move a clean linked worktree's branch to <commit> (reset --keep)", | |
| worktree_sync, | |
| ), | |
| GitOp( | |
| "git-rebase", | |
| ("worktree", "onto", "expected"), | |
| "rebase the clean topic branch checked out in <worktree> onto <onto>, a full SHA on a " | |
| "branch git-fetch brought in; <expected> is the branch's current full SHA. Re-signs per " | |
| "the user's global git config; on a conflict, aborts and names the conflicting paths", | |
| rebase_onto, | |
| ), | |
| GitOp( | |
| "git-cherry-pick", | |
| ("worktree", "commit", "expected"), | |
| "replay one plain <commit> onto the clean topic branch checked out in <worktree>; <expected> is " | |
| "the branch's current full SHA. Signs per the user's global git config, and when that signs, " | |
| "<commit> must already carry the user's signature; on a conflict, aborts and names the paths", | |
| cherry_pick, | |
| ), | |
| GitOp( | |
| "git-merge-upstream", | |
| ("worktree", "onto", "expected", "pr"), | |
| "merge <onto>, a full SHA on the upstream pr_base (fetched by the operation), into the clean " | |
| "topic branch checked out in <worktree>; <expected> is the branch's current full SHA, <pr> the " | |
| "pull request whose branch it is ('none' for your own). A signed merge commit with a fixed " | |
| "message; when you sign, only your commits (on top of the pull request's head) must carry " | |
| "your signature. On a conflict, aborts and names the conflicting paths", | |
| merge_upstream, | |
| ), | |
| GitOp( | |
| "git-switch", | |
| ("worktree", "branch"), | |
| "switch a clean working tree to an existing local <branch>; refused when the branch's own " | |
| "commits change a file that steers the agent harness (.claude/, hooks, skills, the policy)", | |
| switch_branch, | |
| ), | |
| GitOp( | |
| "git-switch-create", | |
| ("worktree", "branch"), | |
| "create a new topic <branch> at upstream's pr_base, asked of the policy's URL now, and switch " | |
| "the clean working tree to it, with git-switch's checks; never a protected or existing branch", | |
| switch_create, | |
| ), | |
| GitOp( | |
| "git-worktree-add", | |
| ("checkout", "path", "branch", "start"), | |
| "create a linked worktree at <path> on a new <branch> starting at <start>", | |
| worktree_add, | |
| ), | |
| GitOp( | |
| "git-worktree-remove", | |
| ("worktree",), | |
| "remove a linked worktree that has no changes", | |
| worktree_remove, | |
| ), | |
| GitOp( | |
| "git-stage", | |
| ("worktree", "paths_file"), | |
| "stage exactly the relative paths listed, one per line, in <paths_file> (a workspace " | |
| "file); literal pathspecs, nothing outside the worktree", | |
| stage_paths, | |
| ), | |
| GitOp( | |
| "git-commit", | |
| ("worktree", "message_file"), | |
| "commit what is staged on the current (non-protected) branch, message from <message_file> " | |
| "(a workspace file), signed per the user's global git config. No hook runs out here: " | |
| "refused unless `vetted-op-checks` passed every staged path, as it is now, in the sandbox", | |
| commit_staged, | |
| ), | |
| GitOp( | |
| "git-fetch", | |
| ("checkout", "branch"), | |
| "fetch upstream <branch> into refs/remotes/<upstream_remote>/<branch>, from the policy's " | |
| "upstream URL", | |
| fetch_upstream, | |
| ), | |
| GitOp( | |
| "git-pr-create", | |
| ("checkout", "branch", "title", "body_file"), | |
| "open a pull request from <fork>:<branch> against the upstream's pr_base; <title> on the " | |
| "command line (so the confirmation shows it), body from a workspace file; refused if " | |
| "either holds a never-publish term", | |
| pr_create, | |
| ), | |
| ) | |
| } | |
| def main(argv: list[str] | None = None, *, git: Git | None = None) -> int: | |
| """The ``vetted-op-git`` console script.""" | |
| raw = list(sys.argv[1:] if argv is None else argv) | |
| # allow_abbrev=False: every long option is matched exactly, as the `--caller` | |
| # count below assumes; a prefix such as `--call` is an argparse error. | |
| parser = argparse.ArgumentParser( | |
| prog=PROG, | |
| description="Run one fixed, policy-scoped git operation outside the sandbox. No pass-through arguments.", | |
| allow_abbrev=False, | |
| ) | |
| parser.add_argument("--caller", help="the skill or plugin invoking this operation") | |
| parser.add_argument("--dry-run", action="store_true", help="validate, print the git command, run nothing") | |
| parser.add_argument( | |
| "--policy-from", | |
| metavar="DIR", | |
| type=Path, | |
| default=None, | |
| help="discover the policy from this absolute directory instead of the working directory", | |
| ) | |
| parser.add_argument("operation", nargs="?", help="operation name, or 'list-ops' / 'policy'") | |
| parser.add_argument("params", nargs="*", help="operation parameters, positionally") | |
| args = parser.parse_args(raw) | |
| if args.operation in (None, "list-ops"): | |
| for name, entry in sorted(OPS.items()): | |
| print(f"write {name:<22} {' '.join(entry.params)}\n {entry.summary}") | |
| return EXIT_OK | |
| for option in ("--caller", "--policy-from"): | |
| if sum(1 for a in raw if a == option or a.startswith(f"{option}=")) > 1: | |
| print(f"{PROG}: refused: {option} given more than once", file=sys.stderr) | |
| return EXIT_POLICY | |
| # Where the policy is discovered: the working directory, or the directory | |
| # `--policy-from` names. Either is the caller's choice, and either way only | |
| # a policy the user approved acts (`load`'s ``approved_only``), so naming it | |
| # widens nothing; it lets a session in one repository reach the policy of | |
| # another (a site repository) and shows that choice in the confirmed command. | |
| base: Path | None = None | |
| if args.policy_from is not None: | |
| try: | |
| base = policy_from_checkout(args.policy_from) | |
| except ConfigError as exc: | |
| print(f"{PROG}: refused: {exc}", file=sys.stderr) | |
| return EXIT_POLICY | |
| # Like every entry point that runs outside the sandbox: only a policy the user | |
| # placed in the approved directory themselves drives git. A dry run against | |
| # one that is not approved yet still checks its parameters, but runs no git | |
| # command at all: even read-only git, out here, is steered by that policy. | |
| approved = True | |
| try: | |
| try: | |
| config = load(cwd=base, approved_only=args.operation != "policy") | |
| except ConfigError: | |
| if not args.dry_run: | |
| raise | |
| config = load(cwd=base, approved_only=False) | |
| approved = False | |
| if base is not None: | |
| check_policy_from_upstream(config, base) | |
| policy = git_policy(config) if base is None else git_policy(config, base) | |
| except ConfigError as exc: | |
| print(f"{PROG}: config error: {exc}", file=sys.stderr) | |
| return EXIT_POLICY | |
| if args.operation == "policy": | |
| print(describe(config)) | |
| print(describe_git(config, policy)) | |
| return EXIT_OK | |
| if not args.caller: | |
| print(f"{PROG}: --caller is required for any operation", file=sys.stderr) | |
| return EXIT_USAGE | |
| op = OPS.get(args.operation) | |
| try: | |
| if op is None: | |
| raise GitRefused(f"unknown operation {args.operation!r}; see '{PROG} list-ops'") | |
| permitted = config.ops_for(args.caller) | |
| if op.name not in permitted: | |
| raise GitRefused( | |
| f"caller {args.caller!r} is not permitted to run {op.name!r}; " | |
| f"permitted: {', '.join(sorted(permitted)) or '(none)'}" | |
| ) | |
| if len(args.params) != len(op.params): | |
| raise GitRefused( | |
| f"operation {op.name!r} takes {len(op.params)} parameter(s) ({', '.join(op.params)}), " | |
| f"got {len(args.params)}" | |
| ) | |
| params = dict(zip(op.params, args.params, strict=True)) | |
| for name, value in params.items(): | |
| _param(value, name) | |
| if not approved: | |
| print( | |
| f"{PROG}: dry run against a policy that is not approved: the parameters are well formed; " | |
| "no git command was run. Approve the policy to see the command it would run." | |
| ) | |
| return EXIT_OK | |
| runner = git or Git() | |
| try: | |
| print(op.run(runner, policy, params, args.dry_run)) | |
| finally: | |
| runner.close() | |
| except (GitRefused, ConfigError) as exc: | |
| print(f"{PROG}: refused: {exc}", file=sys.stderr) | |
| return EXIT_POLICY | |
| except GitFailed as exc: | |
| sys.stderr.write(exc.stdout) | |
| sys.stderr.write(exc.stderr) | |
| print(f"{PROG}: {op.name if op else args.operation} failed: {exc}", file=sys.stderr) | |
| return EXIT_COMMAND | |
| return EXIT_OK |