diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 2f0946f..a65b660 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -1,7 +1,7 @@ { "name": "holocron", "description": "AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows.", - "version": "0.9.2", + "version": "0.9.3", "owner": { "name": "Mortis", "url": "https://git.rkdr.net/Mortis/" @@ -24,7 +24,7 @@ { "name": "git", "description": "Skills and agents for working with a local Git clone over the git wire protocol, and for authoring and running the pre-commit hooks that guard it.", - "version": "1.3.9", + "version": "1.4.0", "category": "Version Control", "source": "./plugins/git" }, diff --git a/apm.yml b/apm.yml index 542a6a9..3ee7c50 100644 --- a/apm.yml +++ b/apm.yml @@ -1,5 +1,5 @@ name: holocron -version: 0.9.2 +version: 0.9.3 description: AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows. license: MIT @@ -86,6 +86,9 @@ executables: # full-identity, version-in-key convention as above, kept by the same check. git.rkdr.net/Mortis/Holocron/plugins/delivery#0.8.1: hooks: true + # git ships the hook that refuses a push to main. + git.rkdr.net/Mortis/Holocron/plugins/git#1.4.0: + hooks: true marketplace: # apm's Claude marketplace mapper only emits description:/version: into the @@ -93,7 +96,7 @@ marketplace: # top-level apm.yml description:/version: above are NOT inherited into the # compiled output despite being used elsewhere (e.g. by `apm audit`). description: AI development skills for Claude Code, and for GitHub Copilot through apm — factory, design, implement, review, and cross-cutting workflows. - version: 0.9.2 + version: 0.9.3 owner: name: Mortis url: https://git.rkdr.net/Mortis/ diff --git a/docs/spec/gates.md b/docs/spec/gates.md index 462087c..4daf1fb 100644 --- a/docs/spec/gates.md +++ b/docs/spec/gates.md @@ -1357,7 +1357,8 @@ every key stays an accurate record of what was approved. It covers every plugin that ships executables, not one named package. The script scans `plugins/*/` and treats a plugin as shipping executables when `plugins//.apm/hooks/` or -`plugins//bin/` exists — kyberforge ships both, delivery ships a guard hook. For each one it +`plugins//bin/` exists — kyberforge ships both, delivery ships a guard hook, +git ships a hook that refuses a push to `main`. For each one it reads `name:` and `version:` from `plugins//apm.yml` and asserts root `apm.yml` carries the `#` key under `executables.allow`. The `name:` must equal the directory name, so one that differs fails rather than being guessed at. Every failing package is diff --git a/plugins/git/.apm/hooks/hooks.json b/plugins/git/.apm/hooks/hooks.json new file mode 100644 index 0000000..daa1e44 --- /dev/null +++ b/plugins/git/.apm/hooks/hooks.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "PreToolUse": [ + { + "hooks": [ + { + "command": "${CLAUDE_PLUGIN_ROOT}/.apm/hooks/refuse-push-to-main.py", + "timeout": 10, + "type": "command" + } + ], + "matcher": "Bash" + } + ] + } +} diff --git a/plugins/git/.apm/hooks/refuse-push-to-main.py b/plugins/git/.apm/hooks/refuse-push-to-main.py new file mode 100755 index 0000000..cf83c7d --- /dev/null +++ b/plugins/git/.apm/hooks/refuse-push-to-main.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""PreToolUse hook: refuse a `git push` that can update `main`. + +A guardrail against accidents, not a security boundary: whatever it cannot read +in the command line goes through. Limits and opt-out: the git plugin's README. +""" + +import fnmatch +import json +import os +import re +import shlex +import subprocess +import sys + +MAIN_NAMES = ("main", "heads/main", "refs/heads/main") + +HEREDOC = re.compile( + r"""(?'"\\]|\\.|'[^']*'|"(?:[^"\\]|\\.)*")+""" +TOKEN = re.compile( + rf"""(?P[ \t\r]+|\\\n|\#[^\n]*|(?:\d*|&)[<>]+[&|]?[ \t]*(?:{WORD})?) + |(?P[;&|()`\n]+) + |(?P{WORD})""", + re.S | re.X, +) + +ASSIGNMENT = re.compile(r"\w+=") +SHELL_KEYWORDS = {"!", "{", "if", "then", "elif", "else", "while", "until", "do"} +WRAPPERS = {"rtk", "proxy", "command", "env", "sudo", "time", "timeout", "nohup"} +WRAPPER_ARGUMENT = re.compile(r"-|\d+[smhd]?$") + +GIT_OPTIONS_WITH_VALUE = {"-c", "--git-dir", "--work-tree", "--namespace", "--config-env"} +PUSH_OPTIONS_WITH_VALUE = { + "--repo", + "--push-option", + "--receive-pack", + "--exec", + "--recurse-submodules", +} + + +def simple_commands(command): + """Split a command line into word lists; None when it does not parse.""" + command = HEREDOC.sub(r"\1", command) + commands, position = [[]], 0 + while position < len(command): + token = TOKEN.match(command, position) + if not token: + return None + if token["separator"]: + commands.append([]) + elif token["word"]: + commands[-1].append("".join(shlex.split(token["word"]))) + position = token.end() + return commands + + +def strip_prefixes(words): + wrapped = False + for index, word in enumerate(words): + if word in WRAPPERS: + wrapped = True + elif not ( + word in SHELL_KEYWORDS + or ASSIGNMENT.match(word) + or (wrapped and WRAPPER_ARGUMENT.match(word)) + ): + return words[index:] + return [] + + +def split_git_command(words): + """(-C directories, subcommand, its arguments) of a git command.""" + directories = [] + rest = iter(words[1:]) + for word in rest: + if word == "-C": + directories.append(os.path.expanduser(next(rest, ""))) + elif word in GIT_OPTIONS_WITH_VALUE: + next(rest, None) + elif not word.startswith("-"): + return directories, word, list(rest) + return directories, "", [] + + +def parse_push(arguments): + """(long-form option names, refspecs) of a git push.""" + options, positional = set(), [] + rest = iter(arguments) + for argument in rest: + if argument == "--": + positional.extend(rest) + elif argument.startswith("--"): + options.add(argument.split("=")[0]) + if argument in PUSH_OPTIONS_WITH_VALUE: + next(rest, None) + elif argument.startswith("-"): + flags, push_option, value = argument[1:].partition("o") + options.update({"d": "--delete", "n": "--dry-run"}.get(f, f) for f in flags) + if push_option and not value: + next(rest, None) + else: + positional.append(argument) + return options, positional[1:] + + +def updates_main(arguments, on_main): + """Whether a push can update main. `on_main` is called only when it matters.""" + options, refspecs = parse_push(arguments) + if "--dry-run" in options: + return False + if options & {"--all", "--branches", "--mirror"}: + return True + if not refspecs: + return "--tags" not in options and on_main() + + rest = iter(refspecs) + for refspec in rest: + if refspec == "tag": + next(rest, None) + continue + source, colon, destination = refspec.removeprefix("+").partition(":") + if colon and not source and not destination: + return True + target = destination if colon else source + if any(fnmatch.fnmatchcase(name, target) for name in MAIN_NAMES): + return True + if not colon and source in ("HEAD", "@") and on_main(): + return True + return False + + +def current_branch_is_main(cwd, directories): + git = ["git"] + for directory in directories: + git += ["-C", directory] + head = subprocess.run( + [*git, "symbolic-ref", "--quiet", "HEAD"], cwd=cwd, capture_output=True, text=True + ) + return head.stdout.strip() == "refs/heads/main" + + +def pushes_to_main(command, cwd): + moved = False + for words in simple_commands(command) or []: + words = strip_prefixes(words) + if not words: + continue + if words[0] in ("cd", "pushd", "popd"): + moved = True + if os.path.basename(words[0]) != "git": + continue + directories, subcommand, arguments = split_git_command(words) + if subcommand == "switch" or (subcommand == "checkout" and "--" not in arguments): + moved = True + if subcommand == "push" and updates_main( + arguments, lambda: not moved and current_branch_is_main(cwd, directories) + ): + return True + return False + + +def main(): + # apm deploys this file to Copilot and Codex too, where it must do nothing. + if "/.claude/hooks/" not in os.path.abspath(__file__).replace("\\", "/"): + return 0 + if os.environ.get("GIT_ALLOW_PUSH_TO_MAIN") == "1": + return 0 + payload = json.load(sys.stdin) + if payload["tool_name"] != "Bash": + return 0 + if pushes_to_main(payload["tool_input"]["command"], payload.get("cwd")): + print( + "Refused: this git push can update main. " + "Push a feature branch by name and open a pull request instead.", + file=sys.stderr, + ) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/plugins/git/README.md b/plugins/git/README.md index 07efef4..a4b67b7 100644 --- a/plugins/git/README.md +++ b/plugins/git/README.md @@ -35,9 +35,61 @@ Installing this plugin without `rtk`? Every prefixed command is a plain `git` in |---|---|---| | Skills | `.apm/skills/` | `git-commits`, `git-branches`, `git-history`, `git-remotes`, `git-submodules`, `git-workflow`, `git-worktrees`, `pc-author`, `pc-run` | | Agents | `.apm/agents/` | `git-orchestrate` | +| Hooks | `.apm/hooks/` | `refuse-push-to-main.py`, see [Push-to-main hook](#push-to-main-hook) | `.apm/` is the authoring source and the only thing apm deploys (ADR-0024). +## Push-to-main hook + +On Claude Code, a `PreToolUse` hook refuses a Bash `git push` that can update `main`: + +- an explicit destination: `main`, `HEAD:main`, `:main`, `refs/heads/main`, or deleting `main` +- a bare `git push`, `HEAD` or `@` while `main` is checked out +- a bulk push: `--all`, `--mirror`, `:`, or a wildcard refspec that covers `main` +- any of these with `--force` or `--force-with-lease` + +Pushes to other branches, tag pushes and `--dry-run` go through. apm also deploys the files to Copilot and Codex, where the hook does nothing. + +### Limits + +The hook is a guardrail against accidents. Server-side branch protection is the real control. If the hook itself fails, the push goes through. It does not see: + +- git aliases, shell variables such as `$BRANCH`, scripts, `bash -c`, command substitution inside double quotes, or pushes made through an MCP server +- git config that redirects a push (`push.default=upstream`, `remote..push`) +- a bare `git push`, `HEAD` or `@` after a `cd`, `git switch` or `git checkout` in the same command, because the branch is not known yet + +### Opt-out + +To allow pushes to `main`, set the variable under `env` in `.claude/settings.json`, or in `.claude/settings.local.json` for yourself only: + +```json +{ + "env": { + "GIT_ALLOW_PUSH_TO_MAIN": "1" + } +} +``` + +Claude Code puts `env` values into its own environment, which hooks inherit. Setting the variable inside the command (`GIT_ALLOW_PUSH_TO_MAIN=1 git push`) has no effect. After you remove the setting, restart Claude Code for the hook to refuse again. + +### Approval + +The hook is an executable primitive, so whether it deploys depends on the `executables:` block in the consuming project's `apm.yml`: + +- **No `executables:` block:** hooks deploy without approval. +- **With an `executables:` block:** the hook is parked until it is granted. Grant it in one of two ways, then run `apm install` and commit the `executables` entry: + - `apm approve` writes the entry and pins it to the hook's content, so a later change to the script needs approval again. + - A hand-written entry under the full package identity is not pinned: + + ```yaml + executables: + allow: + git.rkdr.net/Mortis/Holocron/plugins/git: + hooks: true + ``` + +The first `apm approve` in a project creates the block and so turns the gate on. The next install then parks every other package's unapproved executables. + ## Author Defame1297 diff --git a/plugins/git/apm.yml b/plugins/git/apm.yml index 26dbd6f..23c9753 100644 --- a/plugins/git/apm.yml +++ b/plugins/git/apm.yml @@ -1,5 +1,5 @@ name: git -version: 1.3.9 +version: 1.4.0 description: Skills and agents for working with a local Git clone over the git wire protocol, and for authoring and running the pre-commit hooks that guard it. author: name: Mortis diff --git a/tests/test-git-push-main-hook.sh b/tests/test-git-push-main-hook.sh new file mode 100755 index 0000000..f67b689 --- /dev/null +++ b/tests/test-git-push-main-hook.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# Tests for plugins/git/.apm/hooks/refuse-push-to-main.py, the PreToolUse hook +# that refuses a `git push` to `main` (#178). +# +# The hook acts only when run from a .claude/hooks/ path, so it is copied to the +# path apm deploys it to and driven with real payloads against fixture repos. +set -euo pipefail + +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_COMMON_DIR +unset GIT_ALLOW_PUSH_TO_MAIN + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +HOOKS_DIR="$REPO_ROOT/plugins/git/.apm/hooks" +SRC="$HOOKS_DIR/refuse-push-to-main.py" +PASS=0 +FAIL=0 + +pass() { PASS=$((PASS + 1)); } +fail() { echo " FAIL: $1"; FAIL=$((FAIL + 1)); } + +command -v python3 > /dev/null 2>&1 || { echo "python3 required"; exit 77; } +[[ -f "$SRC" ]] || { echo "FAIL: $SRC does not exist"; exit 1; } + +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +for d in .claude/hooks/git/.apm/hooks .github/hooks/scripts/git/.apm/hooks \ + .codex/hooks/git/.apm/hooks elsewhere; do + mkdir -p "$WORK/$d" + cp "$SRC" "$WORK/$d/" +done +HOOK="$WORK/.claude/hooks/git/.apm/hooks/refuse-push-to-main.py" + +git init -q -b main "$WORK/on-main" +git init -q -b feat "$WORK/on-feat" + +# decision