The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(ci): reject PRs that add binaries or new files over 500 KiB
Tekniumdb5e61820547
diff --git a/.github/blob-size-allowlist.txt b/.github/blob-size-allowlist.txtnew file mode 100644index 00000000000..8db4603189f--- /dev/null+++ b/.github/blob-size-allowlist.txt@@ -0,0 +1,12 @@+# Exact repo paths exempt from scripts/ci/check_blob_size.py (binaries over 500 KiB, and new+# files over 500 KiB). One path per line; no globs, no directories. Keep this list short: every+# entry is a file whose bytes every clone carries again each time it changes.+#+# Admit a path only when the file must ship at its size AND legitimately changes (a generated+# icon, an installer asset). A large file added once and never touched again does not need an+# entry: only adding or modifying it is judged. Editing this file needs a hermes-agent-core review+# (CODEOWNERS: /.github/).++# Generated by scripts/generate_icons.py from assets/dmg-volume.png; icons-freshness-check.yml+# fails any PR that changes the master without committing this re-render.+apps/desktop/packaging/dmg-volume.icnsdiff --git a/.github/workflows/blob-size-check.yml b/.github/workflows/blob-size-check.ymlnew file mode 100644index 00000000000..db53dc165f5--- /dev/null+++ b/.github/workflows/blob-size-check.yml@@ -0,0 +1,32 @@+name: Blob Size Check++# Rejects PRs that add or modify a binary over 500 KiB, or add any new file over 500 KiB.+#+# Every blob a merge adds stays in every clone and every CI checkout forever, even after a later+# commit deletes it. In three summer months main received a 2 MB PR screenshot, a 2 MB+# default.tar.gz, PR infographics, a Windows cache database and a 1 MB fuzz corpus, none of+# which any check looked at. Edits to existing text files are left to the code-health+# FILE_LINES ratchet. Exact-path exceptions live in .github/blob-size-allowlist.txt+# (CODEOWNERS-reviewed). Local: `python scripts/check --only blob-size`.+#+# Runs unconditionally (no change-classifier gate): a docs-only or asset-only PR skips the+# Python and frontend lanes, and that is exactly the kind of PR that commits a screenshot.++on:+ workflow_call:++permissions:+ contents: read++jobs:+ check-blob-size:+ name: Reject large binaries+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7.0.1+ with:+ fetch-depth: 2 # the merge commit and its first parent (the base branch tip)++ - name: Judge files added or modified against the base branch tip+ run: python3 scripts/ci/check_blob_size.py --base HEAD^1diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yamlindex d0dc83f232f..834fd9ce673 100644--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@ -293,6 +293,11 @@ jobs:needs: detectuses: ./.github/workflows/case-collision-check.yml+ blob-size-check:+ name: Check no large binaries+ needs: detect+ uses: ./.github/workflows/blob-size-check.yml+lazy-deps-guard:name: No production imports of the tools.lazy_deps stubneeds: detect@@ -373,6 +378,7 @@ jobs:- uv-lockfile- infographic-check- case-collision-check+ - blob-size-check- lazy-deps-guard- lockfile-diff- prompt-surface-diffdiff --git a/scripts/ci/check_blob_size.py b/scripts/ci/check_blob_size.pynew file mode 100644index 00000000000..81c4b669bee--- /dev/null+++ b/scripts/ci/check_blob_size.py@@ -0,0 +1,256 @@+#!/usr/bin/env python3+"""Fail when a change adds a large binary, or a large new file, to the repository.++Every blob a merge adds stays in every clone forever, so a screenshot, a test database or an+archive committed by mistake costs every contributor and every CI checkout from then on, even+after a later commit deletes it. This summer main received a 2 MB PR screenshot, a 2 MB+``default.tar.gz``, a 4 MB background JPEG, SQLite files a test wrote into the checkout, and a+1 MB fuzz-corpus JSON at the repo root.++Judged per changed path, base -> head:++* a binary file (git's own detection: ``--numstat`` prints ``- -``) whose new content is over+ ``MAX_BYTES``, whether added, modified or renamed with edits;+* a newly added text file over ``MAX_BYTES``. Edits to existing text files are not judged here:+ the code-health FILE_LINES ratchet already caps their growth, and the repo has legitimate+ generated or vendored text files over the limit (``uv.lock``, lockfiles, the OpenRPC contract).++Content the base tree already holds (a pure rename, a copy, a revert to a tracked version) adds no+bytes to the pack and is never judged. Paths listed in+``.github/blob-size-allowlist.txt`` (exact paths, one per line) are exempt; that file is+CODEOWNERS-reviewed, so every exception gets a core review.++ python scripts/ci/check_blob_size.py # working tree vs merge-base with origin/main+ python scripts/ci/check_blob_size.py --base HEAD^1 # CI: the PR merge commit vs main+ python scripts/ci/check_blob_size.py --base A --head B # any two revisions++Exit codes: 0 = nothing over the limit, 1 = at least one offender, 2 = git or usage error.+"""++from __future__ import annotations++import argparse+import os+import subprocess+import sys+from collections.abc import Collection+from dataclasses import dataclass+from pathlib import Path++MAX_BYTES = 500 * 1024+ALLOWLIST = ".github/blob-size-allowlist.txt"+_GITLINK = "160000"+_ZERO_SHA = "0" * 40+# git's own heuristic (xdiff buffer_is_binary): a NUL byte in the first 8000 bytes.+_SNIFF_BYTES = 8000+++class GitError(RuntimeError):+ pass+++@dataclass(frozen=True)+class Change:+ status: str # A (added or copied), M, R (renamed), T (type change)+ path: str+ old_path: str | None+ blob: str | None # head blob sha; None for a working-tree file not yet hashed+++@dataclass(frozen=True)+class Offender:+ path: str+ size: int+ kind: str # "binary" or "new file"+ status: str+++def _git(repo: Path, *args: str, check: bool = True) -> str:+ proc = subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True, encoding="utf-8",+ errors="surrogateescape", stdin=subprocess.DEVNULL, timeout=300, check=False)+ if check and proc.returncode != 0:+ raise GitError(f"git {' '.join(args)}: {proc.stderr.strip()}")+ return proc.stdout+++def default_base(repo: Path, head: str | None) -> str:+ """Merge-base of the judged commit (HEAD for a tree or the working tree) with origin/main."""+ tip = "HEAD"+ if head and _git(repo, "rev-parse", "--verify", "--quiet", f"{head}^{{commit}}", check=False).strip():+ tip = head+ for ref in ("origin/main", "main"):+ out = _git(repo, "merge-base", tip, ref, check=False).strip()+ if out:+ return out+ raise GitError("no merge-base with origin/main or main; pass --base")+++def _parse_raw(out: str) -> list[Change]:+ """``git diff --raw -z -M -C`` records -> changes that introduce content at a path."""+ fields = out.split("\0")+ changes: list[Change] = []+ i = 0+ while i < len(fields) and fields[i].startswith(":"):+ meta = fields[i][1:].split()+ new_mode, new_sha, status = meta[1], meta[3], meta[4]+ code = status[0]+ if code in "RC":+ old_path, path = fields[i + 1], fields[i + 2]+ i += 3+ else:+ old_path, path = None, fields[i + 1]+ i += 2+ if code in "DU" or new_mode == _GITLINK:+ continue+ blob = None if new_sha == _ZERO_SHA else new_sha+ changes.append(Change("A" if code == "C" else code, path, old_path, blob))+ return changes+++def _binary_paths(repo: Path, base: str, head: str | None) -> set[str]:+ args = ["diff", "--numstat", "-z", "-M", "-C", base] + ([head] if head else [])+ fields = _git(repo, *args).split("\0")+ paths: set[str] = set()+ i = 0+ while i < len(fields) and fields[i]:+ added, deleted, path = fields[i].split("\t", 2)+ if path: # plain record: "<a>\t<d>\t<path>"+ i += 1+ else: # rename/copy record: "<a>\t<d>\t" then old and new path as their own fields+ path = fields[i + 2]+ i += 3+ if added == "-" and deleted == "-":+ paths.add(path)+ return paths+++def _tree_blobs(repo: Path, rev: str) -> set[str]:+ out = _git(repo, "ls-tree", "-r", "-z", "--full-tree", rev) # "<mode> <type> <sha>\t<path>"+ return {entry.split("\t", 1)[0].split()[2] for entry in out.split("\0") if entry}+++def _untracked(repo: Path) -> list[str]:+ out = _git(repo, "ls-files", "--others", "--exclude-standard", "-z")+ return [p for p in out.split("\0") if p]+++def _sniff_binary(path: Path) -> bool:+ with path.open("rb") as fh:+ return b"\0" in fh.read(_SNIFF_BYTES)+++def _sizes(repo: Path, blobs: list[str]) -> dict[str, int]:+ if not blobs:+ return {}+ proc = subprocess.run(["git", "cat-file", "--batch-check=%(objectname) %(objectsize)"], cwd=repo,+ input="\n".join(blobs) + "\n", capture_output=True, text=True,+ encoding="utf-8", timeout=300, check=False)+ if proc.returncode != 0:+ raise GitError(f"git cat-file --batch-check: {proc.stderr.strip()}")+ sizes: dict[str, int] = {}+ for line in proc.stdout.splitlines():+ parts = line.split()+ if len(parts) == 2 and parts[1].isdigit():+ sizes[parts[0]] = int(parts[1])+ return sizes+++def read_allowlist(path: Path) -> set[str]:+ if not path.is_file():+ return set()+ entries = set()+ for line in path.read_text(encoding="utf-8-sig").splitlines():+ line = line.strip()+ if line and not line.startswith("#"):+ entries.add(line)+ return entries+++def find_offenders(repo: Path, base: str, head: str | None, limit: int = MAX_BYTES,+ allowlist: Collection[str] = frozenset()) -> list[Offender]:+ """Changed paths base -> head (None = working tree + untracked files) over ``limit``."""+ args = ["diff", "--raw", "-z", "-M", "-C", "--no-abbrev", base] + ([head] if head else [])+ known = _tree_blobs(repo, base)+ changes = [c for c in _parse_raw(_git(repo, *args)) if c.blob not in known and c.path not in allowlist]+ binary = _binary_paths(repo, base, head)+ sizes = _sizes(repo, sorted({c.blob for c in changes if c.blob}))+ offenders: list[Offender] = []+ for change in changes:+ if change.blob is not None:+ size = sizes.get(change.blob, 0)+ else: # working-tree content git has not hashed (an unstaged edit)+ disk = repo / change.path+ size = disk.stat().st_size if disk.is_file() and not disk.is_symlink() else 0+ is_binary = change.path in binary+ if size > limit and (is_binary or change.status == "A"):+ offenders.append(Offender(change.path, size, "binary" if is_binary else "new file", change.status))+ if head is None:+ for rel in _untracked(repo):+ disk = repo / rel+ if rel in allowlist or not disk.is_file() or disk.is_symlink():+ continue+ size = disk.stat().st_size+ if size > limit:+ kind = "binary" if _sniff_binary(disk) else "new file"+ offenders.append(Offender(rel, size, kind, "A"))+ return sorted(offenders, key=lambda o: (-o.size, o.path))+++def _kib(size: int) -> str:+ return f"{size / 1024:,.0f} KiB"+++def render(offenders: list[Offender], limit: int) -> list[str]:+ lines = [f"::error file={o.path}::{o.path} is {_kib(o.size)} ({o.kind}); the limit is {_kib(limit)}"+ for o in offenders]+ lines += [+ "",+ f"{len(offenders)} file(s) over the {_kib(limit)} blob limit. Every blob a merge adds stays in",+ "every clone forever, even after a later commit deletes it. Fix one of these ways:",+ " - screenshots, recordings, PR assets: put them in the PR description, not in git",+ " - images that must ship: compress them (oxipng -o max / pngquant / jpegoptim / webp)",+ " - test data or archives: generate them in the test's tmp dir instead of committing them",+ f" - a file that must ship at this size: add its exact path to {ALLOWLIST}",+ " (needs a hermes-agent-core review; keep that list short)",+ "Reproduce locally: python scripts/ci/check_blob_size.py",+ ]+ return lines+++def summary_table(offenders: list[Offender], limit: int) -> str:+ if not offenders:+ return f"### Blob size\n\nNo added or modified file is over {_kib(limit)}.\n"+ rows = "\n".join(f"| `{o.path}` | {o.kind} | {o.status} | {_kib(o.size)} |" for o in offenders)+ return (f"### Blob size: {len(offenders)} file(s) over {_kib(limit)}\n\n"+ f"| Path | Kind | Status | Size |\n|---|---|---|---|\n{rows}\n\n"+ f"Compress the file, move it out of git, or add its exact path to `{ALLOWLIST}`.\n")+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])+ parser.add_argument("--base", help="base revision (default: merge-base with origin/main)")+ parser.add_argument("--head", help="head revision or tree (default: the working tree)")+ parser.add_argument("--limit", type=int, default=MAX_BYTES, help=f"bytes (default {MAX_BYTES})")+ parser.add_argument("--repo", type=Path, default=Path.cwd())+ args = parser.parse_args(argv)+ repo = args.repo.resolve()+ try:+ base = args.base or default_base(repo, args.head)+ allowlist = read_allowlist(repo / ALLOWLIST)+ offenders = find_offenders(repo, base, args.head, args.limit, allowlist)+ except GitError as exc:+ print(f"check_blob_size: {exc}", file=sys.stderr)+ return 2+ step_summary = os.environ.get("GITHUB_STEP_SUMMARY")+ if step_summary:+ with open(step_summary, "a", encoding="utf-8") as fh:+ fh.write(summary_table(offenders, args.limit))+ if not offenders:+ print(f"check_blob_size: no added or modified file over {_kib(args.limit)}")+ return 0+ print("\n".join(render(offenders, args.limit)))+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/ci/test_check_blob_size.py b/tests/ci/test_check_blob_size.pynew file mode 100644index 00000000000..0230d8ab650--- /dev/null+++ b/tests/ci/test_check_blob_size.py@@ -0,0 +1,168 @@+"""scripts/ci/check_blob_size.py on real temp git repos: what a PR may add, and what it may not."""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++import pytest++REPO = Path(__file__).resolve().parents[2]+SCRIPT = REPO / "scripts" / "ci" / "check_blob_size.py"+sys.path.insert(0, str(SCRIPT.parent))++import check_blob_size as cbs++LIMIT = 4096+++def _env() -> dict[str, str]:+ env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}+ env.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1")+ return env+++def _git(repo: Path, *args: str) -> str:+ proc = subprocess.run(["git", *args], cwd=repo, env=_env(), capture_output=True, text=True,+ encoding="utf-8", stdin=subprocess.DEVNULL, timeout=60, check=False)+ assert proc.returncode == 0, (args, proc.stderr)+ return proc.stdout.strip()+++def _binary(n: int, seed: int = 0) -> bytes:+ return bytes((i * 7 + seed) % 256 for i in range(n)) # contains NUL bytes: git calls it binary+++def _text(n: int, seed: str = "x") -> bytes:+ return (seed * 63 + "\n").encode() * (n // 64 + 1)+++def _commit(repo: Path, files: dict[str, bytes | None], msg: str = "step") -> str:+ for rel, data in files.items():+ path = repo / rel+ if data is None:+ _git(repo, "rm", "-q", "--", rel)+ continue+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ _git(repo, "add", "--", rel)+ _git(repo, "commit", "-q", "--allow-empty", "-m", msg)+ return _git(repo, "rev-parse", "HEAD")+++def repo(tmp_path: Path) -> Path:+ root = tmp_path / "repo"+ root.mkdir()+ _git(root, "init", "-q", "-b", "main")+ _git(root, "config", "user.email", "[email protected]")+ _git(root, "config", "user.name", "t")+ _commit(root, {+ "big.lock": _text(LIMIT * 3, "l"), # legacy text file already over the limit+ "assets/icon.icns": _binary(LIMIT * 2, 1), # legacy binary already over the limit+ "assets/small.png": _binary(100, 2),+ }, "base")+ return root+++def _offenders(repo: Path, base: str, head: str | None, allow: frozenset[str] | set[str] = frozenset()):+ return [(o.path, o.kind, o.status) for o in cbs.find_offenders(repo, base, head, LIMIT, allow)]++[email protected]("files, expected", [+ # added binary over the limit+ ({"docs/shot.png": _binary(LIMIT + 1)}, [("docs/shot.png", "binary", "A")]),+ # added binary at exactly the limit, and a small one+ ({"docs/a.png": _binary(LIMIT), "docs/b.png": _binary(10)}, []),+ # a modified binary is judged on its new size, legacy or not+ ({"assets/icon.icns": _binary(LIMIT * 2, 9)}, [("assets/icon.icns", "binary", "M")]),+ ({"assets/small.png": _binary(LIMIT + 1, 3)}, [("assets/small.png", "binary", "M")]),+ # shrinking a legacy binary under the limit passes+ ({"assets/icon.icns": _binary(LIMIT - 1, 9)}, []),+ # a new text file over the limit (fuzz corpus, dumped JSON)+ ({"r318C_fuzz_new.json": _text(LIMIT + 64)}, [("r318C_fuzz_new.json", "new file", "A")]),+ # growing an existing text file is the FILE_LINES ratchet's job, not this check's+ ({"big.lock": _text(LIMIT * 4, "m")}, []),+ # deleting a big file is always fine+ ({"assets/icon.icns": None}, []),+])+def test_verdict(repo, files, expected):+ base = _git(repo, "rev-parse", "HEAD")+ head = _commit(repo, files)+ assert _offenders(repo, base, head) == expected+++def test_pure_move_adds_no_bytes_but_move_with_edit_is_judged(repo):+ base = _git(repo, "rev-parse", "HEAD")+ (repo / "packaging").mkdir()+ (repo / "deps").mkdir()+ _git(repo, "mv", "assets/icon.icns", "packaging/icon.icns")+ _git(repo, "mv", "big.lock", "deps/big.lock")+ moved = _commit(repo, {})+ assert _offenders(repo, base, moved) == []+ edited = _commit(repo, {"packaging/icon.icns": _binary(LIMIT * 2, 5)})+ assert _offenders(repo, base, edited) == [("packaging/icon.icns", "binary", "R")]+++def test_content_the_base_already_holds_adds_no_bytes(repo):+ # A byte-identical copy shares the blob; so does reverting to a version main still tracks.+ base = _git(repo, "rev-parse", "HEAD")+ copied = _commit(repo, {"other/icon.icns": (repo / "assets/icon.icns").read_bytes()})+ assert _offenders(repo, base, copied) == []+ tweaked = _commit(repo, {"other/icon.icns": _binary(LIMIT * 2, 7)})+ assert _offenders(repo, copied, tweaked) == [("other/icon.icns", "binary", "M")]+++def test_allowlist_exempts_exact_paths_only(repo):+ base = _git(repo, "rev-parse", "HEAD")+ head = _commit(repo, {"assets/icon.icns": _binary(LIMIT * 2, 9), "assets/icon-dark.icns": _binary(LIMIT * 2, 8)})+ allow = {"assets/icon.icns", "assets/"}+ assert _offenders(repo, base, head, allow) == [("assets/icon-dark.icns", "binary", "A")]+++def test_allowlist_file_ignores_comments_and_blanks(tmp_path):+ path = tmp_path / "allow.txt"+ path.write_text("# why\n\n apps/a.icns \n# b.png\n", encoding="utf-8")+ assert cbs.read_allowlist(path) == {"apps/a.icns"}+ assert cbs.read_allowlist(tmp_path / "missing.txt") == set()+++def test_working_tree_mode_sees_unstaged_and_untracked_files(repo):+ base = _git(repo, "rev-parse", "HEAD")+ (repo / "assets/small.png").write_bytes(_binary(LIMIT + 5, 4)) # unstaged edit+ (repo / "log.db").write_bytes(_binary(LIMIT + 5, 6)) # untracked+ (repo / "dump.txt").write_bytes(_text(LIMIT + 64)) # untracked text+ (repo / ".gitignore").write_text("ignored.bin\n", encoding="utf-8")+ (repo / "ignored.bin").write_bytes(_binary(LIMIT * 2))+ assert sorted(_offenders(repo, base, None)) == [+ ("assets/small.png", "binary", "M"), ("dump.txt", "new file", "A"), ("log.db", "binary", "A"),+ ]+++def test_cli_fails_with_fix_text_and_writes_step_summary(repo, tmp_path):+ base = _git(repo, "rev-parse", "HEAD")+ (repo / ".github").mkdir()+ (repo / ".github/blob-size-allowlist.txt").write_text("assets/icon.icns\n", encoding="utf-8")+ head = _commit(repo, {".github/blob-size-allowlist.txt": (repo / ".github/blob-size-allowlist.txt").read_bytes(),+ "assets/icon.icns": _binary(LIMIT * 2, 9), "pr-assets/shot.png": _binary(LIMIT * 3)})+ summary = tmp_path / "summary.md"+ env = {**_env(), "GITHUB_STEP_SUMMARY": str(summary)}+ proc = subprocess.run([sys.executable, str(SCRIPT), "--base", base, "--head", head, "--limit", str(LIMIT)],+ cwd=repo, env=env, capture_output=True, text=True, encoding="utf-8", timeout=60, check=False)+ assert proc.returncode == 1, proc.stdout + proc.stderr+ assert "::error file=pr-assets/shot.png::" in proc.stdout+ assert "assets/icon.icns" not in proc.stdout # allowlisted by the head's own list+ assert "blob-size-allowlist.txt" in proc.stdout and "python scripts/ci/check_blob_size.py" in proc.stdout+ assert "| `pr-assets/shot.png` | binary | A |" in summary.read_text(encoding="utf-8")++ clean = subprocess.run([sys.executable, str(SCRIPT), "--base", head, "--head", head], cwd=repo, env=_env(),+ capture_output=True, text=True, encoding="utf-8", timeout=60, check=False)+ assert clean.returncode == 0, clean.stdout + clean.stderr+++def test_bad_revision_is_a_usage_error_not_a_pass(repo):+ proc = subprocess.run([sys.executable, str(SCRIPT), "--base", "no-such-rev", "--head", "HEAD"], cwd=repo,+ env=_env(), capture_output=True, text=True, encoding="utf-8", timeout=60, check=False)+ assert proc.returncode == 2 and "check_blob_size:" in proc.stderr