Artificial Intelligence

Block Claude's Co-Authored-By in Git Commits with a Claude Code Hook

Team Nippysoft
• • 17 min read
Block Claude's Co-Authored-By in Git Commits with a Claude Code Hook

When Claude Code makes a commit for you, it closes the message with a trailer by default: a Co-Authored-By line in Claude's name. The fix that makes the rounds is a one-liner: empty the attribution setting and you're done. We tested it in real Claude Code 2.1.317 sessions, and there's a catch: the setting drops the trailer Claude adds on its own, but if someone asks for one, the commit still carries it.

The setting and a CLAUDE.md only change what the model reads; a hook is code Claude Code always runs, and a PreToolUse hook runs before every tool call. This post sets up all three layers: the setting, which turns off the default behavior; a Node PreToolUse hook that rejects git commit commands carrying a Claude trailer, tested through Bash and PowerShell; and a git hook as a backstop. It also covers how to test them and where they fall short.

What Claude Code adds and what attribution turns off

With no configuration, Claude Code adds Co-Authored-By: <name> <noreply@anthropic.com> to every commit, named after the model in use, and the text 🤖 Generated with [Claude Code](https://claude.com/claude-code) to every pull request. In our tests, a plain commit request produced Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>.

The first layer is the attribution setting:

  • "commit": "" hides the trailer and "pr": "" hides the pull request text. The example uses these because they also work before v2.1.281; in the cloud, hiding the session link also takes "sessionUrl": false.
  • "attribution": false hides everything, but it requires v2.1.281 or later. Older versions reject the value and skip the entire settings file that holds it.
  • includeCoAuthoredBy, the old setting, has been deprecated since v2.0.62.

Why the setting is not a guarantee

According to the documentation, Claude Code tells the model that the user's own instructions about attribution, such as a CLAUDE.md, take precedence over the setting's lines, unless those lines come from managed settings. The setting changes what the model is asked to do, and the model writes the trailer inside the shell command, and if the user asks for it, nothing stops it.

We checked it on Windows 11 with Haiku sessions, with no user settings and no CLAUDE.md:

ConfigurationPromptResult
No setting, no hookAsks for the trailerCommit with trailer
Empty attribution onlyPlain commitCommit without trailer
Empty attribution onlyAsks for the trailerCommit with trailer
attribution plus hookAsks for the trailer, through Bash and through PowerShellBlocked; through PowerShell, even in bypassPermissions mode

A CLAUDE.md rule won't do it either, as the documentation itself says: Claude treats it "as context, not enforced configuration", and to block an action regardless of what Claude decides, it points to a PreToolUse hook. The underlying mistake is relying on an instruction for something that needs a rule.

The PreToolUse hook that blocks the trailer

Claude Code runs hooks at fixed points in its lifecycle, which the documentation calls deterministic control. PreToolUse runs before every tool call and receives a JSON object on stdin, with the command in tool_input.command. With exit code 2, the call is blocked and Claude receives the stderr text; with 0 it goes through the normal permission flow.

PreToolUse hook flow: Claude's command goes through no-coauthor.js; with a Claude trailer it exits 2 and is blocked, without it exits 0 and the permission flow continues 1) Claude writes a git commit command. 2) Before running it, Claude Code fires the PreToolUse hook, which runs node no-coauthor.js with the call's JSON. 3) If the command, or the file it passes with -F, carries a Claude Co-Authored-By line, the script exits with code 2: the call is blocked and Claude receives the stderr text. 4) Otherwise it exits 0 and the call goes through the normal permission flow. Claude writes git commit -m "…" Bash or PowerShell PreToolUse node no-coauthor.js reads the command and its -F file exit 2: blocked Claude Co-Authored-By found Claude receives the stderr text exit 0: no objection commit without that trailer normal permission flow continues The hook runs before every Bash or PowerShell call; it only blocks the commit that carries the trailer.

The configuration: .claude/settings.json

