From 29a14c12760e16874d0df0a8773f471d081a9bd6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 11 Sep 2026 21:39:27 +0000 Subject: [PATCH 1/3] tools: add commit-cleaner to strip Claude attribution from commits Adds a commit-msg hook that removes Co-Authored-By: Claude and Claude-Session trailers, an installer (per-repo or global), a Claude Code PreToolUse guard against --no-verify and hooksPath bypasses, a dry-run-by-default git filter-repo wrapper for existing commits, tests, and a workflow that runs them. --- .github/workflows/commit-cleaner-tests.yml | 27 ++++ tools/commit-cleaner/README.md | 89 +++++++++++ .../__pycache__/guard.cpython-311.pyc | Bin 0 -> 9283 bytes .../claude-settings.example.json | 25 ++++ tools/commit-cleaner/clean-history.sh | 84 +++++++++++ tools/commit-cleaner/commit-msg | 50 +++++++ tools/commit-cleaner/guard.py | 138 ++++++++++++++++++ tools/commit-cleaner/install.sh | 97 ++++++++++++ tools/commit-cleaner/test.sh | 80 ++++++++++ 9 files changed, 590 insertions(+) create mode 100644 .github/workflows/commit-cleaner-tests.yml create mode 100644 tools/commit-cleaner/README.md create mode 100644 tools/commit-cleaner/__pycache__/guard.cpython-311.pyc create mode 100644 tools/commit-cleaner/claude-settings.example.json create mode 100755 tools/commit-cleaner/clean-history.sh create mode 100755 tools/commit-cleaner/commit-msg create mode 100755 tools/commit-cleaner/guard.py create mode 100755 tools/commit-cleaner/install.sh create mode 100755 tools/commit-cleaner/test.sh diff --git a/.github/workflows/commit-cleaner-tests.yml b/.github/workflows/commit-cleaner-tests.yml new file mode 100644 index 0000000..87066e9 --- /dev/null +++ b/.github/workflows/commit-cleaner-tests.yml @@ -0,0 +1,27 @@ +name: commit-cleaner tests + +# tools/commit-cleaner is copied into other repositories as their .githooks and +# .claude/hooks; a regression here would silently stop stripping attribution +# everywhere. Runs only when the tool or this workflow changes. + +on: + push: + branches: [main] + paths: + - tools/commit-cleaner/** + - .github/workflows/commit-cleaner-tests.yml + pull_request: + paths: + - tools/commit-cleaner/** + - .github/workflows/commit-cleaner-tests.yml + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - run: tools/commit-cleaner/test.sh diff --git a/tools/commit-cleaner/README.md b/tools/commit-cleaner/README.md new file mode 100644 index 0000000..a3ee905 --- /dev/null +++ b/tools/commit-cleaner/README.md @@ -0,0 +1,89 @@ +# commit-cleaner + +Keeps Claude Code's attribution out of Git history. Claude Code appends +`Co-Authored-By: Claude … ` and `Claude-Session: …` +trailers to every commit it makes. These scripts strip them at commit time, +stop the hook being bypassed from inside a Claude Code session, and scrub +commits that already carry them. + +| File | Purpose | +| --- | --- | +| `commit-msg` | Git `commit-msg` hook. Removes the attribution lines; leaves everything else byte-identical. | +| `install.sh` | Copies the hook into a repository, or into a global hooks directory for every repository. Chains any hook already there. | +| `guard.py` | Claude Code `PreToolUse` hook. Refuses `git commit --no-verify`, `-n`, `core.hooksPath` overrides, and edits to the hook itself. | +| `clean-history.sh` | `git filter-repo` wrapper for commits that already have the trailers. Dry-run by default. | +| `claude-settings.example.json` | Drop-in `.claude/settings.json` for a repository that vendors the hook under `.githooks/`. | +| `test.sh` | Tests for all of the above. | + +## What is removed + +* `Co-Authored-By:` lines whose address is `@anthropic.com`, or whose name starts with `Claude` +* `Claude-Session:` lines +* `Generated with [Claude Code](…)` footers, with or without the emoji +* bare `https://claude.ai/code/session_…` lines + +Human `Co-Authored-By:` trailers are kept. A message that is nothing but +attribution becomes empty, so Git aborts that commit rather than recording an +empty message. + +## Option 1: one repository + +```sh +tools/commit-cleaner/install.sh /path/to/repo +``` + +This copies the hook into that repository's hooks directory (honouring +`core.hooksPath` and worktrees). Re-run to update. `--uninstall` removes it and +restores any hook it chained. + +## Option 2: every repository on this machine + +```sh +tools/commit-cleaner/install.sh --global +``` + +Sets `core.hooksPath` to `~/.config/git/hooks` (or uses the one already set) +and installs the hook there. Note that a global `core.hooksPath` makes Git +ignore each repository's own `.git/hooks/`, so move any such hooks into the +global directory. + +## Option 3: checked into a repository, active in Claude Code sessions + +For repositories worked on through Claude Code on the web, where each session +is a fresh clone with no hooks installed: + +1. Copy `commit-msg` to `.githooks/commit-msg` in the repository. +2. Copy `guard.py` to `.claude/hooks/commit-guard.py`. +3. Copy `claude-settings.example.json` to `.claude/settings.json`. + +The `SessionStart` hook points `core.hooksPath` at `.githooks/` at the start of +every session, and the `PreToolUse` hook blocks bypasses. Contributors working +locally run `git config core.hooksPath .githooks` once. `beanstalk` and +`docassemble` are set up this way. + +## Scrubbing existing commits + +```sh +pip install git-filter-repo +tools/commit-cleaner/clean-history.sh -n 5 # dry run: shows what would change +tools/commit-cleaner/clean-history.sh -n 5 --force # rewrite HEAD~5..HEAD +``` + +This rewrites history. Every affected commit gets a new hash; a branch that was +already pushed needs `git push --force-with-lease`, and anyone who has the old +commits must rebase. Make a backup branch first. On a shared branch, prefer +leaving history alone and relying on the hook from now on. + +## Limits + +* The hook runs only on `git commit`. `cherry-pick`, `rebase`, and + `commit --amend` without an edited message replay the stored message. +* GitHub's squash-merge box is composed in the browser and is not covered. +* The guard unwraps one layer of `bash -c`, `eval`, `$(…)`, and backticks. It + is a speed bump, not a sandbox; the `commit-msg` hook is the real control. +* Branch protection cannot enforce trailer content. If a clean history must be + guaranteed, add a CI check that greps `git log` on pull requests. + +Based on the approach in [ya8282/commit-cleaner-hook](https://github.com/ya8282/commit-cleaner-hook), +reimplemented here so the foundation's repositories do not depend on a +third-party plugin. diff --git a/tools/commit-cleaner/__pycache__/guard.cpython-311.pyc b/tools/commit-cleaner/__pycache__/guard.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1602eae99e1857faf42bbc9ce0c37f94c54170b GIT binary patch literal 9283 zcmbt4TTB~SmbdKky8r_w;SobYNP-hgLZ_1ec?|&)@*)q?=_H*r6s`gsjP0%}NN|k8 zv@%+!MXQ~N5$@i!+C3U|lj%sq*D6}g?q=p^=VL$0$WpA5SVdZ`w7p+$Wmn4P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k?6#2#YI(1ryarIwBo}@a0&yQhqt}CYTSC%!dl|;j6SE--7J79$4$SCl@MU!D(AW zaG{YiW($J^a)DErzrfO-GqZ?Xa1=OHnF|g%=NtmXT)Oy_qLAi-18sb@!Rxdy;qI8^KmHfoV*MJ9#sl%ch)s3liT!`iEQ|aNoJlg%>K} zqSGA=^ZHp`p&O;SA}NxWc8m~iZg^L@5mVkWKn!-(g0B^a{M@9V()glQwUPp_KM27} zQ})I}birW7^8i!>u}57t2ywzKuuA&^94}%;!68%l_XE|^ciSTb$%%+BUBLPmWOC|d z0-5-Tf>sd9cj;AAkeeX{aGaE!i4qQ8z`;gBpDI1cdHo``O|U~Qy#@fWPo3W2SgqK! z;QG4f(aA)`_GHEOh$&)vwQ7UioiY@FRkLm04BMJ*-WDN02t67cIP_>L{hK?V-iaPe zm>QC%hWP#!lS?tVH25i7#TN%ZI~WZoY|Tkqvtrx1qYODb3VH7 z{>1!5!d#m)*DB;)cQY$tA$?lkh`z1w*6IIDQ2s5EV-=rqEh2~o_P4gXTeGDm(X#LSUj3R&mKFKyIQ_9z_q@QJ}h!KWB7PO2=r zHI3j?41Ps*P&2; exit 1 ;; + esac + shift +done + +git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo "not inside a git repository" >&2; exit 1; } +command -v git-filter-repo >/dev/null 2>&1 || git filter-repo --version >/dev/null 2>&1 \ + || { echo "git-filter-repo is not installed (pip install git-filter-repo)" >&2; exit 1; } + +if [ -n "$(git status --porcelain)" ]; then + echo "working tree is not clean; commit or stash first" >&2; exit 1 +fi + +if [ -z "$range" ]; then + total=$(git rev-list --count HEAD) + if [ "$total" -le "$count" ]; then + range="HEAD" # whole (short) history + else + range="HEAD~$count..HEAD" + fi +fi + +branch=$(git symbolic-ref --short -q HEAD || echo "(detached)") +echo "branch: $branch" +echo "range: $range" +echo "commits carrying attribution in range:" +git log --format=' %h %s' --grep='Co-Authored-By: Claude' --grep='Claude-Session:' --grep='anthropic.com' --grep='Generated with \[Claude Code\]' -i "$range" || true +echo + +if [ "$force" -ne 1 ]; then + echo "dry run. Re-run with --force to rewrite these commits." + echo "Back up first: git branch backup/pre-clean-$(date +%Y%m%d)" + exit 0 +fi + +# filter-repo insists on a fresh clone unless told otherwise; --refs limits the +# rewrite to the chosen range so the rest of history keeps its hashes. +git filter-repo --force --refs "$range" --message-callback ' +import re +msg = message.decode("utf-8", "surrogateescape") +pat = re.compile( + r"^(Co-Authored-By:\s*(Claude\b[^\n]*|[^\n]*<[^>\n]*@anthropic\.com>)" + r"|Claude-Session:[^\n]*" + r"|[^\n]*Generated with \[Claude Code\]\([^\n]*" + r"|\s*https://claude\.ai/code/session_[A-Za-z0-9_-]+\s*)$\n?", + re.IGNORECASE | re.MULTILINE, +) +new = pat.sub("", msg) +if new != msg: + new = new.rstrip("\n") + "\n" +return new.encode("utf-8", "surrogateescape") +' +echo +echo "done. Rewritten commits:" +git log --oneline -"$count" +echo "If the branch was already pushed: git push --force-with-lease" diff --git a/tools/commit-cleaner/commit-msg b/tools/commit-cleaner/commit-msg new file mode 100755 index 0000000..dbad6dc --- /dev/null +++ b/tools/commit-cleaner/commit-msg @@ -0,0 +1,50 @@ +#!/bin/sh +# commit-msg hook: strip Claude Code attribution from the commit message. +# +# Removes, wherever they appear in the message: +# Co-Authored-By: Claude ... <...@anthropic.com> +# Claude-Session: https://claude.ai/code/session_... +# Generated with [Claude Code](...) (with or without the robot emoji) +# bare https://claude.ai/code/session_... lines +# +# Ordinary Co-Authored-By trailers for human collaborators are kept. A message +# with nothing to strip is left byte-identical. Trailing blank lines left +# behind by the removal are trimmed; git's own cleanup collapses the rest. +# +# Installed by tools/commit-cleaner/install.sh (see README.md). Safe under +# `set -e`: every failure path exits 0 with the original message intact, so +# the hook can never block a commit. + +msg_file="$1" +[ -n "$msg_file" ] && [ -f "$msg_file" ] || exit 0 + +tmp="${msg_file}.commit-cleaner.$$" +trap 'rm -f "$tmp"' EXIT + +awk ' +function is_attribution(line) { + l = tolower(line) + if (l ~ /^co-authored-by:[[:space:]]*.*<[^>]*@anthropic\.com>[[:space:]]*$/) return 1 + if (l ~ /^co-authored-by:[[:space:]]*claude([[:space:]]|$)/) return 1 + if (l ~ /^claude-session:/) return 1 + if (l ~ /generated with \[claude code\]\(/) return 1 + if (l ~ /^[[:space:]]*https:\/\/claude\.ai\/code\/session_[a-z0-9_-]+[[:space:]]*$/) return 1 + return 0 +} +{ + if (is_attribution($0)) { removed = 1; next } + lines[++n] = $0 +} +END { + if (!removed) exit 3 # nothing to do: caller keeps the file as-is + while (n > 0 && lines[n] ~ /^[[:space:]]*$/) n-- + for (i = 1; i <= n; i++) print lines[i] +} +' "$msg_file" > "$tmp" +status=$? + +case "$status" in + 0) cat "$tmp" > "$msg_file" ;; # rewrite in place, preserving the inode + *) : ;; # 3 = unchanged; anything else = leave alone +esac +exit 0 diff --git a/tools/commit-cleaner/guard.py b/tools/commit-cleaner/guard.py new file mode 100755 index 0000000..380a08b --- /dev/null +++ b/tools/commit-cleaner/guard.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Claude Code PreToolUse hook: keep the commit-msg hook from being bypassed. + +Reads the Bash tool call from stdin (Claude Code hook JSON) and exits 2 with a +reason when the command would skip git hooks for a commit. Exit 0 lets the +call through. Nothing here rewrites the command; it only refuses the evasions. + +Blocked, in commands that invoke `git commit`: + --no-verify / -n (and -n inside a flag cluster such as -anm) + -c core.hooksPath=... / --config-env / core.hooksPath overrides + HOME=, GIT_DIR=, GIT_CONFIG_GLOBAL= prefixes that relocate the hooks + git config ... core.hooksPath (changing where hooks live) +Also blocked: writing over .git/hooks/commit-msg or a .githooks/commit-msg. + +Wire it in .claude/settings.json: + {"hooks": {"PreToolUse": [{"matcher": "Bash", + "hooks": [{"type": "command", "command": "python3 /guard.py"}]}]}} +""" +import json +import re +import shlex +import sys + + +def deny(reason: str) -> None: + # Exit code 2 = block the tool call; stderr is shown to Claude as feedback. + sys.stderr.write(f"commit-cleaner guard: {reason}\n") + sys.exit(2) + + +def segments(cmd: str): + """Split a shell command into simple-command word lists, unwrapping one + layer of `bash -c '...'`, `sh -c`, `eval`, and $(...)/backtick bodies.""" + # Pull out substitution bodies so nested commands are inspected too. + bodies = [cmd] + bodies += re.findall(r"\$\(([^()]*)\)", cmd) + bodies += re.findall(r"`([^`]*)`", cmd) + out = [] + for body in bodies: + for piece in re.split(r"(?= len(words): + return + sub, args = words[i], words[i + 1:] + + if sub == "config" and any("hookspath" in a.lower() for a in args): + deny("changing core.hooksPath would disable the commit-msg hook") + + if sub != "commit": + return + + for a in args: + if a in ("--no-verify",) or a.startswith("--no-verif"): + deny("`--no-verify` skips the commit-msg hook; commit without it") + if re.match(r"^-[a-zA-Z]*n[a-zA-Z]*$", a): # -n, -an, -anm ... + deny("`-n` (--no-verify) skips the commit-msg hook; commit without it") + for o in opts: + if "hookspath" in o.lower(): + deny("overriding core.hooksPath on the command line skips the hook") + if any(o == "--git-dir" or o.startswith("--git-dir=") for o in opts): + deny("relocating --git-dir for a commit bypasses the repository hooks") + for k in ("HOME", "GIT_DIR", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_CONFIG_PARAMETERS", "XDG_CONFIG_HOME"): + if k in env: + deny(f"setting {k} for a commit can relocate the hooks; commit without it") + + +def main() -> None: + try: + payload = json.load(sys.stdin) + except Exception: + sys.exit(0) + if payload.get("tool_name") != "Bash": + sys.exit(0) + cmd = (payload.get("tool_input") or {}).get("command") or "" + if "commit" not in cmd and "hooks" not in cmd.lower(): + sys.exit(0) + for words in segments(cmd): + check(list(words)) + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/tools/commit-cleaner/install.sh b/tools/commit-cleaner/install.sh new file mode 100755 index 0000000..76f1522 --- /dev/null +++ b/tools/commit-cleaner/install.sh @@ -0,0 +1,97 @@ +#!/bin/sh +# Install the commit-cleaner commit-msg hook. +# +# install.sh install into the current repository (.git/hooks) +# install.sh /path/to/repo install into that repository +# install.sh --global install for every repository of this user via a +# hooks directory at ~/.config/git/hooks and +# core.hooksPath (existing global hooksPath is +# respected and the hook is placed there instead) +# install.sh --uninstall [repo|--global] +# +# The hook is copied, not symlinked, so a repository keeps working when this +# checkout moves. Re-running the installer updates the copy. If a commit-msg +# hook already exists and is not ours, it is preserved and chained: our hook +# runs first, then the original. + +set -eu + +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +src="$here/commit-msg" +marker="commit-cleaner" + +die() { printf 'install.sh: %s\n' "$*" >&2; exit 1; } + +hooks_dir_for_repo() { + repo=$1 + git -C "$repo" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die "$repo is not a git repository" + # Honors core.hooksPath (repo or global) and worktrees alike. + git -C "$repo" rev-parse --path-format=absolute --git-path hooks +} + +install_into() { + dir=$1 + mkdir -p "$dir" + target="$dir/commit-msg" + if [ -f "$target" ] && ! grep -q "$marker" "$target"; then + # Preserve a foreign hook and chain to it. + mv "$target" "$dir/commit-msg.pre-commit-cleaner" + { + cat "$src" + printf '\n# --- chained by commit-cleaner: run the hook that was here before ---\n' + printf 'exec "$(dirname -- "$0")/commit-msg.pre-commit-cleaner" "$@"\n' + } > "$target" + # The copied hook ends in `exit 0`; drop that line so the chain runs. + sed -i.bak '/^exit 0$/d' "$target" && rm -f "$target.bak" + printf 'chained existing commit-msg hook as %s\n' "$dir/commit-msg.pre-commit-cleaner" + else + cp "$src" "$target" + fi + chmod +x "$target" + printf 'installed %s\n' "$target" +} + +uninstall_from() { + dir=$1 + target="$dir/commit-msg" + [ -f "$target" ] || { printf 'nothing installed at %s\n' "$target"; return; } + grep -q "$marker" "$target" || die "$target is not the commit-cleaner hook; leaving it alone" + rm -f "$target" + if [ -f "$dir/commit-msg.pre-commit-cleaner" ]; then + mv "$dir/commit-msg.pre-commit-cleaner" "$target" + printf 'restored previous hook at %s\n' "$target" + else + printf 'removed %s\n' "$target" + fi +} + +mode=install +target_arg="" +for a in "$@"; do + case "$a" in + --uninstall) mode=uninstall ;; + --global) target_arg=--global ;; + -h|--help) sed -n '2,16p' "$0"; exit 0 ;; + -*) die "unknown option $a" ;; + *) target_arg=$a ;; + esac +done + +if [ "$target_arg" = "--global" ]; then + hp=$(git config --global --get core.hooksPath || true) + if [ -z "$hp" ]; then + hp="${XDG_CONFIG_HOME:-$HOME/.config}/git/hooks" + if [ "$mode" = install ]; then + git config --global core.hooksPath "$hp" + printf 'set global core.hooksPath to %s\n' "$hp" + printf 'note: repositories with their own .git/hooks/* scripts now need those moved into %s\n' "$hp" + fi + fi + case "$hp" in "~"*) hp="$HOME${hp#\~}" ;; esac + if [ "$mode" = install ]; then install_into "$hp"; else uninstall_from "$hp"; fi +else + repo=${target_arg:-.} + dir=$(hooks_dir_for_repo "$repo") + if [ "$mode" = install ]; then install_into "$dir"; else uninstall_from "$dir"; fi +fi diff --git a/tools/commit-cleaner/test.sh b/tools/commit-cleaner/test.sh new file mode 100755 index 0000000..20a4d71 --- /dev/null +++ b/tools/commit-cleaner/test.sh @@ -0,0 +1,80 @@ +#!/bin/sh +# Tests for the commit-msg hook, the installer, and the PreToolUse guard. +# Run: tools/commit-cleaner/test.sh (needs git and python3) +set -eu +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +fails=0 +pass() { printf 'ok %s\n' "$1"; } +fail() { printf 'FAIL %s\n' "$1"; fails=$((fails+1)); } + +# ---- hook: message rewriting ------------------------------------------- +run_hook() { printf '%b' "$1" > "$work/msg"; "$here/commit-msg" "$work/msg"; cat "$work/msg"; } + +out=$(run_hook 'feat: add thing\n\nBody line.\n\nCo-Authored-By: Claude Fable 5.1 \nClaude-Session: https://claude.ai/code/session_01ABC\n') +[ "$out" = "$(printf 'feat: add thing\n\nBody line.')" ] && pass "strips trailers and trailing blanks" || { fail "strips trailers: got [$out]"; } + +out=$(run_hook 'fix: x\n\nCo-Authored-By: Jane Doe \nCo-Authored-By: claude \n') +[ "$out" = "$(printf 'fix: x\n\nCo-Authored-By: Jane Doe ')" ] && pass "keeps human co-authors" || fail "keeps human co-authors: [$out]" + +out=$(run_hook 'docs: y\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nhttps://claude.ai/code/session_01MU3X\n') +[ "$out" = "docs: y" ] && pass "strips generated-with footer and bare session URL" || fail "footer: [$out]" + +printf 'chore: clean message\n\nNothing to see.\n\n# comment line\n' > "$work/msg"; cp "$work/msg" "$work/orig" +"$here/commit-msg" "$work/msg" +cmp -s "$work/msg" "$work/orig" && pass "clean message is byte-identical" || fail "clean message modified" + +printf 'Co-Authored-By: Claude \n' > "$work/msg" +"$here/commit-msg" "$work/msg"; [ ! -s "$work/msg" ] && pass "attribution-only message becomes empty (git then aborts the commit)" || fail "attribution-only" + +"$here/commit-msg" "$work/does-not-exist" && pass "missing file exits 0" || fail "missing file" + +# ---- hook: end to end in a real repository ----------------------------- +repo="$work/repo"; git init -q "$repo"; cd "$repo" +git config user.name t; git config user.email t@example.org; git config commit.gpgsign false +"$here/install.sh" "$repo" >/dev/null +echo a > a; git add a +git commit -q -m "first" -m "Co-Authored-By: Claude Opus " -m "Claude-Session: https://claude.ai/code/session_x" +[ "$(git log -1 --format=%B)" = "first" ] && pass "installed hook cleans a real commit" || fail "real commit: [$(git log -1 --format=%B)]" + +# chaining a pre-existing hook +repo2="$work/repo2"; git init -q "$repo2"; cd "$repo2" +git config user.name t; git config user.email t@example.org; git config commit.gpgsign false +printf '#!/bin/sh\necho chained-ran > "%s/chained"\n' "$work" > .git/hooks/commit-msg; chmod +x .git/hooks/commit-msg +"$here/install.sh" >/dev/null +echo b > b; git add b; git commit -q -m "second" -m "Claude-Session: https://claude.ai/code/session_y" +[ -f "$work/chained" ] && [ "$(git log -1 --format=%B)" = "second" ] && pass "chains an existing commit-msg hook" || fail "chain" +"$here/install.sh" --uninstall >/dev/null +grep -q chained-ran .git/hooks/commit-msg && pass "uninstall restores the previous hook" || fail "uninstall restore" + +# ---- hook: core.hooksPath (.githooks) layout --------------------------- +repo3="$work/repo3"; git init -q "$repo3"; cd "$repo3" +git config user.name t; git config user.email t@example.org; git config commit.gpgsign false +mkdir .githooks; cp "$here/commit-msg" .githooks/; git config core.hooksPath .githooks +echo c > c; git add c; git commit -q -m "third" -m "Co-Authored-By: Claude " +[ "$(git log -1 --format=%B)" = "third" ] && pass "works via core.hooksPath=.githooks" || fail "hooksPath" + +# ---- guard -------------------------------------------------------------- +guard() { printf '{"tool_name":"Bash","tool_input":{"command":%s}}' "$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$1")" | python3 "$here/guard.py" 2>/dev/null; } +allow() { guard "$1" && pass "guard allows: $1" || fail "guard wrongly blocked: $1"; } +block() { if guard "$1"; then fail "guard wrongly allowed: $1"; else pass "guard blocks: $1"; fi; } +allow 'git commit -m "normal"' +allow 'git add -A && git commit -am "msg" && git push -u origin b' +allow 'git commit -m "note: we no longer use --no-verify anywhere"' +allow 'git log --oneline -n 5' +allow 'npm test' +block 'git commit --no-verify -m x' +block 'git commit --no-verif -m x' +block 'git commit -n -m x' +block 'git commit -anm x' +block 'git -c core.hooksPath=/dev/null commit -m x' +block 'HOME=/tmp git commit -m x' +block 'bash -c "git commit -n -m x"' +block 'eval "git commit --no-verify -m x"' +block 'git config core.hooksPath /nowhere' +block 'rm .git/hooks/commit-msg' +block 'echo "$(git commit -n -m x)"' + +echo +[ "$fails" -eq 0 ] && echo "all tests passed" || { echo "$fails test(s) failed"; exit 1; } From 385a8493af08d336405e906537ea6321e7f0ac95 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 11 Sep 2026 22:07:11 +0000 Subject: [PATCH 2/3] commit-cleaner: turn attribution off via settings, make SessionStart cwd-safe Adds the supported attribution.commit="" / attribution.sessionUrl=false setting to the example settings and documents it as the first line of defense; the hook stays as a backstop. The SessionStart command now cds into CLAUDE_PROJECT_DIR first, so it works when the session's working directory is not the repository. --- tools/commit-cleaner/README.md | 25 ++++++++++++++++++- .../claude-settings.example.json | 6 ++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/tools/commit-cleaner/README.md b/tools/commit-cleaner/README.md index a3ee905..250930c 100644 --- a/tools/commit-cleaner/README.md +++ b/tools/commit-cleaner/README.md @@ -15,6 +15,28 @@ commits that already carry them. | `claude-settings.example.json` | Drop-in `.claude/settings.json` for a repository that vendors the hook under `.githooks/`. | | `test.sh` | Tests for all of the above. | +## First line of defense: turn the trailers off + +Claude Code has a supported setting that stops it writing the trailers in the +first place. Put this in `.claude/settings.json` (project) or +`~/.claude/settings.json` (every project on your machine): + +```json +{ + "attribution": { + "commit": "", + "sessionUrl": false + } +} +``` + +`commit: ""` removes the `Co-Authored-By` trailer and `sessionUrl: false` +removes the `Claude-Session:` link that cloud and Remote Control sessions add. +Add `"pr": ""` to drop the pull-request footer too. This works everywhere the +settings file loads, with no git configuration. The hook below is the backstop +for anything that still slips through (older clients, other tools, pasted +messages). + ## What is removed * `Co-Authored-By:` lines whose address is `@anthropic.com`, or whose name starts with `Claude` @@ -54,7 +76,8 @@ is a fresh clone with no hooks installed: 1. Copy `commit-msg` to `.githooks/commit-msg` in the repository. 2. Copy `guard.py` to `.claude/hooks/commit-guard.py`. -3. Copy `claude-settings.example.json` to `.claude/settings.json`. +3. Copy `claude-settings.example.json` to `.claude/settings.json`. It carries + the `attribution` setting above plus the two hooks. The `SessionStart` hook points `core.hooksPath` at `.githooks/` at the start of every session, and the `PreToolUse` hook blocks bypasses. Contributors working diff --git a/tools/commit-cleaner/claude-settings.example.json b/tools/commit-cleaner/claude-settings.example.json index 5165e25..c38bba0 100644 --- a/tools/commit-cleaner/claude-settings.example.json +++ b/tools/commit-cleaner/claude-settings.example.json @@ -1,11 +1,15 @@ { + "attribution": { + "commit": "", + "sessionUrl": false + }, "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", - "command": "git config core.hooksPath .githooks" + "command": "cd \"${CLAUDE_PROJECT_DIR:-.}\" && git config core.hooksPath .githooks" } ] } From 40ac2e51653597b2895ab91e66815e4cd2016001 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 11 Sep 2026 22:14:05 +0000 Subject: [PATCH 3/3] commit-cleaner: format guard.py to black/ruff style Repositories that run ruff format --check or black over the whole tree rejected the vendored copy. No behaviour change; tests still pass. --- tools/commit-cleaner/guard.py | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/tools/commit-cleaner/guard.py b/tools/commit-cleaner/guard.py index 380a08b..a8b0d59 100755 --- a/tools/commit-cleaner/guard.py +++ b/tools/commit-cleaner/guard.py @@ -16,6 +16,7 @@ {"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "python3 /guard.py"}]}]}} """ + import json import re import shlex @@ -79,8 +80,18 @@ def check(words): if not words or words[0] != "git": # Tampering with the hook file itself. joined = " ".join(words) - if re.search(r"hooks/commit-msg|\.githooks/commit-msg", joined) and words[0] in ( - "rm", "mv", "cp", "chmod", "truncate", "tee", "sed", "install", "ln", + if re.search(r"hooks/commit-msg|\.githooks/commit-msg", joined) and words[ + 0 + ] in ( + "rm", + "mv", + "cp", + "chmod", + "truncate", + "tee", + "sed", + "install", + "ln", ): deny("refusing to modify or remove the commit-msg hook") return @@ -89,14 +100,21 @@ def check(words): opts, i = [], 1 while i < len(words) and words[i].startswith("-"): opts.append(words[i]) - if words[i] in ("-c", "-C", "--git-dir", "--work-tree", "--config-env", "--exec-path"): + if words[i] in ( + "-c", + "-C", + "--git-dir", + "--work-tree", + "--config-env", + "--exec-path", + ): if i + 1 < len(words): opts.append(words[i + 1]) i += 1 i += 1 if i >= len(words): return - sub, args = words[i], words[i + 1:] + sub, args = words[i], words[i + 1 :] if sub == "config" and any("hookspath" in a.lower() for a in args): deny("changing core.hooksPath would disable the commit-msg hook") @@ -114,7 +132,14 @@ def check(words): deny("overriding core.hooksPath on the command line skips the hook") if any(o == "--git-dir" or o.startswith("--git-dir=") for o in opts): deny("relocating --git-dir for a commit bypasses the repository hooks") - for k in ("HOME", "GIT_DIR", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_CONFIG_PARAMETERS", "XDG_CONFIG_HOME"): + for k in ( + "HOME", + "GIT_DIR", + "GIT_CONFIG_GLOBAL", + "GIT_CONFIG_SYSTEM", + "GIT_CONFIG_PARAMETERS", + "XDG_CONFIG_HOME", + ): if k in env: deny(f"setting {k} for a commit can relocate the hooks; commit without it")