From 4e4cb31a5635a46345eec882d2a507f2a30f7f93 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 14:30:46 -0500
Subject: [PATCH 01/13] ci: fix the claude code hooks that never fire
Claude Code passes hook input as JSON on stdin and never sets
CLAUDE_FILE_PATHS, so the edit hooks (format, mypy, and the block on
editing main) never saw a file. They now read tool_input.file_path.
The format hook leaves unused imports alone, so an import added
before its first use survives the edit. The mypy hook exits 2 so its
errors reach Claude. The Stop hook read stdin twice and looked for a
field that doesn't exist; it now reads stdin once and checks
last_assistant_message. The commit hook only matched commands that
start with "git commit" and resolved .venv against the current
directory; it now matches compound and "git -C" commits and runs
from the repo root.
---
.claude/settings.json | 10 +++++-----
AGENTS.md | 14 ++++++++------
2 files changed, 13 insertions(+), 11 deletions(-)
diff --git a/.claude/settings.json b/.claude/settings.json
index f5c0fb68..3760e3a1 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -91,7 +91,7 @@
"hooks": [
{
"type": "command",
- "command": "FILE_PATHS=\"$CLAUDE_FILE_PATHS\"; for f in $FILE_PATHS; do if [[ \"$f\" =~ \\.py$ ]]; then .venv/bin/python -m ruff format \"$f\" 2>/dev/null; .venv/bin/python -m ruff check --fix \"$f\" 2>/dev/null; fi; done; exit 0"
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; case \"$F\" in \"$R\"/*.py) \"$R\"/.venv/bin/python -m ruff check --fix --unfixable F401 --force-exclude \"$F\" >/dev/null 2>&1; \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; esac; exit 0"
}
]
},
@@ -100,7 +100,7 @@
"hooks": [
{
"type": "command",
- "command": "FILE_PATHS=\"$CLAUDE_FILE_PATHS\"; HAS_SRC=false; for f in $FILE_PATHS; do if [[ \"$f\" =~ src/.*\\.py$ ]]; then HAS_SRC=true; break; fi; done; if [ \"$HAS_SRC\" = true ]; then .venv/bin/python -m mypy src/ --no-error-summary 2>&1 | tail -20 || true; fi; exit 0"
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; case \"$F\" in \"$R\"/src/*.py) OUT=$(cd \"$R\" && .venv/bin/python -m mypy src/ --no-error-summary 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; exit 2; } ;; esac; exit 0"
}
]
}
@@ -129,7 +129,7 @@
"hooks": [
{
"type": "command",
- "command": "[ \"$(git branch --show-current 2>/dev/null)\" != \"main\" ] && exit 0; REPO=\"$(git rev-parse --show-toplevel 2>/dev/null)\"; for f in $CLAUDE_FILE_PATHS; do case \"$f\" in \"$REPO\"/AGENTS.md|\"$REPO\"/CLAUDE.md) continue ;; \"$REPO\"/*) echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch.' >&2; exit 2 ;; esac; done; exit 0",
+ "command": "[ \"$(git branch --show-current 2>/dev/null)\" != \"main\" ] && exit 0; REPO=\"$(git rev-parse --show-toplevel 2>/dev/null)\"; F=$(cat | jq -r '.tool_input.file_path // empty'); case \"$F\" in \"$REPO\"/AGENTS.md|\"$REPO\"/CLAUDE.md) ;; \"$REPO\"/*) echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch.' >&2; exit 2 ;; esac; exit 0",
"timeout": 5
}
]
@@ -139,7 +139,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if echo \"$CMD\" | grep -qE '^git commit'; then .venv/bin/python -m ruff format --check src/ tests/ >/dev/null 2>&1 || { echo '❌ BLOCKED: Unformatted files. Run ruff format first.' >&2; exit 2; }; fi; exit 0",
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_./-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*[[:space:]]+commit([[:space:]]|$)'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check src/ tests/ 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix first.' >&2; exit 2; }; fi; exit 0",
"timeout": 30
}
]
@@ -151,7 +151,7 @@
"hooks": [
{
"type": "command",
- "command": "STOP_ACTIVE=$(cat | jq -r '.stop_hook_active // false'); if [ \"$STOP_ACTIVE\" = \"true\" ]; then exit 0; fi; RESPONSE=$(cat | jq -r '.assistant_response // empty' | tail -200); if echo \"$RESPONSE\" | grep -qiE 'TODO|FIXME|will implement later|placeholder|stub'; then echo '⚠️ Response contains incomplete markers (TODO/FIXME/placeholder). Consider finishing before stopping.' >&2; exit 2; fi; exit 0"
+ "command": "IN=$(cat); STOP_ACTIVE=$(printf '%s' \"$IN\" | jq -r '.stop_hook_active // false'); if [ \"$STOP_ACTIVE\" = \"true\" ]; then exit 0; fi; RESPONSE=$(printf '%s' \"$IN\" | jq -r '.last_assistant_message // empty' | tail -200); if printf '%s\\n' \"$RESPONSE\" | grep -qiE 'TODO|FIXME|will implement later|placeholder|stub'; then echo '⚠️ Response contains incomplete markers (TODO/FIXME/placeholder). Consider finishing before stopping.' >&2; exit 2; fi; exit 0"
}
]
}
diff --git a/AGENTS.md b/AGENTS.md
index e7c438a2..aadad64d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -427,17 +427,19 @@ Currently known minor discrepancies:
The project's `.claude/settings.json` defines 7 hooks that enforce formatting, type checking, branch protection, and code quality. These hooks only fire on the tools they match. Using the wrong tool for a task can silently bypass safety checks.
+Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory, and hooks 1, 2, 5, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo.
+
#### Bash file writes bypass Write/Edit/MultiEdit hooks
Hooks 1, 2, and 5 match `Write|Edit|MultiEdit` only. They do NOT fire when files are created or modified via Bash (`cat >`, `echo >`, `tee`, `sed -i`, `printf >`, heredocs, or any other shell redirection).
Hooks defeated by Bash file writes:
-- Hook 1 (PostToolUse): auto-formats `.py` files with `ruff format` and `ruff check --fix`. Skipping this means the file stays unformatted until the next explicit format run.
-- Hook 2 (PostToolUse): runs `mypy src/` when `src/**/*.py` files change. Skipping this means type errors go unreported until the next explicit mypy run.
+- Hook 1 (PostToolUse): runs `ruff check --fix` and then `ruff format` on an edited `.py` file. Unused imports are left for `just fix`, so an import added before the code that uses it survives. Skipping this means the file stays unformatted until the next explicit format run.
+- Hook 2 (PostToolUse): runs `mypy src/` when a `src/**/*.py` file changes and reports any errors back to Claude. Skipping this means type errors go unreported until the next explicit mypy run.
- Hook 5 (PreToolUse): blocks editing repo files on the `main` branch (only AGENTS.md and CLAUDE.md are allowed). Skipping this defeats branch protection entirely.
-Hook 6 (format check before `git commit`) fires on `Bash` matching `^git commit`, so it still catches unformatted files at commit time regardless of how they were written. This is the backstop, not the primary defense.
+Hook 6 (format check before `git commit`) fires on any Bash command that runs `git commit`, including `cd
&& git commit` and `git -C commit`, and checks from the repo root, so it still catches unformatted files at commit time regardless of how they were written. This is the backstop, not the primary defense.
#### When to use Write/Edit/MultiEdit vs Bash
@@ -445,7 +447,7 @@ Use Write, Edit, or MultiEdit for all file creation and modification. These are
Use Bash for running commands, not writing files. Acceptable Bash uses: shell commands, git operations, test runners, linters, build tools.
-Do not use Bash to write files as a workaround when a hook blocks an action. If hook 5 blocks an edit on main, create a feature branch first. If hook 6 blocks a commit, run `ruff format` first. The hooks exist to catch mistakes; working around them reintroduces the mistakes.
+Do not use Bash to write files as a workaround when a hook blocks an action. If hook 5 blocks an edit on main, create a feature branch first. If hook 6 blocks a commit, run `just fix` first. The hooks exist to catch mistakes; working around them reintroduces the mistakes.
#### What to do when a hook blocks an action
@@ -458,8 +460,8 @@ In every case: fix the underlying issue, do not bypass the hook.
#### Other edge cases
-- Hook 7 (Stop): warns on TODO/FIXME/placeholder/stub in responses. This is a case-insensitive grep on the full response text, including code blocks and file paths. A path like `src/todo_handler.py` or a quoted `# TODO` from existing code will trigger the warning. Low-severity false positive; acknowledge and continue if the marker is in quoted or referenced text.
-- Hook 1 (auto-format): only runs on `.py` files. Non-Python files (`.md`, `.yml`, `.json`, `.html`) are silently skipped.
+- Hook 7 (Stop): warns when Claude's final reply contains TODO/FIXME/placeholder/stub, and lets the stop that follows the warning through (`stop_hook_active`), so it fires at most once per turn. This is a case-insensitive grep on the last 200 lines of the reply, including code blocks and file paths. A path like `src/todo_handler.py` or a quoted `# TODO` from existing code will trigger the warning. Low-severity false positive; acknowledge and continue if the marker is in quoted or referenced text.
+- Hook 1 (auto-format): only runs on `.py` files inside the repo, with `--force-exclude` so ruff's excludes and `.gitignore` apply. Other files (`.md`, `.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
From 9b0ae41b65e9b592b024522ad8eaa4f157e02d41 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 14:41:06 -0500
Subject: [PATCH 02/13] ci: run local ruff gates over the same files as ci
quality.yml runs `ruff check .` and `ruff format --check .`, but just
lint, fmt-check and fix, the pre-commit hook, the /check and /bump
skills and CONTRIBUTING.md only covered src/ and tests/. Anything else
CI checks, like scripts/ and Python code blocks in Markdown, could
pass locally and still fail CI, and just fix couldn't repair it.
All of them now run ruff on the whole repo. The format-on-edit hook
also formats Markdown files, and it skips gitignored files, which
ruff's --force-exclude still formats when they're passed by path.
---
.agents/skills/bump/SKILL.md | 4 ++--
.agents/skills/check/SKILL.md | 6 +++---
.claude/settings.json | 4 ++--
AGENTS.md | 6 +++---
CONTRIBUTING.md | 4 ++--
justfile | 10 +++++-----
6 files changed, 17 insertions(+), 17 deletions(-)
diff --git a/.agents/skills/bump/SKILL.md b/.agents/skills/bump/SKILL.md
index 7edef184..d8139aaa 100644
--- a/.agents/skills/bump/SKILL.md
+++ b/.agents/skills/bump/SKILL.md
@@ -81,8 +81,8 @@ Rename `## [Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD` and insert a fresh empty U
## 8. Run Quality Gates
```
-.venv/bin/python -m ruff check src/ tests/
-.venv/bin/python -m ruff format --check src/ tests/
+.venv/bin/python -m ruff check .
+.venv/bin/python -m ruff format --check .
.venv/bin/python -m mypy src/
.venv/bin/python -m bandit -r src/ -c pyproject.toml
```
diff --git a/.agents/skills/check/SKILL.md b/.agents/skills/check/SKILL.md
index 0a0a214b..03487a2e 100644
--- a/.agents/skills/check/SKILL.md
+++ b/.agents/skills/check/SKILL.md
@@ -10,7 +10,7 @@ Run every quality check in sequence. Report results clearly. Stop and fix if any
## 1. Lint
```
-.venv/bin/python -m ruff check src/ tests/
+.venv/bin/python -m ruff check .
```
Report: pass or fail with error count.
@@ -18,10 +18,10 @@ Report: pass or fail with error count.
## 2. Format Check
```
-.venv/bin/python -m ruff format --check src/ tests/
+.venv/bin/python -m ruff format --check .
```
-If files are unformatted, run `.venv/bin/python -m ruff format src/ tests/` to fix, then re-check.
+If files are unformatted, run `.venv/bin/python -m ruff format .` to fix, then re-check.
## 3. Type Check
diff --git a/.claude/settings.json b/.claude/settings.json
index 3760e3a1..9125ae72 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -91,7 +91,7 @@
"hooks": [
{
"type": "command",
- "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; case \"$F\" in \"$R\"/*.py) \"$R\"/.venv/bin/python -m ruff check --fix --unfixable F401 --force-exclude \"$F\" >/dev/null 2>&1; \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; esac; exit 0"
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; git check-ignore -q \"$F\" 2>/dev/null && exit 0; case \"$F\" in \"$R\"/*.py) \"$R\"/.venv/bin/python -m ruff check --fix --unfixable F401 --force-exclude \"$F\" >/dev/null 2>&1; \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; \"$R\"/*.md) \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; esac; exit 0"
}
]
},
@@ -139,7 +139,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_./-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*[[:space:]]+commit([[:space:]]|$)'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check src/ tests/ 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix first.' >&2; exit 2; }; fi; exit 0",
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_./-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*[[:space:]]+commit([[:space:]]|$)'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check --output-format concise . 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix first.' >&2; exit 2; }; fi; exit 0",
"timeout": 30
}
]
diff --git a/AGENTS.md b/AGENTS.md
index aadad64d..22788f57 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -435,11 +435,11 @@ Hooks 1, 2, and 5 match `Write|Edit|MultiEdit` only. They do NOT fire when files
Hooks defeated by Bash file writes:
-- Hook 1 (PostToolUse): runs `ruff check --fix` and then `ruff format` on an edited `.py` file. Unused imports are left for `just fix`, so an import added before the code that uses it survives. Skipping this means the file stays unformatted until the next explicit format run.
+- Hook 1 (PostToolUse): runs `ruff check --fix` and then `ruff format` on an edited `.py` file, and `ruff format` on an edited `.md` file, which formats its Python code blocks. Unused imports are left for `just fix`, so an import added before the code that uses it survives. Skipping this means the file stays unformatted until the next explicit format run.
- Hook 2 (PostToolUse): runs `mypy src/` when a `src/**/*.py` file changes and reports any errors back to Claude. Skipping this means type errors go unreported until the next explicit mypy run.
- Hook 5 (PreToolUse): blocks editing repo files on the `main` branch (only AGENTS.md and CLAUDE.md are allowed). Skipping this defeats branch protection entirely.
-Hook 6 (format check before `git commit`) fires on any Bash command that runs `git commit`, including `cd && git commit` and `git -C commit`, and checks from the repo root, so it still catches unformatted files at commit time regardless of how they were written. This is the backstop, not the primary defense.
+Hook 6 (format check before `git commit`) fires on Bash commands that run `git commit`, including `cd && git commit` and `git -C commit`, and runs `ruff format --check .` from the repo root, the same check CI runs, so it still catches unformatted files at commit time regardless of how they were written. This is the backstop, not the primary defense.
#### When to use Write/Edit/MultiEdit vs Bash
@@ -461,7 +461,7 @@ In every case: fix the underlying issue, do not bypass the hook.
#### Other edge cases
- Hook 7 (Stop): warns when Claude's final reply contains TODO/FIXME/placeholder/stub, and lets the stop that follows the warning through (`stop_hook_active`), so it fires at most once per turn. This is a case-insensitive grep on the last 200 lines of the reply, including code blocks and file paths. A path like `src/todo_handler.py` or a quoted `# TODO` from existing code will trigger the warning. Low-severity false positive; acknowledge and continue if the marker is in quoted or referenced text.
-- Hook 1 (auto-format): only runs on `.py` files inside the repo, with `--force-exclude` so ruff's excludes and `.gitignore` apply. Other files (`.md`, `.yml`, `.json`, `.html`) are silently skipped.
+- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 38826147..d53e70b5 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -34,8 +34,8 @@ For releases, open a separate `chore: bump version to X.Y.Z` PR that changes onl
## Required local checks
```bash
-uv run ruff check src/ tests/
-uv run ruff format --check src/ tests/
+uv run ruff check .
+uv run ruff format --check .
uv run mypy src/
uv run bandit -r src/ -c pyproject.toml
uv run pytest
diff --git a/justfile b/justfile
index 8fdeabfd..ab077608 100644
--- a/justfile
+++ b/justfile
@@ -35,12 +35,12 @@ check: lint fmt-check type sec test
# Fast feedback loop: skip format-check, bandit, and integration tests.
quick: lint type test-quick
-# Individual gates
+# Individual gates. Ruff covers the whole repo, the same files quality.yml checks.
lint:
- {{python}} -m ruff check src/ tests/
+ {{python}} -m ruff check .
fmt-check:
- {{python}} -m ruff format --check src/ tests/
+ {{python}} -m ruff format --check .
type:
{{python}} -m mypy src/
@@ -82,8 +82,8 @@ test-parallel:
# Apply ruff auto-fixes and reformat in place.
fix:
- {{python}} -m ruff check --fix src/ tests/
- {{python}} -m ruff format src/ tests/
+ {{python}} -m ruff check --fix .
+ {{python}} -m ruff format .
# Hydrate the dev venv (idempotent). Run before `just dev` on a fresh clone
# or after dependency edits. Symphony's Stage D bring-up uses this as
From 0241c903e1b3ba7b630154a8f1d6fc69d5c33892 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 15:19:28 -0500
Subject: [PATCH 03/13] ci: guard main per checkout and test the hooks
The main-branch guard took the branch from Claude's current directory,
so an edit to a checkout on main went through from a worktree on a
feature branch, and gitignored local files such as
.claude/settings.local.json were blocked. It now checks the branch of
the checkout the edited file is in, limited to this repo's checkouts,
and skips gitignored files.
The commit hook also matches "/usr/bin/git commit" and a commit
followed by ";" or ")". Its message says to re-add the files after
just fix, since it checks the working tree while git commits the
index.
tests/test_gates/test_claude_hooks_gate.py runs each hook with the
JSON Claude Code sends, inside throwaway repos.
---
.claude/settings.json | 4 +-
AGENTS.md | 10 +-
tests/test_gates/test_claude_hooks_gate.py | 292 +++++++++++++++++++++
3 files changed, 299 insertions(+), 7 deletions(-)
create mode 100644 tests/test_gates/test_claude_hooks_gate.py
diff --git a/.claude/settings.json b/.claude/settings.json
index 9125ae72..028c8050 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -129,7 +129,7 @@
"hooks": [
{
"type": "command",
- "command": "[ \"$(git branch --show-current 2>/dev/null)\" != \"main\" ] && exit 0; REPO=\"$(git rev-parse --show-toplevel 2>/dev/null)\"; F=$(cat | jq -r '.tool_input.file_path // empty'); case \"$F\" in \"$REPO\"/AGENTS.md|\"$REPO\"/CLAUDE.md) ;; \"$REPO\"/*) echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch.' >&2; exit 2 ;; esac; exit 0",
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); case \"$F\" in /*) ;; *) exit 0 ;; esac; D=${F%/*}; while [ -n \"$D\" ] && [ ! -d \"$D\" ]; do D=${D%/*}; done; [ \"$(git -C \"${D:-/}\" branch --show-current 2>/dev/null)\" = main ] || exit 0; REPO=$(git -C \"${D:-/}\" rev-parse --show-toplevel 2>/dev/null) || exit 0; [ \"$(git -C \"$REPO\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)\" = \"$(git -C \"${CLAUDE_PROJECT_DIR:-.}\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)\" ] || exit 0; git -C \"$REPO\" check-ignore -q \"$F\" 2>/dev/null && exit 0; case \"$F\" in \"$REPO\"/AGENTS.md|\"$REPO\"/CLAUDE.md) ;; \"$REPO\"/*) echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch, or edit the copy in your worktree.' >&2; exit 2 ;; esac; exit 0",
"timeout": 5
}
]
@@ -139,7 +139,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_./-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*[[:space:]]+commit([[:space:]]|$)'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check --output-format concise . 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix first.' >&2; exit 2; }; fi; exit 0",
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_.-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*[[:space:]]+commit([[:space:]]|$|[;&|)])'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check --output-format concise . 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix, re-add the files you are committing, then retry.' >&2; exit 2; }; fi; exit 0",
"timeout": 30
}
]
diff --git a/AGENTS.md b/AGENTS.md
index 22788f57..a944a3e0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -427,7 +427,7 @@ Currently known minor discrepancies:
The project's `.claude/settings.json` defines 7 hooks that enforce formatting, type checking, branch protection, and code quality. These hooks only fire on the tools they match. Using the wrong tool for a task can silently bypass safety checks.
-Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory, and hooks 1, 2, 5, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo.
+Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory. Hooks 1, 2, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo. Hook 5 checks the checkout the edited file belongs to instead, so it also covers edits made from another worktree.
#### Bash file writes bypass Write/Edit/MultiEdit hooks
@@ -437,9 +437,9 @@ Hooks defeated by Bash file writes:
- Hook 1 (PostToolUse): runs `ruff check --fix` and then `ruff format` on an edited `.py` file, and `ruff format` on an edited `.md` file, which formats its Python code blocks. Unused imports are left for `just fix`, so an import added before the code that uses it survives. Skipping this means the file stays unformatted until the next explicit format run.
- Hook 2 (PostToolUse): runs `mypy src/` when a `src/**/*.py` file changes and reports any errors back to Claude. Skipping this means type errors go unreported until the next explicit mypy run.
-- Hook 5 (PreToolUse): blocks editing repo files on the `main` branch (only AGENTS.md and CLAUDE.md are allowed). Skipping this defeats branch protection entirely.
+- Hook 5 (PreToolUse): blocks editing files in any checkout of this repo that is on the `main` branch, including from another worktree. AGENTS.md, CLAUDE.md, and gitignored files such as `.claude/settings.local.json` are allowed. Skipping this defeats branch protection entirely.
-Hook 6 (format check before `git commit`) fires on Bash commands that run `git commit`, including `cd && git commit` and `git -C commit`, and runs `ruff format --check .` from the repo root, the same check CI runs, so it still catches unformatted files at commit time regardless of how they were written. This is the backstop, not the primary defense.
+Hook 6 (format check before `git commit`) fires on Bash commands that run `git commit`, including `cd && git commit` and `git -C commit`, and runs `ruff format --check .` from the root of the repo Claude is working in, the same check CI runs. It checks the working tree, so it catches unformatted files at commit time however they were written, and a file fixed after `git add` has to be added again. This is the backstop, not the primary defense.
#### When to use Write/Edit/MultiEdit vs Bash
@@ -451,8 +451,8 @@ Do not use Bash to write files as a workaround when a hook blocks an action. If
#### What to do when a hook blocks an action
-- Hook 5 blocks a file edit on main: create a feature branch (`git checkout -b type/slug`) and make the edit there.
-- Hook 6 blocks a commit: run `just fix` (or `just fmt-check` to see the diff first) to fix formatting, then retry the commit.
+- Hook 5 blocks a file edit on main: create a feature branch (`git checkout -b type/slug`) and make the edit there. From a worktree, edit the worktree's copy of the file instead.
+- Hook 6 blocks a commit: run `just fix` (or `just fmt-check` to see the diff first), `git add` the fixed files that belong in the commit, then retry the commit.
- Hook 3 blocks `rm -rf`: use a more specific path instead of a dangerous wildcard target.
- Hook 4 blocks a git push: you are pushing to main or force-pushing. Push to a feature branch and open a PR instead.
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
new file mode 100644
index 00000000..393c1d47
--- /dev/null
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -0,0 +1,292 @@
+"""Consolidated invariant: the Claude Code hooks act on the input Claude Code sends.
+
+Claude Code passes hook input as JSON on stdin (``tool_input.file_path``,
+``tool_input.command``, ``last_assistant_message``) and sets no file-path
+environment variable. The edit hooks in ``.claude/settings.json`` once looped
+over an unset ``$CLAUDE_FILE_PATHS`` and silently did nothing (#868), and
+nothing in the suite ran them. These tests run each hook command under bash
+with that JSON, inside a throwaway git repo whose ``.venv`` links to the
+environment running pytest, and check the acceptance criteria of #867 and #868.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+_SETTINGS = Path(__file__).resolve().parents[2] / ".claude" / "settings.json"
+
+pytestmark = pytest.mark.skipif(
+ not all(shutil.which(tool) for tool in ("bash", "git", "jq")),
+ reason="the hook commands need bash, git and jq",
+)
+
+# Inherited GIT_* variables (set when pytest runs under a git hook) would point
+# every git call at the outer repo; CLAUDE_PROJECT_DIR is set per test.
+_ENV = {
+ key: value
+ for key, value in os.environ.items()
+ if not key.startswith("GIT_") and key != "CLAUDE_PROJECT_DIR"
+}
+_GIT_ENV = {
+ **_ENV,
+ "GIT_AUTHOR_NAME": "test",
+ "GIT_AUTHOR_EMAIL": "test@example.invalid",
+ "GIT_COMMITTER_NAME": "test",
+ "GIT_COMMITTER_EMAIL": "test@example.invalid",
+}
+
+
+def _hook(event: str, marker: str) -> str:
+ """Return the one ``event`` hook command that contains ``marker``."""
+ groups = json.loads(_SETTINGS.read_text())["hooks"][event]
+ commands = [h["command"] for g in groups for h in g["hooks"] if marker in h["command"]]
+ assert len(commands) == 1, f"expected one {event} hook containing {marker!r}"
+ return commands[0]
+
+
+_FORMAT_HOOK = _hook("PostToolUse", "ruff format")
+_MYPY_HOOK = _hook("PostToolUse", "mypy")
+_MAIN_GUARD_HOOK = _hook("PreToolUse", "branch --show-current")
+_COMMIT_HOOK = _hook("PreToolUse", "ruff format --check")
+_STOP_HOOK = _hook("Stop", "last_assistant_message")
+
+_UNFORMATTED_MD = "# Notes\n\n```python\nx=1\n```\n"
+
+
+def _run(
+ command: str, payload: dict[str, Any], cwd: Path, **env: str
+) -> subprocess.CompletedProcess[str]:
+ """Run a hook command the way Claude Code does: bash, JSON on stdin, Claude's directory."""
+ return subprocess.run(
+ ["bash", "-c", command],
+ input=json.dumps(payload),
+ capture_output=True,
+ text=True,
+ cwd=cwd,
+ env={**_ENV, **env},
+ timeout=120,
+ check=False,
+ )
+
+
+def _git(cwd: Path, *args: str) -> str:
+ result = subprocess.run(
+ ["git", *args], cwd=cwd, env=_GIT_ENV, capture_output=True, text=True, check=True
+ )
+ return result.stdout.strip()
+
+
+def _edit(path: Path) -> dict[str, Any]:
+ return {"tool_name": "Write", "tool_input": {"file_path": str(path), "content": ""}}
+
+
+def _bash(command: str) -> dict[str, Any]:
+ return {"tool_name": "Bash", "tool_input": {"command": command}}
+
+
+@pytest.fixture()
+def repo(tmp_path: Path) -> Path:
+ """A git repo on a feature branch whose ``.venv`` links to this test run's environment."""
+ root = tmp_path.resolve() / "repo"
+ (root / "sub").mkdir(parents=True)
+ _git(root, "init", "-q", "-b", "feat")
+ (root / ".venv").symlink_to(sys.prefix, target_is_directory=True)
+ (root / ".gitignore").write_text(".venv\nignored/\n")
+ return root
+
+
+@pytest.fixture()
+def main_repo(repo: Path) -> Path:
+ """The repo with one commit on main, so a worktree can branch from it."""
+ _git(repo, "symbolic-ref", "HEAD", "refs/heads/main")
+ commit = _git(repo, "commit-tree", _git(repo, "write-tree"), "-m", "init")
+ _git(repo, "update-ref", "HEAD", commit)
+ return repo
+
+
+@pytest.mark.parametrize("cwd", ["", "sub"])
+def test_format_hook_formats_python_and_keeps_unused_imports(repo: Path, cwd: str) -> None:
+ """An import added before the code that uses it must survive the edit."""
+ target = repo / "probe.py"
+ target.write_text("import os\nx=1\n")
+
+ assert _run(_FORMAT_HOOK, _edit(target), repo / cwd).returncode == 0
+ text = target.read_text()
+ assert "import os" in text
+ assert "x = 1" in text
+
+
+def test_format_hook_formats_python_blocks_in_markdown(repo: Path) -> None:
+ target = repo / "notes.md"
+ target.write_text(_UNFORMATTED_MD)
+
+ assert _run(_FORMAT_HOOK, _edit(target), repo).returncode == 0
+ assert target.read_text() == "# Notes\n\n```python\nx = 1\n```\n"
+
+
+def test_format_hook_leaves_ignored_and_outside_files_alone(repo: Path, tmp_path: Path) -> None:
+ """ruff's --force-exclude still formats a gitignored file passed by path."""
+ (repo / "ignored").mkdir()
+ untouched = {
+ repo / "ignored" / "probe.py": "x=1\n",
+ repo / "ignored" / "notes.md": _UNFORMATTED_MD,
+ repo / "config.yml": "a: 1\n",
+ tmp_path.resolve() / "outside.py": "x=1\n",
+ }
+ for path, text in untouched.items():
+ path.write_text(text)
+
+ for path, text in untouched.items():
+ assert _run(_FORMAT_HOOK, _edit(path), repo).returncode == 0
+ assert path.read_text() == text, path
+
+
+def test_mypy_hook_reports_type_errors_to_claude(repo: Path) -> None:
+ """A PostToolUse hook's output only reaches Claude when it exits 2."""
+ target = repo / "src" / "pkg" / "probe.py"
+ target.parent.mkdir(parents=True)
+ target.write_text('x: int = "a"\n')
+
+ result = _run(_MYPY_HOOK, _edit(target), repo / "sub")
+
+ assert result.returncode == 2
+ assert "probe.py:1: error" in result.stderr
+
+
+def test_mypy_hook_is_quiet_on_clean_code_and_outside_src(repo: Path) -> None:
+ clean = repo / "src" / "pkg" / "probe.py"
+ clean.parent.mkdir(parents=True)
+ clean.write_text("x: int = 1\n")
+ outside_src = repo / "tests" / "test_probe.py"
+ outside_src.parent.mkdir()
+ outside_src.write_text('x: int = "a"\n')
+
+ assert _run(_MYPY_HOOK, _edit(clean), repo).returncode == 0
+ assert _run(_MYPY_HOOK, _edit(outside_src), repo).returncode == 0
+
+
+def test_main_guard_blocks_repo_edits_on_main(main_repo: Path) -> None:
+ result = _run(
+ _MAIN_GUARD_HOOK,
+ _edit(main_repo / "src" / "app.py"),
+ main_repo / "sub",
+ CLAUDE_PROJECT_DIR=str(main_repo),
+ )
+
+ assert result.returncode == 2
+ assert "BLOCKED" in result.stderr
+
+
+@pytest.mark.parametrize("relative", ["AGENTS.md", "CLAUDE.md", "ignored/notes.txt"])
+def test_main_guard_allows_agent_and_ignored_files_on_main(main_repo: Path, relative: str) -> None:
+ result = _run(
+ _MAIN_GUARD_HOOK,
+ _edit(main_repo / relative),
+ main_repo,
+ CLAUDE_PROJECT_DIR=str(main_repo),
+ )
+
+ assert result.returncode == 0
+
+
+def test_main_guard_follows_the_file_into_other_worktrees(main_repo: Path, tmp_path: Path) -> None:
+ """The branch that counts is the edited file's checkout, not Claude's directory."""
+ worktree = tmp_path.resolve() / "worktree"
+ _git(main_repo, "worktree", "add", "-q", "-b", "feature", str(worktree))
+
+ from_worktree = _run(
+ _MAIN_GUARD_HOOK,
+ _edit(main_repo / "src" / "app.py"),
+ worktree,
+ CLAUDE_PROJECT_DIR=str(main_repo),
+ )
+ into_worktree = _run(
+ _MAIN_GUARD_HOOK,
+ _edit(worktree / "src" / "app.py"),
+ main_repo,
+ CLAUDE_PROJECT_DIR=str(main_repo),
+ )
+
+ assert from_worktree.returncode == 2
+ assert into_worktree.returncode == 0
+
+
+def test_main_guard_ignores_feature_branches_and_other_repos(repo: Path, tmp_path: Path) -> None:
+ other = tmp_path.resolve() / "other"
+ other.mkdir()
+ _git(other, "init", "-q", "-b", "main")
+
+ on_feature = _run(
+ _MAIN_GUARD_HOOK, _edit(repo / "src" / "app.py"), repo, CLAUDE_PROJECT_DIR=str(repo)
+ )
+ elsewhere = _run(
+ _MAIN_GUARD_HOOK, _edit(other / "notes.txt"), repo, CLAUDE_PROJECT_DIR=str(repo)
+ )
+
+ assert on_feature.returncode == 0
+ assert elsewhere.returncode == 0
+
+
+@pytest.mark.parametrize(
+ "command",
+ [
+ "git commit -m x",
+ "cd {repo} && git commit -m x",
+ "git -C {repo} commit -m x",
+ "git -c a=b commit -m x",
+ "git add -A && git commit --amend --no-edit",
+ "(cd {repo} && git commit)",
+ "git commit;",
+ "/usr/bin/git commit -m x",
+ ],
+)
+def test_commit_hook_blocks_commits_with_unformatted_files(repo: Path, command: str) -> None:
+ (repo / "notes.md").write_text(_UNFORMATTED_MD)
+
+ result = _run(_COMMIT_HOOK, _bash(command.format(repo=repo)), repo / "sub")
+
+ assert result.returncode == 2
+ assert "notes.md" in result.stderr
+
+
+@pytest.mark.parametrize(
+ "command",
+ [
+ "git log --grep commit",
+ "git commit-tree HEAD^{tree} -m x",
+ 'git stash push -m "wip commit"',
+ "ls .git/",
+ "grep 'git commit' AGENTS.md",
+ ],
+)
+def test_commit_hook_ignores_commands_that_do_not_commit(repo: Path, command: str) -> None:
+ (repo / "notes.md").write_text(_UNFORMATTED_MD)
+
+ assert _run(_COMMIT_HOOK, _bash(command), repo).returncode == 0
+
+
+def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) -> None:
+ (repo / "probe.py").write_text("x = 1\n")
+
+ assert _run(_COMMIT_HOOK, _bash("git commit -m x"), repo / "sub").returncode == 0
+
+
+def test_stop_hook_warns_once_about_unfinished_markers(tmp_path: Path) -> None:
+ def stop(message: str, *, active: bool) -> subprocess.CompletedProcess[str]:
+ payload = {"stop_hook_active": active, "last_assistant_message": message}
+ return _run(_STOP_HOOK, payload, tmp_path)
+
+ warned = stop("Left a TODO in the parser.", active=False)
+
+ assert warned.returncode == 2
+ assert "incomplete markers" in warned.stderr
+ assert stop("Left a TODO in the parser.", active=True).returncode == 0
+ assert stop("All done.", active=False).returncode == 0
From 72f37d85bef3bb44d1d77c0d9854126cab67c890 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 16:02:01 -0500
Subject: [PATCH 04/13] ci: fail closed in the main guard
The main-branch guard placed the edited file by string prefix, so a
path spelled through a symlink or in another case slipped past it, and
it let edits under .git/ through on main. It now asks git where the
file sits (rev-parse --show-prefix) and blocks anything it can't
place: an edit outside a work tree, or a project dir git can't read.
The mypy hook keeps mypy's "Found N errors" line, so a cut-off list
still says how many errors there were. The commit hook only lets the
git options that take a value (-C, -c, --git-dir, --work-tree,
--namespace, --config-env) take one, so `git --no-pager log --grep
commit` isn't mistaken for a commit, and `git commit>file` is caught.
AGENTS.md notes that the hooks need jq and that CI skips .claude/**.
The hook tests cover the new cases.
---
.claude/settings.json | 6 +-
AGENTS.md | 6 +-
tests/test_gates/test_claude_hooks_gate.py | 72 +++++++++++++++++++---
3 files changed, 69 insertions(+), 15 deletions(-)
diff --git a/.claude/settings.json b/.claude/settings.json
index 028c8050..89444084 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -100,7 +100,7 @@
"hooks": [
{
"type": "command",
- "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; case \"$F\" in \"$R\"/src/*.py) OUT=$(cd \"$R\" && .venv/bin/python -m mypy src/ --no-error-summary 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; exit 2; } ;; esac; exit 0"
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; case \"$F\" in \"$R\"/src/*.py) OUT=$(cd \"$R\" && .venv/bin/python -m mypy src/ 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; exit 2; } ;; esac; exit 0"
}
]
}
@@ -129,7 +129,7 @@
"hooks": [
{
"type": "command",
- "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); case \"$F\" in /*) ;; *) exit 0 ;; esac; D=${F%/*}; while [ -n \"$D\" ] && [ ! -d \"$D\" ]; do D=${D%/*}; done; [ \"$(git -C \"${D:-/}\" branch --show-current 2>/dev/null)\" = main ] || exit 0; REPO=$(git -C \"${D:-/}\" rev-parse --show-toplevel 2>/dev/null) || exit 0; [ \"$(git -C \"$REPO\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)\" = \"$(git -C \"${CLAUDE_PROJECT_DIR:-.}\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)\" ] || exit 0; git -C \"$REPO\" check-ignore -q \"$F\" 2>/dev/null && exit 0; case \"$F\" in \"$REPO\"/AGENTS.md|\"$REPO\"/CLAUDE.md) ;; \"$REPO\"/*) echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch, or edit the copy in your worktree.' >&2; exit 2 ;; esac; exit 0",
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); case \"$F\" in /*) ;; *) exit 0 ;; esac; D=${F%/*}; while [ -n \"$D\" ] && [ ! -d \"$D\" ]; do D=${D%/*}; done; D=${D:-/}; [ \"$(git -C \"$D\" branch --show-current 2>/dev/null)\" = main ] || exit 0; P=$(git -C \"${CLAUDE_PROJECT_DIR:-.}\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null); [ -n \"$P\" ] && [ \"$(git -C \"$D\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)\" != \"$P\" ] && exit 0; T=${F#\"$D\"/}; if [ \"$(git -C \"$D\" rev-parse --is-inside-work-tree 2>/dev/null)\" = true ]; then git -C \"$D\" check-ignore -q -- \"$T\" 2>/dev/null && exit 0; case \"$(git -C \"$D\" rev-parse --show-prefix 2>/dev/null)$T\" in AGENTS.md|CLAUDE.md) exit 0 ;; esac; fi; echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch, or edit the copy in your worktree.' >&2; exit 2",
"timeout": 5
}
]
@@ -139,7 +139,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_.-])git([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*[[:space:]]+commit([[:space:]]|$|[;&|)])'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check --output-format concise . 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix, re-add the files you are committing, then retry.' >&2; exit 2; }; fi; exit 0",
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_.-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+commit([[:space:]]|$|[;&|)<>])'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check --output-format concise . 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix, re-add the files you are committing, then retry.' >&2; exit 2; }; fi; exit 0",
"timeout": 30
}
]
diff --git a/AGENTS.md b/AGENTS.md
index a944a3e0..f1815d74 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,7 +29,9 @@ review before being added.
`just` is the canonical interface. Install it via `brew install just`
(macOS) or `cargo install just`. The repo's `justfile` wires every
gate, every test slice, and the dev server, so most agent work goes
-through `just ` rather than `.venv/bin/...`.
+through `just ` rather than `.venv/bin/...`. The Claude Code
+hooks in `.claude/settings.json` read their input with `jq`, so it
+has to be on PATH; without it they do nothing.
```bash
# Create venv and install (one-time bootstrap; uv reads pyproject.toml +
@@ -427,7 +429,7 @@ Currently known minor discrepancies:
The project's `.claude/settings.json` defines 7 hooks that enforce formatting, type checking, branch protection, and code quality. These hooks only fire on the tools they match. Using the wrong tool for a task can silently bypass safety checks.
-Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory. Hooks 1, 2, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo. Hook 5 checks the checkout the edited file belongs to instead, so it also covers edits made from another worktree.
+Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory. Hooks 1, 2, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo. Hook 5 checks the checkout the edited file belongs to instead, so it also covers edits made from another worktree. CI's path filters skip `.claude/**`, so a PR that only changes the hooks runs no tests in CI; run `just check` locally before pushing one.
#### Bash file writes bypass Write/Edit/MultiEdit hooks
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index 393c1d47..723a365e 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -6,7 +6,8 @@
over an unset ``$CLAUDE_FILE_PATHS`` and silently did nothing (#868), and
nothing in the suite ran them. These tests run each hook command under bash
with that JSON, inside a throwaway git repo whose ``.venv`` links to the
-environment running pytest, and check the acceptance criteria of #867 and #868.
+environment running pytest, and check the hook acceptance criteria of #867 and
+#868.
"""
from __future__ import annotations
@@ -23,9 +24,12 @@
_SETTINGS = Path(__file__).resolve().parents[2] / ".claude" / "settings.json"
+_MISSING_TOOLS = [tool for tool in ("bash", "git", "jq") if shutil.which(tool) is None]
+
+# In CI a missing tool fails the hook tests instead of skipping them.
pytestmark = pytest.mark.skipif(
- not all(shutil.which(tool) for tool in ("bash", "git", "jq")),
- reason="the hook commands need bash, git and jq",
+ bool(_MISSING_TOOLS) and not os.environ.get("CI"),
+ reason=f"the hook commands need {', '.join(_MISSING_TOOLS)}",
)
# Inherited GIT_* variables (set when pytest runs under a git hook) would point
@@ -114,14 +118,14 @@ def main_repo(repo: Path) -> Path:
@pytest.mark.parametrize("cwd", ["", "sub"])
def test_format_hook_formats_python_and_keeps_unused_imports(repo: Path, cwd: str) -> None:
- """An import added before the code that uses it must survive the edit."""
+ """Lint fixes and formatting apply, but an import added before its first use survives."""
target = repo / "probe.py"
- target.write_text("import os\nx=1\n")
+ target.write_text('import os\nx=f"a"\n')
assert _run(_FORMAT_HOOK, _edit(target), repo / cwd).returncode == 0
text = target.read_text()
assert "import os" in text
- assert "x = 1" in text
+ assert 'x = "a"' in text
def test_format_hook_formats_python_blocks_in_markdown(repo: Path) -> None:
@@ -150,7 +154,7 @@ def test_format_hook_leaves_ignored_and_outside_files_alone(repo: Path, tmp_path
def test_mypy_hook_reports_type_errors_to_claude(repo: Path) -> None:
- """A PostToolUse hook's output only reaches Claude when it exits 2."""
+ """A PostToolUse hook's plain-text stderr only reaches Claude when it exits 2."""
target = repo / "src" / "pkg" / "probe.py"
target.parent.mkdir(parents=True)
target.write_text('x: int = "a"\n')
@@ -162,14 +166,16 @@ def test_mypy_hook_reports_type_errors_to_claude(repo: Path) -> None:
def test_mypy_hook_is_quiet_on_clean_code_and_outside_src(repo: Path) -> None:
+ """An edit outside src/ never runs mypy, even while src/ has a type error."""
clean = repo / "src" / "pkg" / "probe.py"
clean.parent.mkdir(parents=True)
clean.write_text("x: int = 1\n")
+ assert _run(_MYPY_HOOK, _edit(clean), repo).returncode == 0
+
+ (repo / "src" / "pkg" / "broken.py").write_text('x: int = "a"\n')
outside_src = repo / "tests" / "test_probe.py"
outside_src.parent.mkdir()
- outside_src.write_text('x: int = "a"\n')
-
- assert _run(_MYPY_HOOK, _edit(clean), repo).returncode == 0
+ outside_src.write_text("x = 1\n")
assert _run(_MYPY_HOOK, _edit(outside_src), repo).returncode == 0
@@ -219,6 +225,49 @@ def test_main_guard_follows_the_file_into_other_worktrees(main_repo: Path, tmp_p
assert into_worktree.returncode == 0
+def test_main_guard_resolves_symlinked_paths(main_repo: Path, tmp_path: Path) -> None:
+ """A path through a symlink is matched by where git places it, not by its spelling."""
+ link = tmp_path.resolve() / "link"
+ link.symlink_to(main_repo, target_is_directory=True)
+
+ code = _run(
+ _MAIN_GUARD_HOOK, _edit(link / "src" / "app.py"), main_repo, CLAUDE_PROJECT_DIR=str(link)
+ )
+ agents = _run(
+ _MAIN_GUARD_HOOK, _edit(link / "AGENTS.md"), main_repo, CLAUDE_PROJECT_DIR=str(link)
+ )
+
+ assert code.returncode == 2
+ assert agents.returncode == 0
+
+
+def test_main_guard_fails_closed_when_it_cannot_place_the_edit(
+ main_repo: Path, tmp_path: Path
+) -> None:
+ """Git metadata, or a project directory git cannot read, blocks rather than passes."""
+ nowhere = tmp_path.resolve() / "not-a-repo"
+ nowhere.mkdir()
+
+ git_metadata = [
+ _run(
+ _MAIN_GUARD_HOOK,
+ _edit(main_repo / ".git" / name),
+ main_repo,
+ CLAUDE_PROJECT_DIR=str(main_repo),
+ )
+ for name in ("config", "AGENTS.md")
+ ]
+ unknown_project = _run(
+ _MAIN_GUARD_HOOK,
+ _edit(main_repo / "src" / "app.py"),
+ nowhere,
+ CLAUDE_PROJECT_DIR=str(nowhere),
+ )
+
+ assert [result.returncode for result in git_metadata] == [2, 2]
+ assert unknown_project.returncode == 2
+
+
def test_main_guard_ignores_feature_branches_and_other_repos(repo: Path, tmp_path: Path) -> None:
other = tmp_path.resolve() / "other"
other.mkdir()
@@ -242,9 +291,11 @@ def test_main_guard_ignores_feature_branches_and_other_repos(repo: Path, tmp_pat
"cd {repo} && git commit -m x",
"git -C {repo} commit -m x",
"git -c a=b commit -m x",
+ "git --no-pager commit -m x",
"git add -A && git commit --amend --no-edit",
"(cd {repo} && git commit)",
"git commit;",
+ "git commit>/dev/null",
"/usr/bin/git commit -m x",
],
)
@@ -261,6 +312,7 @@ def test_commit_hook_blocks_commits_with_unformatted_files(repo: Path, command:
"command",
[
"git log --grep commit",
+ "git --no-pager log --grep commit",
"git commit-tree HEAD^{tree} -m x",
'git stash push -m "wip commit"',
"ls .git/",
From ba4d68c2e0f0097a2afeede8664bcbede32ea1b2 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 16:34:28 -0500
Subject: [PATCH 05/13] ci: cover the remaining hook edge cases
The commit hook also lets --attr-source take a separate value, so
`git --attr-source HEAD commit` is checked. The hook tests now cover
a nested AGENTS.md on main, which stays blocked, and a _build/ file,
which only ruff's own excludes keep away from the format hook.
AGENTS.md says CI's path filters also skip Markdown-only and
scripts/marketing/-only PRs, so those get no ruff check in CI.
---
.claude/settings.json | 2 +-
AGENTS.md | 2 +-
tests/test_gates/test_claude_hooks_gate.py | 9 +++++++--
3 files changed, 9 insertions(+), 4 deletions(-)
diff --git a/.claude/settings.json b/.claude/settings.json
index 89444084..b90557b1 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -139,7 +139,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_.-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+commit([[:space:]]|$|[;&|)<>])'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check --output-format concise . 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix, re-add the files you are committing, then retry.' >&2; exit 2; }; fi; exit 0",
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if printf '%s\\n' \"$CMD\" | grep -qE '(^|[^[:alnum:]_.-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+commit([[:space:]]|$|[;&|)<>])'; then R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; OUT=$(cd \"$R\" && .venv/bin/python -m ruff format --check --output-format concise . 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; echo '❌ BLOCKED: Unformatted files. Run just fix, re-add the files you are committing, then retry.' >&2; exit 2; }; fi; exit 0",
"timeout": 30
}
]
diff --git a/AGENTS.md b/AGENTS.md
index f1815d74..726c788b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -429,7 +429,7 @@ Currently known minor discrepancies:
The project's `.claude/settings.json` defines 7 hooks that enforce formatting, type checking, branch protection, and code quality. These hooks only fire on the tools they match. Using the wrong tool for a task can silently bypass safety checks.
-Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory. Hooks 1, 2, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo. Hook 5 checks the checkout the edited file belongs to instead, so it also covers edits made from another worktree. CI's path filters skip `.claude/**`, so a PR that only changes the hooks runs no tests in CI; run `just check` locally before pushing one.
+Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory. Hooks 1, 2, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo. Hook 5 checks the checkout the edited file belongs to instead, so it also covers edits made from another worktree. CI's `paths-ignore` list (see CI Checks) covers `.claude/**`, Markdown, and `scripts/marketing/**`, so a PR that only touches those gets no ruff check or test run in CI; run `just check` locally before pushing one.
#### Bash file writes bypass Write/Edit/MultiEdit hooks
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index 723a365e..4b46044d 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -139,10 +139,12 @@ def test_format_hook_formats_python_blocks_in_markdown(repo: Path) -> None:
def test_format_hook_leaves_ignored_and_outside_files_alone(repo: Path, tmp_path: Path) -> None:
"""ruff's --force-exclude still formats a gitignored file passed by path."""
(repo / "ignored").mkdir()
+ (repo / "_build").mkdir()
untouched = {
repo / "ignored" / "probe.py": "x=1\n",
repo / "ignored" / "notes.md": _UNFORMATTED_MD,
repo / "config.yml": "a: 1\n",
+ repo / "_build" / "probe.py": "x=1\n",
tmp_path.resolve() / "outside.py": "x=1\n",
}
for path, text in untouched.items():
@@ -179,10 +181,12 @@ def test_mypy_hook_is_quiet_on_clean_code_and_outside_src(repo: Path) -> None:
assert _run(_MYPY_HOOK, _edit(outside_src), repo).returncode == 0
-def test_main_guard_blocks_repo_edits_on_main(main_repo: Path) -> None:
+@pytest.mark.parametrize("relative", ["src/app.py", "sub/AGENTS.md"])
+def test_main_guard_blocks_repo_edits_on_main(main_repo: Path, relative: str) -> None:
+ """Only the root AGENTS.md and CLAUDE.md are exempt."""
result = _run(
_MAIN_GUARD_HOOK,
- _edit(main_repo / "src" / "app.py"),
+ _edit(main_repo / relative),
main_repo / "sub",
CLAUDE_PROJECT_DIR=str(main_repo),
)
@@ -292,6 +296,7 @@ def test_main_guard_ignores_feature_branches_and_other_repos(repo: Path, tmp_pat
"git -C {repo} commit -m x",
"git -c a=b commit -m x",
"git --no-pager commit -m x",
+ "git --attr-source HEAD commit -m x",
"git add -A && git commit --amend --no-edit",
"(cd {repo} && git commit)",
"git commit;",
From 53fd966e046f390a38e5472f46940505b9581811 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 16:57:36 -0500
Subject: [PATCH 06/13] ci: run quality on every pr and harden push guard
quality.yml and tests.yml only ran when a PR touched something outside
docs/, Markdown, website/, .claude/ and scripts/marketing/, and
ci-skip.yml stubbed their checks otherwise. Ruff checks every .py and
.md file and the tests read docs/api/, scripts/marketing/ and
.claude/settings.json, so a PR touching only those merged without the
checks that cover them. Both workflows now run on every PR, and
ci-skip.yml only stubs the four workflows that keep their filters.
The push guard only matched --force, -f or "origin main" right after
"git push". It now finds git push after git's global options and
blocks force pushes (--force, -f, --force-with-lease, --mirror, --all,
+refspecs) and any main or master target. On main, a push that names
no branch, or names a ref that resolves to main, is blocked too; the
branch is read in the checkout -C points at.
The format hook also leaves unused except bindings alone (F841).
---
.agents/skills/houndarr-ci/SKILL.md | 11 ++-
.claude/settings.json | 4 +-
.github/workflows/ci-skip.yml | 14 ++--
.github/workflows/quality.yml | 8 +-
.github/workflows/tests.yml | 8 +-
AGENTS.md | 16 ++--
tests/test_gates/test_claude_hooks_gate.py | 96 +++++++++++++++++++++-
7 files changed, 123 insertions(+), 34 deletions(-)
diff --git a/.agents/skills/houndarr-ci/SKILL.md b/.agents/skills/houndarr-ci/SKILL.md
index 763fc25e..27f32c42 100644
--- a/.agents/skills/houndarr-ci/SKILL.md
+++ b/.agents/skills/houndarr-ci/SKILL.md
@@ -24,11 +24,13 @@ paths:
| Trivy image scan | `docker.yml` | Trivy scan of built Docker image (CRITICAL/HIGH with known fix) |
| Security smoke test | `security-smoke-test.yml` | Live container: unauthenticated sweep, CSRF, XFF, rate limiting, API key exposure, container security |
-The six main workflows (`quality`, `tests`, `security`, `dependency-review`,
-`docker`, `security-smoke-test`) use
+`quality` and `tests` run on every PR: ruff checks every `.py` and `.md`
+file, and the tests read `docs/api/`, `scripts/marketing/` and
+`.claude/settings.json`. The other four main workflows (`security`,
+`dependency-review`, `docker`, `security-smoke-test`) use
`paths-ignore: ["docs/**", "**/*.md", "website/**", ".claude/**", "scripts/marketing/**"]`. When a PR
touches only those paths, `ci-skip.yml` provides passing no-op jobs with
-identical check names so branch protection is satisfied. Fork PRs get a
+their check names so branch protection is satisfied. Fork PRs get a
read-only token, so the stubs can't be created there and a docs-only fork
PR stays blocked.
@@ -66,7 +68,8 @@ PR stays blocked.
- Do not modify the 12 required check job names; branch protection
depends on exact name matches.
- Do not change `ci-skip.yml` job names without updating branch protection.
-- Keep `paths-ignore` patterns in sync across the six main workflows.
+- Keep the `paths-ignore` patterns of the four filtered workflows in sync
+ with each other and with `ci-skip.yml`'s `paths`.
- If mypy CI fails with "merge ref not found": push an empty commit to
retrigger.
- Keep every action pinned to a full 40-character commit SHA with the
diff --git a/.claude/settings.json b/.claude/settings.json
index b90557b1..88c15105 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -91,7 +91,7 @@
"hooks": [
{
"type": "command",
- "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; git check-ignore -q \"$F\" 2>/dev/null && exit 0; case \"$F\" in \"$R\"/*.py) \"$R\"/.venv/bin/python -m ruff check --fix --unfixable F401 --force-exclude \"$F\" >/dev/null 2>&1; \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; \"$R\"/*.md) \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; esac; exit 0"
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; git check-ignore -q \"$F\" 2>/dev/null && exit 0; case \"$F\" in \"$R\"/*.py) \"$R\"/.venv/bin/python -m ruff check --fix --unfixable F401,F841 --force-exclude \"$F\" >/dev/null 2>&1; \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; \"$R\"/*.md) \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; esac; exit 0"
}
]
},
@@ -120,7 +120,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); if echo \"$CMD\" | grep -qE 'git\\s+push\\s+(--force|-f)|git\\s+push\\s+origin\\s+(main|master)'; then echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2; exit 2; fi; exit 0"
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | grep -oE '(^|[^[:alnum:]_.-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>]*)?($|[;&|<>)])'); [ -n \"$SEGS\" ] || exit 0; printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '[[:space:]](--force(-with-lease)?|--mirror|--all|-[[:alnum:]]*f[[:alnum:]]*)([=[:space:]]|$|[;&|<>)])|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)(refs/heads/)?(main|master)([[:space:]]|$|[;&|<>)])' && exit 2; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"-C\" && i < NF) d = $(i + 1); if ($i == \"push\") break }; print d }'); REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[;&|<>)]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j == \"-o\" || $j == \"--push-option\" || $j == \"--repo\" || $j == \"--receive-pack\" || $j == \"--exec\") { j++; continue }; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \"\"|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && case \"$S\" in *--tags*) ;; *) exit 2 ;; esac ;; esac; :; done || { echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2; exit 2; }; exit 0"
}
]
},
diff --git a/.github/workflows/ci-skip.yml b/.github/workflows/ci-skip.yml
index 2c595ba4..004f8240 100644
--- a/.github/workflows/ci-skip.yml
+++ b/.github/workflows/ci-skip.yml
@@ -1,10 +1,11 @@
name: CI Skip (docs-only)
# Provide passing required-check statuses when a PR touches only
-# documentation or agent-config files. Every other workflow uses
-# paths-ignore to skip these paths, so without this shim those required
-# checks would never report and the PR would stay blocked by branch
-# protection.
+# documentation or agent-config files. The security, dependency review,
+# docker and smoke test workflows use paths-ignore to skip these paths, so
+# without this shim their required checks would never report and the PR
+# would stay blocked by branch protection. Quality and Tests run on every
+# PR (ruff and the tests read these paths), so their checks are not stubbed.
on:
pull_request:
@@ -35,11 +36,6 @@ jobs:
with:
script: |
const checks = [
- 'Lint (ruff)',
- 'Format (ruff)',
- 'Type check (mypy)',
- 'Test (Python 3.13)',
- 'Test (Python 3.14)',
'Dependency audit (pip-audit)',
'SAST (bandit)',
'Trivy filesystem scan',
diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml
index 383c05f8..73dcb0fb 100644
--- a/.github/workflows/quality.yml
+++ b/.github/workflows/quality.yml
@@ -1,13 +1,9 @@
name: Quality
+# No paths-ignore: ruff checks every .py and .md file in the repo, docs/ and
+# website/ included, so ci-skip.yml must not stub these checks either.
on:
pull_request:
- paths-ignore:
- - "docs/**"
- - "**/*.md"
- - "website/**"
- - ".claude/**"
- - "scripts/marketing/**"
permissions:
contents: read
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 53e633e2..426500a6 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -1,13 +1,9 @@
name: Tests
+# No paths-ignore: the tests read docs/api/, scripts/marketing/ and
+# .claude/settings.json, so ci-skip.yml must not stub these checks either.
on:
pull_request:
- paths-ignore:
- - "docs/**"
- - "**/*.md"
- - "website/**"
- - ".claude/**"
- - "scripts/marketing/**"
permissions:
contents: read
diff --git a/AGENTS.md b/AGENTS.md
index 726c788b..5fe0194b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -103,9 +103,11 @@ ci-skip pattern live in the `houndarr-ci` skill (loads on
| Build (no push), Trivy image scan | `docker.yml` |
| Security smoke test | `security-smoke-test.yml` |
-The six main workflows use
+`quality.yml` and `tests.yml` run on every PR: ruff checks every `.py`
+and `.md` file, and the tests read `docs/api/`, `scripts/marketing/` and
+`.claude/settings.json`. The other four main workflows use
`paths-ignore: ["docs/**", "**/*.md", "website/**", ".claude/**", "scripts/marketing/**"]`;
-`ci-skip.yml` provides passing no-op jobs with identical check names so
+`ci-skip.yml` provides passing no-op jobs with their check names so
docs-only PRs satisfy branch protection (except fork PRs, whose token
cannot create check runs). **Do not modify the 12 required check job
names**: branch protection depends on exact name matches.
@@ -403,7 +405,8 @@ someone comments, so reporters get immediate feedback.
PR, and `/bump` reseeds an empty one after each promotion
- Do not change `ci-skip.yml` job names without updating branch protection
- If mypy CI fails with "merge ref not found": push an empty commit to retrigger
-- Keep `paths-ignore` patterns in sync across the six main workflows
+- Keep the `paths-ignore` patterns of the four filtered workflows in sync
+ with each other and with `ci-skip.yml`'s `paths`
- Keep every action pinned to a full 40-character commit SHA with the release
version as the last token of a trailing comment
(`uses: owner/repo@ # vX.Y.Z`). Dependabot rewrites the SHA and the
@@ -429,7 +432,7 @@ Currently known minor discrepancies:
The project's `.claude/settings.json` defines 7 hooks that enforce formatting, type checking, branch protection, and code quality. These hooks only fire on the tools they match. Using the wrong tool for a task can silently bypass safety checks.
-Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory. Hooks 1, 2, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo. Hook 5 checks the checkout the edited file belongs to instead, so it also covers edits made from another worktree. CI's `paths-ignore` list (see CI Checks) covers `.claude/**`, Markdown, and `scripts/marketing/**`, so a PR that only touches those gets no ruff check or test run in CI; run `just check` locally before pushing one.
+Claude Code passes each hook its input as JSON on stdin: `tool_input.file_path` for Write, Edit, and MultiEdit, `tool_input.command` for Bash, and `last_assistant_message` for Stop. No environment variable carries the edited file's path. Hooks run in Claude's current directory. Hooks 1, 2, and 6 act on the git repo that contains it (`git rev-parse --show-toplevel`), so they work from a subdirectory such as `website/` and do nothing outside a repo. Hook 5 checks the checkout the edited file belongs to instead, so it also covers edits made from another worktree.
#### Bash file writes bypass Write/Edit/MultiEdit hooks
@@ -437,7 +440,7 @@ Hooks 1, 2, and 5 match `Write|Edit|MultiEdit` only. They do NOT fire when files
Hooks defeated by Bash file writes:
-- Hook 1 (PostToolUse): runs `ruff check --fix` and then `ruff format` on an edited `.py` file, and `ruff format` on an edited `.md` file, which formats its Python code blocks. Unused imports are left for `just fix`, so an import added before the code that uses it survives. Skipping this means the file stays unformatted until the next explicit format run.
+- Hook 1 (PostToolUse): runs `ruff check --fix` and then `ruff format` on an edited `.py` file, and `ruff format` on an edited `.md` file, which formats its Python code blocks. Unused imports and unused `except ... as e` bindings are left for `just fix`, so code added before its first use survives the edit. Skipping this means the file stays unformatted until the next explicit format run.
- Hook 2 (PostToolUse): runs `mypy src/` when a `src/**/*.py` file changes and reports any errors back to Claude. Skipping this means type errors go unreported until the next explicit mypy run.
- Hook 5 (PreToolUse): blocks editing files in any checkout of this repo that is on the `main` branch, including from another worktree. AGENTS.md, CLAUDE.md, and gitignored files such as `.claude/settings.local.json` are allowed. Skipping this defeats branch protection entirely.
@@ -456,7 +459,7 @@ Do not use Bash to write files as a workaround when a hook blocks an action. If
- Hook 5 blocks a file edit on main: create a feature branch (`git checkout -b type/slug`) and make the edit there. From a worktree, edit the worktree's copy of the file instead.
- Hook 6 blocks a commit: run `just fix` (or `just fmt-check` to see the diff first), `git add` the fixed files that belong in the commit, then retry the commit.
- Hook 3 blocks `rm -rf`: use a more specific path instead of a dangerous wildcard target.
-- Hook 4 blocks a git push: you are pushing to main or force-pushing. Push to a feature branch and open a PR instead.
+- Hook 4 blocks a git push: you are pushing to main, force-pushing, or pushing from `main` without naming a branch. Push to a feature branch and open a PR instead.
In every case: fix the underlying issue, do not bypass the hook.
@@ -466,6 +469,7 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
+- Hook 4 (push guard): matches `git push` after any global options (`git -C push`, `git -c k=v push`). It blocks `--force`, `-f`, `--force-with-lease`, `--mirror`, `--all` and `+` refspecs, any target named `main` or `master` (including `HEAD:main` and `:main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` go through.
---
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index 4b46044d..3d2eb3f3 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -58,7 +58,8 @@ def _hook(event: str, marker: str) -> str:
_FORMAT_HOOK = _hook("PostToolUse", "ruff format")
_MYPY_HOOK = _hook("PostToolUse", "mypy")
-_MAIN_GUARD_HOOK = _hook("PreToolUse", "branch --show-current")
+_PUSH_GUARD_HOOK = _hook("PreToolUse", "Direct push to main")
+_MAIN_GUARD_HOOK = _hook("PreToolUse", "Cannot edit repo files on main")
_COMMIT_HOOK = _hook("PreToolUse", "ruff format --check")
_STOP_HOOK = _hook("Stop", "last_assistant_message")
@@ -128,6 +129,15 @@ def test_format_hook_formats_python_and_keeps_unused_imports(repo: Path, cwd: st
assert 'x = "a"' in text
+def test_format_hook_keeps_an_exception_binding_used_later(repo: Path) -> None:
+ """An ``except ... as e:`` written before the code that uses ``e`` survives too."""
+ target = repo / "probe.py"
+ target.write_text("try:\n pass\nexcept ValueError as e:\n pass\n")
+
+ assert _run(_FORMAT_HOOK, _edit(target), repo).returncode == 0
+ assert "except ValueError as e:" in target.read_text()
+
+
def test_format_hook_formats_python_blocks_in_markdown(repo: Path) -> None:
target = repo / "notes.md"
target.write_text(_UNFORMATTED_MD)
@@ -336,6 +346,90 @@ def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) ->
assert _run(_COMMIT_HOOK, _bash("git commit -m x"), repo / "sub").returncode == 0
+@pytest.mark.parametrize(
+ "command",
+ [
+ "git push --force",
+ "git push origin feat --force",
+ "git push -uf origin feat",
+ "git push --force-with-lease",
+ "git push origin +feat",
+ "git push --mirror",
+ "git push --all origin",
+ "git push origin main",
+ "git push -u origin main",
+ "git push origin HEAD:main",
+ "git push origin :main",
+ "git -C . push --force",
+ "git -c a=b push -f",
+ "git --no-pager push origin main",
+ "git --attr-source HEAD push -f",
+ "/usr/bin/git push --force",
+ "cd /x && git push origin main",
+ "(cd /x && git push origin main)",
+ "git push origin main;",
+ ],
+)
+def test_push_guard_blocks_force_pushes_and_pushes_to_main(repo: Path, command: str) -> None:
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
+
+ assert result.returncode == 2
+ assert "BLOCKED" in result.stderr
+
+
+@pytest.mark.parametrize(
+ "command",
+ [
+ "git push",
+ "git push origin feat",
+ "git push -u origin feat",
+ "git push origin HEAD",
+ "git push origin feature/maintenance",
+ "git push origin main-fix",
+ "git push origin v1.2.3",
+ "git push origin --delete feat",
+ 'grep "git push origin main" AGENTS.md',
+ ],
+)
+def test_push_guard_allows_feature_and_tag_pushes(repo: Path, command: str) -> None:
+ assert _run(_PUSH_GUARD_HOOK, _bash(command), repo).returncode == 0
+
+
+@pytest.mark.parametrize(
+ ("command", "expected"),
+ [
+ ("git push", 2),
+ ("git push -u origin", 2),
+ ("git push origin HEAD", 2),
+ ("git push origin @", 2),
+ ("git push origin heads/main", 2),
+ ("git push --tags origin HEAD", 2),
+ ("git push --follow-tags", 2),
+ ("git push origin v1.2.3", 0),
+ ("git push --tags", 0),
+ ("git push origin feat", 0),
+ ],
+)
+def test_push_guard_on_main_needs_a_named_target(
+ main_repo: Path, command: str, expected: int
+) -> None:
+ """On main, a push that names no branch, or names the current one, pushes main."""
+ assert _run(_PUSH_GUARD_HOOK, _bash(command), main_repo).returncode == expected
+
+
+def test_push_guard_reads_the_branch_of_the_checkout_named_by_dash_c(
+ main_repo: Path, tmp_path: Path
+) -> None:
+ worktree = tmp_path.resolve() / "worktree"
+ _git(main_repo, "worktree", "add", "-q", "-b", "feature", str(worktree))
+
+ into_main = _run(_PUSH_GUARD_HOOK, _bash(f"git -C {main_repo} push"), worktree)
+ into_feature = _run(_PUSH_GUARD_HOOK, _bash(f"git -C {worktree} push"), main_repo)
+
+ assert into_main.returncode == 2
+ assert into_feature.returncode == 0
+
+
def test_stop_hook_warns_once_about_unfinished_markers(tmp_path: Path) -> None:
def stop(message: str, *, active: bool) -> subprocess.CompletedProcess[str]:
payload = {"stop_hook_active": active, "last_assistant_message": message}
From 7dc86314422f14ee3d1d62088646ad6560694872 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 18:10:54 -0500
Subject: [PATCH 07/13] ci: refuse pushes the push guard cannot read
The push guard matched raw command text, so a quoted or expanded
branch or flag slipped a push to main or a force push past it, and
it only followed -C to find the checkout, so --git-dir, --work-tree
or GIT_DIR pointed the push at a branch it never read.
It now reads the push with quotes removed and across line breaks,
and refuses one it cannot read: $, backticks, backslashes, quoted
text with spaces, the repo overrides above, or a -C directory that
is not a repo.
---
.claude/settings.json | 2 +-
AGENTS.md | 4 +-
tests/test_gates/test_claude_hooks_gate.py | 62 +++++++++++++++++++---
3 files changed, 57 insertions(+), 11 deletions(-)
diff --git a/.claude/settings.json b/.claude/settings.json
index 88c15105..e3173e13 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -120,7 +120,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | grep -oE '(^|[^[:alnum:]_.-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>]*)?($|[;&|<>)])'); [ -n \"$SEGS\" ] || exit 0; printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '[[:space:]](--force(-with-lease)?|--mirror|--all|-[[:alnum:]]*f[[:alnum:]]*)([=[:space:]]|$|[;&|<>)])|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)(refs/heads/)?(main|master)([[:space:]]|$|[;&|<>)])' && exit 2; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"-C\" && i < NF) d = $(i + 1); if ($i == \"push\") break }; print d }'); REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[;&|<>)]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j == \"-o\" || $j == \"--push-option\" || $j == \"--repo\" || $j == \"--receive-pack\" || $j == \"--exec\") { j++; continue }; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \"\"|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && case \"$S\" in *--tags*) ;; *) exit 2 ;; esac ;; esac; :; done || { echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2; exit 2; }; exit 0"
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | awk '{ if (sub(/\\\\$/, \"\")) printf \"%s\", $0; else print }' | grep -oE '(^|[^[:alnum:]_.\"'\\''-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source)[[:space:]]+(\"[^\"]*\"|'\\''[^'\\'']*'\\''|[^[:space:]]+)|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>]*)?($|[;&|<>)])'); [ -n \"$SEGS\" ] || exit 0; printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '\"[^\"]*[[:space:]][^\"]*\"|'\\''[^'\\'']*[[:space:]][^'\\'']*'\\''' && exit 3; S=$(printf '%s\\n' \"$S\" | tr -d '\\042\\047'); printf '%s\\n' \"$S\" | grep -qE '[[:space:]](--force(-with-lease)?|--mirror|--all|-[[:alnum:]]*f[[:alnum:]]*)([=[:space:]]|$|[;&|<>)])|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)(refs/heads/)?(main|master)([[:space:]]|$|[;&|<>)])' && exit 2; case \"$S\" in *\\$*|*'`'*|*'\\'*|*--git-dir*|*--work-tree*) exit 3 ;; esac; case \"$CMD\" in *GIT_DIR=*|*GIT_WORK_TREE=*) exit 3 ;; esac; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"push\") break; if ($i == \"-C\" && i < NF) { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v } }; print d }'); [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 3; REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[;&|<>)]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j == \"-o\" || $j == \"--push-option\" || $j == \"--repo\" || $j == \"--receive-pack\" || $j == \"--exec\") { j++; continue }; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \"\"|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && case \"$S\" in *--tags*) ;; *) exit 2 ;; esac ;; esac; :; done; case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: Cannot read this git push. Write the branch and any -C directory out literally, without $, backticks, backslashes, quoted spaces, --git-dir, --work-tree, GIT_DIR or GIT_WORK_TREE.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
}
]
},
diff --git a/AGENTS.md b/AGENTS.md
index 5fe0194b..d1ce8634 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -459,7 +459,7 @@ Do not use Bash to write files as a workaround when a hook blocks an action. If
- Hook 5 blocks a file edit on main: create a feature branch (`git checkout -b type/slug`) and make the edit there. From a worktree, edit the worktree's copy of the file instead.
- Hook 6 blocks a commit: run `just fix` (or `just fmt-check` to see the diff first), `git add` the fixed files that belong in the commit, then retry the commit.
- Hook 3 blocks `rm -rf`: use a more specific path instead of a dangerous wildcard target.
-- Hook 4 blocks a git push: you are pushing to main, force-pushing, or pushing from `main` without naming a branch. Push to a feature branch and open a PR instead.
+- Hook 4 blocks a git push: you are pushing to main, force-pushing, pushing from `main` without naming a branch, or the hook cannot read where the push goes. Push to a feature branch, with its name written out (`git push -u origin `), and open a PR instead.
In every case: fix the underlying issue, do not bypass the hook.
@@ -469,7 +469,7 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
-- Hook 4 (push guard): matches `git push` after any global options (`git -C push`, `git -c k=v push`). It blocks `--force`, `-f`, `--force-with-lease`, `--mirror`, `--all` and `+` refspecs, any target named `main` or `master` (including `HEAD:main` and `:main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` go through.
+- Hook 4 (push guard): matches `git push` after any global options (`git -C push`, `git -c k=v push`), also across a backslash line break, and reads it with quotes removed, so `"main"` counts as `main`. It blocks `--force`, `-f`, `--force-with-lease`, `--mirror`, `--all` and `+` refspecs, any target named `main` or `master` (including `HEAD:main` and `:main`), and, while the current branch is `main`, a push that names no branch. It also blocks a push it cannot read: one containing `$`, a backtick, a backslash or quoted text with spaces, one using `--git-dir`, `--work-tree`, `GIT_DIR=` or `GIT_WORK_TREE=`, and one whose `-C` directory is not a repo. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Text that starts right after a quote is not read as a push: `grep "git push"` goes through, and so does `bash -c "git push ..."`. Tag pushes such as `git push origin v1.2.3` go through.
---
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index 3d2eb3f3..e3343929 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -368,13 +368,43 @@ def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) ->
"cd /x && git push origin main",
"(cd /x && git push origin main)",
"git push origin main;",
+ 'git push origin "main"',
+ "git push origin m''ain",
+ "git push origin 'HEAD:main'",
+ 'git push "--force" origin feat',
+ "git \\\n push --force origin feat",
],
)
def test_push_guard_blocks_force_pushes_and_pushes_to_main(repo: Path, command: str) -> None:
result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
assert result.returncode == 2
- assert "BLOCKED" in result.stderr
+ assert "Direct push to main or force push" in result.stderr
+
+
+@pytest.mark.parametrize(
+ "command",
+ [
+ 'git push origin "$BRANCH"',
+ 'git push -u origin "$(git branch --show-current)"',
+ "git push origin `git branch --show-current`",
+ "\\git push origin feat",
+ "git push origin ma\\in",
+ "git --git-dir=/x/.git push origin feat",
+ "git --work-tree /x push origin feat",
+ "GIT_DIR=/x/.git git push origin feat",
+ "env GIT_WORK_TREE=/x git push origin feat",
+ "git -C /nonexistent/dir push origin feat",
+ 'git -c "user.name=A B" push origin feat',
+ "git -C '/tmp/a b' push origin feat",
+ ],
+)
+def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, command: str) -> None:
+ """Expansions, escapes, quoted spaces, repo overrides and a missing -C dir hide the target."""
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
+
+ assert result.returncode == 2
+ assert "Cannot read this git push" in result.stderr
@pytest.mark.parametrize(
@@ -388,7 +418,13 @@ def test_push_guard_blocks_force_pushes_and_pushes_to_main(repo: Path, command:
"git push origin main-fix",
"git push origin v1.2.3",
"git push origin --delete feat",
+ 'git push origin "feat"',
+ 'git -c "user.name=AB" push origin feat',
+ "git push \\\n origin feat",
+ 'git push origin feat && echo "$?"',
'grep "git push origin main" AGENTS.md',
+ "grep 'git push --force' AGENTS.md",
+ "git commit -F - <<'EOF'\nci: x\n\nThe guard's git push check reads quotes.\nEOF",
],
)
def test_push_guard_allows_feature_and_tag_pushes(repo: Path, command: str) -> None:
@@ -420,14 +456,24 @@ def test_push_guard_on_main_needs_a_named_target(
def test_push_guard_reads_the_branch_of_the_checkout_named_by_dash_c(
main_repo: Path, tmp_path: Path
) -> None:
- worktree = tmp_path.resolve() / "worktree"
+ root = tmp_path.resolve()
+ worktree = root / "worktree"
_git(main_repo, "worktree", "add", "-q", "-b", "feature", str(worktree))
-
- into_main = _run(_PUSH_GUARD_HOOK, _bash(f"git -C {main_repo} push"), worktree)
- into_feature = _run(_PUSH_GUARD_HOOK, _bash(f"git -C {worktree} push"), main_repo)
-
- assert into_main.returncode == 2
- assert into_feature.returncode == 0
+ # Cut at its space, this path would name the feature worktree.
+ on_main_with_space = root / "worktree two"
+ _git(root, "init", "-q", "-b", "main", str(on_main_with_space))
+
+ def push(command: str, cwd: Path) -> int:
+ return _run(_PUSH_GUARD_HOOK, _bash(command), cwd, HOME=str(root)).returncode
+
+ assert push(f"git -C {main_repo} push", worktree) == 2
+ assert push(f'git -C "{main_repo}" push', worktree) == 2
+ assert push(f"git -C {root} -C {main_repo.name} push", worktree) == 2
+ assert push(f"git -C ~/{main_repo.name} push", worktree) == 2
+ assert push(f'git -C "{on_main_with_space}" push', main_repo) == 2
+ assert push(f"git -C {worktree} push", main_repo) == 0
+ assert push(f"git -C {root} -C {worktree.name} push", main_repo) == 0
+ assert push(f"git -C ~/{worktree.name} push", main_repo) == 0
def test_stop_hook_warns_once_about_unfinished_markers(tmp_path: Path) -> None:
From e939b98328513e91a08a2e90352be2cdacdc1666 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 19:18:39 -0500
Subject: [PATCH 08/13] ci: close the push guard's remaining gaps
Some spellings still slipped a push to main or a force push past the
guard: --branches and abbreviated options, heads/main targets, ':'
and '*' refspecs, braces, quotes or backslashes inside the git or
push words, xargs, -c and GIT_CONFIG overrides, and a second push
glued on with ';' and no space.
The guard now reads each push the way the shell would and refuses
the forms it still cannot read. Its loop runs in an explicit
subshell, so an exit inside it means the same under zsh, where the
old code exited 3 with no message and let the push through.
---
.claude/settings.json | 2 +-
AGENTS.md | 5 +-
tests/test_gates/test_claude_hooks_gate.py | 78 +++++++++++++++++-----
3 files changed, 65 insertions(+), 20 deletions(-)
diff --git a/.claude/settings.json b/.claude/settings.json
index e3173e13..347002fb 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -120,7 +120,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | awk '{ if (sub(/\\\\$/, \"\")) printf \"%s\", $0; else print }' | grep -oE '(^|[^[:alnum:]_.\"'\\''-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source)[[:space:]]+(\"[^\"]*\"|'\\''[^'\\'']*'\\''|[^[:space:]]+)|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>]*)?($|[;&|<>)])'); [ -n \"$SEGS\" ] || exit 0; printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '\"[^\"]*[[:space:]][^\"]*\"|'\\''[^'\\'']*[[:space:]][^'\\'']*'\\''' && exit 3; S=$(printf '%s\\n' \"$S\" | tr -d '\\042\\047'); printf '%s\\n' \"$S\" | grep -qE '[[:space:]](--force(-with-lease)?|--mirror|--all|-[[:alnum:]]*f[[:alnum:]]*)([=[:space:]]|$|[;&|<>)])|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)(refs/heads/)?(main|master)([[:space:]]|$|[;&|<>)])' && exit 2; case \"$S\" in *\\$*|*'`'*|*'\\'*|*--git-dir*|*--work-tree*) exit 3 ;; esac; case \"$CMD\" in *GIT_DIR=*|*GIT_WORK_TREE=*) exit 3 ;; esac; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"push\") break; if ($i == \"-C\" && i < NF) { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v } }; print d }'); [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 3; REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[;&|<>)]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j == \"-o\" || $j == \"--push-option\" || $j == \"--repo\" || $j == \"--receive-pack\" || $j == \"--exec\") { j++; continue }; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \"\"|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && case \"$S\" in *--tags*) ;; *) exit 2 ;; esac ;; esac; :; done; case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: Cannot read this git push. Write the branch and any -C directory out literally, without $, backticks, backslashes, quoted spaces, --git-dir, --work-tree, GIT_DIR or GIT_WORK_TREE.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | awk '{ if (sub(/\\\\$/, \"\")) printf \"%s\", $0; else print }' | sed -E 's/\\\\//g; s/\\$([\"'\\''])/\\1/g; s/\"([^\"[:space:]]*)\"/\\1/g; s/'\\''([^'\\''[:space:]]*)'\\''/\\1/g; s/[;&|()]/& /g' | grep -oE '(^|[^[:alnum:]_.\"'\\''-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source)[[:space:]]+(\"[^\"]*\"|'\\''[^'\\'']*'\\''|[^[:space:]]+)|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>]*)?($|[;&|<>)])'); [ -n \"$SEGS\" ] || exit 0; (printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '\"[^\"]*[[:space:]][^\"]*\"|'\\''[^'\\'']*[[:space:]][^'\\'']*'\\''' && exit 3; printf '%s\\n' \"$S\" | grep -qE '[[:space:]]-[[:alnum:]]*f[[:alnum:]]*([=[:space:]]|$|[;&|<>)])|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)((refs/)?heads/)?(main|master)([[:space:]]|$|[;&|<>)])' && exit 2; printf '%s\\n' \"$S\" | awk '{ for (i = 1; i <= NF; i++) { t = $i; sub(/=.*/, \"\", t); if (t ~ /^--[a-z]/ && (index(\"--all\", t) == 1 || index(\"--branches\", t) == 1 || index(\"--mirror\", t) == 1 || index(\"--force-with-lease\", t) == 1)) b = 1 } } END { exit !b }' && exit 2; case \"$S\" in *\\$*|*'`'*|*[{}]*|*--git-dir*|*--work-tree*) exit 3 ;; esac; printf '%s\\n' \"$S\" | grep -qE '[[:space:]](-c|--config-env)([[:space:]=]|$)' && exit 3; case \"$CMD\" in *GIT_DIR=*|*GIT_WORK_TREE=*|*GIT_CONFIG*|*xargs*|*\\$\\'*|*\\$\\\"*) exit 3 ;; esac; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"push\") break; if ($i == \"-C\" && i < NF) { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v } }; print d }'); [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 3; REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[;&|<>)]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j ~ /^-[^-]*o$/ || ($j ~ /^--[a-z][^=]*$/ && (index(\"--push-option\", $j) == 1 || index(\"--repo\", $j) == 1 || index(\"--receive-pack\", $j) == 1 || index(\"--exec\", $j) == 1 || index(\"--recurse-submodules\", $j) == 1))) { j++; continue }; if ($j == \"--tags\") print $j; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \":\"|*\\**) exit 2 ;; \"\"|--tags|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && exit 2 ;; esac; :; done); case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: Cannot read this git push. Write the branch and any -C directory out literally, with no $, backticks, braces, quoted spaces, -c, --config-env, --git-dir, --work-tree, GIT_DIR, GIT_WORK_TREE, GIT_CONFIG or xargs.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
}
]
},
diff --git a/AGENTS.md b/AGENTS.md
index d1ce8634..c1d72a98 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -459,7 +459,7 @@ Do not use Bash to write files as a workaround when a hook blocks an action. If
- Hook 5 blocks a file edit on main: create a feature branch (`git checkout -b type/slug`) and make the edit there. From a worktree, edit the worktree's copy of the file instead.
- Hook 6 blocks a commit: run `just fix` (or `just fmt-check` to see the diff first), `git add` the fixed files that belong in the commit, then retry the commit.
- Hook 3 blocks `rm -rf`: use a more specific path instead of a dangerous wildcard target.
-- Hook 4 blocks a git push: you are pushing to main, force-pushing, pushing from `main` without naming a branch, or the hook cannot read where the push goes. Push to a feature branch, with its name written out (`git push -u origin `), and open a PR instead.
+- Hook 4 blocks a git push: you are pushing to main, force-pushing, pushing from `main` without naming a branch, or the hook cannot read where the push goes. Push to a feature branch, with its name written out (`git push -u origin `), and open a PR instead. If the block comes from commit or PR text that mentions `git push`, pass the text from a file (`git commit -F `, `gh pr create --body-file `).
In every case: fix the underlying issue, do not bypass the hook.
@@ -469,7 +469,8 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
-- Hook 4 (push guard): matches `git push` after any global options (`git -C push`, `git -c k=v push`), also across a backslash line break, and reads it with quotes removed, so `"main"` counts as `main`. It blocks `--force`, `-f`, `--force-with-lease`, `--mirror`, `--all` and `+` refspecs, any target named `main` or `master` (including `HEAD:main` and `:main`), and, while the current branch is `main`, a push that names no branch. It also blocks a push it cannot read: one containing `$`, a backtick, a backslash or quoted text with spaces, one using `--git-dir`, `--work-tree`, `GIT_DIR=` or `GIT_WORK_TREE=`, and one whose `-C` directory is not a repo. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Text that starts right after a quote is not read as a push: `grep "git push"` goes through, and so does `bash -c "git push ..."`. Tag pushes such as `git push origin v1.2.3` go through.
+- Hook 4 (push guard): reads each `git push` the way the shell would: after git's global options (`git -C push`, `git -c k=v push`), across backslash line breaks, after `;`, `&` or `|` with no space, and with quotes and backslashes inside words removed, so `"main"`, `m''ain`, `g''it` and `p\ush` all count. It blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` and `*` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push it cannot read: one containing `$`, a backtick, braces or quoted text with spaces, one using `-c`, `--config-env`, `--git-dir` or `--work-tree`, one in a command that sets `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` or uses `xargs`, and one whose `-C` directory is not a repo.
+- Hook 4 limits: it catches mistakes, not deliberate evasion. A push through a git alias, a script, `eval` or a quoted `bash -c "..."` string is not seen; text that starts right after a quote is not read as a push, so `grep "git push"` goes through. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Commit or PR text that mentions `git push` with arguments can still be read as a push; pass it from a file.
---
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index e3343929..f231169d 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -65,13 +65,16 @@ def _hook(event: str, marker: str) -> str:
_UNFORMATTED_MD = "# Notes\n\n```python\nx=1\n```\n"
+# Claude Code runs a hook command through bash or the user's $SHELL, and sh is dash on Linux.
+_SHELLS = [shell for shell in ("bash", "sh", "zsh") if shutil.which(shell)]
+
def _run(
- command: str, payload: dict[str, Any], cwd: Path, **env: str
+ command: str, payload: dict[str, Any], cwd: Path, shell: str = "bash", **env: str
) -> subprocess.CompletedProcess[str]:
- """Run a hook command the way Claude Code does: bash, JSON on stdin, Claude's directory."""
+ """Run a hook command the way Claude Code does: a shell, JSON on stdin, Claude's directory."""
return subprocess.run(
- ["bash", "-c", command],
+ [shell, "-c", command],
input=json.dumps(payload),
capture_output=True,
text=True,
@@ -108,6 +111,11 @@ def repo(tmp_path: Path) -> Path:
return root
+@pytest.fixture(params=_SHELLS)
+def shell(request: pytest.FixtureRequest) -> str:
+ return str(request.param)
+
+
@pytest.fixture()
def main_repo(repo: Path) -> Path:
"""The repo with one commit on main, so a worktree can branch from it."""
@@ -373,10 +381,27 @@ def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) ->
"git push origin 'HEAD:main'",
'git push "--force" origin feat',
"git \\\n push --force origin feat",
+ "git push origin ma\\in",
+ "git push origin feat;git push origin main",
+ "git push origin feat&git push --force",
+ "git push --branches origin",
+ "git push --force-w origin feat",
+ "git push --mirro",
+ "git push --al origin",
+ "git push origin feat:heads/main",
+ "git push origin HEAD:refs/heads/main",
+ "git push origin :",
+ "git push origin 'refs/heads/*'",
+ "g''it push origin main",
+ 'git "push" origin main',
+ "git p\\ush --force origin feat",
+ "git $'push' --force origin feat",
],
)
-def test_push_guard_blocks_force_pushes_and_pushes_to_main(repo: Path, command: str) -> None:
- result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
+def test_push_guard_blocks_force_pushes_and_pushes_to_main(
+ repo: Path, shell: str, command: str
+) -> None:
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell)
assert result.returncode == 2
assert "Direct push to main or force push" in result.stderr
@@ -388,8 +413,6 @@ def test_push_guard_blocks_force_pushes_and_pushes_to_main(repo: Path, command:
'git push origin "$BRANCH"',
'git push -u origin "$(git branch --show-current)"',
"git push origin `git branch --show-current`",
- "\\git push origin feat",
- "git push origin ma\\in",
"git --git-dir=/x/.git push origin feat",
"git --work-tree /x push origin feat",
"GIT_DIR=/x/.git git push origin feat",
@@ -397,11 +420,18 @@ def test_push_guard_blocks_force_pushes_and_pushes_to_main(repo: Path, command:
"git -C /nonexistent/dir push origin feat",
'git -c "user.name=A B" push origin feat',
"git -C '/tmp/a b' push origin feat",
+ 'git -c "user.name=AB" push origin feat',
+ "git push origin {main,feat}",
+ "echo main | xargs git push origin",
+ "git -c push.default=matching push",
+ "X=matching git --config-env=push.default=X push",
+ "GIT_CONFIG_PARAMETERS=\"'push.default=matching'\" git push",
+ "git push origin $'\\x6dain'",
],
)
-def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, command: str) -> None:
- """Expansions, escapes, quoted spaces, repo overrides and a missing -C dir hide the target."""
- result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
+def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, shell: str, command: str) -> None:
+ """Expansions, quoted spaces, overrides, xargs and a missing -C dir hide where it goes."""
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell)
assert result.returncode == 2
assert "Cannot read this git push" in result.stderr
@@ -419,16 +449,20 @@ def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, command: str) -> No
"git push origin v1.2.3",
"git push origin --delete feat",
'git push origin "feat"',
- 'git -c "user.name=AB" push origin feat',
+ "\\git push origin feat",
+ "git push -o ci.skip origin feat",
+ "git push --follow-tags origin feat",
+ "git push --force-if-includes origin feat",
"git push \\\n origin feat",
'git push origin feat && echo "$?"',
'grep "git push origin main" AGENTS.md',
"grep 'git push --force' AGENTS.md",
+ 'git commit -m "docs: explain git push origin main"',
"git commit -F - <<'EOF'\nci: x\n\nThe guard's git push check reads quotes.\nEOF",
],
)
-def test_push_guard_allows_feature_and_tag_pushes(repo: Path, command: str) -> None:
- assert _run(_PUSH_GUARD_HOOK, _bash(command), repo).returncode == 0
+def test_push_guard_allows_feature_and_tag_pushes(repo: Path, shell: str, command: str) -> None:
+ assert _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell).returncode == 0
@pytest.mark.parametrize(
@@ -441,20 +475,30 @@ def test_push_guard_allows_feature_and_tag_pushes(repo: Path, command: str) -> N
("git push origin heads/main", 2),
("git push --tags origin HEAD", 2),
("git push --follow-tags", 2),
+ ("git push -o ci.skip origin", 2),
+ ("git push -uo ci.skip origin", 2),
+ ("git push -o note=--tags", 2),
+ ('git push -o "a b" origin', 2),
+ ("git push --push-o ci.skip origin", 2),
+ ("git push --recu check origin", 2),
+ ("git push --recurse-submodules check origin", 2),
+ ("git push origin :", 2),
("git push origin v1.2.3", 0),
("git push --tags", 0),
("git push origin feat", 0),
],
)
def test_push_guard_on_main_needs_a_named_target(
- main_repo: Path, command: str, expected: int
+ main_repo: Path, shell: str, command: str, expected: int
) -> None:
"""On main, a push that names no branch, or names the current one, pushes main."""
- assert _run(_PUSH_GUARD_HOOK, _bash(command), main_repo).returncode == expected
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), main_repo, shell=shell)
+
+ assert result.returncode == expected
def test_push_guard_reads_the_branch_of_the_checkout_named_by_dash_c(
- main_repo: Path, tmp_path: Path
+ main_repo: Path, tmp_path: Path, shell: str
) -> None:
root = tmp_path.resolve()
worktree = root / "worktree"
@@ -464,7 +508,7 @@ def test_push_guard_reads_the_branch_of_the_checkout_named_by_dash_c(
_git(root, "init", "-q", "-b", "main", str(on_main_with_space))
def push(command: str, cwd: Path) -> int:
- return _run(_PUSH_GUARD_HOOK, _bash(command), cwd, HOME=str(root)).returncode
+ return _run(_PUSH_GUARD_HOOK, _bash(command), cwd, shell=shell, HOME=str(root)).returncode
assert push(f"git -C {main_repo} push", worktree) == 2
assert push(f'git -C "{main_repo}" push', worktree) == 2
From 86e66d4892d5e3889e8adf9349b09682f8ab53b4 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 20:50:59 -0500
Subject: [PATCH 09/13] ci: tokenize commands in the push guard
The push guard matched shell text with sed and grep, so an operator
glued to a word could hide a flag or a target: git push --force; git
log, (git push origin HEAD) from main, and git push origin 2>&1 from
main all went through.
It now splits each line into simple commands the way the shell does,
at operators, parentheses and substitutions with or without spaces
around them, drops redirections and comments, and checks every push on
its own. A command substitution is checked as a command of its own,
and quoted text stays one word, so a commit message that mentions a
push is no longer read as one.
The guard also stops reading -ofoo as -f, stops refusing a push because
another command on the line ends a pattern in $, sees GIT and
--shallow-file, and refuses a push with a quoted or escaped shell
operator in it.
---
.claude/settings.json | 2 +-
AGENTS.md | 4 +-
tests/test_gates/test_claude_hooks_gate.py | 91 ++++++++++++++++++++--
3 files changed, 89 insertions(+), 8 deletions(-)
diff --git a/.claude/settings.json b/.claude/settings.json
index 347002fb..86a99ca4 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -120,7 +120,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | awk '{ if (sub(/\\\\$/, \"\")) printf \"%s\", $0; else print }' | sed -E 's/\\\\//g; s/\\$([\"'\\''])/\\1/g; s/\"([^\"[:space:]]*)\"/\\1/g; s/'\\''([^'\\''[:space:]]*)'\\''/\\1/g; s/[;&|()]/& /g' | grep -oE '(^|[^[:alnum:]_.\"'\\''-])git([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source)[[:space:]]+(\"[^\"]*\"|'\\''[^'\\'']*'\\''|[^[:space:]]+)|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>]*)?($|[;&|<>)])'); [ -n \"$SEGS\" ] || exit 0; (printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '\"[^\"]*[[:space:]][^\"]*\"|'\\''[^'\\'']*[[:space:]][^'\\'']*'\\''' && exit 3; printf '%s\\n' \"$S\" | grep -qE '[[:space:]]-[[:alnum:]]*f[[:alnum:]]*([=[:space:]]|$|[;&|<>)])|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)((refs/)?heads/)?(main|master)([[:space:]]|$|[;&|<>)])' && exit 2; printf '%s\\n' \"$S\" | awk '{ for (i = 1; i <= NF; i++) { t = $i; sub(/=.*/, \"\", t); if (t ~ /^--[a-z]/ && (index(\"--all\", t) == 1 || index(\"--branches\", t) == 1 || index(\"--mirror\", t) == 1 || index(\"--force-with-lease\", t) == 1)) b = 1 } } END { exit !b }' && exit 2; case \"$S\" in *\\$*|*'`'*|*[{}]*|*--git-dir*|*--work-tree*) exit 3 ;; esac; printf '%s\\n' \"$S\" | grep -qE '[[:space:]](-c|--config-env)([[:space:]=]|$)' && exit 3; case \"$CMD\" in *GIT_DIR=*|*GIT_WORK_TREE=*|*GIT_CONFIG*|*xargs*|*\\$\\'*|*\\$\\\"*) exit 3 ;; esac; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"push\") break; if ($i == \"-C\" && i < NF) { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v } }; print d }'); [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 3; REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[;&|<>)]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j ~ /^-[^-]*o$/ || ($j ~ /^--[a-z][^=]*$/ && (index(\"--push-option\", $j) == 1 || index(\"--repo\", $j) == 1 || index(\"--receive-pack\", $j) == 1 || index(\"--exec\", $j) == 1 || index(\"--recurse-submodules\", $j) == 1))) { j++; continue }; if ($j == \"--tags\") print $j; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \":\"|*\\**) exit 2 ;; \"\"|--tags|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && exit 2 ;; esac; :; done); case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: Cannot read this git push. Write the branch and any -C directory out literally, with no $, backticks, braces, quoted spaces, -c, --config-env, --git-dir, --work-tree, GIT_DIR, GIT_WORK_TREE, GIT_CONFIG or xargs.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | awk 'function fl() { if (iw) { if (sk) sk = 0; else { gsub(/[[:space:];&|()<>]/, \"$\", w); ob[f] = ob[f] \" \" w } }; w = \"\"; iw = 0; wq = 0 } function op(t) { fl(); sk = 0; ob[f] = ob[f] \" \" t } function fo(b) { f++; fw[f] = w \"$\"; fk[f] = sk; fq[f] = q; fp[f] = 0; fb[f] = b; ob[f] = \"\"; w = \"\"; iw = 0; wq = 0; sk = 0; q = \"\" } function fc() { fl(); print ob[f]; q = fq[f]; w = fw[f]; sk = fk[f]; f--; iw = 1 } function lx(s, n, i, c, d) { ob[0] = \"\"; w = \"\"; iw = 0; wq = 0; sk = 0; q = \"\"; f = 0; n = length(s); for (i = 1; i <= n; i++) { c = substr(s, i, 1); d = substr(s, i + 1, 1); if (q == \"s\") { if (c == sq) q = \"\"; else w = w c; continue }; if (q == \"a\") { if (c == bs) { w = w \"$\"; i++ } else if (c == sq) q = \"\"; else w = w c; continue }; if (q == \"d\" && c == dq) { q = \"\"; continue }; if (q == \"d\" && c == bs) { if (d != \"\" && index(\"$\" bq dq bs, d)) { w = w d; i++ } else w = w c; continue }; if (c == \"$\" && d == \"(\") { i++; fo(0); continue }; if (c == bq) { if (f && fb[f] && q == \"\") fc(); else fo(1); continue }; if (q == \"d\") { w = w c; continue }; if (c == \" \" || c == \"\\t\") { fl(); continue }; if (c == bs) { if (d != \"\") { w = w d; i++; iw = 1; wq = 1 }; continue }; if (c == sq || c == dq) { q = (c == sq) ? \"s\" : \"d\"; iw = 1; wq = 1; continue }; if (c == \"$\" && (d == sq || d == dq)) { q = (d == sq) ? \"a\" : \"d\"; iw = 1; wq = 1; i++; continue }; if (c == \"#\" && !iw) break; if (c == \"<\" || c == \">\") { if (iw && !wq && w ~ /^[0-9]+$/) { w = \"\"; iw = 0 } else fl(); while (d == \"<\" || d == \">\") { i++; d = substr(s, i + 1, 1) }; if (d == \"&\" || d == \"|\" || d == \"-\") { i++; d = substr(s, i + 1, 1) }; if (d == \"(\") { i++; fo(0) } else sk = 1; continue }; if (c == \";\" || c == \"&\" || c == \"|\") { op(c); continue }; if (c == \"(\") { op(c); if (f) fp[f]++; continue }; if (c == \")\") { if (f && !fb[f] && !fp[f]) { fc(); continue }; if (f && fp[f]) fp[f]--; op(c); continue }; w = w c; iw = 1 }; while (f > 0) fc(); fl(); print ob[0] } BEGIN { sq = sprintf(\"%c\", 39); dq = sprintf(\"%c\", 34); bs = sprintf(\"%c\", 92); bq = sprintf(\"%c\", 96) } { if (sub(/\\\\$/, \"\")) { b = b $0; next }; lx(b $0); b = \"\" } END { if (b != \"\") lx(b) }' | grep -oE '(^|[^[:alnum:]_.$\"-])[Gg][Ii][Tt]([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source|--shallow-file)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>()]*)?($|[;&|<>()])'); [ -n \"$SEGS\" ] || exit 0; (printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '[[:space:]]-[vqdnu46]*f|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)((refs/)?heads/)?(main|master)([[:space:]]|$|[;&|<>()])' && exit 2; printf '%s\\n' \"$S\" | awk '{ for (i = 1; i <= NF; i++) { t = $i; sub(/=.*/, \"\", t); if (t ~ /^--[a-z]/ && (index(\"--all\", t) == 1 || index(\"--branches\", t) == 1 || index(\"--mirror\", t) == 1 || index(\"--force-with-lease\", t) == 1)) b = 1 } } END { exit !b }' && exit 2; case \"$S\" in *\\$*|*[{}]*|*--git-dir*|*--work-tree*) exit 3 ;; esac; printf '%s\\n' \"$S\" | grep -qE '[[:space:]](-c|--config-env)([[:space:]=]|$)' && exit 3; case \"$CMD\" in *GIT_DIR=*|*GIT_WORK_TREE=*|*GIT_CONFIG*|*xargs*) exit 3 ;; esac; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"push\") break; if ($i == \"-C\" && i < NF) { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v } }; print d }'); [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 3; REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[[:space:];&|<>()]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j ~ /^-[vqdnfu46]*o$/ || ($j ~ /^--[a-z][^=]*$/ && (index(\"--push-option\", $j) == 1 || index(\"--repo\", $j) == 1 || index(\"--receive-pack\", $j) == 1 || index(\"--exec\", $j) == 1 || index(\"--recurse-submodules\", $j) == 1))) { j++; continue }; if ($j == \"--tags\") print $j; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \":\"|*\\**) exit 2 ;; \"\"|--tags|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && exit 2 ;; esac; :; done); case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: Cannot read this git push. Write the branch and any -C directory out literally, with no $, backticks, braces, quoted spaces or shell operators, -c, --config-env, --git-dir, --work-tree, GIT_DIR, GIT_WORK_TREE, GIT_CONFIG or xargs.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
}
]
},
diff --git a/AGENTS.md b/AGENTS.md
index c1d72a98..0a1b3c33 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -469,8 +469,8 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
-- Hook 4 (push guard): reads each `git push` the way the shell would: after git's global options (`git -C push`, `git -c k=v push`), across backslash line breaks, after `;`, `&` or `|` with no space, and with quotes and backslashes inside words removed, so `"main"`, `m''ain`, `g''it` and `p\ush` all count. It blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` and `*` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push it cannot read: one containing `$`, a backtick, braces or quoted text with spaces, one using `-c`, `--config-env`, `--git-dir` or `--work-tree`, one in a command that sets `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` or uses `xargs`, and one whose `-C` directory is not a repo.
-- Hook 4 limits: it catches mistakes, not deliberate evasion. A push through a git alias, a script, `eval` or a quoted `bash -c "..."` string is not seen; text that starts right after a quote is not read as a push, so `grep "git push"` goes through. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Commit or PR text that mentions `git push` with arguments can still be read as a push; pass it from a file.
+- Hook 4 (push guard): splits the command into simple commands the way the shell does: at newlines, `;`, `&`, `|`, parentheses, `$(...)` and backticks, whether or not spaces surround them, after joining backslash line breaks. It drops redirections such as `2>&1` and comments, and removes quotes and backslashes inside words, so `"main"`, `m''ain`, `g''it`, `p\ush` and `$'push'` all count. Text inside quotes is never read as a command, except `$(...)` and backticks inside double quotes, which the shell runs. In each `git push`, after git's global options (`git -C push`, `git -c k=v push`), it blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` and `*` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push it cannot read: one whose words hold an expansion (`$`, a backtick), braces, or a quoted or escaped space or shell operator, one using `-c`, `--config-env`, `--git-dir` or `--work-tree`, one in a command that sets `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` or uses `xargs`, and one whose `-C` directory is not a repo.
+- Hook 4 limits: it catches mistakes, not deliberate evasion. It only sees `git` and `push` written out as words, so a push through a git alias, a shell alias or function, a script, `eval`, a quoted `bash -c "..."` string, a `git` or `push` word built from an expansion (`"$GIT" push`), or another command that pushes (`git subtree push`, `git send-pack`) is not seen. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Heredoc and unquoted text that mention `git push` with arguments can still be read as a push; pass commit and PR text from a file.
---
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index f231169d..80eb1023 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -4,10 +4,10 @@
``tool_input.command``, ``last_assistant_message``) and sets no file-path
environment variable. The edit hooks in ``.claude/settings.json`` once looped
over an unset ``$CLAUDE_FILE_PATHS`` and silently did nothing (#868), and
-nothing in the suite ran them. These tests run each hook command under bash
-with that JSON, inside a throwaway git repo whose ``.venv`` links to the
-environment running pytest, and check the hook acceptance criteria of #867 and
-#868.
+nothing in the suite ran them. These tests run each hook command with that
+JSON, inside a throwaway git repo whose ``.venv`` links to the environment
+running pytest, and check the hook acceptance criteria of #867 and #868. Most
+push guard cases also run under every shell in ``_SHELLS``.
"""
from __future__ import annotations
@@ -65,9 +65,37 @@ def _hook(event: str, marker: str) -> str:
_UNFORMATTED_MD = "# Notes\n\n```python\nx=1\n```\n"
-# Claude Code runs a hook command through bash or the user's $SHELL, and sh is dash on Linux.
+# The hooks reference runs shell-form hooks with sh -c (dash on Ubuntu), and the settings
+# schema says its default bash shell means $SHELL when that is bash, zsh or sh.
_SHELLS = [shell for shell in ("bash", "sh", "zsh") if shutil.which(shell)]
+# Places an agent's command often puts a push, with the operators glued on.
+_SHELL_WRAPPERS = [
+ "CMD",
+ "CMD;echo ok",
+ "CMD&&echo ok",
+ "CMD||echo failed",
+ "CMD|tail -1",
+ "CMD|&tee log",
+ "CMD&",
+ "CMD>/dev/null",
+ "CMD 2>&1",
+ "CMD &>/dev/null",
+ "(CMD)",
+ "out=$(CMD)",
+ 'out="$(CMD 2>&1)"',
+ "x=`CMD`",
+ "if CMD;then echo ok;fi",
+ "{ CMD;}",
+ "true;CMD",
+ "true&&CMD",
+ "CMD # note",
+]
+
+
+def _wrapped(*commands: str) -> list[str]:
+ return [wrapper.replace("CMD", command) for command in commands for wrapper in _SHELL_WRAPPERS]
+
def _run(
command: str, payload: dict[str, Any], cwd: Path, shell: str = "bash", **env: str
@@ -396,6 +424,12 @@ def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) ->
'git "push" origin main',
"git p\\ush --force origin feat",
"git $'push' --force origin feat",
+ "git push --repo 'x;' origin main",
+ "git push --repo x\\; origin main",
+ "GIT push --force",
+ "git --shallow-file /dev/null push origin main",
+ 'echo "$(git log -1)" && git push --force',
+ 'x="$( (true) && git push --force )"',
],
)
def test_push_guard_blocks_force_pushes_and_pushes_to_main(
@@ -427,6 +461,9 @@ def test_push_guard_blocks_force_pushes_and_pushes_to_main(
"X=matching git --config-env=push.default=X push",
"GIT_CONFIG_PARAMETERS=\"'push.default=matching'\" git push",
"git push origin $'\\x6dain'",
+ "git push -o 'a;b' origin feat",
+ 'git -C "$(pwd)" push origin feat',
+ "git push origin $(\n echo main\n)",
],
)
def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, shell: str, command: str) -> None:
@@ -459,6 +496,9 @@ def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, shell: str, command
"grep 'git push --force' AGENTS.md",
'git commit -m "docs: explain git push origin main"',
"git commit -F - <<'EOF'\nci: x\n\nThe guard's git push check reads quotes.\nEOF",
+ "git push origin feat 2>&1 | grep -v '^$'",
+ "git push -ofoo origin feat",
+ "git push -u origin feat # not main",
],
)
def test_push_guard_allows_feature_and_tag_pushes(repo: Path, shell: str, command: str) -> None:
@@ -483,6 +523,8 @@ def test_push_guard_allows_feature_and_tag_pushes(repo: Path, shell: str, comman
("git push --recu check origin", 2),
("git push --recurse-submodules check origin", 2),
("git push origin :", 2),
+ ("git push origin 2>&1", 2),
+ ("git push -otodo origin HEAD feat", 2),
("git push origin v1.2.3", 0),
("git push --tags", 0),
("git push origin feat", 0),
@@ -520,6 +562,45 @@ def push(command: str, cwd: Path) -> int:
assert push(f"git -C ~/{worktree.name} push", main_repo) == 0
+# The wrappers change only the text the hook reads, so these cases run under bash alone.
+@pytest.mark.parametrize(
+ "command",
+ _wrapped(
+ "git push --force",
+ "git push --force-with-lease",
+ "git push -f origin feat",
+ "git push --all",
+ "git push --mirror",
+ "git push --branches",
+ "git push origin main",
+ "git push origin HEAD:main",
+ "git push origin +feat",
+ "git push origin :",
+ ),
+)
+def test_push_guard_blocks_pushes_wrapped_in_shell_syntax(repo: Path, command: str) -> None:
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
+
+ assert result.returncode == 2
+ assert "Direct push to main or force push" in result.stderr
+
+
+@pytest.mark.parametrize(
+ "command",
+ _wrapped("git push", "git push origin", "git push -u origin HEAD", "git push origin @"),
+)
+def test_push_guard_blocks_wrapped_pushes_of_main(main_repo: Path, command: str) -> None:
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), main_repo)
+
+ assert result.returncode == 2
+ assert "Direct push to main or force push" in result.stderr
+
+
+@pytest.mark.parametrize("command", _wrapped("git push origin feat", "git push -u origin HEAD"))
+def test_push_guard_allows_wrapped_feature_pushes(repo: Path, command: str) -> None:
+ assert _run(_PUSH_GUARD_HOOK, _bash(command), repo).returncode == 0
+
+
def test_stop_hook_warns_once_about_unfinished_markers(tmp_path: Path) -> None:
def stop(message: str, *, active: bool) -> subprocess.CompletedProcess[str]:
payload = {"stop_hook_active": active, "last_assistant_message": message}
From 8565951bb2e151f6c085bc54ffd316403d7f0948 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 20:52:10 -0500
Subject: [PATCH 10/13] docs: note the push guard reads line by line
Quoted text on a line is never read as a push, but the guard reads one
line at a time, so the later lines of a multi-line quoted message can
still be.
---
AGENTS.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 0a1b3c33..1317f16c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -469,8 +469,8 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
-- Hook 4 (push guard): splits the command into simple commands the way the shell does: at newlines, `;`, `&`, `|`, parentheses, `$(...)` and backticks, whether or not spaces surround them, after joining backslash line breaks. It drops redirections such as `2>&1` and comments, and removes quotes and backslashes inside words, so `"main"`, `m''ain`, `g''it`, `p\ush` and `$'push'` all count. Text inside quotes is never read as a command, except `$(...)` and backticks inside double quotes, which the shell runs. In each `git push`, after git's global options (`git -C push`, `git -c k=v push`), it blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` and `*` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push it cannot read: one whose words hold an expansion (`$`, a backtick), braces, or a quoted or escaped space or shell operator, one using `-c`, `--config-env`, `--git-dir` or `--work-tree`, one in a command that sets `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` or uses `xargs`, and one whose `-C` directory is not a repo.
-- Hook 4 limits: it catches mistakes, not deliberate evasion. It only sees `git` and `push` written out as words, so a push through a git alias, a shell alias or function, a script, `eval`, a quoted `bash -c "..."` string, a `git` or `push` word built from an expansion (`"$GIT" push`), or another command that pushes (`git subtree push`, `git send-pack`) is not seen. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Heredoc and unquoted text that mention `git push` with arguments can still be read as a push; pass commit and PR text from a file.
+- Hook 4 (push guard): splits the command into simple commands the way the shell does: at newlines, `;`, `&`, `|`, parentheses, `$(...)` and backticks, whether or not spaces surround them, after joining backslash line breaks. It drops redirections such as `2>&1` and comments, and removes quotes and backslashes inside words, so `"main"`, `m''ain`, `g''it`, `p\ush` and `$'push'` all count. It reads one line at a time, and within a line quoted text is never read as a command, except `$(...)` and backticks inside double quotes, which the shell runs. In each `git push`, after git's global options (`git -C push`, `git -c k=v push`), it blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` and `*` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push it cannot read: one whose words hold an expansion (`$`, a backtick), braces, or a quoted or escaped space or shell operator, one using `-c`, `--config-env`, `--git-dir` or `--work-tree`, one in a command that sets `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` or uses `xargs`, and one whose `-C` directory is not a repo.
+- Hook 4 limits: it catches mistakes, not deliberate evasion. It only sees `git` and `push` written out as words, so a push through a git alias, a shell alias or function, a script, `eval`, a quoted `bash -c "..."` string, a `git` or `push` word built from an expansion (`"$GIT" push`), or another command that pushes (`git subtree push`, `git send-pack`) is not seen. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Heredoc text, unquoted text and the later lines of a multi-line quoted message that mention `git push` with arguments can still be read as a push; pass commit and PR text from a file.
---
From 596a00d24d4555ec313f36fc74ef47843b027b4b Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Tue, 10 Nov 2026 23:51:20 -0500
Subject: [PATCH 11/13] ci: accept only plain pushes in the push guard
The guard read shell syntax line by line, so a push that followed a
multi-line quoted string got through, such as a heredoc commit message
chained with && git push. A checkout earlier in the same command also
made the on-main check read the wrong branch. Patching the parser kept
opening gaps like these.
Any command that mentions git push is now refused unless the whole
command is one plain git push line, which keeps the existing checks.
The refusal message says how to run the push, or to pass text that
spells out git push from a file. The release steps and /bump show the
tag push as its own command.
---
.agents/skills/bump/SKILL.md | 2 +-
.claude/settings.json | 2 +-
AGENTS.md | 9 +-
tests/test_gates/test_claude_hooks_gate.py | 172 ++++++++++++---------
4 files changed, 109 insertions(+), 76 deletions(-)
diff --git a/.agents/skills/bump/SKILL.md b/.agents/skills/bump/SKILL.md
index d8139aaa..0ab9b3ed 100644
--- a/.agents/skills/bump/SKILL.md
+++ b/.agents/skills/bump/SKILL.md
@@ -101,7 +101,7 @@ git push -u origin HEAD
gh pr create --title "chore: bump version to X.Y.Z" --body "..."
```
-After merge, remind the user to run `git tag vX.Y.Z && git push origin vX.Y.Z` to trigger docker.yml, release.yml, and chart.yml.
+After merge, remind the user to run `git tag vX.Y.Z` and then `git push origin vX.Y.Z` to trigger docker.yml, release.yml, and chart.yml.
## 11. Verify the Tag Push
diff --git a/.claude/settings.json b/.claude/settings.json
index 86a99ca4..f1fa8273 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -120,7 +120,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); SEGS=$(printf '%s\\n' \"$CMD\" | awk 'function fl() { if (iw) { if (sk) sk = 0; else { gsub(/[[:space:];&|()<>]/, \"$\", w); ob[f] = ob[f] \" \" w } }; w = \"\"; iw = 0; wq = 0 } function op(t) { fl(); sk = 0; ob[f] = ob[f] \" \" t } function fo(b) { f++; fw[f] = w \"$\"; fk[f] = sk; fq[f] = q; fp[f] = 0; fb[f] = b; ob[f] = \"\"; w = \"\"; iw = 0; wq = 0; sk = 0; q = \"\" } function fc() { fl(); print ob[f]; q = fq[f]; w = fw[f]; sk = fk[f]; f--; iw = 1 } function lx(s, n, i, c, d) { ob[0] = \"\"; w = \"\"; iw = 0; wq = 0; sk = 0; q = \"\"; f = 0; n = length(s); for (i = 1; i <= n; i++) { c = substr(s, i, 1); d = substr(s, i + 1, 1); if (q == \"s\") { if (c == sq) q = \"\"; else w = w c; continue }; if (q == \"a\") { if (c == bs) { w = w \"$\"; i++ } else if (c == sq) q = \"\"; else w = w c; continue }; if (q == \"d\" && c == dq) { q = \"\"; continue }; if (q == \"d\" && c == bs) { if (d != \"\" && index(\"$\" bq dq bs, d)) { w = w d; i++ } else w = w c; continue }; if (c == \"$\" && d == \"(\") { i++; fo(0); continue }; if (c == bq) { if (f && fb[f] && q == \"\") fc(); else fo(1); continue }; if (q == \"d\") { w = w c; continue }; if (c == \" \" || c == \"\\t\") { fl(); continue }; if (c == bs) { if (d != \"\") { w = w d; i++; iw = 1; wq = 1 }; continue }; if (c == sq || c == dq) { q = (c == sq) ? \"s\" : \"d\"; iw = 1; wq = 1; continue }; if (c == \"$\" && (d == sq || d == dq)) { q = (d == sq) ? \"a\" : \"d\"; iw = 1; wq = 1; i++; continue }; if (c == \"#\" && !iw) break; if (c == \"<\" || c == \">\") { if (iw && !wq && w ~ /^[0-9]+$/) { w = \"\"; iw = 0 } else fl(); while (d == \"<\" || d == \">\") { i++; d = substr(s, i + 1, 1) }; if (d == \"&\" || d == \"|\" || d == \"-\") { i++; d = substr(s, i + 1, 1) }; if (d == \"(\") { i++; fo(0) } else sk = 1; continue }; if (c == \";\" || c == \"&\" || c == \"|\") { op(c); continue }; if (c == \"(\") { op(c); if (f) fp[f]++; continue }; if (c == \")\") { if (f && !fb[f] && !fp[f]) { fc(); continue }; if (f && fp[f]) fp[f]--; op(c); continue }; w = w c; iw = 1 }; while (f > 0) fc(); fl(); print ob[0] } BEGIN { sq = sprintf(\"%c\", 39); dq = sprintf(\"%c\", 34); bs = sprintf(\"%c\", 92); bq = sprintf(\"%c\", 96) } { if (sub(/\\\\$/, \"\")) { b = b $0; next }; lx(b $0); b = \"\" } END { if (b != \"\") lx(b) }' | grep -oE '(^|[^[:alnum:]_.$\"-])[Gg][Ii][Tt]([[:space:]]+(-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source|--shallow-file)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+push([[:space:]][^;&|<>()]*)?($|[;&|<>()])'); [ -n \"$SEGS\" ] || exit 0; (printf '%s\\n' \"$SEGS\" | while IFS= read -r S; do printf '%s\\n' \"$S\" | grep -qE '[[:space:]]-[vqdnu46]*f|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)((refs/)?heads/)?(main|master)([[:space:]]|$|[;&|<>()])' && exit 2; printf '%s\\n' \"$S\" | awk '{ for (i = 1; i <= NF; i++) { t = $i; sub(/=.*/, \"\", t); if (t ~ /^--[a-z]/ && (index(\"--all\", t) == 1 || index(\"--branches\", t) == 1 || index(\"--mirror\", t) == 1 || index(\"--force-with-lease\", t) == 1)) b = 1 } } END { exit !b }' && exit 2; case \"$S\" in *\\$*|*[{}]*|*--git-dir*|*--work-tree*) exit 3 ;; esac; printf '%s\\n' \"$S\" | grep -qE '[[:space:]](-c|--config-env)([[:space:]=]|$)' && exit 3; case \"$CMD\" in *GIT_DIR=*|*GIT_WORK_TREE=*|*GIT_CONFIG*|*xargs*) exit 3 ;; esac; CD=$(printf '%s\\n' \"$S\" | awk '{ d = \".\"; for (i = 1; i <= NF; i++) { if ($i == \"push\") break; if ($i == \"-C\" && i < NF) { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v } }; print d }'); [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 3; REFS=$(printf '%s\\n' \"$S\" | awk '{ sub(/[[:space:];&|<>()]+$/, \"\"); p = 0; for (i = 1; i <= NF; i++) if ($i == \"push\") { p = i; break }; r = 0; for (j = p + 1; j <= NF; j++) { if ($j ~ /^-[vqdnfu46]*o$/ || ($j ~ /^--[a-z][^=]*$/ && (index(\"--push-option\", $j) == 1 || index(\"--repo\", $j) == 1 || index(\"--receive-pack\", $j) == 1 || index(\"--exec\", $j) == 1 || index(\"--recurse-submodules\", $j) == 1))) { j++; continue }; if ($j == \"--tags\") print $j; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \":\"|*\\**) exit 2 ;; \"\"|--tags|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && exit 2 ;; esac; :; done); case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: Cannot read this git push. Write the branch and any -C directory out literally, with no $, backticks, braces, quoted spaces or shell operators, -c, --config-env, --git-dir, --work-tree, GIT_DIR, GIT_WORK_TREE, GIT_CONFIG or xargs.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); (GO='-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source|--shallow-file'; BQ=$(printf '\\140'); norm() { tr -d '$\\\\\"'\"'\" | tr '\\n\\t;&|()<>{}`' ' '; }; N1=$(printf '%s\\n' \"$CMD\" | norm); N2=$(printf '%s\\n' \"$CMD\" | sed -e 's/\"[^\"]*\"/Q/g' -e \"s/'[^']*'/Q/g\" -e 's/\\\\[[:space:]]/Q/g' -e 's/[$][(][^()]*[)]/Q/g' -e \"s/${BQ}[^${BQ}]*${BQ}/Q/g\" | norm); printf '%s\\n%s\\n' \"$N1\" \"$N2\" | grep -qE '(^|[^[:alnum:]_.-])[Gg][Ii][Tt]([[:space:]]+('\"$GO\"')[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+[Pp][Uu][Ss][Hh]([[:space:]]|$)' || exit 0; printf '%s\\n' \"$CMD\" | awk -v sq=\"'\" '/[];&|()<>{}`\"*?#$\\\\[]/ || index($0, sq) || $1 !~ /^([^[:space:]]*\\/)?[Gg][Ii][Tt]$/ { b = 1 } END { exit b || NR != 1 }' || exit 3; CD=$(printf '%s\\n' \"$CMD\" | awk -v go=\"$GO\" '{ d = \".\"; for (i = 2; i <= NF; i++) { if (tolower($i) == \"push\") { print d; exit 0 }; if ($i !~ /^-/) exit 1; if ($i ~ (\"^(\" go \")$\")) { if ($i == \"-C\") { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v }; i++ } }; exit 1 }') || exit 0; S=\" $CMD\"; printf '%s\\n' \"$S\" | grep -qE '[[:space:]]-[vqdnu46]*f|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)((refs/)?heads/)?(main|master)([[:space:]]|$)' && exit 2; printf '%s\\n' \"$S\" | awk '{ for (i = 1; i <= NF; i++) { t = $i; sub(/=.*/, \"\", t); if (t ~ /^--[a-z]/ && (index(\"--all\", t) == 1 || index(\"--branches\", t) == 1 || index(\"--mirror\", t) == 1 || index(\"--force-with-lease\", t) == 1)) b = 1 } } END { exit !b }' && exit 2; printf '%s\\n' \"$S\" | grep -qE -e '--git-dir|--work-tree|[[:space:]](-c|--config-env)([[:space:]=]|$)' && exit 4; [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 4; REFS=$(printf '%s\\n' \"$CMD\" | awk -v go=\"$GO\" '{ for (i = 2; i <= NF; i++) { if (tolower($i) == \"push\") break; if ($i ~ (\"^(\" go \")$\")) i++ }; r = 0; for (j = i + 1; j <= NF; j++) { if ($j ~ /^-[vqdnfu46]*o$/ || ($j ~ /^--[a-z][^=]*$/ && (index(\"--push-option\", $j) == 1 || index(\"--repo\", $j) == 1 || index(\"--receive-pack\", $j) == 1 || index(\"--exec\", $j) == 1 || index(\"--recurse-submodules\", $j) == 1))) { j++; continue }; if ($j == \"--tags\") print $j; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \":\") exit 2 ;; \"\"|--tags|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && exit 2 ;; esac; :); case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: This command mentions git push. Run the push as a command of its own, on one line, with the branch written out (git push -u origin ) and nothing before or after it: no &&, ;, pipes, redirects, quotes, $, backslashes, braces, globs or comments. Pass commit or PR text that mentions git push from a file (git commit -F, gh pr create --body-file), and search for it with a pattern such as git.push.' >&2 ;; 4) echo '❌ BLOCKED: Cannot read this git push. Drop -c, --config-env, --git-dir and --work-tree, and point -C at a repo.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
}
]
},
diff --git a/AGENTS.md b/AGENTS.md
index 1317f16c..0b12671f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -324,7 +324,8 @@ Subject line max 50 characters (including the `type(scope): ` prefix); body line
versioned block
- Change only VERSION and CHANGELOG.md (no other files)
3. Merge the version bump PR.
-4. Tag and push: git tag vX.Y.Z && git push origin vX.Y.Z
+4. Tag and push: git tag vX.Y.Z
+ git push origin vX.Y.Z
→ docker.yml builds + pushes to GHCR as vX.Y.Z + latest
→ release.yml extracts the X.Y.Z CHANGELOG block, creates GitHub Release
→ chart.yml packages + pushes Helm chart to oci://ghcr.io/av1155/charts
@@ -459,7 +460,7 @@ Do not use Bash to write files as a workaround when a hook blocks an action. If
- Hook 5 blocks a file edit on main: create a feature branch (`git checkout -b type/slug`) and make the edit there. From a worktree, edit the worktree's copy of the file instead.
- Hook 6 blocks a commit: run `just fix` (or `just fmt-check` to see the diff first), `git add` the fixed files that belong in the commit, then retry the commit.
- Hook 3 blocks `rm -rf`: use a more specific path instead of a dangerous wildcard target.
-- Hook 4 blocks a git push: you are pushing to main, force-pushing, pushing from `main` without naming a branch, or the hook cannot read where the push goes. Push to a feature branch, with its name written out (`git push -u origin `), and open a PR instead. If the block comes from commit or PR text that mentions `git push`, pass the text from a file (`git commit -F `, `gh pr create --body-file `).
+- Hook 4 blocks a git push: you are pushing to main, force-pushing, pushing from `main` without naming a branch, or the command is not a plain push on its own. Run the push as its own one-line command with the branch written out (`git push -u origin `), and open a PR. If the command only mentions `git push` in text, pass the text from a file (`git commit -F `, `gh pr create --body-file `), and search for it with a pattern such as `git.push`.
In every case: fix the underlying issue, do not bypass the hook.
@@ -469,8 +470,8 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
-- Hook 4 (push guard): splits the command into simple commands the way the shell does: at newlines, `;`, `&`, `|`, parentheses, `$(...)` and backticks, whether or not spaces surround them, after joining backslash line breaks. It drops redirections such as `2>&1` and comments, and removes quotes and backslashes inside words, so `"main"`, `m''ain`, `g''it`, `p\ush` and `$'push'` all count. It reads one line at a time, and within a line quoted text is never read as a command, except `$(...)` and backticks inside double quotes, which the shell runs. In each `git push`, after git's global options (`git -C push`, `git -c k=v push`), it blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` and `*` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push it cannot read: one whose words hold an expansion (`$`, a backtick), braces, or a quoted or escaped space or shell operator, one using `-c`, `--config-env`, `--git-dir` or `--work-tree`, one in a command that sets `GIT_DIR`, `GIT_WORK_TREE` or `GIT_CONFIG*` or uses `xargs`, and one whose `-C` directory is not a repo.
-- Hook 4 limits: it catches mistakes, not deliberate evasion. It only sees `git` and `push` written out as words, so a push through a git alias, a shell alias or function, a script, `eval`, a quoted `bash -c "..."` string, a `git` or `push` word built from an expansion (`"$GIT" push`), or another command that pushes (`git subtree push`, `git send-pack`) is not seen. It reads the branch from Claude's current directory or the `-C` directory, so push another checkout with `git -C push`, not `cd && git push`. Heredoc text, unquoted text and the later lines of a multi-line quoted message that mention `git push` with arguments can still be read as a push; pass commit and PR text from a file.
+- Hook 4 (push guard): reads every Bash command that mentions `git push`, after git's global options (`git -C push`, `git -c k=v push`), in any letter case and through quotes, backslashes, `$`, line breaks and shell operators. Unless the whole command is one plain `git push` line, with nothing chained, piped or redirected and no quotes, `$`, backticks, backslashes, braces, globs or comments, it refuses it, so a commit message, PR body or search that spells out `git push` is refused too. In a plain push it blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. It reads the branch from Claude's current directory or the `-C` directory. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push using `-c`, `--config-env`, `--git-dir` or `--work-tree`, and one whose `-C` directory is not a repo.
+- Hook 4 limits: it catches mistakes, not deliberate evasion. It only sees `git` followed by `push`, so a push through a git alias, a shell alias or function, a script, a variable that holds the command or the `git` word (`eval "$cmd"`, `$G push`), or another command that pushes (`git subtree push`, `git send-pack`) is not seen.
---
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index 80eb1023..853fb4f6 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -69,9 +69,9 @@ def _hook(event: str, marker: str) -> str:
# schema says its default bash shell means $SHELL when that is bash, zsh or sh.
_SHELLS = [shell for shell in ("bash", "sh", "zsh") if shutil.which(shell)]
-# Places an agent's command often puts a push, with the operators glued on.
+# Shell syntax an agent might put around a push: chained, piped, redirected, nested, on a
+# later line, or behind a quoted string that spans lines.
_SHELL_WRAPPERS = [
- "CMD",
"CMD;echo ok",
"CMD&&echo ok",
"CMD||echo failed",
@@ -90,6 +90,14 @@ def _hook(event: str, marker: str) -> str:
"true;CMD",
"true&&CMD",
"CMD # note",
+ "git commit -m \"$(cat <<'EOF'\nfeat: x\n\nBody.\nEOF\n)\" && CMD",
+ 'git commit -m "fix: x\n\nBody." && CMD',
+ "git add -A && \\\n # commit and push \\\n CMD",
+ "echo done\\\\\nCMD",
+ "git checkout main && CMD",
+ 'eval "CMD"',
+ 'bash -c "CMD"',
+ "\\CMD",
]
@@ -401,17 +409,7 @@ def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) ->
"git --no-pager push origin main",
"git --attr-source HEAD push -f",
"/usr/bin/git push --force",
- "cd /x && git push origin main",
- "(cd /x && git push origin main)",
- "git push origin main;",
- 'git push origin "main"',
- "git push origin m''ain",
- "git push origin 'HEAD:main'",
- 'git push "--force" origin feat',
- "git \\\n push --force origin feat",
- "git push origin ma\\in",
- "git push origin feat;git push origin main",
- "git push origin feat&git push --force",
+ "git push origin master",
"git push --branches origin",
"git push --force-w origin feat",
"git push --mirro",
@@ -419,17 +417,10 @@ def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) ->
"git push origin feat:heads/main",
"git push origin HEAD:refs/heads/main",
"git push origin :",
- "git push origin 'refs/heads/*'",
- "g''it push origin main",
- 'git "push" origin main',
- "git p\\ush --force origin feat",
- "git $'push' --force origin feat",
- "git push --repo 'x;' origin main",
- "git push --repo x\\; origin main",
"GIT push --force",
+ "git PUSH origin main",
"git --shallow-file /dev/null push origin main",
- 'echo "$(git log -1)" && git push --force',
- 'x="$( (true) && git push --force )"',
+ " git push origin main",
],
)
def test_push_guard_blocks_force_pushes_and_pushes_to_main(
@@ -444,30 +435,76 @@ def test_push_guard_blocks_force_pushes_and_pushes_to_main(
@pytest.mark.parametrize(
"command",
[
+ "cd /x && git push origin main",
+ "git push origin main;",
+ 'git push origin "main"',
+ "git push origin m''ain",
+ 'git push "--force" origin feat',
+ "git \\\n push --force origin feat",
+ "git push origin ma\\in",
+ "git push origin feat;git push origin main",
+ "git fetch origin\ngit push --force",
+ "git push origin 'refs/heads/*'",
+ "g''it push origin main",
+ "git p\\ush --force origin feat",
+ "git $'push' --force origin feat",
+ "git push --repo 'x;' origin main",
'git push origin "$BRANCH"',
+ "git push origin $BRANCH",
'git push -u origin "$(git branch --show-current)"',
"git push origin `git branch --show-current`",
- "git --git-dir=/x/.git push origin feat",
- "git --work-tree /x push origin feat",
"GIT_DIR=/x/.git git push origin feat",
"env GIT_WORK_TREE=/x git push origin feat",
- "git -C /nonexistent/dir push origin feat",
- 'git -c "user.name=A B" push origin feat',
- "git -C '/tmp/a b' push origin feat",
- 'git -c "user.name=AB" push origin feat',
+ "git -C '/tmp/a b' push --force",
+ "git -C /tmp/a\\ b push --force",
+ 'git -c "user.name=A B" push --force',
+ "git -C $(git rev-parse --show-toplevel) push --force",
+ "git -C `git rev-parse --show-toplevel` push --force",
+ 'git -C "$(pwd)" push origin feat',
+ "git push origin refs/heads/*",
+ "git push origin ma?n",
"git push origin {main,feat}",
"echo main | xargs git push origin",
- "git -c push.default=matching push",
- "X=matching git --config-env=push.default=X push",
"GIT_CONFIG_PARAMETERS=\"'push.default=matching'\" git push",
"git push origin $'\\x6dain'",
- "git push -o 'a;b' origin feat",
- 'git -C "$(pwd)" push origin feat',
"git push origin $(\n echo main\n)",
+ '"$GIT" push --force',
+ 'sh -c "git push>/dev/null"',
+ "x=`echo '`; git push origin main; y=`'`",
+ 'echo "${x%\'"\'}" ; git push --force',
+ "git push &>/dev/null origin main",
+ "git push -u origin feat 2>&1",
+ "git push origin feat && gh pr create --fill",
+ "\\git push origin feat",
+ "git push -u origin feat # not main",
+ "git push \\\n origin feat",
+ 'grep "git push origin main" AGENTS.md',
+ 'git commit -m "docs: explain git push origin main"',
+ "git commit -F - <<'EOF'\nci: x\n\nRun git push from a branch.\nEOF",
+ 'gh pr create --title x --body "Blocks git push --force"',
+ ],
+)
+def test_push_guard_refuses_anything_but_a_plain_push(repo: Path, shell: str, command: str) -> None:
+ """Shell syntax can hide where a push goes, so only a plain one-line push is read."""
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell)
+
+ assert result.returncode == 2
+ assert "mentions git push" in result.stderr
+
+
+@pytest.mark.parametrize(
+ "command",
+ [
+ "git --git-dir=/x/.git push origin feat",
+ "git --work-tree /x push origin feat",
+ "git -C /nonexistent/dir push origin feat",
+ "git -c push.default=matching push",
+ "git --config-env=push.default=X push",
+ "git -c user.name=AB push origin feat",
],
)
def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, shell: str, command: str) -> None:
- """Expansions, quoted spaces, overrides, xargs and a missing -C dir hide where it goes."""
+ """Config overrides, another git dir and a missing -C dir hide where it goes."""
result = _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell)
assert result.returncode == 2
@@ -484,27 +521,40 @@ def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, shell: str, command
"git push origin feature/maintenance",
"git push origin main-fix",
"git push origin v1.2.3",
+ "git push --tags",
"git push origin --delete feat",
- 'git push origin "feat"',
- "\\git push origin feat",
"git push -o ci.skip origin feat",
"git push --follow-tags origin feat",
"git push --force-if-includes origin feat",
- "git push \\\n origin feat",
- 'git push origin feat && echo "$?"',
- 'grep "git push origin main" AGENTS.md',
- "grep 'git push --force' AGENTS.md",
- 'git commit -m "docs: explain git push origin main"',
- "git commit -F - <<'EOF'\nci: x\n\nThe guard's git push check reads quotes.\nEOF",
- "git push origin feat 2>&1 | grep -v '^$'",
"git push -ofoo origin feat",
- "git push -u origin feat # not main",
+ "git push --dry-run origin feat",
+ "git -C . push origin feat",
+ "/usr/bin/git push origin feat",
],
)
def test_push_guard_allows_feature_and_tag_pushes(repo: Path, shell: str, command: str) -> None:
assert _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell).returncode == 0
+@pytest.mark.parametrize(
+ "command",
+ [
+ "git stash push -m wip",
+ "git stash push -m 'wip: push guard'",
+ 'git commit -m "ci: refuse pushes the push guard cannot read"',
+ "git commit -F - <<'EOF'\nci: x\n\nPush the branch first.\nEOF",
+ "git log --grep=push",
+ "git --no-pager log --oneline | grep -i push",
+ "git -C /tmp log --oneline | grep push",
+ "git log --oneline git push --force",
+ "docker push ghcr.io/x/y:1",
+ "gh pr create --title x --body-file /tmp/body.md",
+ ],
+)
+def test_push_guard_ignores_commands_that_do_not_push(repo: Path, shell: str, command: str) -> None:
+ assert _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell).returncode == 0
+
+
@pytest.mark.parametrize(
("command", "expected"),
[
@@ -518,12 +568,10 @@ def test_push_guard_allows_feature_and_tag_pushes(repo: Path, shell: str, comman
("git push -o ci.skip origin", 2),
("git push -uo ci.skip origin", 2),
("git push -o note=--tags", 2),
- ('git push -o "a b" origin', 2),
("git push --push-o ci.skip origin", 2),
("git push --recu check origin", 2),
("git push --recurse-submodules check origin", 2),
("git push origin :", 2),
- ("git push origin 2>&1", 2),
("git push -otodo origin HEAD feat", 2),
("git push origin v1.2.3", 0),
("git push --tags", 0),
@@ -537,6 +585,7 @@ def test_push_guard_on_main_needs_a_named_target(
result = _run(_PUSH_GUARD_HOOK, _bash(command), main_repo, shell=shell)
assert result.returncode == expected
+ assert ("Direct push to main" in result.stderr) == bool(expected)
def test_push_guard_reads_the_branch_of_the_checkout_named_by_dash_c(
@@ -545,18 +594,13 @@ def test_push_guard_reads_the_branch_of_the_checkout_named_by_dash_c(
root = tmp_path.resolve()
worktree = root / "worktree"
_git(main_repo, "worktree", "add", "-q", "-b", "feature", str(worktree))
- # Cut at its space, this path would name the feature worktree.
- on_main_with_space = root / "worktree two"
- _git(root, "init", "-q", "-b", "main", str(on_main_with_space))
def push(command: str, cwd: Path) -> int:
return _run(_PUSH_GUARD_HOOK, _bash(command), cwd, shell=shell, HOME=str(root)).returncode
assert push(f"git -C {main_repo} push", worktree) == 2
- assert push(f'git -C "{main_repo}" push', worktree) == 2
assert push(f"git -C {root} -C {main_repo.name} push", worktree) == 2
assert push(f"git -C ~/{main_repo.name} push", worktree) == 2
- assert push(f'git -C "{on_main_with_space}" push', main_repo) == 2
assert push(f"git -C {worktree} push", main_repo) == 0
assert push(f"git -C {root} -C {worktree.name} push", main_repo) == 0
assert push(f"git -C ~/{worktree.name} push", main_repo) == 0
@@ -566,39 +610,27 @@ def push(command: str, cwd: Path) -> int:
@pytest.mark.parametrize(
"command",
_wrapped(
+ "git push origin feat",
+ "git push -u origin HEAD",
"git push --force",
- "git push --force-with-lease",
- "git push -f origin feat",
- "git push --all",
- "git push --mirror",
- "git push --branches",
"git push origin main",
- "git push origin HEAD:main",
- "git push origin +feat",
"git push origin :",
),
)
-def test_push_guard_blocks_pushes_wrapped_in_shell_syntax(repo: Path, command: str) -> None:
+def test_push_guard_refuses_pushes_wrapped_in_shell_syntax(repo: Path, command: str) -> None:
result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
assert result.returncode == 2
- assert "Direct push to main or force push" in result.stderr
+ assert "mentions git push" in result.stderr
-@pytest.mark.parametrize(
- "command",
- _wrapped("git push", "git push origin", "git push -u origin HEAD", "git push origin @"),
-)
-def test_push_guard_blocks_wrapped_pushes_of_main(main_repo: Path, command: str) -> None:
+@pytest.mark.parametrize("command", _wrapped("git push", "git push origin HEAD"))
+def test_push_guard_refuses_wrapped_pushes_on_main(main_repo: Path, command: str) -> None:
+ """The refusal comes before the branch is read, so a wrapped push can't pass for one on main."""
result = _run(_PUSH_GUARD_HOOK, _bash(command), main_repo)
assert result.returncode == 2
- assert "Direct push to main or force push" in result.stderr
-
-
-@pytest.mark.parametrize("command", _wrapped("git push origin feat", "git push -u origin HEAD"))
-def test_push_guard_allows_wrapped_feature_pushes(repo: Path, command: str) -> None:
- assert _run(_PUSH_GUARD_HOOK, _bash(command), repo).returncode == 0
+ assert "mentions git push" in result.stderr
def test_stop_hook_warns_once_about_unfinished_markers(tmp_path: Path) -> None:
From 5f25916822533d77530c1e0af1bbb14274e7ba5d Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Wed, 11 Nov 2026 00:55:32 -0500
Subject: [PATCH 12/13] ci: widen the push guard and resolve edit paths
The push guard looked for git, its global options and then push, so an
option value built from a variable, such as git -C ${HOME}/repo push,
hid the push and it ran without any check. Any command with the word
git followed later by the word push is now treated as a push, and
unless it is one plain git push line it is refused.
The format and mypy hooks now resolve the edited path before matching
it against the repo root, so an edit through a symlink is checked. The
branch hook resolves .. the way the Write tool does, so a path through
a missing directory can no longer land in a checkout on main unseen.
---
.agents/skills/bump/SKILL.md | 5 +
.claude/settings.json | 8 +-
AGENTS.md | 6 +-
tests/test_gates/test_claude_hooks_gate.py | 101 ++++++++++++++++++---
4 files changed, 101 insertions(+), 19 deletions(-)
diff --git a/.agents/skills/bump/SKILL.md b/.agents/skills/bump/SKILL.md
index 0ab9b3ed..783be15c 100644
--- a/.agents/skills/bump/SKILL.md
+++ b/.agents/skills/bump/SKILL.md
@@ -92,6 +92,11 @@ Rename `## [Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD` and insert a fresh empty U
```
git add VERSION CHANGELOG.md
git commit -m "chore: bump version to X.Y.Z"
+```
+
+Then push, as a command of its own:
+
+```
git push -u origin HEAD
```
diff --git a/.claude/settings.json b/.claude/settings.json
index f1fa8273..2ce65dc7 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -91,7 +91,7 @@
"hooks": [
{
"type": "command",
- "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; git check-ignore -q \"$F\" 2>/dev/null && exit 0; case \"$F\" in \"$R\"/*.py) \"$R\"/.venv/bin/python -m ruff check --fix --unfixable F401,F841 --force-exclude \"$F\" >/dev/null 2>&1; \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; \"$R\"/*.md) \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; esac; exit 0"
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; D=$(cd \"${F%/*}\" 2>/dev/null && pwd -P) && F=$D/${F##*/}; git check-ignore -q \"$F\" 2>/dev/null && exit 0; case \"$F\" in \"$R\"/*.py) \"$R\"/.venv/bin/python -m ruff check --fix --unfixable F401,F841 --force-exclude \"$F\" >/dev/null 2>&1; \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; \"$R\"/*.md) \"$R\"/.venv/bin/python -m ruff format --force-exclude \"$F\" >/dev/null 2>&1 ;; esac; exit 0"
}
]
},
@@ -100,7 +100,7 @@
"hooks": [
{
"type": "command",
- "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; case \"$F\" in \"$R\"/src/*.py) OUT=$(cd \"$R\" && .venv/bin/python -m mypy src/ 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; exit 2; } ;; esac; exit 0"
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); R=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0; D=$(cd \"${F%/*}\" 2>/dev/null && pwd -P) && F=$D/${F##*/}; case \"$F\" in \"$R\"/src/*.py) OUT=$(cd \"$R\" && .venv/bin/python -m mypy src/ 2>&1) || { printf '%s\\n' \"$OUT\" | tail -20 >&2; exit 2; } ;; esac; exit 0"
}
]
}
@@ -120,7 +120,7 @@
"hooks": [
{
"type": "command",
- "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); (GO='-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source|--shallow-file'; BQ=$(printf '\\140'); norm() { tr -d '$\\\\\"'\"'\" | tr '\\n\\t;&|()<>{}`' ' '; }; N1=$(printf '%s\\n' \"$CMD\" | norm); N2=$(printf '%s\\n' \"$CMD\" | sed -e 's/\"[^\"]*\"/Q/g' -e \"s/'[^']*'/Q/g\" -e 's/\\\\[[:space:]]/Q/g' -e 's/[$][(][^()]*[)]/Q/g' -e \"s/${BQ}[^${BQ}]*${BQ}/Q/g\" | norm); printf '%s\\n%s\\n' \"$N1\" \"$N2\" | grep -qE '(^|[^[:alnum:]_.-])[Gg][Ii][Tt]([[:space:]]+('\"$GO\"')[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+[Pp][Uu][Ss][Hh]([[:space:]]|$)' || exit 0; printf '%s\\n' \"$CMD\" | awk -v sq=\"'\" '/[];&|()<>{}`\"*?#$\\\\[]/ || index($0, sq) || $1 !~ /^([^[:space:]]*\\/)?[Gg][Ii][Tt]$/ { b = 1 } END { exit b || NR != 1 }' || exit 3; CD=$(printf '%s\\n' \"$CMD\" | awk -v go=\"$GO\" '{ d = \".\"; for (i = 2; i <= NF; i++) { if (tolower($i) == \"push\") { print d; exit 0 }; if ($i !~ /^-/) exit 1; if ($i ~ (\"^(\" go \")$\")) { if ($i == \"-C\") { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v }; i++ } }; exit 1 }') || exit 0; S=\" $CMD\"; printf '%s\\n' \"$S\" | grep -qE '[[:space:]]-[vqdnu46]*f|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)((refs/)?heads/)?(main|master)([[:space:]]|$)' && exit 2; printf '%s\\n' \"$S\" | awk '{ for (i = 1; i <= NF; i++) { t = $i; sub(/=.*/, \"\", t); if (t ~ /^--[a-z]/ && (index(\"--all\", t) == 1 || index(\"--branches\", t) == 1 || index(\"--mirror\", t) == 1 || index(\"--force-with-lease\", t) == 1)) b = 1 } } END { exit !b }' && exit 2; printf '%s\\n' \"$S\" | grep -qE -e '--git-dir|--work-tree|[[:space:]](-c|--config-env)([[:space:]=]|$)' && exit 4; [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 4; REFS=$(printf '%s\\n' \"$CMD\" | awk -v go=\"$GO\" '{ for (i = 2; i <= NF; i++) { if (tolower($i) == \"push\") break; if ($i ~ (\"^(\" go \")$\")) i++ }; r = 0; for (j = i + 1; j <= NF; j++) { if ($j ~ /^-[vqdnfu46]*o$/ || ($j ~ /^--[a-z][^=]*$/ && (index(\"--push-option\", $j) == 1 || index(\"--repo\", $j) == 1 || index(\"--receive-pack\", $j) == 1 || index(\"--exec\", $j) == 1 || index(\"--recurse-submodules\", $j) == 1))) { j++; continue }; if ($j == \"--tags\") print $j; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \":\") exit 2 ;; \"\"|--tags|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && exit 2 ;; esac; :); case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: This command mentions git push. Run the push as a command of its own, on one line, with the branch written out (git push -u origin ) and nothing before or after it: no &&, ;, pipes, redirects, quotes, $, backslashes, braces, globs or comments. Pass commit or PR text that mentions git push from a file (git commit -F, gh pr create --body-file), and search for it with a pattern such as git.push.' >&2 ;; 4) echo '❌ BLOCKED: Cannot read this git push. Drop -c, --config-env, --git-dir and --work-tree, and point -C at a repo.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
+ "command": "CMD=$(cat | jq -r '.tool_input.command // empty'); (GO='-[Cc]|--git-dir|--work-tree|--namespace|--config-env|--attr-source|--shallow-file'; norm() { sed 's/[$][{]*IFS[}]*/ /g' | tr -d '$\\\\\"'\"'\" | tr '\\n\\t;&|()<>{}`,' ' '; }; N1=$(printf '%s\\n' \"$CMD\" | norm); N3=$(printf '%s\\n' \"$CMD\" | awk '{ if (sub(/\\\\$/, \"\")) printf \"%s\", $0; else print }' | norm); printf '%s\\n%s\\n' \"$N1\" \"$N3\" | grep -qE '(^|[^[:alnum:]_.])[Gg][Ii][Tt]([[:space:]](.*[[:space:]])?|-)[Pp][Uu][Ss][Hh]([[:space:]]|$)' || exit 0; printf '%s\\n' \"$CMD\" | awk -v sq=\"'\" '/[];&|()<>{}`\"*?#$\\\\[]/ || index($0, sq) || $1 !~ /^([^[:space:]]*\\/)?[Gg][Ii][Tt]$/ { b = 1 } END { exit b || NR != 1 }' || exit 3; CD=$(printf '%s\\n' \"$CMD\" | awk -v go=\"$GO\" '{ d = \".\"; for (i = 2; i <= NF; i++) { if (tolower($i) == \"push\") { print d; exit 0 }; if ($i !~ /^-/) exit 1; if ($i ~ (\"^(\" go \")$\")) { if ($i == \"-C\") { v = $(i + 1); if (v ~ /^~(\\/|$)/) v = ENVIRON[\"HOME\"] substr(v, 2); d = (v ~ /^\\// || d == \".\") ? v : d \"/\" v }; i++ } }; exit 1 }') || exit 0; S=\" $CMD\"; printf '%s\\n' \"$S\" | grep -qE '[[:space:]]-[vqdnu46]*f|[[:space:]]\\+[^[:space:]]|([[:space:]]|:)((refs/)?heads/)?(main|master)([[:space:]]|$)' && exit 2; printf '%s\\n' \"$S\" | awk '{ for (i = 1; i <= NF; i++) { t = $i; sub(/=.*/, \"\", t); if (t ~ /^--[a-z]/ && (index(\"--all\", t) == 1 || index(\"--branches\", t) == 1 || index(\"--mirror\", t) == 1 || index(\"--force-with-lease\", t) == 1)) b = 1 } } END { exit !b }' && exit 2; printf '%s\\n' \"$S\" | grep -qE -e '--git-dir|--work-tree|[[:space:]](-c|--config-env)([[:space:]=]|$)' && exit 4; [ \"$CD\" = . ] || git -C \"$CD\" rev-parse --git-dir >/dev/null 2>&1 || exit 4; REFS=$(printf '%s\\n' \"$CMD\" | awk -v go=\"$GO\" '{ for (i = 2; i <= NF; i++) { if (tolower($i) == \"push\") break; if ($i ~ (\"^(\" go \")$\")) i++ }; r = 0; for (j = i + 1; j <= NF; j++) { if ($j ~ /^-[vqdnfu46]*o$/ || ($j ~ /^--[a-z][^=]*$/ && (index(\"--push-option\", $j) == 1 || index(\"--repo\", $j) == 1 || index(\"--receive-pack\", $j) == 1 || index(\"--exec\", $j) == 1 || index(\"--recurse-submodules\", $j) == 1))) { j++; continue }; if ($j == \"--tags\") print $j; if (substr($j, 1, 1) == \"-\") continue; r++; if (r > 1) print $j } }'); printf '%s\\n' \"$REFS\" | while IFS= read -r T; do case \"$T\" in \":\") exit 2 ;; \"\"|--tags|*:*) ;; *) case \"$(git -C \"$CD\" rev-parse --symbolic-full-name \"$T\" 2>/dev/null)\" in refs/heads/main|refs/heads/master) exit 2 ;; esac ;; esac; done || exit 2; case \"$(git -C \"$CD\" branch --show-current 2>/dev/null)\" in main|master) [ -z \"$REFS\" ] && exit 2 ;; esac; :); case $? in 0) exit 0 ;; 3) echo '❌ BLOCKED: This command has git followed by push, so it is read as a push. Run the push as a command of its own, on one line, with the branch written out (git push -u origin ) and nothing before or after it: no &&, ;, pipes, redirects, quotes, $, backslashes, braces, globs or comments. Pass commit or PR text that has git and push in it from a file (git commit -F, gh pr create --body-file), and search with git log --grep=push or a pattern such as git.push.' >&2 ;; 4) echo '❌ BLOCKED: Cannot read this git push. Drop -c, --config-env, --git-dir and --work-tree, and point -C at a repo.' >&2 ;; *) echo '❌ BLOCKED: Direct push to main or force push. Create a feature branch and PR.' >&2 ;; esac; exit 2"
}
]
},
@@ -129,7 +129,7 @@
"hooks": [
{
"type": "command",
- "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); case \"$F\" in /*) ;; *) exit 0 ;; esac; D=${F%/*}; while [ -n \"$D\" ] && [ ! -d \"$D\" ]; do D=${D%/*}; done; D=${D:-/}; [ \"$(git -C \"$D\" branch --show-current 2>/dev/null)\" = main ] || exit 0; P=$(git -C \"${CLAUDE_PROJECT_DIR:-.}\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null); [ -n \"$P\" ] && [ \"$(git -C \"$D\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)\" != \"$P\" ] && exit 0; T=${F#\"$D\"/}; if [ \"$(git -C \"$D\" rev-parse --is-inside-work-tree 2>/dev/null)\" = true ]; then git -C \"$D\" check-ignore -q -- \"$T\" 2>/dev/null && exit 0; case \"$(git -C \"$D\" rev-parse --show-prefix 2>/dev/null)$T\" in AGENTS.md|CLAUDE.md) exit 0 ;; esac; fi; echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch, or edit the copy in your worktree.' >&2; exit 2",
+ "command": "F=$(cat | jq -r '.tool_input.file_path // empty'); case \"$F\" in /*) ;; *) exit 0 ;; esac; F=$(printf '%s\\n' \"$F\" | awk -F/ '{ n = 0; for (i = 2; i <= NF; i++) { if ($i == \"\" || $i == \".\") continue; if ($i == \"..\") { if (n) n--; continue }; s[++n] = $i }; p = \"\"; for (i = 1; i <= n; i++) p = p \"/\" s[i]; print (p == \"\" ? \"/\" : p) }'); D=${F%/*}; while [ -n \"$D\" ] && [ ! -d \"$D\" ]; do D=${D%/*}; done; D=${D:-/}; [ \"$(git -C \"$D\" branch --show-current 2>/dev/null)\" = main ] || exit 0; P=$(git -C \"${CLAUDE_PROJECT_DIR:-.}\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null); [ -n \"$P\" ] && [ \"$(git -C \"$D\" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)\" != \"$P\" ] && exit 0; T=${F#\"$D\"/}; if [ \"$(git -C \"$D\" rev-parse --is-inside-work-tree 2>/dev/null)\" = true ]; then git -C \"$D\" check-ignore -q -- \"$T\" 2>/dev/null && exit 0; case \"$(git -C \"$D\" rev-parse --show-prefix 2>/dev/null)$T\" in AGENTS.md|CLAUDE.md) exit 0 ;; esac; fi; echo '❌ BLOCKED: Cannot edit repo files on main. Allowed: AGENTS.md, CLAUDE.md. Create a feature branch, or edit the copy in your worktree.' >&2; exit 2",
"timeout": 5
}
]
diff --git a/AGENTS.md b/AGENTS.md
index 0b12671f..0cce9bcb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -460,7 +460,7 @@ Do not use Bash to write files as a workaround when a hook blocks an action. If
- Hook 5 blocks a file edit on main: create a feature branch (`git checkout -b type/slug`) and make the edit there. From a worktree, edit the worktree's copy of the file instead.
- Hook 6 blocks a commit: run `just fix` (or `just fmt-check` to see the diff first), `git add` the fixed files that belong in the commit, then retry the commit.
- Hook 3 blocks `rm -rf`: use a more specific path instead of a dangerous wildcard target.
-- Hook 4 blocks a git push: you are pushing to main, force-pushing, pushing from `main` without naming a branch, or the command is not a plain push on its own. Run the push as its own one-line command with the branch written out (`git push -u origin `), and open a PR. If the command only mentions `git push` in text, pass the text from a file (`git commit -F `, `gh pr create --body-file `), and search for it with a pattern such as `git.push`.
+- Hook 4 blocks a git push: you are pushing to main, force-pushing, pushing from `main` without naming a branch, or the command is not a plain push on its own. Run the push as its own one-line command with the branch written out (`git push -u origin `), and open a PR. If the refusal comes from text that has git and then push in it, such as a commit message, pass the text from a file (`git commit -F `, `gh pr create --body-file `), and search with `git log --grep=push` or a pattern such as `git.push`.
In every case: fix the underlying issue, do not bypass the hook.
@@ -470,8 +470,8 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
-- Hook 4 (push guard): reads every Bash command that mentions `git push`, after git's global options (`git -C push`, `git -c k=v push`), in any letter case and through quotes, backslashes, `$`, line breaks and shell operators. Unless the whole command is one plain `git push` line, with nothing chained, piped or redirected and no quotes, `$`, backticks, backslashes, braces, globs or comments, it refuses it, so a commit message, PR body or search that spells out `git push` is refused too. In a plain push it blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main`, a push that names no branch. It reads the branch from Claude's current directory or the `-C` directory. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push using `-c`, `--config-env`, `--git-dir` or `--work-tree`, and one whose `-C` directory is not a repo.
-- Hook 4 limits: it catches mistakes, not deliberate evasion. It only sees `git` followed by `push`, so a push through a git alias, a shell alias or function, a script, a variable that holds the command or the `git` word (`eval "$cmd"`, `$G push`), or another command that pushes (`git subtree push`, `git send-pack`) is not seen.
+- Hook 4 (push guard): treats any Bash command with the word `git` followed, anywhere later, by the word `push` (or `git-push`) as a push, in any letter case and through quotes, backslashes, `$`, braces, commas, line continuations and shell operators. Unless the whole command is one plain `git push` line, with nothing chained, piped or redirected and no quotes, `$`, backticks, backslashes, braces, globs or comments, it refuses it, so a `git commit -m` message, a PR body or a `git log | grep push` that has git and then push is refused too. In a plain push it reads git's global options (`git -C push`, `git -c k=v push`) and blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main` or `master`, a push that names no branch. It reads the branch from Claude's current directory or the `-C` directory. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push using `-c`, `--config-env`, `--git-dir` or `--work-tree`, and one whose `-C` directory is not a repo.
+- Hook 4 limits: it catches mistakes, not deliberate evasion. A push through a git alias, a shell alias or function, a script, a variable that holds the command or the `git` word (`eval "$cmd"`, `$G push`), a `git` word built from pieces (`gi${X}t push`), or a command that pushes without the word push (`git send-pack`) is not seen, and a plain line whose subcommand is not `push`, such as `git subtree push`, is not checked.
---
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index 853fb4f6..801be554 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -152,15 +152,25 @@ def shell(request: pytest.FixtureRequest) -> str:
return str(request.param)
-@pytest.fixture()
-def main_repo(repo: Path) -> Path:
- """The repo with one commit on main, so a worktree can branch from it."""
- _git(repo, "symbolic-ref", "HEAD", "refs/heads/main")
+def _commit_on(repo: Path, branch: str) -> Path:
+ _git(repo, "symbolic-ref", "HEAD", f"refs/heads/{branch}")
commit = _git(repo, "commit-tree", _git(repo, "write-tree"), "-m", "init")
_git(repo, "update-ref", "HEAD", commit)
return repo
+@pytest.fixture()
+def main_repo(repo: Path) -> Path:
+ """The repo with one commit on main, so a worktree can branch from it."""
+ return _commit_on(repo, "main")
+
+
+@pytest.fixture()
+def master_repo(repo: Path) -> Path:
+ """The repo with one commit on master."""
+ return _commit_on(repo, "master")
+
+
@pytest.mark.parametrize("cwd", ["", "sub"])
def test_format_hook_formats_python_and_keeps_unused_imports(repo: Path, cwd: str) -> None:
"""Lint fixes and formatting apply, but an import added before its first use survives."""
@@ -235,6 +245,24 @@ def test_mypy_hook_is_quiet_on_clean_code_and_outside_src(repo: Path) -> None:
assert _run(_MYPY_HOOK, _edit(outside_src), repo).returncode == 0
+def test_format_and_mypy_hooks_follow_an_edit_through_a_symlink(repo: Path, tmp_path: Path) -> None:
+ """git reports the physical repo root, so the edited path is resolved before it is matched."""
+ link = tmp_path.resolve() / "link"
+ link.symlink_to(repo, target_is_directory=True)
+ target = repo / "src" / "pkg" / "probe.py"
+ target.parent.mkdir(parents=True)
+ target.write_text('x: int ="a"\n')
+ edit = _edit(link / "src" / "pkg" / "probe.py")
+
+ formatted = _run(_FORMAT_HOOK, edit, link)
+ typed = _run(_MYPY_HOOK, edit, link)
+
+ assert formatted.returncode == 0
+ assert target.read_text() == 'x: int = "a"\n'
+ assert typed.returncode == 2
+ assert "probe.py:1: error" in typed.stderr
+
+
@pytest.mark.parametrize("relative", ["src/app.py", "sub/AGENTS.md"])
def test_main_guard_blocks_repo_edits_on_main(main_repo: Path, relative: str) -> None:
"""Only the root AGENTS.md and CLAUDE.md are exempt."""
@@ -299,6 +327,15 @@ def test_main_guard_resolves_symlinked_paths(main_repo: Path, tmp_path: Path) ->
assert agents.returncode == 0
+def test_main_guard_reads_dot_dot_like_the_write_tool(main_repo: Path, tmp_path: Path) -> None:
+ """The Write tool resolves .. lexically, even through a directory that does not exist."""
+ edit = _edit(tmp_path.resolve() / "no-such-dir" / ".." / main_repo.name / "src" / "app.py")
+
+ result = _run(_MAIN_GUARD_HOOK, edit, main_repo, CLAUDE_PROJECT_DIR=str(main_repo))
+
+ assert result.returncode == 2
+
+
def test_main_guard_fails_closed_when_it_cannot_place_the_edit(
main_repo: Path, tmp_path: Path
) -> None:
@@ -420,6 +457,7 @@ def test_commit_hook_passes_a_formatted_tree_from_a_subdirectory(repo: Path) ->
"GIT push --force",
"git PUSH origin main",
"git --shallow-file /dev/null push origin main",
+ "git --namespace x push --force origin feat",
" git push origin main",
],
)
@@ -463,6 +501,7 @@ def test_push_guard_blocks_force_pushes_and_pushes_to_main(
'git -C "$(pwd)" push origin feat',
"git push origin refs/heads/*",
"git push origin ma?n",
+ "git push origin ma[i]n",
"git push origin {main,feat}",
"echo main | xargs git push origin",
"GIT_CONFIG_PARAMETERS=\"'push.default=matching'\" git push",
@@ -482,6 +521,29 @@ def test_push_guard_blocks_force_pushes_and_pushes_to_main(
'git commit -m "docs: explain git push origin main"',
"git commit -F - <<'EOF'\nci: x\n\nRun git push from a branch.\nEOF",
'gh pr create --title x --body "Blocks git push --force"',
+ "git -C ${D}/sub push origin main",
+ "git -C ${HOME}/repo push --force origin feat",
+ "git -C ~/${N} push origin main",
+ "git -c user.name=${N} push --force",
+ "git --git-dir=${D}/.git push origin main",
+ "git -C $(dirname $(pwd))/repo push origin main",
+ "git -C ${PWD}/../repo push",
+ "gi\\\nt push origin main",
+ "{git,push} origin main",
+ "git 2>&1 push --force",
+ "git >/dev/null push origin main",
+ "git${IFS}push${IFS}--force",
+ "git $OPTS push --force",
+ "git $X push origin main",
+ "git $(echo push) origin main",
+ "${GIT:-git} push origin main",
+ "git push$IFS origin main",
+ "$(git --exec-path)/git-push origin main",
+ "git-push origin main",
+ "git stash push -m 'wip: push guard'",
+ 'git commit -m "ci: refuse pushes the push guard cannot read"',
+ "git commit -F - <<'EOF'\nci: x\n\nPush the branch first.\nEOF",
+ "git --no-pager log --oneline | grep -i push",
],
)
def test_push_guard_refuses_anything_but_a_plain_push(repo: Path, shell: str, command: str) -> None:
@@ -489,7 +551,7 @@ def test_push_guard_refuses_anything_but_a_plain_push(repo: Path, shell: str, co
result = _run(_PUSH_GUARD_HOOK, _bash(command), repo, shell=shell)
assert result.returncode == 2
- assert "mentions git push" in result.stderr
+ assert "git followed by push" in result.stderr
@pytest.mark.parametrize(
@@ -501,6 +563,8 @@ def test_push_guard_refuses_anything_but_a_plain_push(repo: Path, shell: str, co
"git -c push.default=matching push",
"git --config-env=push.default=X push",
"git -c user.name=AB push origin feat",
+ "git --git-dir ../x/.git push origin feat",
+ "git --config-env push.default=PD push",
],
)
def test_push_guard_blocks_pushes_it_cannot_read(repo: Path, shell: str, command: str) -> None:
@@ -540,15 +604,17 @@ def test_push_guard_allows_feature_and_tag_pushes(repo: Path, shell: str, comman
"command",
[
"git stash push -m wip",
- "git stash push -m 'wip: push guard'",
- 'git commit -m "ci: refuse pushes the push guard cannot read"',
- "git commit -F - <<'EOF'\nci: x\n\nPush the branch first.\nEOF",
"git log --grep=push",
- "git --no-pager log --oneline | grep -i push",
- "git -C /tmp log --oneline | grep push",
"git log --oneline git push --force",
+ "git config push.default current",
+ "git status && git config --get remote.origin.push",
+ "git commit -m 'feat: add pushover alerts' && git log -1",
+ "grep -rn push .github/workflows && git status",
+ "git-lfs push origin main",
"docker push ghcr.io/x/y:1",
+ "npm run push",
"gh pr create --title x --body-file /tmp/body.md",
+ "git commit -F /tmp/msg.txt",
],
)
def test_push_guard_ignores_commands_that_do_not_push(repo: Path, shell: str, command: str) -> None:
@@ -573,6 +639,9 @@ def test_push_guard_ignores_commands_that_do_not_push(repo: Path, shell: str, co
("git push --recurse-submodules check origin", 2),
("git push origin :", 2),
("git push -otodo origin HEAD feat", 2),
+ ("git push --repo x origin", 2),
+ ("git push --exec x origin", 2),
+ ("git push --receive-pack x origin", 2),
("git push origin v1.2.3", 0),
("git push --tags", 0),
("git push origin feat", 0),
@@ -588,6 +657,14 @@ def test_push_guard_on_main_needs_a_named_target(
assert ("Direct push to main" in result.stderr) == bool(expected)
+@pytest.mark.parametrize("command", ["git push", "git push origin HEAD"])
+def test_push_guard_treats_master_like_main(master_repo: Path, shell: str, command: str) -> None:
+ result = _run(_PUSH_GUARD_HOOK, _bash(command), master_repo, shell=shell)
+
+ assert result.returncode == 2
+ assert "Direct push to main or force push" in result.stderr
+
+
def test_push_guard_reads_the_branch_of_the_checkout_named_by_dash_c(
main_repo: Path, tmp_path: Path, shell: str
) -> None:
@@ -621,7 +698,7 @@ def test_push_guard_refuses_pushes_wrapped_in_shell_syntax(repo: Path, command:
result = _run(_PUSH_GUARD_HOOK, _bash(command), repo)
assert result.returncode == 2
- assert "mentions git push" in result.stderr
+ assert "git followed by push" in result.stderr
@pytest.mark.parametrize("command", _wrapped("git push", "git push origin HEAD"))
@@ -630,7 +707,7 @@ def test_push_guard_refuses_wrapped_pushes_on_main(main_repo: Path, command: str
result = _run(_PUSH_GUARD_HOOK, _bash(command), main_repo)
assert result.returncode == 2
- assert "mentions git push" in result.stderr
+ assert "git followed by push" in result.stderr
def test_stop_hook_warns_once_about_unfinished_markers(tmp_path: Path) -> None:
From e2987b0c10751e203469e3c98760beda43375c11 Mon Sep 17 00:00:00 2001
From: Andrea Arturo Venti Fuentes <117413846+av1155@users.noreply.github.com>
Date: Wed, 11 Nov 2026 03:07:48 -0500
Subject: [PATCH 13/13] ci: list push guard limits and pin format test
A push word built from a shell expansion, such as pu$(:)sh, or a space
held in a variable gets past the push guard, and so do push settings
stored with git config. The hook notes now list them and no longer say
the guard reads through $ and braces.
The format hook test used fixtures that only ruff format changes, so it
passed with --force-exclude dropped from the ruff check step. They now
need a lint fix as well.
---
AGENTS.md | 4 ++--
tests/test_gates/test_claude_hooks_gate.py | 12 ++++++++----
2 files changed, 10 insertions(+), 6 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 0cce9bcb..07ae542b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -470,8 +470,8 @@ In every case: fix the underlying issue, do not bypass the hook.
- Hook 1 (auto-format): only runs on `.py` and `.md` files inside the repo, and skips files that git ignores (`git check-ignore`) or that ruff excludes (`--force-exclude`). Other files (`.yml`, `.json`, `.html`) are silently skipped.
- Hook 2 (mypy): only runs when `src/**/*.py` files are changed. Test file edits do not trigger mypy. This is intentional (tests are exempt from ANN rules).
- Hook 6 (format check): if `.venv` does not exist, the hook blocks the commit. This is correct; set up the project before committing.
-- Hook 4 (push guard): treats any Bash command with the word `git` followed, anywhere later, by the word `push` (or `git-push`) as a push, in any letter case and through quotes, backslashes, `$`, braces, commas, line continuations and shell operators. Unless the whole command is one plain `git push` line, with nothing chained, piped or redirected and no quotes, `$`, backticks, backslashes, braces, globs or comments, it refuses it, so a `git commit -m` message, a PR body or a `git log | grep push` that has git and then push is refused too. In a plain push it reads git's global options (`git -C push`, `git -c k=v push`) and blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main` or `master`, a push that names no branch. It reads the branch from Claude's current directory or the `-C` directory. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push using `-c`, `--config-env`, `--git-dir` or `--work-tree`, and one whose `-C` directory is not a repo.
-- Hook 4 limits: it catches mistakes, not deliberate evasion. A push through a git alias, a shell alias or function, a script, a variable that holds the command or the `git` word (`eval "$cmd"`, `$G push`), a `git` word built from pieces (`gi${X}t push`), or a command that pushes without the word push (`git send-pack`) is not seen, and a plain line whose subcommand is not `push`, such as `git subtree push`, is not checked.
+- Hook 4 (push guard): treats any Bash command with the word `git` followed, anywhere later, by the word `push` (or `git-push`) as a push, in any letter case. Unless the whole command is one plain `git push` line, with nothing chained, piped or redirected and no quotes, `$`, backticks, backslashes, braces, globs or comments, it refuses it, so a `git commit -m` message, a PR body or a `git log | grep push` that has git and then push is refused too. In a plain push it reads git's global options (`git -C push`, `git -c k=v push`) and blocks force pushes (`-f`, `--force`, `--force-with-lease`, `+` refspecs), `--all`, `--branches` and `--mirror` (abbreviations included), `:` refspecs, any target named `main` or `master` (including `HEAD:main`, `:main` and `heads/main`), and, while the current branch is `main` or `master`, a push that names no branch. It reads the branch from Claude's current directory or the `-C` directory. Tag pushes such as `git push origin v1.2.3` or `git push --tags` go through. It refuses a push using `-c`, `--config-env`, `--git-dir` or `--work-tree`, and one whose `-C` directory is not a repo.
+- Hook 4 limits: it catches mistakes, not deliberate evasion. A push can get past it through a git alias, a shell alias or function, a script, or a variable that holds the command (`eval "$cmd"`); when its `git` or `push` word, or the space between them, comes from a shell expansion (`$G push`, `gi${X}t push`, `pu$(:)sh`, `git$S"push"`); or when it runs without the word push (`git send-pack`). The hook does not check a plain line whose subcommand is not `push`, such as `git subtree push`, or push settings stored with `git config`, such as `remote.origin.mirror` or `push.default=matching`, which can change what a plain push does.
---
diff --git a/tests/test_gates/test_claude_hooks_gate.py b/tests/test_gates/test_claude_hooks_gate.py
index 801be554..b42f18c7 100644
--- a/tests/test_gates/test_claude_hooks_gate.py
+++ b/tests/test_gates/test_claude_hooks_gate.py
@@ -64,6 +64,7 @@ def _hook(event: str, marker: str) -> str:
_STOP_HOOK = _hook("Stop", "last_assistant_message")
_UNFORMATTED_MD = "# Notes\n\n```python\nx=1\n```\n"
+_UNFIXED_PY = 'x=f"a"\n'
# The hooks reference runs shell-form hooks with sh -c (dash on Ubuntu), and the settings
# schema says its default bash shell means $SHELL when that is bash, zsh or sh.
@@ -201,15 +202,18 @@ def test_format_hook_formats_python_blocks_in_markdown(repo: Path) -> None:
def test_format_hook_leaves_ignored_and_outside_files_alone(repo: Path, tmp_path: Path) -> None:
- """ruff's --force-exclude still formats a gitignored file passed by path."""
+ """ruff's --force-exclude still formats a gitignored file passed by path.
+
+ The .py fixtures need a lint fix and formatting, so either ruff step would change them.
+ """
(repo / "ignored").mkdir()
(repo / "_build").mkdir()
untouched = {
- repo / "ignored" / "probe.py": "x=1\n",
+ repo / "ignored" / "probe.py": _UNFIXED_PY,
repo / "ignored" / "notes.md": _UNFORMATTED_MD,
repo / "config.yml": "a: 1\n",
- repo / "_build" / "probe.py": "x=1\n",
- tmp_path.resolve() / "outside.py": "x=1\n",
+ repo / "_build" / "probe.py": _UNFIXED_PY,
+ tmp_path.resolve() / "outside.py": _UNFIXED_PY,
}
for path, text in untouched.items():
path.write_text(text)