|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Check AI attribution in commits: humans author commits, AI help is disclosed. |
| 3 | +
|
| 4 | +Canonical copy: agent-tooling, hooks/check_ai_attribution.py. Repos vendor it as |
| 5 | +.github/scripts/check_ai_attribution.py. Change the canonical copy (and its tests), |
| 6 | +then copy it over; don't edit a vendored copy. |
| 7 | +
|
| 8 | +Rules |
| 9 | +----- |
| 10 | +1. AI help is disclosed with one trailer per agent, spelled exactly |
| 11 | +
|
| 12 | + Assisted-by: <Harness>:<model> |
| 13 | +
|
| 14 | + so `git log --grep='^Assisted-by: '` finds every AI-assisted commit. |
| 15 | + - <Harness> is one word: the agent harness (ClaudeCode, OpenCode, Codex, ...). |
| 16 | + Harnesses in KNOWN_HARNESSES have one spelling ("Claude Code" -> ClaudeCode). |
| 17 | + Any other harness is accepted as long as it is one word. |
| 18 | + - <model> is the exact model id the vendor's API uses, without a provider |
| 19 | + prefix: claude-opus-5-5, gpt-5.1-codex, gemini-3-pro, kimi-k2.6. Models of |
| 20 | + the vendors in MODEL_RULES are checked against that vendor's id format; any |
| 21 | + other model is accepted as long as it is one token with no "/". |
| 22 | +2. AI agents and bots never appear in a commit as its author, its committer or a |
| 23 | + Co-authored-by/Signed-off-by, except the non-AI automation in AUTOMATION |
| 24 | + (Dependabot, GitHub Actions, the GitHub web UI, ...). See is_agent(). |
| 25 | +3. Commit messages carry no "Generated with <agent>" lines; the trailer is the |
| 26 | + disclosure. |
| 27 | +
|
| 28 | +Usage |
| 29 | +----- |
| 30 | + check_ai_attribution.py COMMIT_MSG_FILE commit-msg hook: checks the message |
| 31 | + and the author/committer git is about |
| 32 | + to use |
| 33 | + check_ai_attribution.py --since BASE [--head REV] |
| 34 | + CI: checks every commit in BASE..REV |
| 35 | + (REV defaults to HEAD; only REV if |
| 36 | + BASE is empty, all zeros or unknown). |
| 37 | + On pull_request events pass the PR's |
| 38 | + head SHA: HEAD is GitHub's synthetic |
| 39 | + merge commit, not a real one. |
| 40 | +
|
| 41 | +Standard library only, Python >= 3.9, so it runs from prek/pre-commit or a bare |
| 42 | +`python3` on any OS. |
| 43 | +""" |
| 44 | + |
| 45 | +# Vendored copies must stay byte-identical to the canonical one, so the repos' |
| 46 | +# own linters and formatters (each with its own rules and line length) leave this |
| 47 | +# file alone. agent-tooling checks it with `ruff check --ignore-noqa`. |
| 48 | +# ruff: noqa |
| 49 | +# fmt: off |
| 50 | +from __future__ import annotations |
| 51 | + |
| 52 | +import argparse |
| 53 | +import re |
| 54 | +import subprocess |
| 55 | +import sys |
| 56 | + |
| 57 | +# --- Harnesses --------------------------------------------------------------- |
| 58 | +# Known harnesses, keyed by their name lowercased with everything but letters and |
| 59 | +# digits removed. A harness that normalizes to a key must be spelled as the value. |
| 60 | +KNOWN_HARNESSES = { |
| 61 | + "claudecode": "ClaudeCode", |
| 62 | + "claudedesktop": "ClaudeDesktop", |
| 63 | + "claudeai": "ClaudeAI", |
| 64 | + "opencode": "OpenCode", |
| 65 | + "codex": "Codex", |
| 66 | + "codexcli": "Codex", |
| 67 | + "copilot": "Copilot", |
| 68 | + "githubcopilot": "Copilot", |
| 69 | + "cursor": "Cursor", |
| 70 | + "geminicli": "GeminiCLI", |
| 71 | + "aider": "Aider", |
| 72 | + "pi": "Pi", |
| 73 | + "windsurf": "Windsurf", |
| 74 | + "junie": "Junie", |
| 75 | + "amp": "Amp", |
| 76 | + "goose": "Goose", |
| 77 | + "cline": "Cline", |
| 78 | + "roocode": "RooCode", |
| 79 | + "kilocode": "KiloCode", |
| 80 | + "zed": "Zed", |
| 81 | +} |
| 82 | + |
| 83 | +HARNESS_RE = re.compile(r"[A-Za-z][A-Za-z0-9.+-]*") |
| 84 | + |
| 85 | +# --- Models ------------------------------------------------------------------ |
| 86 | +# (what marks a model as this vendor's, the vendor's id format, an example). |
| 87 | +# Ids are the API's: lowercase, no spaces, no provider prefix. |
| 88 | +MODEL_RULES = [ |
| 89 | + ( |
| 90 | + re.compile(r"claude|opus|sonnet|haiku|fable", re.I), |
| 91 | + re.compile(r"claude(?:-[a-z0-9]+)+"), |
| 92 | + "claude-opus-5-5", |
| 93 | + ), |
| 94 | + ( |
| 95 | + re.compile(r"^(?:gpt|chatgpt|o\d|codex)", re.I), |
| 96 | + re.compile(r"(?:gpt|chatgpt|o\d+|codex)[a-z0-9.-]*"), |
| 97 | + "gpt-5.1-codex", |
| 98 | + ), |
| 99 | + ( |
| 100 | + re.compile(r"gemini|gemma", re.I), |
| 101 | + re.compile(r"(?:gemini|gemma)-[a-z0-9.-]+"), |
| 102 | + "gemini-3-pro", |
| 103 | + ), |
| 104 | + (re.compile(r"kimi", re.I), re.compile(r"kimi-[a-z0-9.-]+"), "kimi-k2.6"), |
| 105 | + (re.compile(r"glm", re.I), re.compile(r"glm-[a-z0-9.-]+"), "glm-5.1"), |
| 106 | + ( |
| 107 | + re.compile(r"deepseek", re.I), |
| 108 | + re.compile(r"deepseek-[a-z0-9.-]+"), |
| 109 | + "deepseek-v3.2", |
| 110 | + ), |
| 111 | + (re.compile(r"qwen", re.I), re.compile(r"qwen[a-z0-9.-]+"), "qwen3-coder-plus"), |
| 112 | + (re.compile(r"grok", re.I), re.compile(r"grok-[a-z0-9.-]+"), "grok-code-fast-1"), |
| 113 | + ( |
| 114 | + re.compile(r"mistral|codestral|devstral", re.I), |
| 115 | + re.compile(r"(?:mistral|codestral|devstral)[a-z0-9.-]*"), |
| 116 | + "devstral-medium-2507", |
| 117 | + ), |
| 118 | +] |
| 119 | + |
| 120 | +# --- Identities ---------------------------------------------------------------- |
| 121 | +# Non-AI automation that may author or commit (matched on the name, lowercased). |
| 122 | +AUTOMATION = { |
| 123 | + "dependabot[bot]", |
| 124 | + "github-actions[bot]", |
| 125 | + "renovate[bot]", |
| 126 | + "pre-commit-ci[bot]", |
| 127 | + "github", # committer of web UI edits and merge-button merges |
| 128 | + "web-flow", |
| 129 | +} |
| 130 | + |
| 131 | +# Email domains that only AI agents commit from. |
| 132 | +AGENT_EMAIL_DOMAINS = { |
| 133 | + "anthropic.com", |
| 134 | + "openai.com", |
| 135 | + "cursor.com", |
| 136 | + "cursor.sh", |
| 137 | + "aider.chat", |
| 138 | + "codeium.com", |
| 139 | + "windsurf.com", |
| 140 | + "devin.ai", |
| 141 | + "cognition.ai", |
| 142 | + "moonshot.ai", |
| 143 | + "moonshot.cn", |
| 144 | + "z.ai", |
| 145 | + "zhipuai.cn", |
| 146 | + "deepseek.com", |
| 147 | + "mistral.ai", |
| 148 | + "x.ai", |
| 149 | + "opencode.ai", |
| 150 | + "ampcode.com", |
| 151 | + "sweep.dev", |
| 152 | +} |
| 153 | + |
| 154 | +# Names (or GitHub logins) that are AI agents. Matched at the start of the name, |
| 155 | +# so "Claude", "Claude Opus 5.5" and "Copilot" match but a person whose surname |
| 156 | +# is one of these words does not. First names that are also agent names (Devin, |
| 157 | +# Kimi, Jules, Cody, Amp) are left out on purpose: those agents commit from a |
| 158 | +# bot account or an agent domain, which the other checks catch. |
| 159 | +AGENT_NAME_RE = re.compile( |
| 160 | + r"^(?:claude|anthropic|copilot|github copilot|codex|openai|chatgpt|gpt-?\d" |
| 161 | + r"|gemini|cursor(?: ?agent)?|aider|windsurf|codeium|cascade|junie|opencode" |
| 162 | + r"|qwen|deepseek|glm-?\d|tabnine|amazon q|sweep)\b", |
| 163 | + re.I, |
| 164 | +) |
| 165 | +# "Jane Doe (aider)", the author name aider writes by default, and the like. |
| 166 | +AGENT_SUFFIX_RE = re.compile(r"\((?:aider|ai|bot|agent|assistant)\)\s*$", re.I) |
| 167 | +# A GitHub App account: login[bot], or its <id>+login[bot]@users.noreply.github.com. |
| 168 | +BOT_RE = re.compile(r"\[bot\]", re.I) |
| 169 | +NOREPLY_LOGIN_RE = re.compile( |
| 170 | + r"^(?:\d+\+)?(?P<login>[^@]+)@users\.noreply\.github\.com$", re.I |
| 171 | +) |
| 172 | + |
| 173 | + |
| 174 | +def is_agent(name: str, email: str) -> str | None: |
| 175 | + """Why this identity is an AI agent or a non-allowed bot, or None for a person.""" |
| 176 | + name, email = name.strip(), email.strip().lower() |
| 177 | + if name.lower() in AUTOMATION: |
| 178 | + return None |
| 179 | + if BOT_RE.search(name) or BOT_RE.search(email): |
| 180 | + return "a bot account (only the automation in AUTOMATION may commit)" |
| 181 | + domain = email.rpartition("@")[2] |
| 182 | + if any(domain == d or domain.endswith("." + d) for d in AGENT_EMAIL_DOMAINS): |
| 183 | + return f"an AI vendor's address ({domain})" |
| 184 | + m = NOREPLY_LOGIN_RE.match(email) |
| 185 | + if m and AGENT_NAME_RE.match(m["login"]): |
| 186 | + return f"an AI agent's GitHub account ({m['login']})" |
| 187 | + if AGENT_NAME_RE.match(name) or AGENT_SUFFIX_RE.search(name): |
| 188 | + return f"an AI agent's name ({name})" |
| 189 | + return None |
| 190 | + |
| 191 | + |
| 192 | +# --- Messages ------------------------------------------------------------------ |
| 193 | +# A trailer-like line: "Key: value" at the start of the line. |
| 194 | +KEY_RE = re.compile(r"^(?P<key>[A-Za-z][A-Za-z _-]*?)\s*:\s*(?P<value>.*)$") |
| 195 | +IDENT_RE = re.compile(r"^(?P<name>.*?)\s*<(?P<email>[^>]*)>\s*$") |
| 196 | +ASSISTED_RE = re.compile(r"Assisted-by: (?P<harness>[^\s:]+):(?P<model>\S+)") |
| 197 | +IDENTITY_KEYS = {"coauthoredby", "signedoffby"} |
| 198 | +GENERATED_RE = re.compile(r"^\W{0,4}generated (?:with|by)\b", re.I) |
| 199 | +AGENT_WORD_RE = re.compile( |
| 200 | + r"\b(?:claude|anthropic|copilot|codex|openai|chatgpt|gpt|gemini|cursor|aider" |
| 201 | + r"|windsurf|codeium|junie|opencode|kimi|qwen|deepseek|glm|grok|devin|jules|ai)\b", |
| 202 | + re.I, |
| 203 | +) |
| 204 | +SCISSORS = "------------------------ >8 ------------------------" |
| 205 | + |
| 206 | +FORMAT_HINT = "write it as `Assisted-by: <Harness>:<model>`, e.g. `Assisted-by: ClaudeCode:claude-opus-5-5`" |
| 207 | + |
| 208 | + |
| 209 | +def _norm(s: str) -> str: |
| 210 | + return re.sub(r"[^a-z0-9]", "", s.lower()) |
| 211 | + |
| 212 | + |
| 213 | +def check_assisted_by(line: str) -> list[str]: |
| 214 | + m = ASSISTED_RE.fullmatch(line) |
| 215 | + if not m: |
| 216 | + return [f"malformed Assisted-by trailer; {FORMAT_HINT}"] |
| 217 | + harness, model = m["harness"], m["model"] |
| 218 | + errors = [] |
| 219 | + canonical = KNOWN_HARNESSES.get(_norm(harness)) |
| 220 | + if canonical and harness != canonical: |
| 221 | + errors.append(f"spell the harness `{canonical}`, not `{harness}`") |
| 222 | + elif not canonical and not HARNESS_RE.fullmatch(harness): |
| 223 | + errors.append( |
| 224 | + f"the harness must be one word (letters, digits, . + -), not `{harness}`" |
| 225 | + ) |
| 226 | + if "/" in model: |
| 227 | + errors.append( |
| 228 | + f"drop the provider prefix from the model: `{model.rpartition('/')[2]}`" |
| 229 | + ) |
| 230 | + else: |
| 231 | + for vendor, id_re, example in MODEL_RULES: |
| 232 | + if vendor.search(model): |
| 233 | + if not id_re.fullmatch(model) or not re.search(r"\d", model): |
| 234 | + errors.append( |
| 235 | + f"use the exact model id (like `{example}`), not `{model}`: " |
| 236 | + "lowercase, hyphens, no display name" |
| 237 | + ) |
| 238 | + break |
| 239 | + return errors |
| 240 | + |
| 241 | + |
| 242 | +def message_lines(message: str, comment_char: str = "#") -> list[tuple[int, str]]: |
| 243 | + """(line number, text) for the lines git keeps: no comments, nothing below the scissors.""" |
| 244 | + out = [] |
| 245 | + for i, line in enumerate(message.splitlines(), 1): |
| 246 | + if line.startswith(comment_char) and SCISSORS in line: |
| 247 | + break |
| 248 | + if line.startswith(comment_char): |
| 249 | + continue |
| 250 | + out.append((i, line.rstrip("\r"))) |
| 251 | + return out |
| 252 | + |
| 253 | + |
| 254 | +def check_message(message: str, comment_char: str = "#") -> list[str]: |
| 255 | + errors = [] |
| 256 | + for n, line in message_lines(message, comment_char): |
| 257 | + m = KEY_RE.match(line) |
| 258 | + key = _norm(m["key"]) if m else "" |
| 259 | + if key == "assistedby": |
| 260 | + errors += [f"line {n}: {e}\n {line}" for e in check_assisted_by(line)] |
| 261 | + elif key in IDENTITY_KEYS: |
| 262 | + ident = IDENT_RE.match(m["value"]) |
| 263 | + name, email = (ident["name"], ident["email"]) if ident else (m["value"], "") |
| 264 | + why = is_agent(name, email) |
| 265 | + if why: |
| 266 | + errors.append( |
| 267 | + f"line {n}: {m['key']} names {why}. AI agents are not authors: " |
| 268 | + f"remove the line and disclose the help with Assisted-by instead\n {line}" |
| 269 | + ) |
| 270 | + elif GENERATED_RE.match(line) and AGENT_WORD_RE.search(line): |
| 271 | + errors.append( |
| 272 | + f"line {n}: remove the 'Generated with' line; the Assisted-by trailer " |
| 273 | + f"is the disclosure\n {line}" |
| 274 | + ) |
| 275 | + return errors |
| 276 | + |
| 277 | + |
| 278 | +def check_identities(author: tuple[str, str], committer: tuple[str, str]) -> list[str]: |
| 279 | + errors = [] |
| 280 | + for role, (name, email) in (("author", author), ("committer", committer)): |
| 281 | + why = is_agent(name, email) |
| 282 | + if why: |
| 283 | + errors.append( |
| 284 | + f"the commit {role} `{name} <{email}>` is {why}. Commit as yourself and " |
| 285 | + "disclose AI help with Assisted-by. To re-author commits on a branch: " |
| 286 | + "git rebase -x 'git commit --amend --no-edit --reset-author " |
| 287 | + '--trailer "Assisted-by: <Harness>:<model>"\' <base>' |
| 288 | + ) |
| 289 | + return errors |
| 290 | + |
| 291 | + |
| 292 | +# --- Git ----------------------------------------------------------------------- |
| 293 | +def _git(*args: str) -> str: |
| 294 | + return subprocess.run( |
| 295 | + ["git", *args], check=True, capture_output=True, text=True, encoding="utf-8" |
| 296 | + ).stdout |
| 297 | + |
| 298 | + |
| 299 | +def _ident(var: str) -> tuple[str, str] | None: |
| 300 | + try: |
| 301 | + m = IDENT_RE.match(_git("var", var).rsplit(" ", 2)[0]) |
| 302 | + except (subprocess.CalledProcessError, OSError): |
| 303 | + return None # no identity configured; git itself will complain |
| 304 | + return (m["name"], m["email"]) if m else None |
| 305 | + |
| 306 | + |
| 307 | +def _comment_char() -> str: |
| 308 | + try: |
| 309 | + c = _git("config", "core.commentChar").strip() |
| 310 | + except subprocess.CalledProcessError: |
| 311 | + return "#" |
| 312 | + return c if len(c) == 1 else "#" |
| 313 | + |
| 314 | + |
| 315 | +def check_msg_file(path: str) -> list[str]: |
| 316 | + with open(path, encoding="utf-8", errors="replace") as f: |
| 317 | + errors = check_message(f.read(), _comment_char()) |
| 318 | + author, committer = _ident("GIT_AUTHOR_IDENT"), _ident("GIT_COMMITTER_IDENT") |
| 319 | + if author and committer: |
| 320 | + errors += check_identities(author, committer) |
| 321 | + return errors |
| 322 | + |
| 323 | + |
| 324 | +def check_since(base: str, head: str = "HEAD") -> list[str]: |
| 325 | + known = base and set(base) != {"0"} |
| 326 | + if known: |
| 327 | + try: |
| 328 | + _git("rev-parse", "--quiet", "--verify", f"{base}^{{commit}}") |
| 329 | + except subprocess.CalledProcessError: |
| 330 | + known = False |
| 331 | + if not known: |
| 332 | + print( |
| 333 | + f"check_ai_attribution: base {base!r} unknown, checking {head} only", |
| 334 | + file=sys.stderr, |
| 335 | + ) |
| 336 | + commits = _git( |
| 337 | + "rev-list", f"{base}..{head}" if known else "-1", *([] if known else [head]) |
| 338 | + ) |
| 339 | + commits = commits.split() |
| 340 | + errors = [] |
| 341 | + for sha in commits: |
| 342 | + an, ae, cn, ce, body = _git( |
| 343 | + "show", "-s", "--format=%an%x00%ae%x00%cn%x00%ce%x00%B", sha |
| 344 | + ).split("\0", 4) |
| 345 | + errs = check_identities((an, ae), (cn, ce)) + check_message(body) |
| 346 | + errors += [ |
| 347 | + f"{sha[:10]} {body.splitlines()[0] if body else ''}\n {e}" for e in errs |
| 348 | + ] |
| 349 | + print(f"check_ai_attribution: checked {len(commits)} commit(s)", file=sys.stderr) |
| 350 | + return errors |
| 351 | + |
| 352 | + |
| 353 | +def main(argv: list[str] | None = None) -> int: |
| 354 | + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 355 | + group = parser.add_mutually_exclusive_group(required=True) |
| 356 | + group.add_argument( |
| 357 | + "msg_file", nargs="?", help="commit message file (commit-msg hook)" |
| 358 | + ) |
| 359 | + group.add_argument( |
| 360 | + "--since", metavar="BASE", help="check the commits in BASE..--head" |
| 361 | + ) |
| 362 | + parser.add_argument( |
| 363 | + "--head", default="HEAD", help="last commit to check (default HEAD)" |
| 364 | + ) |
| 365 | + args = parser.parse_args(argv) |
| 366 | + if args.since is not None: |
| 367 | + errors = check_since(args.since, args.head or "HEAD") |
| 368 | + else: |
| 369 | + errors = check_msg_file(args.msg_file) |
| 370 | + for e in errors: |
| 371 | + print(e, file=sys.stderr) |
| 372 | + if errors: |
| 373 | + print( |
| 374 | + "\nAI attribution: humans author commits; AI help is disclosed with one " |
| 375 | + "`Assisted-by: <Harness>:<model>` trailer per agent. See the docstring of " |
| 376 | + "check_ai_attribution.py.", |
| 377 | + file=sys.stderr, |
| 378 | + ) |
| 379 | + return 1 if errors else 0 |
| 380 | + |
| 381 | + |
| 382 | +if __name__ == "__main__": |
| 383 | + sys.exit(main()) |
0 commit comments