{
  "attribution": {
    "commit": "",
    "pr": ""
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash|PowerShell",
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/no-coauthor.js"],
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}
  • The Bash|PowerShell matcher. On Windows, Claude Code can run git through the PowerShell tool: it turns on by itself without Git Bash, and with Git Bash, by default for claude.ai and Console accounts. One of our blocks came through as PreToolUse:PowerShell; with a Bash-only matcher, the hook would not have fired.
  • Exec form. With args, Claude Code launches node directly, with no shell in between. It works the same on Windows, macOS and Linux. ${CLAUDE_PROJECT_DIR} is the project root where the session started.
  • "onFailure": "block". By default, on most events, when a hook fails, the action goes ahead, so a script with a mistyped path would let everything through. With "block" (v2.1.295 or later), the call is blocked instead.

The script: .claude/hooks/no-coauthor.js

// .claude/hooks/no-coauthor.js
// PreToolUse: blocks a git commit whose message carries a Claude Co-Authored-By line,
// either in the command itself (-m, heredoc) or in the -F/--file or stdin message file,
// and it doesn't let Claude turn off git's own hooks (--no-verify, -n, -c core.hooksPath).
const fs = require("fs");
const path = require("path");
const TRAILER = /co-authored-by\s*[:=][^\n]*(claude|anthropic)/i; // also --trailer "Co-Authored-By=…"
const NO_VERIFY = "this commit uses --no-verify (-n), which skips git's own hooks. Commit without it.";
const LIVE = "the commit uses $( ), <( ), backticks or printf escapes, so the hook can't see its final text. Write the message in the command or in a file.";

function block(reason) {
  process.stderr.write(`Blocked by hook: ${reason}\n`);
  process.exit(2); // 2 = block; Claude receives the stderr text
}
const unparsable = () => block("could not parse this command (unclosed quote or $( )).");

// Splits the command into simple commands without cutting inside quotes, $( ), heredocs
// or here-strings. Bash escapes with \ and PowerShell with `.
// Marks as "live" the words the shell will change when it runs: $( ), <( ), backticks.
function parse(src, ps) {
  const esc = ps ? "`" : "\\";
  let live = false; // the current word holds something that gets expanded
  const single = (j) => { // '...'; in PowerShell, '' is a quote
    for (j++; j < src.length; j++)
      if (src[j] === "'") { if (ps && src[j + 1] === "'") j++; else return j + 1; }
    unparsable();
  };
  const tick = (j) => { const k = src.indexOf("`", j + 1); return k < 0 ? unparsable() : k + 1; }; // `...` in bash
  // $(cat <<'EOF' ... EOF), as Claude Code writes its commits: the text is already in the command
  const literalCat = (s) => {
    const m = /^\s*cat\s+<<-?\s*(['"]?)([\w.-]+)\1[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\2\s*$/.exec(s);
    return !ps && !!m && (m[1] !== "" || !/\$\(|`/.test(m[3]));
  };
  const subst = (j) => { const k = sub(j + 2); if (!literalCat(src.slice(j + 2, k - 1))) live = true; return k; };
  const double = (j) => { // "..."
    for (j++; j < src.length; j++) {
      if (src[j] === esc) j++;
      else if (src.startsWith("$(", j)) j = subst(j) - 1;
      else if (!ps && src[j] === "`") { live = true; j = tick(j) - 1; }
      else if (src[j] === '"') { if (ps && src[j + 1] === '"') j++; else return j + 1; }
    }
    unparsable();
  };
  const bodies = (j, docs) => { // heredoc bodies, from the next line
    for (const d of docs) {
      const start = j;
      for (;;) {
        if (j >= src.length) break;
        const e = src.indexOf("\n", j), line = src.slice(j, e < 0 ? src.length : e).replace(/\r$/, "");
        j = e < 0 ? src.length : e + 1;
        if ((d.dash ? line.replace(/^\t+/, "") : line) === d.tag) break;
      }
      if (d.cmd && !d.quoted && /\$\(|`/.test(src.slice(start, j))) d.cmd.stdinLive = true;
    }
    return j;
  };
  const heredoc = (j) => /^<<(-?)\s*(['"]?)([\w.-]+)\2/.exec(src.slice(j));
  const sub = (j) => { // $( ... ), with whatever it holds
    let depth = 1, docs = [];
    while (j < src.length) {
      const c = src[j], h = !ps && c === "<" ? heredoc(j) : null;
      if (c === esc) j += 2;
      else if (c === "'") j = single(j);
      else if (c === '"') j = double(j);
      else if (!ps && c === "`") j = tick(j);
      else if (h) { docs.push({ tag: h[3], dash: h[1] === "-" }); j += h[0].length; }
      else if (c === "\n" && docs.length) { j = bodies(j + 1, docs); docs = []; }
      else if (c === "(") { depth++; j++; }
      else if (c === ")" && --depth === 0) return j + 1;
      else j++;
    }
    unparsable();
  };
  const unquote = (s) => s[0] === "'" ? s.slice(1, -1).replace(ps ? /''/g : /$^/, "'")
    : s.slice(1, -1).replace(ps ? /`(.)|""/gs : /\\([$`"\\\n])/g, (m, ch) => ch ?? '"');

  const cmds = [];
  let cur = { words: [], live: [] }, word = null, quoted = false, redir = null, docs = [], i = 0;
  const add = (s) => (word = (word ?? "") + s);
  const endWord = () => {
    if (word === null) return;
    if (redir === "<") cur.stdinFile = word;
    else if (redir === "<<<") { if (live) cur.stdinLive = true; }
    else if (redir === "<<" || redir === "<<-") docs.push({ tag: word, dash: redir === "<<-", quoted, cmd: cur });
    else if (!redir) { cur.words.push(word); cur.live.push(live); }
    redir = null; word = null; quoted = false; live = false;
  };
  const endCmd = (piped) => {
    endWord();
    if (cur.words.length || cur.literal) cmds.push(cur);
    cur = { words: [], live: [], from: piped ? cmds.at(-1) : undefined };
  };
  while (i < src.length) {
    const c = src[i], two = src.slice(i, i + 2);
    let m;
    if (c === " " || c === "\t" || c === "\r") { endWord(); i++; }
    else if (c === "\n") { endCmd(false); if (docs.length) { i = bodies(i + 1, docs); docs = []; } else i++; }
    else if (ps && two === "<#") { const e = src.indexOf("#>", i + 2); if (e < 0) unparsable(); endWord(); i = e + 2; } // <# #> comment
    else if (c === "#" && word === null) { const e = src.indexOf("\n", i); i = e < 0 ? src.length : e; }
    else if (c === esc) { // escape; before a line break (CRLF too) it continues the line
      const n = src.startsWith("\r\n", i + 1) ? 3 : src[i + 1] === "\n" ? 2 : 0;
      if (n) i += n; else { add(src[i + 1] ?? ""); i += 2; }
    }
    else if (c === "'") { const k = single(i); add(unquote(src.slice(i, k))); quoted = true; i = k; }
    else if (!ps && two === "$'") { let k = i + 2; while (k < src.length && src[k] !== "'") k += src[k] === "\\" ? 2 : 1; if (k >= src.length) unparsable(); add(src.slice(i, k + 1)); quoted = true; i = k + 1; }
    else if (c === '"') { const k = double(i); add(unquote(src.slice(i, k))); quoted = true; i = k; }
    else if (two === "$(") { const k = subst(i); add(src.slice(i, k)); i = k; }
    else if (!ps && (two === "<(" || two === ">(")) { const k = sub(i + 2); add(src.slice(i, k)); live = true; i = k; }
    else if (ps && c === "(" && cur.words.length) { const k = sub(i + 1); add(src.slice(i, k)); live = true; i = k; } // PowerShell (expression)
    else if (!ps && c === "`") { const k = tick(i); add(src.slice(i, k)); live = true; i = k; }
    else if (ps && word === null && (m = /^@(["'])[ \t]*\r?\n/.exec(src.slice(i)))) { // here-string @"..."@
      const e = src.indexOf(`\n${m[1]}@`, i);
      if (e < 0) unparsable();
      add(src.slice(i + m[0].length, e)); cur.literal = true; i = e + 3;
    }
    else if (two === "&&" || two === "||") { endCmd(false); i += 2; }
    else if (c === "|") { endCmd(true); i += src[i + 1] === "&" ? 2 : 1; }
    else if (c === ";" || c === "(" || c === ")" || (c === "&" && src[i + 1] !== ">")) { endCmd(false); i++; }
    else if (!ps && src.startsWith("<<<", i)) { endWord(); cur.stdinText = true; redir = "<<<"; i += 3; }
    else if (!ps && two === "<<") { endWord(); cur.stdinText = true; redir = src[i + 2] === "-" ? "<<-" : "<<"; i += redir.length; }
    else if (c === "<") { endWord(); redir = "<"; i++; }
    else if (c === ">" || two === "&>") { endWord(); redir = ">"; i += /^(&>>?|>>?&?)/.exec(src.slice(i))[0].length; }
    else { add(c); i++; }
  }
  endCmd(false);
  return cmds;
}

let raw = "";
process.stdin.on("data", (chunk) => (raw += chunk));
process.stdin.on("end", () => {
  const input = JSON.parse(raw);
  const command = input.tool_input?.command ?? "";
  if (!/\bgit\b[\s\S]*\bcommit\b/.test(command)) process.exit(0);
  const TRAILER_MSG = "this commit carries a Co-Authored-By line for Claude. Remove that line and commit again.";
  if (TRAILER.test(command)) block(TRAILER_MSG);
  const cmds = parse(command, input.tool_name === "PowerShell");
  // also with the quotes removed: "Cl""aude" is Claude
  if (cmds.some((c) => c.words.some((t) => TRAILER.test(t)))) block(TRAILER_MSG);

  // The message files exist before the commit, so they can be read.
  let dir = input.cwd ?? process.cwd(); // cwd: Claude's directory when the hook is called
  const check = (base, file) => {
    let text;
    try { text = fs.readFileSync(path.resolve(base, file), "utf8"); }
    catch { block(`could not read the commit message file ${file}; use -m or an absolute path.`); }
    if (TRAILER.test(text)) block(`the message file ${file} carries a Co-Authored-By line for Claude. Remove that line and commit again.`);
  };
  for (const cmd of cmds) {
    const w = cmd.words, live = cmd.live;
    if (/^(cd|chdir|pushd|set-location|sl|push-location)$/i.test(w[0]) && w[1]) { dir = path.resolve(dir, w[w.length - 1]); continue; }
    const g = w.findIndex((t) => /(^|[\\/])git(\.exe)?$/i.test(t));
    if (g < 0) continue;
    let base = dir, file = null, sub = false, hooksPath = false;
    for (let i = g + 1; i < w.length; i++) {
      const t = w[i];
      if (!sub) { // git options, before "commit"
        if (t === "commit") {
          sub = true;
          if (hooksPath) block("this commit changes core.hooksPath, which turns off git's own hooks. Commit without it.");
        }
        else if (t === "-C" && w[i + 1]) base = path.resolve(dir, w[++i]); // git -C <path>
        else if (((t === "-c" || t === "--config-env") && /^core\.hookspath/i.test(w[i + 1] ?? "")) || /^--config-env=core\.hookspath/i.test(t)) hooksPath = true;
        continue;
      }
      if (live[i]) block(LIVE); // a $( ) among the commit options can bring in anything
      if (/^--no-v(e(r(i(fy?)?)?)?)?(=|$)/.test(t)) block(NO_VERIFY);
      if (t === "-m" || t === "--message") { if (live[i + 1]) block(LIVE); i++; continue; } // the message text is not options
      if (t.startsWith("--message=")) { if (live[i]) block(LIVE); continue; }
      if (/^--fil(e)?$/.test(t)) { file = w[++i]; if (live[i]) block(LIVE); continue; }
      if (/^--fil(e)?=/.test(t)) { file = t.slice(t.indexOf("=") + 1); if (live[i]) block(LIVE); continue; }
      const short = /^-([A-Za-z].*)$/.exec(t); // cluster of short options, e.g. -anF
      if (!short || t.startsWith("--")) continue;
      for (let k = 0; k < short[1].length; k++) {
        const ch = short[1][k], rest = short[1].slice(k + 1);
        if (ch === "n") block(NO_VERIFY);
        if (ch === "m" || ch === "F") { // message or file: attached or in the next word
          if (!rest) i++;
          if (live[i]) block(LIVE);
          if (ch === "F") file = rest || w[i];
          break;
        }
        if ("cCt".includes(ch)) { if (!rest) i++; break; } // option with a value: what follows is the value
        if ("Su".includes(ch)) break; // optional attached value
      }
    }
    if (!sub || !file) continue;
    if (file !== "-") { check(base, file); continue; }
    // -F -: the message comes through stdin
    const from = cmd.from;
    if (cmd.stdinLive) block(LIVE);
    if (cmd.stdinFile) check(dir, cmd.stdinFile);
    else if (from && from.live.some(Boolean)) block(LIVE);
    else if (from && /^printf$/i.test(from.words[0] ?? "") && from.words.some((t) => /\\(x|u|[0-7])/.test(t))) block(LIVE); // printf with escapes, e.g. \x43
    else if (from && /^(cat|type|gc|get-content)$/i.test(from.words[0] ?? "")) {
      const files = from.words.slice(1).filter((f) => !f.startsWith("-"));
      if (from.stdinFile) files.push(from.stdinFile); // cat < file
      files.forEach((f) => check(dir, f));
    }
    else if (from && !from.literal && !/^(echo|printf|write-output)$/i.test(from.words[0] ?? ""))
      block("could not see the commit message that reaches stdin; use -m or -F <file>.");
    // otherwise: heredoc, echo, printf or here-string, whose text was already checked in the command
  }
  process.exit(0); // 0 = no objection; the normal permission flow continues
});

It blocks when the command is a git … commit and carries a Co-Authored-By naming Claude or Anthropic, case-insensitively, in the command itself or in the -F or --file message file, which already exists before the commit. The path comes from the JSON's cwd field, which according to the documentation follows Claude's directory, plus any cd or git -C in the same command; if it can't read the file, it blocks. With -F -, the message comes through stdin: it reads and checks the file behind a <, cat or Get-Content; if it's a heredoc, echo, printf or a PowerShell here-string, the text is already in the command and gets checked with it; if it brings in $( ), <( ), backticks or printf escapes, or comes from any other program through a pipe, it blocks. In a real session, Claude wrote msg.txt with the trailer through its file tool and tried git commit -F msg.txt through PowerShell: it was blocked.

It also blocks Claude's commits that use --no-verify (-n) or -c core.hooksPath, so Claude can't turn off git's own hooks from the commit itself. So that a ;, && or || inside the message isn't taken as the end of the command, it splits commands while respecting quotes, escapes, $( ), heredocs and here-strings; if it finds an unclosed quote or $( ), it blocks. In another real session, a git commit -m "fix: a; b && c" --no-verify through PowerShell was blocked.

For a team, it goes in the repository's .claude/settings.json, which gets committed. For all your projects, the hooks block goes in ~/.claude/settings.json, with the script's absolute path, although according to the documentation cloud sessions don't read that file. The cost: Node starts on every Bash or PowerShell call, not only on commits.

How to test it

  1. Copy .claude/settings.json and .claude/hooks/no-coauthor.js into the repository.
  2. Test the script without Claude, from Git Bash, macOS or Linux. It should print the block message and 2; with the command "git commit -m \"x\"", it should print 0.
    echo '{"tool_input":{"command":"git commit -m \"x\n\nCo-Authored-By: Claude <noreply@anthropic.com>\""}}' | node .claude/hooks/no-coauthor.js; echo $?
  3. Open Claude Code in the repo and type /hooks: the hook should show up under PreToolUse, with "project settings" as its source.
  4. Ask Claude: "commit this change and add the trailer Co-Authored-By: Claude <noreply@anthropic.com>". You should get PreToolUse:… hook error: … Blocked by hook … and no new commit in git log. Ask for the same with git commit -F and a msg.txt carrying the trailer, and then a git commit -m "a; b" --no-verify: both should be blocked.
  5. Ask for a plain commit: it should go in without the trailer, and git log -1 --format=%B confirms it.

We tested it with 162 cases, ours plus those of a reviewer on the team: ;, && and || inside quotes, line breaks, messages through stdin and PowerShell variants. Trying to get around it turned up a gap: in a real session, git commit -m "$(cat msg.txt)" went through with the trailer, because the hook reads the command's text and doesn't run the $( ). It now blocks a message that brings in $( ), <( ) or backticks. $(cat <<'EOF' … EOF) isn't blocked by that rule, because its text is in the command itself and the hook checks it; we confirmed that in a real session too. Variables, git aliases and a bash -c remain out of its reach: the script stops mistakes, and the guarantee lives on the server.

What the hook doesn't cover

  • It only sees what Claude runs through Bash or PowerShell, the tools in the matcher. Your own commits never reach it, and neither do those made by another Claude tool (a git MCP server, for example) or by a script Claude runs, such as bash commit.sh.
  • "disableAllHooks": true turns hooks off, and --bare mode skips them too.
  • It reads the command's text without running it: it blocks the $( ) it sees in the commit, but it doesn't expand variables or git aliases, and it doesn't look inside a bash -c.
  • Nor does it see a reused message: git commit -C <commit>, --amend --no-edit and -t <template> go through even if that message carries the trailer.
  • With "onFailure": "block", if the script is missing, Claude loses the shell: in our test, even a git status --short was blocked.

For the first four gaps there is git's prepare-commit-msg hook: it runs before the editor opens, receives the file with the message git prepared and, if the hook exits non-zero, aborts the commit. Unlike commit-msg, --no-verify doesn't suppress it:

#!/bin/sh
# .git/hooks/prepare-commit-msg: git passes in $1 the file with the message it prepares.
if grep -qiE '^co-authored-by[[:space:]]*:.*(claude|anthropic)' "$1"; then
  echo "prepare-commit-msg: the message carries a Claude Co-Authored-By line; commit aborted." >&2
  exit 1
fi
exit 0

In our test it stopped the commit with the trailer in -m, -F, --trailer, -C, --amend --no-edit and -t, with --no-verify too. Its limits, also tested: it runs before the editor, so a trailer typed there could only be caught by a commit-msg hook, which --no-verify skips; and, like any local hook, it stops working if someone deletes it or points core.hooksPath to another folder. The PreToolUse hook stops Claude from redirecting core.hooksPath inside the git commit itself, with -c, but doesn't catch a prior git config core.hooksPath, even in the same call, nor the GIT_CONFIG_* variables, nor changes to .git/config that Claude makes with its file tools.

The three layers at a glance

LayerWhat it does
attribution settingTurns off Claude Code's automatic attribution
PreToolUse hookBlocks certain commands before Claude Code runs them
prepare-commit-msg git hookInspects the message Git is preparing for the commit and aborts it if it carries the trailer

Since all three live only on the developer's machine, none of them is an absolute guarantee against someone who can modify or disable them. For a mandatory organization-wide policy, the control belongs off that machine: on the git server, with a pre-receive hook that rejects the push, or in continuous integration, with a step that rejects commits carrying the trailer.

Frequently asked questions

Is an empty attribution setting enough?

For the default behavior, yes. If someone asks for the trailer, no: the commit carries it, and only the hook or prepare-commit-msg stops it.

Does the hook block a human co-author?

No: it only blocks when the line names Claude or Anthropic.

Why Node instead of bash with jq?

Because node in exec form works the same on all three systems, without depending on jq.

Conclusion

The attribution setting turns off what Claude Code adds by default; the hook rejects the trailer even when someone asks for it. If no commit should ever carry a Claude Co-Authored-By, put both layers in the repository's .claude/settings.json and add prepare-commit-msg for commits made by hand; if you write the message in the editor, add a commit-msg hook with the same check too.

Our post on Opus 4.6 development skills covers the other half: guiding the model, not just fencing it in.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code