|
| 1 | +"""Fail when a diff looks like an agent run went off the rails. |
| 2 | +
|
| 3 | +Without arguments, check the staged diff (pre-commit mode). |
| 4 | +With --base REF, check REF...HEAD (CI mode). |
| 5 | +""" |
| 6 | + |
| 7 | +import argparse |
| 8 | +import subprocess |
| 9 | +import sys |
| 10 | + |
| 11 | +MAX_CHANGED_LINES = 200 |
| 12 | +IGNORED = ("uv.lock",) |
| 13 | +PROTECTED = ( |
| 14 | + ".github/", |
| 15 | + ".pre-commit-config.yaml", |
| 16 | + "pyproject.toml", |
| 17 | + "scripts/agent_diff_check.py", |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +def changes(base: str | None) -> list[tuple[int, int, str]]: |
| 22 | + # Three dots diff against the merge base: only the branch's own work. |
| 23 | + revs = [f"{base}...HEAD"] if base else ["--cached"] |
| 24 | + out = subprocess.run( |
| 25 | + ["git", "diff", *revs, "--numstat", "--no-renames", "-z"], |
| 26 | + capture_output=True, |
| 27 | + text=True, |
| 28 | + check=True, |
| 29 | + ).stdout |
| 30 | + rows = [] |
| 31 | + for line in out.split("\0")[:-1]: # -z ends every row with NUL |
| 32 | + added, deleted, path = line.split("\t", 2) |
| 33 | + if path in IGNORED: |
| 34 | + continue |
| 35 | + if added == "-": # A binary file: keep the path, count no lines |
| 36 | + added = deleted = "0" |
| 37 | + rows.append((int(added), int(deleted), path)) |
| 38 | + return rows |
| 39 | + |
| 40 | + |
| 41 | +def main() -> int: |
| 42 | + parser = argparse.ArgumentParser(description=__doc__) |
| 43 | + parser.add_argument("--base", help="compare BASE...HEAD instead of the index") |
| 44 | + args = parser.parse_args() |
| 45 | + try: |
| 46 | + rows = changes(args.base) |
| 47 | + except subprocess.CalledProcessError as error: |
| 48 | + print(f"agent-diff-check: git diff failed: {error.stderr.strip()}") |
| 49 | + print("agent-diff-check: is the checkout shallow? Use fetch-depth: 0.") |
| 50 | + return 2 |
| 51 | + problems = [ |
| 52 | + f"protected path touched: {path}" |
| 53 | + for _, _, path in rows |
| 54 | + if path.startswith(PROTECTED) |
| 55 | + ] |
| 56 | + total = sum(a + d for a, d, _ in rows) |
| 57 | + if total > MAX_CHANGED_LINES: |
| 58 | + problems.append(f"diff changes {total} lines (limit {MAX_CHANGED_LINES})") |
| 59 | + for problem in problems: |
| 60 | + print(f"agent-diff-check: {problem}") |
| 61 | + return 1 if problems else 0 |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + sys.exit(main()) |
0 commit comments