Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

ci(pre-commit): add author-identity consistency check (#4809)

LearningCircuit7510ffa9fb85
diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml
index 4b08f92d80..c8594fd7f1 100644
--- a/.github/workflows/pre-commit.yml
+++ b/.github/workflows/pre-commit.yml
@@ -30,6 +30,11 @@ jobs:
with:
persist-credentials: false
+ # Full history so the author-identity hook can resolve the PR commit
+ # range (merge-base..head) from local objects WITHOUT fetching: a hook
+ # that mutates git state mid-run trips pre-commit's "files were
+ # modified by this hook".
+ fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index e3586db586..937384787c 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -84,6 +84,13 @@ repos:
language: script
files: \.py$
description: "Ensure environment variables are accessed through SettingsManager"
+ - id: check-author-identity
+ name: Author identity consistency
+ entry: .pre-commit-hooks/check-author-identity.py
+ language: script
+ always_run: true
+ pass_filenames: false
+ description: "Ensure commits by a declared project author use that author's declared identity"
- id: file-whitelist-check
name: File Whitelist Security Check
entry: .pre-commit-hooks/file-whitelist-check.sh
diff --git a/.pre-commit-hooks/check-author-identity.py b/.pre-commit-hooks/check-author-identity.py
new file mode 100755
index 0000000000..cf0e4f63c9
--- /dev/null
+++ b/.pre-commit-hooks/check-author-identity.py
@@ -0,0 +1,278 @@
+#!/usr/bin/env python3
+"""Author identity consistency check.
+
+Ensures every commit attributed to a project author declared in
+``pyproject.toml`` (the ``authors`` list) uses an acceptable email identity:
+either a GitHub ``@users.noreply.github.com`` address (always allowed — these
+are privacy-preserving), or that author's own declared address. This keeps
+contributor attribution consistent and prevents a declared author's commits
+from going out under an unintended personal address.
+
+It inspects commit *metadata* (author, committer, and ``Co-authored-by``
+trailers) rather than file contents, so it runs once per invocation
+(``always_run: true`` / ``pass_filenames: false``):
+
+- In CI on a pull request, it checks every commit the PR adds (``merge-base..head``),
+ and reads the allow-list from the *base* ref so a PR cannot authorize an
+ address by editing ``pyproject.toml`` in the same change.
+- Locally at the pre-commit stage, it checks the commit about to be made.
+
+The allow-list is read from ``pyproject.toml`` at runtime — nothing is
+hard-coded here. A mismatching address is never printed (so it can't end up in
+logs); messages name only the declared author. Range-resolution failures fail
+*closed* (the check fails rather than silently passing).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+NOREPLY_SUFFIX = "@users.noreply.github.com"
+
+
+def _git(*args: str) -> tuple[int, str]:
+ """Run git; return (returncode, stdout). stderr is captured and discarded."""
+ proc = subprocess.run(["git", *args], capture_output=True, text=True)
+ return proc.returncode, proc.stdout
+
+
+def parse_identities(text: str) -> dict[str, set[str]]:
+ """Map declared author name (lower-cased) -> set of declared emails (lower).
+
+ Tolerant of key order and surrounding whitespace; anchored to a top-level
+ ``authors = [`` line so an unrelated ``*authors`` key can't hijack it.
+ """
+ identities: dict[str, set[str]] = {}
+ block = re.search(r"(?m)^authors\s*=\s*\[(.*?)\]", text, re.S)
+ if not block:
+ return identities
+ for entry in re.findall(r"\{([^}]*)\}", block.group(1)):
+ name = re.search(r'name\s*=\s*"([^"]+)"', entry)
+ email = re.search(r'email\s*=\s*"([^"]+)"', entry)
+ if name and email:
+ identities.setdefault(name.group(1).strip().lower(), set()).add(
+ email.group(1).strip().lower()
+ )
+ return identities
+
+
+def _is_noreply(email: str) -> bool:
+ return email.endswith(NOREPLY_SUFFIX)
+
+
+def _mismatch(kind: str, name: str, email: str, declared: dict[str, set[str]]):
+ """Return a message if (name, email) is a disallowed identity, else None.
+
+ The offending email is intentionally NOT included in the message.
+ """
+ raw_name = (name or "").strip()
+ name_lc = raw_name.lower()
+ email = (email or "").strip().lower()
+ allowed = declared.get(name_lc)
+ if not allowed:
+ return None # not a declared author -> not enforced
+ if _is_noreply(email):
+ return None # any GitHub noreply is privacy-safe and allowed
+ if email in allowed:
+ return None # the author's own declared address
+ return (
+ f'{kind} "{raw_name}" is a declared author but is using a non-noreply '
+ f"address that is not its declared identity"
+ )
+
+
+_CO_AUTHOR = re.compile(
+ r"^\s*Co-authored-by:\s*(?P<name>.*?)\s*<(?P<email>[^>]+)>\s*$", re.I | re.M
+)
+
+
+def _check(record, declared) -> list[str]:
+ sha, an, ae, cn, ce, body = record
+ out = []
+ for kind, name, email in (("author", an, ae), ("committer", cn, ce)):
+ msg = _mismatch(kind, name, email, declared)
+ if msg:
+ out.append(f" {sha[:9]}: {msg}")
+ for m in _CO_AUTHOR.finditer(body or ""):
+ msg = _mismatch(
+ "Co-authored-by", m.group("name"), m.group("email"), declared
+ )
+ if msg:
+ out.append(f" {sha[:9]}: {msg}")
+ return out
+
+
+def _parse_log(raw: str) -> list[tuple]:
+ records = []
+ for chunk in raw.split("\x1e"):
+ chunk = chunk.strip("\n")
+ if not chunk:
+ continue
+ fields = chunk.split("\x00")
+ if len(fields) < 6:
+ # A control char (\x1e / \x00) injected into the author/committer
+ # name or body corrupts the framing. Never silently skip a commit
+ # -> fail closed.
+ raise RuntimeError("malformed commit record in git log output")
+ # body may itself contain NULs -> rejoin the tail
+ records.append(
+ (
+ fields[0],
+ fields[1],
+ fields[2],
+ fields[3],
+ fields[4],
+ "\x00".join(fields[5:]),
+ )
+ )
+ return records
+
+
+def _resolve_merge_base(base: str, head: str) -> str:
+ """Return merge-base(base, head). Raise on failure.
+
+ Resolve from locally-available history FIRST and fetch only as a fallback.
+ This hook runs inside ``pre-commit run``, which treats any working-tree or
+ git-state change a hook makes as a hook failure. The workflow checks out
+ full history (``fetch-depth: 0``) precisely so the PR-CI path resolves the
+ range with no fetch -- mutating nothing. The fetch fallback exists only for
+ a shallow checkout and should not run in the PR-CI path.
+ """
+ rc, mb = _git("merge-base", base, head)
+ if rc == 0 and mb.strip():
+ return mb.strip()
+ # Endpoints not present locally (shallow clone): fetch, then retry.
+ subprocess.run(
+ ["git", "fetch", "--quiet", "--depth=1000", "origin", head, base],
+ check=False,
+ )
+ rc, mb = _git("merge-base", base, head)
+ if rc != 0 or not mb.strip():
+ # Diverged further than the shallow window — get full history, retry.
+ subprocess.run(
+ ["git", "fetch", "--quiet", "--unshallow", "origin"], check=False
+ )
+ rc, mb = _git("merge-base", base, head)
+ if rc != 0 or not mb.strip():
+ raise RuntimeError("could not resolve the PR commit range")
+ return mb.strip()
+
+
+def _pr_context():
+ """In PR CI: return (records, base_pyproject_text). None if not PR CI.
+
+ Raises RuntimeError on an unresolvable range (caller fails closed).
+ """
+ is_pr_event = os.environ.get("GITHUB_EVENT_NAME", "") in (
+ "pull_request",
+ "pull_request_target",
+ )
+
+ def give_up(reason: str):
+ # On a genuine PR event an unusable payload must FAIL CLOSED, never drop
+ # to the local no-op path. Off a PR event, this simply isn't PR CI.
+ if is_pr_event:
+ raise RuntimeError(reason)
+ return
+
+ event_path = os.environ.get("GITHUB_EVENT_PATH")
+ if not (event_path and Path(event_path).exists()):
+ return give_up("pull_request event but no event payload")
+ try:
+ with open(event_path, encoding="utf-8") as fh:
+ payload = json.load(fh)
+ except (OSError, ValueError):
+ return give_up("could not read the PR event payload")
+ pr = payload.get("pull_request") if isinstance(payload, dict) else None
+ if not isinstance(pr, dict):
+ return give_up("pull_request event missing its payload")
+ base = (pr.get("base") or {}).get("sha")
+ head = (pr.get("head") or {}).get("sha")
+ if not (base and head):
+ return give_up("pull_request event missing base/head sha")
+ merge_base = _resolve_merge_base(base, head) # may raise -> fail closed
+ rc, raw = _git(
+ "log",
+ f"{merge_base}..{head}",
+ "--format=%H%x00%an%x00%ae%x00%cn%x00%ce%x00%B%x1e",
+ )
+ if rc != 0:
+ raise RuntimeError("git log failed for the PR commit range")
+ rc, base_pyproject = _git("show", f"{base}:pyproject.toml")
+ if rc != 0:
+ raise RuntimeError("could not read pyproject.toml from the base ref")
+ return _parse_log(raw), base_pyproject
+
+
+def _pending_records() -> list[tuple]:
+ """Identity of the commit about to be created (local pre-commit stage)."""
+
+ def parse(ident: str):
+ m = re.match(r"^(.*)<([^>]+)>", ident)
+ return (m.group(1).strip(), m.group(2).strip()) if m else ("", "")
+
+ an, ae = parse(_git("var", "GIT_AUTHOR_IDENT")[1])
+ cn, ce = parse(_git("var", "GIT_COMMITTER_IDENT")[1])
+ return [("pending00", an, ae, cn, ce, "")]
+
+
+def main() -> int:
+ try:
+ ctx = _pr_context()
+ except RuntimeError as exc:
+ # Fail CLOSED: never silently pass a required check we couldn't run.
+ print(f"author-identity: {exc}; failing closed.", file=sys.stderr)
+ return 1
+
+ if ctx is not None:
+ records, pyproject_text = ctx
+ declared = parse_identities(pyproject_text)
+ if not declared and re.search(
+ r"(?m)^\s*(authors\s*=|\[\[[^\]]*authors\s*\]\])", pyproject_text
+ ):
+ # The base pyproject declares authors but we parsed none (e.g. the
+ # table format changed). Fail CLOSED rather than silently disabling
+ # the check -- a loud red is the whole point of this guard.
+ print(
+ "author-identity: base pyproject.toml declares authors but none "
+ "could be parsed (unrecognized format?); failing closed.",
+ file=sys.stderr,
+ )
+ return 1
+ else:
+ try:
+ declared = parse_identities(
+ Path("pyproject.toml").read_text(encoding="utf-8")
+ )
+ except OSError:
+ declared = {}
+ records = _pending_records()
+
+ if not declared:
+ return 0
+
+ errors = []
+ for rec in records:
+ errors.extend(_check(rec, declared))
+ if errors:
+ print("Author identity check failed:\n", file=sys.stderr)
+ print("\n".join(errors), file=sys.stderr)
+ print(
+ "\nA commit is attributed to a declared author but uses a personal "
+ "(non-noreply) address.\nUse your GitHub `@users.noreply.github.com` "
+ "address, e.g. re-author with:\n"
+ " git commit --amend --reset-author # latest commit\n"
+ "and ensure your git user.email is your noreply address.",
+ file=sys.stderr,
+ )
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/hooks/test_check_author_identity.py b/tests/hooks/test_check_author_identity.py
new file mode 100644
index 0000000000..f3e77c9457
--- /dev/null
+++ b/tests/hooks/test_check_author_identity.py
@@ -0,0 +1,460 @@
+"""Tests for the check-author-identity pre-commit hook.
+
+All test data uses throwaway addresses (``*.test`` / ``example.com``) or public
+GitHub noreply addresses; no real personal email appears in this file.
+"""
+
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+
+# Load the hook module by path (hyphenated filename isn't importable directly).
+_HOOK_PATH = (
+ Path(__file__).resolve().parents[2]
+ / ".pre-commit-hooks"
+ / "check-author-identity.py"
+)
+_spec = importlib.util.spec_from_file_location(
+ "check_author_identity", _HOOK_PATH
+)
+mod = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(mod)
+
+
+PYPROJECT = """\
+[project]
+name = "x"
+authors = [
+ {name = "LearningCircuit", email = "[email protected]"},
+ {name = "djpetti", email = "[email protected]"},
+]
+"""
+DECLARED = {
+ "learningcircuit": {"[email protected]"},
+ "djpetti": {"[email protected]"},
+}
+
+
+class TestParseIdentities:
+ def test_parses_and_lowercases(self):
+ assert mod.parse_identities(PYPROJECT) == DECLARED
+
+ def test_key_order_independent(self):
+ text = (
+ 'authors = [\n {email = "[email protected]", name = "Bob"},\n]\n'
+ )
+ assert mod.parse_identities(text) == {"bob": {"[email protected]"}}
+
+ def test_anchored_ignores_other_authors_keys(self):
+ text = (
+ 'co_authors = ["x"]\n'
+ 'authors = [\n {name = "A", email = "[email protected]"},\n]\n'
+ )
+ assert mod.parse_identities(text) == {"a": {"[email protected]"}}
+
+ def test_no_block_returns_empty(self):
+ assert mod.parse_identities('[project]\nname = "x"\n') == {}
+
+ def test_multiple_emails_per_name(self):
+ text = (
+ "authors = [\n"
+ ' {name = "A", email = "[email protected]"},\n'
+ ' {name = "A", email = "[email protected]"},\n'
+ "]\n"
+ )
+ assert mod.parse_identities(text) == {"a": {"[email protected]", "[email protected]"}}
+
+
+class TestIsNoreply:
+ def test_user_noreply_allowed(self):
+ assert mod._is_noreply("[email protected]")
+ assert mod._is_noreply("[email protected]")
+
+ def test_personal_and_webflow_not_user_noreply(self):
+ assert not mod._is_noreply("[email protected]")
+ assert not mod._is_noreply("[email protected]") # web-flow committer
+
+
+class TestMismatch:
+ def test_any_noreply_allowed_for_declared_author(self):
+ # djpetti is declared with a non-noreply email; his GH noreply must pass.
+ assert (
+ mod._mismatch(
+ "author",
+ "djpetti",
+ DECLARED,
+ )
+ is None
+ )
+
+ def test_declared_email_allowed(self):
+ assert (
+ mod._mismatch("author", "djpetti", "[email protected]", DECLARED)
+ is None
+ )
+
+ def test_declared_author_personal_email_flagged(self):
+ msg = mod._mismatch(
+ "author", "LearningCircuit", "[email protected]", DECLARED
+ )
+ assert msg is not None
+ assert "LearningCircuit" in msg
+
+ def test_case_insensitive_name_match(self):
+ # A lowercase display name must still be enforced (the hashedviking gap).
+ assert (
+ mod._mismatch(
+ "author", "learningcircuit", "[email protected]", DECLARED
+ )
+ is not None
+ )
+
+ def test_unknown_name_not_enforced(self):
+ assert (
+ mod._mismatch("author", "Outsider", "[email protected]", DECLARED)
+ is None
+ )
+
+ def test_message_never_contains_offending_email(self):
+ secret = "[email protected]"
+ msg = mod._mismatch("author", "LearningCircuit", secret, DECLARED)
+ assert msg is not None
+ assert secret not in msg
+ assert "secret" not in msg.lower()
+
+ def test_empty_declared_never_flags(self):
+ assert mod._mismatch("author", "Anyone", "[email protected]", {}) is None
+
+
+class TestCoAuthorRegex:
+ def test_matches_trailer(self):
+ m = mod._CO_AUTHOR.search("b\n\nCo-authored-by: Some One <[email protected]>\n")
+ assert m is not None
+ assert m.group("name") == "Some One"
+ assert m.group("email") == "[email protected]"
+
+ def test_indented_trailer_matches(self):
+ assert (
+ mod._CO_AUTHOR.search(" Co-authored-by: X <[email protected]>") is not None
+ )
+
+ def test_no_false_match_on_prose(self):
+ assert mod._CO_AUTHOR.search("This was co-authored by someone") is None
+
+
+class TestParseLog:
+ def test_basic_record(self):
+ raw = "sha1\x00An\[email protected]\x00Cn\[email protected]\x00body line\x1e"
+ assert mod._parse_log(raw) == [
+ ("sha1", "An", "[email protected]", "Cn", "[email protected]", "body line")
+ ]
+
+ def test_nul_in_body_is_preserved(self):
+ # A NUL earlier in the body must not truncate it: a real trailer (on its
+ # own line) after the NUL must survive and still be detected.
+ body = "head\x00more\n\nCo-authored-by: LearningCircuit <[email protected]>"
+ raw = f"sha1\x00An\[email protected]\x00Cn\[email protected]\x00{body}\x1e"
+ recs = mod._parse_log(raw)
+ assert (
+ recs[0][5] == body
+ ) # full body kept (old fields[5] would truncate)
+ errs = mod._check(recs[0], DECLARED)
+ assert any("Co-authored-by" in e for e in errs)
+
+
+class TestCheck:
+ @staticmethod
+ def _rec(an="A", ae="[email protected]", cn="C", ce="[email protected]", body=""):
+ return ("deadbeef0123", an, ae, cn, ce, body)
+
+ def test_author_violation(self):
+ errs = mod._check(
+ self._rec(an="LearningCircuit", ae="[email protected]"), DECLARED
+ )
+ assert len(errs) == 1
+ assert "author" in errs[0]
+ assert "deadbeef0" in errs[0]
+
+ def test_committer_violation(self):
+ errs = mod._check(
+ self._rec(cn="LearningCircuit", ce="[email protected]"), DECLARED
+ )
+ assert len(errs) == 1
+ assert "committer" in errs[0]
+
+ def test_co_author_trailer_violation(self):
+ errs = mod._check(
+ self._rec(
+ body="m\n\nCo-authored-by: LearningCircuit <[email protected]>\n"
+ ),
+ DECLARED,
+ )
+ assert len(errs) == 1
+ assert "Co-authored-by" in errs[0]
+
+ def test_clean_noreply_passes(self):
+ errs = mod._check(
+ self._rec(
+ an="LearningCircuit", ae=good, cn="LearningCircuit", ce=good
+ ),
+ DECLARED,
+ )
+ assert errs == []
+
+ def test_external_contributor_passes(self):
+ assert (
+ mod._check(self._rec(an="Outsider", ae="[email protected]"), DECLARED)
+ == []
+ )
+
+ def test_no_offending_email_in_any_message(self):
+ secret = "[email protected]"
+ errs = mod._check(
+ self._rec(
+ an="LearningCircuit",
+ ae=secret,
+ body=f"x\n\nCo-authored-by: LearningCircuit <{secret}>\n",
+ ),
+ DECLARED,
+ )
+ assert errs
+ assert all(secret not in e for e in errs)
+
+
+def clean_ci_env(monkeypatch):
+ """Isolate the GitHub Actions env (set in real CI -> would flake otherwise)."""
+ monkeypatch.delenv("GITHUB_EVENT_PATH", raising=False)
+ monkeypatch.delenv("GITHUB_EVENT_NAME", raising=False)
+ return monkeypatch
+
+
+class TestParseLogFailClosed:
+ def test_malformed_record_raises(self):
+ # An injected record separator splits a record into a <6-field chunk.
+ raw = "s\x00An\[email protected]\x00Cn\[email protected]\x00body\x1eINJECTED\x1e"
+ with pytest.raises(RuntimeError):
+ mod._parse_log(raw)
+
+ def test_multiple_records(self):
+ raw = (
+ "s1\x00A\[email protected]\x00C\[email protected]\x00b1\x1e"
+ "s2\x00A\[email protected]\x00C\[email protected]\x00b2\x1e"
+ )
+ assert [r[0] for r in mod._parse_log(raw)] == ["s1", "s2"]
+
+
+class TestResolveMergeBase:
+ def test_resolves_locally_without_fetching(self, monkeypatch):
+ # With full history present, merge-base succeeds first try -> NO fetch
+ # (the hook must not mutate git state inside `pre-commit run`).
+ runs = []
+ monkeypatch.setattr(
+ mod.subprocess, "run", lambda *a, **k: runs.append(a[0])
+ )
+ monkeypatch.setattr(mod, "_git", lambda *a: (0, "abc1234\n"))
+ assert mod._resolve_merge_base("b", "h") == "abc1234"
+ assert runs == [] # read-only: no git fetch was issued
+
+ def test_fetches_then_succeeds(self, monkeypatch):
+ # Shallow clone: first merge-base fails, a depth fetch makes it resolve.
+ runs = []
+ monkeypatch.setattr(
+ mod.subprocess, "run", lambda *a, **k: runs.append(a[0])
+ )
+ seq = iter([(1, ""), (0, "abc1234\n")])
+ monkeypatch.setattr(mod, "_git", lambda *a: next(seq))
+ assert mod._resolve_merge_base("b", "h") == "abc1234"
+ assert any("--depth=1000" in r for r in runs)
+ assert not any("--unshallow" in r for r in runs)
+
+ def test_retries_unshallow_then_succeeds(self, monkeypatch):
+ runs = []
+ monkeypatch.setattr(
+ mod.subprocess, "run", lambda *a, **k: runs.append(a[0])
+ )
+ seq = iter([(1, ""), (1, ""), (0, "abc1234\n")])
+ monkeypatch.setattr(mod, "_git", lambda *a: next(seq))
+ assert mod._resolve_merge_base("b", "h") == "abc1234"
+ assert any("--unshallow" in r for r in runs) # full-history path taken
+
+ def test_raises_when_unresolvable(self, monkeypatch):
+ monkeypatch.setattr(mod.subprocess, "run", lambda *a, **k: None)
+ monkeypatch.setattr(mod, "_git", lambda *a: (1, ""))
+ with pytest.raises(RuntimeError):
+ mod._resolve_merge_base("b", "h")
+
+
+class TestPrContext:
+ @staticmethod
+ def _event(tmp_path):
+ ev = tmp_path / "event.json"
+ ev.write_text(
+ json.dumps(
+ {
+ "pull_request": {
+ "base": {"sha": "BASE"},
+ "head": {"sha": "HEAD"},
+ }
+ }
+ )
+ )
+ return ev
+
+ def test_reads_allowlist_and_range_from_base(self, clean_ci_env, tmp_path):
+ mp = clean_ci_env
+ mp.setenv("GITHUB_EVENT_NAME", "pull_request")
+ mp.setenv("GITHUB_EVENT_PATH", str(self._event(tmp_path)))
+ mp.setattr(mod, "_resolve_merge_base", lambda b, h: "MB")
+ calls = []
+
+ def fake_git(*a):
+ calls.append(a)
+ if a[0] == "log":
+ return (0, "s\x00n\[email protected]\x00n\[email protected]\x00b\x1e")
+ if a[0] == "show":
+ return (0, PYPROJECT)
+ return (0, "")
+
+ mp.setattr(mod, "_git", fake_git)
+ records, text = mod._pr_context()
+ assert ("show", "BASE:pyproject.toml") in calls # base, not work-tree
+ assert any(c[0] == "log" and "MB..HEAD" in c[1] for c in calls)
+ assert text == PYPROJECT
+ assert records and records[0][0] == "s"
+
+ def test_base_pyproject_read_fails_closed(self, clean_ci_env, tmp_path):
+ mp = clean_ci_env
+ mp.setenv("GITHUB_EVENT_NAME", "pull_request")
+ mp.setenv("GITHUB_EVENT_PATH", str(self._event(tmp_path)))
+ mp.setattr(mod, "_resolve_merge_base", lambda b, h: "MB")
+
+ def fake_git(*a):
+ if a[0] == "log":
+ return (0, "s\x00n\[email protected]\x00n\[email protected]\x00b\x1e")
+ if a[0] == "show":
+ return (1, "") # base pyproject read fails
+ return (0, "")
+
+ mp.setattr(mod, "_git", fake_git)
+ with pytest.raises(RuntimeError):
+ mod._pr_context()
+
+ def test_non_pr_event_returns_none(self, clean_ci_env):
+ # No event + not a PR event -> local mode (None), not fail-closed.
+ assert mod._pr_context() is None
+
+ def test_pr_event_without_payload_fails_closed(self, clean_ci_env):
+ clean_ci_env.setenv("GITHUB_EVENT_NAME", "pull_request")
+ with pytest.raises(RuntimeError):
+ mod._pr_context()
+
+
+class TestMain:
+ def test_fails_closed_on_unresolvable_range(self, monkeypatch, capsys):
+ def boom():
+ raise RuntimeError("could not resolve the PR commit range")
+
+ monkeypatch.setattr(mod, "_pr_context", boom)
+ assert mod.main() == 1
+ assert "failing closed" in capsys.readouterr().err
+
+ def test_violation_in_pr_range_returns_1(self, monkeypatch, capsys):
+ rec = (
+ "deadbeef0",
+ "LearningCircuit",
+ "C",
+ "",
+ )
+ monkeypatch.setattr(mod, "_pr_context", lambda: ([rec], PYPROJECT))
+ assert mod.main() == 1
+ err = capsys.readouterr().err
+ assert "LearningCircuit" in err
+ assert "[email protected]" not in err # offending email never printed
+
+ def test_clean_pr_range_returns_0(self, monkeypatch):
+ rec = (
+ "deadbeef0",
+ "LearningCircuit",
+ good,
+ "LearningCircuit",
+ good,
+ "",
+ )
+ monkeypatch.setattr(mod, "_pr_context", lambda: ([rec], PYPROJECT))
+ assert mod.main() == 0
+
+ def test_no_declared_authors_returns_0(self, monkeypatch):
+ rec = (
+ "deadbeef0",
+ "LearningCircuit",
+ "C",
+ "",
+ )
+ monkeypatch.setattr(
+ mod, "_pr_context", lambda: ([rec], '[project]\nname = "x"\n')
+ )
+ assert mod.main() == 0
+
+
+class TestPendingRecords:
+ def test_parses_git_idents(self, monkeypatch):
+ ident = "LearningCircuit <[email protected]> 1700000000 +0000"
+ monkeypatch.setattr(mod, "_git", lambda *a: (0, ident))
+ recs = mod._pending_records()
+ assert recs[0][1] == "LearningCircuit"
+ assert recs[0][2] == "[email protected]"
+
+
+class TestAnchorBoundary:
+ def test_authors_prefixed_key_not_hijacked(self):
+ text = (
+ 'authors_extra = [{name = "E", email = "[email protected]"}]\n'
+ 'authors = [\n {name = "A", email = "[email protected]"},\n]\n'
+ )
+ assert mod.parse_identities(text) == {"a": {"[email protected]"}}
+
+
+class TestAllowlistFailClosed:
+ """The guard must not silently disable itself if the authors block changes."""
+
+ def test_real_repo_pyproject_still_parses_to_nonempty(self):
+ # If a future reformat of the real pyproject.toml breaks parsing, this
+ # trips here (and the CI path fails closed) instead of silently passing.
+ root = mod.Path(__file__).resolve().parents[2]
+ declared = mod.parse_identities(
+ (root / "pyproject.toml").read_text(encoding="utf-8")
+ )
+ assert declared, (
+ "pyproject.toml authors no longer parse -> guard disabled"
+ )
+ assert "learningcircuit" in declared
+ assert any(
+ e.endswith("@users.noreply.github.com")
+ for e in declared["learningcircuit"]
+ )
+
+ def test_ci_fails_closed_when_authors_declared_but_unparsed(
+ self, monkeypatch
+ ):
+ # array-of-tables form parse_identities does not understand: authors ARE
+ # declared but none parse -> fail closed rather than return 0.
+ unparsable = '[[project.authors]]\nname = "X"\nemail = "[email protected]"\n'
+ monkeypatch.setattr(mod, "_pr_context", lambda: ([], unparsable))
+ assert mod.main() == 1
+
+ def test_ci_passes_when_no_authors_block_at_all(self, monkeypatch):
+ # genuinely no authors declared -> not enforced -> pass (no over-block).
+ monkeypatch.setattr(
+ mod, "_pr_context", lambda: ([], '[project]\nname = "x"\n')
+ )
+ assert mod.main() == 0