blob: 9f8abed21cb4a0c316a1f08cb40eee9a1dc24b67 [file]
#!/usr/bin/env python3
#
# Copyright 2026 The Fuchsia Authors
#
# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
"""Deterministic local pre-push preflight check for Anneal pull requests.
Runs two strictly read-only, in-tree local checks on
`merge_base(--base, --head)..--head` so contributors catch mechanical hygiene
issues, public-sink leaks, and open-PR file overlaps before pushing (intended
for local developer use; not a CI workflow gate; never checks out or executes
candidate code):
1. Deterministic PR hygiene (`anneal/ci/check_pr_hygiene.py`), default-on
`@google.com` author/committer email check (`--no-cla-email-check` to opt
out for external forks), and per-commit public-repository leak scanning
across every linear commit message, per-commit added diff lines (merge
commits fail closed; rebase onto the base branch instead), and optional PR
title/body. Built-in patterns cover generic shortlink and conversation URI
shapes; organization-specific patterns may be supplied out of tree via
`ANNEAL_PREFLIGHT_EXTRA_LEAK_REGEX` or `ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE`
(`.json` object/array or text `label\\tregex` / bare regex lines). Exits `1`
on any blocking finding.
2. Passive open-PR file-overlap radar against open non-draft pull requests on
`google/zerocopy` (via an optional `--gh-cache-path` /
`ANNEAL_PREFLIGHT_GH_CACHE` JSON file or `gh pr list`). Prints structured
`COLLEAGUE_OVERLAP_RADAR:` advisories to stderr without blocking pushes.
Also reports `is_pure_verbatim_rebase` (when `--prior-head` is supplied) by
verifying the merge-base strictly advanced (`--is-ancestor`), the base delta
touched none of the PR's files, and every linear commit preserves identical
commit messages (`%B`) and exact raw tree deltas (blob OIDs, modes, and paths).
This is a structural Git predicate only; policy wrappers deciding whether to
carry forward prior reviews must also check whether base commits altered review
or policy files.
"""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
from typing import Any, Callable
SCHEMA = "anneal-pr-preflight/v1"
DEFAULT_REPO_SLUG = "google/anneal"
DEFAULT_CACHE_MAX_AGE_SEC = 900.0
DEFAULT_GH_OVERLAP_TIMEOUT_SEC = 5.0
DEFAULT_GH_OPEN_PR_LIMIT = 500
EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
# Pin every git setting that could hide content, alter diff formatting, honor
# `refs/replace` substitutions, or run hooks/external programs from ambient
# config or candidate `.gitattributes`.
GIT_OPTIONS: tuple[str, ...] = (
"--no-replace-objects",
"--literal-pathspecs",
"--no-pager",
f"--attr-source={EMPTY_TREE}",
"-c",
"core.hooksPath=/dev/null",
"-c",
"core.fsmonitor=false",
"-c",
"core.quotePath=false",
"-c",
"core.attributesFile=/dev/null",
"-c",
"diff.noprefix=false",
"-c",
"diff.mnemonicPrefix=false",
"-c",
"diff.relative=false",
"-c",
"diff.interHunkContext=0",
"-c",
"diff.suppressBlankEmpty=false",
"-c",
"diff.ignoreSubmodules=none",
"-c",
"diff.submodule=short",
"-c",
"diff.external=",
"-c",
f"diff.orderFile={os.devnull}",
"-c",
"diff.colorMoved=no",
"-c",
"diff.wsErrorHighlight=none",
"-c",
"diff.srcPrefix=a/",
"-c",
"diff.dstPrefix=b/",
"-c",
"diff.algorithm=myers",
"-c",
"diff.renames=false",
"-c",
"submodule.recurse=false",
"-c",
"color.ui=false",
"-c",
"color.diff=false",
"-c",
"log.showSignature=false",
"-c",
"log.mailmap=false",
"-c",
"log.decorate=no",
"-c",
"i18n.logOutputEncoding=UTF-8",
)
# CLI diff flags override even per-submodule `.gitmodules` / `.git/config`
# `submodule.<name>.ignore` settings (`-c diff.ignoreSubmodules=none` alone
# cannot override `submodule.<name>.ignore=all`).
_DIFF_COMMON_FLAGS: tuple[str, ...] = (
"--no-ext-diff",
"--no-textconv",
"--no-color",
"--no-renames",
"--no-relative",
"--ignore-submodules=none",
"--submodule=short",
)
_DIFF_BASE_FLAGS: tuple[str, ...] = ("diff", *_DIFF_COMMON_FLAGS)
_DIFF_TREE_FLAGS: tuple[str, ...] = ("diff-tree", *_DIFF_COMMON_FLAGS)
# Generic public-sink leak patterns that do not collide with Lean/Rust dotted
# identifiers (such as `Std.Internal.*`). Organization- or host-specific
# patterns belong out of tree via `ANNEAL_PREFLIGHT_EXTRA_LEAK_REGEX` or
# `ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE`.
PUBLIC_LEAK_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
(
"shortlink",
re.compile(
r"(?:(?<![A-Za-z0-9_./-])|(?<=://))"
r"\b(?:b|cl|yaqs|xid|fxr)/\d{4,}\b"
),
),
(
"go_shortlink",
re.compile(
r"(?:(?<![A-Za-z0-9_./-])|(?<=://))\bgo/"
r"(?![A-Za-z0-9_-]+\.(?:rs|py|go|lean|md|toml|json|yaml|yml|"
r"sh|c|h|cc|cpp|hpp|txt|lock)\b)"
r"[A-Za-z0-9][A-Za-z0-9_-]{2,}"
r"(?:/[A-Za-z0-9][A-Za-z0-9_.-]*)*\b"
),
),
(
"conversation_uri",
re.compile(r"conversation" r"://", re.IGNORECASE),
),
)
_DIFF_HEADER_PATH_RE = re.compile(r"^diff --git a/(.+) b/(.+)$")
_HUNK_HEADER_RE = re.compile(
r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@"
)
def _sanitized_git_env() -> dict[str, str]:
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env["GIT_CONFIG_NOSYSTEM"] = "1"
env["GIT_CONFIG_GLOBAL"] = os.devnull
env["GIT_NO_REPLACE_OBJECTS"] = "1"
env["LC_ALL"] = "C"
return env
def _run_git_bytes(
repo_dir: Path,
args: list[str],
*,
timeout: float = 30.0,
) -> subprocess.CompletedProcess[bytes]:
return subprocess.run(
["git", *GIT_OPTIONS, "-C", str(repo_dir), *args],
env=_sanitized_git_env(),
stdin=subprocess.DEVNULL,
capture_output=True,
timeout=timeout,
check=False,
)
def _run_git(
repo_dir: Path,
args: list[str],
*,
timeout: float = 30.0,
) -> subprocess.CompletedProcess[str]:
raw = _run_git_bytes(repo_dir, args, timeout=timeout)
return subprocess.CompletedProcess(
args=raw.args,
returncode=raw.returncode,
stdout=raw.stdout.decode("utf-8", "replace"),
stderr=raw.stderr.decode("utf-8", "replace"),
)
def resolve_repo_toplevel(repo_dir: Path) -> Path:
"""Resolves the Git worktree root for `repo_dir`."""
res = _run_git(repo_dir, ["rev-parse", "--show-toplevel"])
if res.returncode != 0 or not res.stdout.strip():
err = (res.stderr or res.stdout).strip()
raise RuntimeError(
f"git rev-parse --show-toplevel failed in {repo_dir}: {err}"
)
return Path(res.stdout.strip()).resolve()
def resolve_changed_files_and_loc(
repo_dir: Path,
base_ref: str,
head_ref: str,
) -> tuple[str, list[str], int, bool]:
"""Returns `(merge_base_sha, changed_paths, total_loc, has_non_text_diff)`."""
mb_res = _run_git(
repo_dir, ["merge-base", "--end-of-options", base_ref, head_ref]
)
if mb_res.returncode != 0 or not mb_res.stdout.strip():
err = mb_res.stderr.strip()
raise RuntimeError(
f"git merge-base {base_ref} {head_ref} failed: {err}"
)
mb_sha = mb_res.stdout.strip()
names_res = _run_git(
repo_dir,
[*_DIFF_BASE_FLAGS, "--name-only", "-z", f"{mb_sha}..{head_ref}"],
)
if names_res.returncode != 0:
err = names_res.stderr.strip()
raise RuntimeError(f"git diff --name-only failed: {err}")
paths = [p for p in names_res.stdout.split("\x00") if p]
num_res = _run_git(
repo_dir,
[*_DIFF_BASE_FLAGS, "--numstat", f"{mb_sha}..{head_ref}"],
)
total_loc = 0
has_non_text = False
if num_res.returncode != 0:
has_non_text = True
else:
for ln in num_res.stdout.split("\n"):
if not ln:
continue
parts = ln.split("\t")
if len(parts) < 3:
continue
if parts[0].isdigit() and parts[1].isdigit():
add_n = int(parts[0])
del_n = int(parts[1])
total_loc += add_n + del_n
else:
has_non_text = True
raw_res = _run_git(
repo_dir,
[*_DIFF_BASE_FLAGS, "--raw", f"{mb_sha}..{head_ref}"],
)
if raw_res.returncode != 0:
has_non_text = True
else:
for ln in raw_res.stdout.split("\n"):
if not ln.startswith(":"):
continue
meta = ln[1:].split("\t", 1)[0].split()
if len(meta) >= 2:
old_mode, new_mode = meta[0], meta[1]
mode_changed = (
old_mode != "000000"
and new_mode != "000000"
and old_mode != new_mode
)
is_special = old_mode in (
"120000",
"160000",
) or new_mode in ("120000", "160000")
if mode_changed or is_special:
has_non_text = True
return mb_sha, paths, total_loc, has_non_text
def _is_pure_tree_rebase(
repo_dir: Path,
base_ref: str,
head_ref: str,
prior_head_ref: str,
) -> bool:
"""Returns True only for a clean forward rebase preserving every commit.
Requires ALL of:
1. The merge-base strictly advanced (`prior_mb != cur_mb` AND
`git merge-base --is-ancestor prior_mb cur_mb`), rejecting both
same-base amends and backward rebases onto older bases.
2. The base advance `prior_mb..cur_mb` is disjoint from every path changed
by `prior_mb..prior_head` and `cur_mb..head`, so base edits to
PR-touched files never pass as a pure rebase.
3. Both ranges are linear (no merge commits) and have the exact same commit
count, per-commit messages (`%B`), and per-commit raw tree deltas
(`git diff-tree` via `_DIFF_TREE_FLAGS`,
`-r --raw --no-abbrev --no-commit-id -z`),
binding every pre/post blob OID, mode, and path so moved hunks,
whitespace edits, mode flips, and intermediate tampering are rejected.
"""
if not prior_head_ref.strip():
return False
head_res = _run_git(
repo_dir,
["rev-parse", "--verify", "--end-of-options", f"{head_ref}^{{commit}}"],
)
prior_res = _run_git(
repo_dir,
[
"rev-parse",
"--verify",
"--end-of-options",
f"{prior_head_ref}^{{commit}}",
],
)
if (
head_res.returncode != 0
or prior_res.returncode != 0
or not head_res.stdout.strip()
or not prior_res.stdout.strip()
):
return False
head_sha = head_res.stdout.strip()
prior_head_sha = prior_res.stdout.strip()
cur_mb = _run_git(
repo_dir, ["merge-base", "--end-of-options", base_ref, head_sha]
)
prior_mb = _run_git(
repo_dir, ["merge-base", "--end-of-options", base_ref, prior_head_sha]
)
if (
cur_mb.returncode != 0
or prior_mb.returncode != 0
or not cur_mb.stdout.strip()
or not prior_mb.stdout.strip()
):
return False
cur_mb_sha = cur_mb.stdout.strip()
prior_mb_sha = prior_mb.stdout.strip()
if cur_mb_sha == prior_mb_sha:
return False
# Base must strictly advance (`prior_mb` is an ancestor of `cur_mb`).
anc = _run_git(
repo_dir, ["merge-base", "--is-ancestor", prior_mb_sha, cur_mb_sha]
)
if anc.returncode != 0:
return False
# Base advance must not touch any path modified by the PR (either side).
def _changed_path_set(a: str, b: str) -> set[str] | None:
r = _run_git(
repo_dir,
[*_DIFF_BASE_FLAGS, "--name-only", "-z", f"{a}..{b}"],
)
if r.returncode != 0:
return None
return {p for p in r.stdout.split("\x00") if p}
base_paths = _changed_path_set(prior_mb_sha, cur_mb_sha)
cur_paths = _changed_path_set(cur_mb_sha, head_sha)
prior_paths = _changed_path_set(prior_mb_sha, prior_head_sha)
if base_paths is None or cur_paths is None or prior_paths is None:
return False
if cur_paths != prior_paths or (base_paths & cur_paths):
return False
def _per_commit_sigs(mb: str, head: str) -> list[tuple[bytes, bytes]] | None:
revs = _run_git(repo_dir, ["rev-list", "--reverse", f"{mb}..{head}"])
if revs.returncode != 0:
return None
shas = [ln.strip() for ln in revs.stdout.split("\n") if ln.strip()]
if not shas:
return None
sigs: list[tuple[bytes, bytes]] = []
for sha in shas:
# Reject merge commits and root commits in pure-rebase fast path.
p_res = _run_git(repo_dir, ["rev-list", "--parents", "-n", "1", sha])
if p_res.returncode != 0 or len(p_res.stdout.strip().split()) != 2:
return None
msg = _run_git_bytes(
repo_dir, ["show", "-s", "--encoding=UTF-8", "--format=%B", sha]
)
if msg.returncode != 0:
return None
raw_tree = _run_git_bytes(
repo_dir,
[
*_DIFF_TREE_FLAGS,
"-r",
"--raw",
"--no-abbrev",
"--no-commit-id",
"-z",
f"{sha}^1",
sha,
],
)
if raw_tree.returncode != 0:
return None
sigs.append((msg.stdout, raw_tree.stdout))
return sigs
cur_sigs = _per_commit_sigs(cur_mb_sha, head_sha)
prior_sigs = _per_commit_sigs(prior_mb_sha, prior_head_sha)
return cur_sigs is not None and prior_sigs is not None and cur_sigs == prior_sigs
def _parse_extra_leak_file(path: Path) -> list[tuple[str, re.Pattern[str]]]:
"""Loads extra leak patterns from `.json` or unambiguous text lines.
Supported formats:
- `.json` file: JSON object `{"label": "regex", ...}` or JSON array of
strings or `{"label": ..., "pattern": ...}` objects.
- Non-`.json` text file (ignoring blank lines and `#` comments):
- `label\\tregex` (tab-delimited, unambiguous even when regex has `:`)
- bare `regex` (used verbatim; never parsed as JSON or split on `:`, so
leading character classes like `[a-z0-9]+` work directly).
"""
raw = path.read_text(encoding="utf-8")
stripped = raw.strip()
if not stripped:
return []
if path.suffix.lower() == ".json":
try:
doc = json.loads(stripped)
except json.JSONDecodeError as exc:
raise ValueError(
f"invalid JSON in extra leak file {path}: {exc}"
) from exc
parsed: list[tuple[str, re.Pattern[str]]] = []
if isinstance(doc, dict):
for lbl, expr in doc.items():
if not isinstance(lbl, str) or not isinstance(expr, str):
raise ValueError(
f"extra leak JSON object entries in {path} must map "
"string labels to string regexes"
)
parsed.append((lbl.strip() or "file_extra", re.compile(expr)))
return parsed
if isinstance(doc, list):
for idx, item in enumerate(doc, start=1):
if isinstance(item, str):
parsed.append((f"file_extra_{idx}", re.compile(item)))
elif (
isinstance(item, dict)
and isinstance(item.get("pattern"), str)
):
lbl = str(item.get("label") or f"file_extra_{idx}").strip()
parsed.append((lbl, re.compile(item["pattern"])))
else:
raise ValueError(
f"invalid JSON array entry #{idx} in {path}"
)
return parsed
raise ValueError(f"extra leak JSON in {path} must be object or array")
out: list[tuple[str, re.Pattern[str]]] = []
for idx, raw_ln in enumerate(raw.split("\n"), start=1):
ln = raw_ln.strip()
if not ln or ln.startswith("#"):
continue
if "\t" in raw_ln:
lbl_raw, expr_raw = raw_ln.split("\t", 1)
lbl = lbl_raw.strip() or f"file_extra_{idx}"
expr = expr_raw.strip()
if not expr:
raise ValueError(
f"empty regex after tab on line {idx} of {path}"
)
out.append((lbl, re.compile(expr)))
else:
out.append((f"file_extra_{idx}", re.compile(ln)))
return out
def _compiled_leak_patterns() -> list[tuple[str, re.Pattern[str]]]:
patterns = list(PUBLIC_LEAK_PATTERNS)
extra = os.environ.get("ANNEAL_PREFLIGHT_EXTRA_LEAK_REGEX", "").strip()
if extra:
patterns.append(("env_extra", re.compile(extra)))
extra_file = os.environ.get("ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE", "").strip()
if extra_file:
p = Path(extra_file)
if not p.is_file():
raise RuntimeError(
f"ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE not found: {extra_file}"
)
patterns.extend(_parse_extra_leak_file(p))
return patterns
def _iter_added_diff_lines(diff_text: str) -> list[tuple[str, str]]:
"""Parses unified=0 git diff output strictly on `\\n` inside active hunks.
Splits strictly on LF (`\\n`) rather than `str.splitlines()` so embedded
CR (`\\r`), form-feed, vertical-tab, record-separator, or Unicode line
separators inside added lines cannot split a single Git line and terminate
the hunk prematurely. Tracks exact old/new line counts from
`@@ -a,b +c,d @@` headers so added lines starting with `++` (including
`++ b/...`) are scanned and never corrupt `cur_path`.
"""
added: list[tuple[str, str]] = []
cur_path = ""
rem_old = 0
rem_new = 0
in_hunk = False
for ln in diff_text.split("\n"):
if in_hunk:
if ln.startswith("\\"):
continue
if rem_old == 0 and rem_new == 0:
in_hunk = False
else:
if ln.startswith("+") and rem_new > 0:
added.append((cur_path, ln[1:]))
rem_new -= 1
continue
if ln.startswith("-") and rem_old > 0:
rem_old -= 1
continue
if ln.startswith(" ") and rem_old > 0 and rem_new > 0:
rem_old -= 1
rem_new -= 1
continue
raise ValueError(
f"malformed diff hunk line in {cur_path or '<unknown>'}: "
f"{ln[:80]!r} (rem_old={rem_old}, rem_new={rem_new})"
)
if ln.startswith("diff --git "):
m_hdr = _DIFF_HEADER_PATH_RE.match(ln)
if m_hdr:
cur_path = m_hdr.group(2)
continue
if ln.startswith("+++ b/"):
cur_path = ln[6:]
continue
if ln.startswith("+++ /dev/null"):
cur_path = ""
continue
if ln.startswith("@@"):
m_hunk = _HUNK_HEADER_RE.match(ln)
if not m_hunk:
raise ValueError(
f"malformed hunk header in {cur_path or '<unknown>'}: "
f"{ln[:80]!r}"
)
old_c = m_hunk.group(2)
new_c = m_hunk.group(4)
rem_old = 1 if old_c is None else int(old_c)
rem_new = 1 if new_c is None else int(new_c)
in_hunk = True
if in_hunk and (rem_old != 0 or rem_new != 0):
raise ValueError(
f"truncated diff hunk in {cur_path or '<unknown>'} "
f"(rem_old={rem_old}, rem_new={rem_new})"
)
return added
def scan_public_leaks_and_cla(
repo_dir: Path,
merge_base: str,
head_ref: str,
*,
require_google_cla_email: bool = True,
pr_title: str | None = None,
pr_body_text: str | None = None,
) -> list[dict[str, Any]]:
"""Checks every commit in `merge_base..head_ref` plus PR title/body."""
findings: list[dict[str, Any]] = []
try:
patterns = _compiled_leak_patterns()
except (OSError, RuntimeError, ValueError, re.error) as exc:
findings.append({
"check": "leak-config",
"message": f"invalid extra leak configuration: {exc}",
})
return findings
rev_res = _run_git(
repo_dir, ["rev-list", "--reverse", f"{merge_base}..{head_ref}"]
)
if rev_res.returncode != 0:
findings.append({
"check": "git-log",
"message": (
f"git rev-list {merge_base}..{head_ref} failed "
f"(exit {rev_res.returncode}): "
f"{(rev_res.stderr or rev_res.stdout).strip()[:200]}"
),
})
commits: list[str] = []
else:
commits = [
ln.strip() for ln in rev_res.stdout.split("\n") if ln.strip()
]
for sha in commits:
meta_res = _run_git_bytes(
repo_dir,
["show", "-s", "--encoding=UTF-8", "--format=%ae%x00%ce%x00%B", sha],
)
if meta_res.returncode != 0:
err = meta_res.stderr.decode("utf-8", "replace").strip()[:200]
findings.append({
"check": "git-log",
"commit": sha[:12],
"message": (
f"git show metadata for {sha[:12]} failed "
f"(exit {meta_res.returncode}): {err}"
),
})
continue
parts = meta_res.stdout.split(b"\x00", 2)
if len(parts) != 3:
findings.append({
"check": "git-log",
"commit": sha[:12],
"message": f"malformed git metadata record for {sha[:12]}",
})
continue
author_email = parts[0].decode("utf-8", "replace")
committer_email = parts[1].decode("utf-8", "replace")
body = parts[2].decode("utf-8", "replace")
if require_google_cla_email:
for role, email in (
("author", author_email),
("committer", committer_email),
):
if not email.lower().endswith("@google.com"):
findings.append({
"check": "cla-email",
"commit": sha[:12],
"message": (
f"Commit {sha[:12]} {role} email {email!r} "
"must use @google.com"
),
})
for label, pat in patterns:
if pat.search(body):
findings.append({
"check": f"public-leak:{label}",
"commit": sha[:12],
"message": (
f"Commit {sha[:12]} message matches forbidden "
f"pattern {label}"
),
})
# Inspect commit parents: ordinary commits diff against their sole
# parent (or empty tree for root). Merge commits fail closed rather
# than relying on combined diffs, which ignore `--text` for binary
# blobs and complicate upstream vs. PR attribution.
p_res = _run_git(repo_dir, ["rev-list", "--parents", "-n", "1", sha])
if p_res.returncode != 0:
findings.append({
"check": "git-diff",
"commit": sha[:12],
"message": (
f"git rev-list --parents {sha[:12]} failed "
f"(exit {p_res.returncode}): "
f"{(p_res.stderr or p_res.stdout).strip()[:200]}"
),
})
continue
parents = p_res.stdout.strip().split()[1:]
if len(parents) > 1:
findings.append({
"check": "merge-commit",
"commit": sha[:12],
"message": (
f"Merge commit {sha[:12]} in PR range is not supported by "
"per-commit leak scanning; rebase onto the base branch "
"instead"
),
})
continue
parent_ref = EMPTY_TREE if len(parents) == 0 else parents[0]
diff_args = [
*_DIFF_BASE_FLAGS,
"--src-prefix=a/",
"--dst-prefix=b/",
"--inter-hunk-context=0",
"--text",
"--unified=0",
parent_ref,
sha,
]
c_diff = _run_git_bytes(repo_dir, diff_args)
if c_diff.returncode != 0:
err = c_diff.stderr.decode("utf-8", "replace").strip()[:200]
findings.append({
"check": "git-diff",
"commit": sha[:12],
"message": (
f"git diff {sha[:12]} failed "
f"(exit {c_diff.returncode}): {err}"
),
})
else:
diff_text = c_diff.stdout.decode("utf-8", "replace")
try:
added_lines = _iter_added_diff_lines(diff_text)
except ValueError as exc:
findings.append({
"check": "git-diff",
"commit": sha[:12],
"message": f"failed to parse diff for {sha[:12]}: {exc}",
})
continue
for cur_path, added_text in added_lines:
for label, pat in patterns:
if pat.search(added_text):
findings.append({
"check": f"public-leak:{label}",
"commit": sha[:12],
"path": cur_path,
"message": (
f"Added line in {cur_path} ({sha[:12]}) "
f"matches forbidden pattern {label}"
),
})
if pr_title is not None:
if not pr_title.strip():
findings.append({
"check": "pr-title",
"path": "<pr-title>",
"message": "--pr-title must not be empty",
})
else:
for label, pat in patterns:
if pat.search(pr_title):
findings.append({
"check": f"public-leak:{label}",
"path": "<pr-title>",
"message": f"PR title matches forbidden pattern {label}",
})
if pr_body_text:
for label, pat in patterns:
if pat.search(pr_body_text):
findings.append({
"check": f"public-leak:{label}",
"path": "<pr-body>",
"message": f"PR body matches forbidden pattern {label}",
})
if rev_res.returncode != 0:
findings.append({
"check": "git-diff",
"message": f"cannot verify diff for invalid range {merge_base}..{head_ref}",
})
return findings
def _read_pr_body_text(pr_body_file: Path | str | None) -> str | None:
if pr_body_file is None:
return None
raw = str(pr_body_file)
if not raw:
raise ValueError("--pr-body-file must not be empty")
if raw == "-":
return sys.stdin.read()
return Path(raw).read_text(encoding="utf-8")
def run_hygiene_stage(
repo_dir: Path,
base_ref: str,
head_ref: str,
*,
hygiene_script: Path | None = None,
pr_title: str | None = None,
pr_body_file: Path | str | None = None,
pr_body_text: str | None = None,
require_google_cla_email: bool = True,
) -> dict[str, Any]:
"""Runs `check_pr_hygiene.py` plus CLA and public-leak checks."""
script = hygiene_script or (
Path(__file__).resolve().parent / "check_pr_hygiene.py"
)
mb_sha, changed_paths, total_loc, has_non_text = (
resolve_changed_files_and_loc(repo_dir, base_ref, head_ref)
)
resolved_body_text = (
pr_body_text
if pr_body_text is not None
else _read_pr_body_text(pr_body_file)
)
tmp_body_file: Path | None = None
try:
argv = [
sys.executable,
"-I",
"-B",
str(script),
"--repo",
str(repo_dir),
"--base",
mb_sha,
"--head",
head_ref,
"--json",
]
if pr_title is not None and pr_title.strip():
argv.append(f"--pr-title={pr_title}")
if resolved_body_text is not None:
# Always pass the already-read content via a single temp file so
# stdin (`-`), FIFOs, and process substitutions are read once.
fd, tmp_name = tempfile.mkstemp(prefix="pr_preflight_body_")
tmp_body_file = Path(tmp_name)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(resolved_body_text)
argv.append(f"--pr-body-file={tmp_body_file}")
proc = subprocess.run(
argv,
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=30.0,
check=False,
)
finally:
if tmp_body_file is not None:
try:
tmp_body_file.unlink()
except OSError:
pass
if proc.returncode not in (0, 1):
detail = (proc.stderr or proc.stdout).strip()[:240]
raise RuntimeError(
f"check_pr_hygiene.py exited {proc.returncode}: {detail}"
)
raw_out = (proc.stdout or "").strip()
hygiene_parse_ok = True
doc_ok = False
hygiene_findings: list[dict[str, Any]] = []
warnings: list[dict[str, Any]] = []
waived_findings: list[dict[str, Any]] = []
opt_outs: list[dict[str, Any]] = []
human_review_surface: list[str] | None = None
try:
doc = json.loads(raw_out) if raw_out else None
if not isinstance(doc, dict):
raise ValueError("expected JSON object from check_pr_hygiene.py")
if not isinstance(doc.get("ok"), bool):
raise ValueError("missing boolean `ok` field in hygiene JSON")
doc_ok = bool(doc["ok"])
raw_findings = doc.get("findings")
raw_warnings = doc.get("warnings")
if not isinstance(raw_findings, list) or not isinstance(
raw_warnings, list
):
raise ValueError("findings/warnings must be lists in hygiene JSON")
hygiene_findings = list(raw_findings)
warnings = list(raw_warnings)
raw_waived = doc.get("waived_findings", [])
raw_opt_outs = doc.get("opt_outs", [])
if not isinstance(raw_waived, list) or not isinstance(
raw_opt_outs, list
):
raise ValueError(
"waived_findings/opt_outs must be lists in hygiene JSON"
)
waived_findings = list(raw_waived)
opt_outs = list(raw_opt_outs)
raw_hrs = doc.get("human_review_surface")
if isinstance(raw_hrs, list) and all(
isinstance(p, str) for p in raw_hrs
):
human_review_surface = list(raw_hrs)
else:
raise ValueError(
"missing or invalid human_review_surface list in hygiene JSON"
)
except (json.JSONDecodeError, ValueError) as exc:
hygiene_parse_ok = False
detail = (proc.stderr or raw_out).strip()[:240]
hygiene_findings.append({
"check": "hygiene-json",
"message": (
f"check_pr_hygiene.py emitted invalid JSON ({exc}): {detail}"
),
})
extra_findings = scan_public_leaks_and_cla(
repo_dir,
mb_sha,
head_ref,
require_google_cla_email=require_google_cla_email,
pr_title=pr_title,
pr_body_text=resolved_body_text,
)
all_findings = hygiene_findings + extra_findings
return {
"ok": (
proc.returncode == 0
and doc_ok
and hygiene_parse_ok
and len(all_findings) == 0
),
"merge_base": mb_sha,
"changed_paths": changed_paths,
"changed_lines": total_loc,
"has_non_text_diff": has_non_text,
"human_review_surface": human_review_surface,
"findings": all_findings,
"warnings": warnings,
"waived_findings": waived_findings,
"opt_outs": opt_outs,
}
def _cache_is_fresh(
cache_path: Path,
doc: dict[str, Any],
*,
max_age_sec: float = DEFAULT_CACHE_MAX_AGE_SEC,
now_epoch: float | None = None,
) -> bool:
now = time.time() if now_epoch is None else float(now_epoch)
ts = doc.get("fetched_at_epoch")
if isinstance(ts, (int, float)) and not isinstance(ts, bool):
return (now - float(ts)) <= max_age_sec
try:
return (now - cache_path.stat().st_mtime) <= max_age_sec
except OSError:
return False
def load_open_prs_for_overlap(
*,
repo_slug: str = DEFAULT_REPO_SLUG,
gh_cache_path: Path | None = None,
gh_fetch_fn: Callable[[str], list[dict[str, Any]]] | None = None,
warnings_out: list[dict[str, Any]] | None = None,
cache_max_age_sec: float = DEFAULT_CACHE_MAX_AGE_SEC,
) -> list[dict[str, Any]]:
"""Loads open PR file sets from fresh cache or bounded `gh pr list`."""
cache_p = gh_cache_path
if cache_p is None and repo_slug == DEFAULT_REPO_SLUG:
env_cache = os.environ.get("ANNEAL_PREFLIGHT_GH_CACHE", "").strip()
if env_cache:
cache_p = Path(env_cache)
if cache_p is not None:
try:
if not cache_p.is_file():
raise FileNotFoundError(cache_p)
doc = json.loads(cache_p.read_text(encoding="utf-8"))
cached_repo = (
str(doc.get("repo") or "").strip()
if isinstance(doc, dict)
else ""
)
repo_ok = (not cached_repo) or (cached_repo == repo_slug)
if (
isinstance(doc, dict)
and repo_ok
and isinstance(doc.get("prs"), list)
and _cache_is_fresh(
cache_p, doc, max_age_sec=cache_max_age_sec
)
):
return [p for p in doc["prs"] if isinstance(p, dict)]
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
pass
if gh_fetch_fn is not None:
return gh_fetch_fn(repo_slug)
gh_bin = shutil.which("gh")
if not gh_bin:
if warnings_out is not None:
warnings_out.append({
"check": "overlap-radar",
"message": "gh CLI unavailable; skipped open-PR overlap radar",
})
return []
try:
proc = subprocess.run(
[
gh_bin,
"pr",
"list",
"-R",
repo_slug,
"--state",
"open",
"--limit",
str(DEFAULT_GH_OPEN_PR_LIMIT),
"--json",
"number,author,headRefName,isDraft,files",
],
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=DEFAULT_GH_OVERLAP_TIMEOUT_SEC,
check=False,
)
except subprocess.TimeoutExpired:
if warnings_out is not None:
warnings_out.append({
"check": "overlap-radar",
"message": "gh pr list timed out; skipped overlap radar",
})
return []
if proc.returncode != 0 or not proc.stdout.strip():
if warnings_out is not None:
warnings_out.append({
"check": "overlap-radar",
"message": "gh pr list unavailable; skipped overlap radar",
})
return []
try:
rows = json.loads(proc.stdout)
if isinstance(rows, list):
return [p for p in rows if isinstance(p, dict)]
except json.JSONDecodeError:
pass
return []
def compute_file_overlaps(
changed_paths: list[str],
open_prs: list[dict[str, Any]],
*,
exclude_branch: str = "",
exclude_pr: int | None = None,
) -> list[dict[str, Any]]:
"""Intersects `changed_paths` against open non-draft PRs (passive radar)."""
touched = {p.strip().lstrip("/") for p in changed_paths if p.strip()}
if not touched:
return []
hits: list[dict[str, Any]] = []
for pr in open_prs:
if not isinstance(pr, dict) or bool(pr.get("isDraft")):
continue
try:
num = int(pr.get("number") or 0)
except (TypeError, ValueError):
continue
if num <= 0 or (exclude_pr is not None and num == int(exclude_pr)):
continue
href = str(pr.get("headRefName") or "").strip()
if exclude_branch and href == exclude_branch:
continue
raw_files = pr.get("files")
nodes = (
raw_files.get("nodes") if isinstance(raw_files, dict) else raw_files
)
if not isinstance(nodes, list):
continue
pr_files = {
str(f.get("path") if isinstance(f, dict) else f or "").strip()
for f in nodes
if (isinstance(f, dict) and f.get("path")) or isinstance(f, str)
}
shared = sorted(touched & pr_files)
if shared:
raw_author = pr.get("author")
author = (
str(raw_author.get("login") or "unknown")
if isinstance(raw_author, dict)
else "unknown"
)
hits.append({
"pr": num,
"author": author,
"head_ref": href,
"overlapping_files": shared[:20],
"overlap_count": len(shared),
})
hits.sort(key=lambda item: (-int(item["overlap_count"]), int(item["pr"])))
return hits
def _resolve_head_branch_name(repo_dir: Path, head_ref: str) -> str:
"""Returns local branch short name if `head_ref` is a branch or `HEAD`."""
br_res = _run_git(
repo_dir, ["symbolic-ref", "--short", "-q", "--end-of-options", head_ref]
)
if br_res.returncode == 0 and br_res.stdout.strip():
return br_res.stdout.strip()
cand = (
head_ref[len("refs/heads/"):]
if head_ref.startswith("refs/heads/")
else head_ref
)
if cand:
chk = _run_git(
repo_dir,
[
"rev-parse",
"--verify",
"--quiet",
"--end-of-options",
f"refs/heads/{cand}",
],
)
if chk.returncode == 0:
return cand
return ""
def run_preflight(
*,
repo_dir: Path,
base_ref: str = "origin/main",
head_ref: str = "HEAD",
prior_head_ref: str = "",
repo_slug: str = DEFAULT_REPO_SLUG,
pr_title: str | None = None,
pr_body_file: Path | str | None = None,
pr_body_text: str | None = None,
require_google_cla_email: bool = True,
gh_cache_path: Path | None = None,
gh_fetch_fn: Callable[[str], list[dict[str, Any]]] | None = None,
) -> tuple[int, dict[str, Any]]:
"""Executes all configured preflight stages and returns `(rc, report)`."""
top_dir = resolve_repo_toplevel(repo_dir)
hygiene = run_hygiene_stage(
top_dir,
base_ref,
head_ref,
pr_title=pr_title,
pr_body_file=pr_body_file,
pr_body_text=pr_body_text,
require_google_cla_email=require_google_cla_email,
)
findings = list(hygiene["findings"])
warnings = list(hygiene["warnings"])
cur_branch = _resolve_head_branch_name(top_dir, head_ref)
open_prs = load_open_prs_for_overlap(
repo_slug=repo_slug,
gh_cache_path=gh_cache_path,
gh_fetch_fn=gh_fetch_fn,
warnings_out=warnings,
)
overlaps = compute_file_overlaps(
hygiene["changed_paths"],
open_prs,
exclude_branch=cur_branch,
)
for ov in overlaps[:10]:
sample = ", ".join(ov["overlapping_files"][:4])
sys.stderr.write(
"COLLEAGUE_OVERLAP_RADAR: overlaps open PR "
f"https://github.com/{repo_slug}/pull/{ov['pr']} ({ov['author']}) "
f"on [{sample}]; coordinate stack base or sequencing order\n"
)
pure_rebase = _is_pure_tree_rebase(
top_dir, base_ref, head_ref, prior_head_ref
)
overall_ok = bool(hygiene["ok"])
report = {
"schema": SCHEMA,
"ok": overall_ok,
"merge_base": hygiene["merge_base"],
"changed_files_count": len(hygiene["changed_paths"]),
"changed_lines": hygiene["changed_lines"],
"has_non_text_diff": hygiene["has_non_text_diff"],
"human_review_surface": hygiene["human_review_surface"],
"is_pure_verbatim_rebase": pure_rebase,
"hygiene_ok": hygiene["ok"],
"findings": findings,
"warnings": warnings,
"waived_findings": list(hygiene["waived_findings"]),
"opt_outs": list(hygiene["opt_outs"]),
"overlaps": overlaps,
}
return (0 if overall_ok else 1), report
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
description="Deterministic local pre-push preflight for Anneal PRs."
)
p.add_argument(
"--repo",
default=".",
help="Git checkout path (default: current directory).",
)
p.add_argument(
"--base",
default="origin/main",
help="Base ref to compute merge-base against (default: origin/main).",
)
p.add_argument(
"--head",
default="HEAD",
help="Head commit or ref to verify (default: HEAD).",
)
p.add_argument(
"--prior-head",
default="",
help=(
"Optional pre-rebase commit ref to report "
"`is_pure_verbatim_rebase`."
),
)
p.add_argument(
"--repo-slug",
default=DEFAULT_REPO_SLUG,
help="GitHub owner/repo slug (default: google/anneal).",
)
p.add_argument(
"--pr-title",
default=None,
help="Optional PR title to check.",
)
p.add_argument(
"--pr-body-file",
default=None,
help="Optional path to PR body Markdown file (or `-` for stdin).",
)
p.add_argument(
"--gh-cache-path",
default="",
help="Optional path to a fresh open-PR JSON cache file.",
)
p.add_argument(
"--no-cla-email-check",
dest="cla_email",
action="store_false",
default=True,
help="Skip @google.com commit email check (for external forks).",
)
p.add_argument(
"--json",
action="store_true",
help="Emit structured JSON report to stdout.",
)
return p
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
if args.pr_body_file is None:
body_arg: Path | str | None = None
elif args.pr_body_file == "-":
body_arg = "-"
elif args.pr_body_file == "":
body_arg = ""
else:
body_arg = Path(args.pr_body_file)
cache_arg = Path(args.gh_cache_path) if args.gh_cache_path else None
rc, report = run_preflight(
repo_dir=Path(args.repo).resolve(),
base_ref=args.base,
head_ref=args.head,
prior_head_ref=args.prior_head,
repo_slug=args.repo_slug,
pr_title=args.pr_title,
pr_body_file=body_arg,
require_google_cla_email=bool(args.cla_email),
gh_cache_path=cache_arg,
)
if args.json:
print(json.dumps(report, indent=2, sort_keys=True))
else:
status = "PASS" if report["ok"] else "FAIL"
print(
f"[pr-preflight] {status}: files={report['changed_files_count']} "
f"lines={report['changed_lines']} overlaps={len(report['overlaps'])} "
f"pure_rebase={report['is_pure_verbatim_rebase']}"
)
for item in report["findings"]:
chk = item.get("check") or "hygiene"
loc = item.get("path") or item.get("commit") or "<repo>"
print(f" [FINDING] {chk} ({loc}): {item.get('message')}")
return rc
if __name__ == "__main__":
raise SystemExit(main())