:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): nudge when a change pushes a file past 1000 lines (#92275)
Julian Beze97a7c44f46d
diff --git a/.github/scripts/check-claude-hooks.sh b/.github/scripts/check-claude-hooks.shnew file mode 100755index 000000000000..6b9a7ecbb7b1--- /dev/null+++ b/.github/scripts/check-claude-hooks.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# Warn when a commit touches .claude/hooks/. Never blocks: a SessionStart hook is a+# legitimate change, and only the author knows which kind this one is.+#+# A warn-only check has to live in the pre-commit hook body. As a lint-staged task it+# would print nothing, because lint-staged discards the output of every task that+# exits 0.+set -uo pipefail++# The staged list is captured before it is matched. Piping it into `grep -q` lets grep+# exit at the first match, which can leave the writer with SIGPIPE, and under pipefail+# the whole pipeline then reads as failed and the warning never prints.+staged=$(git diff --cached --name-only)++if grep -q '^\.claude/hooks/' <<< "$staged"; then+ printf "\n\033[33mWarning: hooks in .claude/ are reserved for env bootstrapping (SessionStart only).\n"+ printf "Prefer skills, AGENTS.md instructions, or lint-staged rules. See Agent automation in AGENTS.md.\033[0m\n\n"+fidiff --git a/.github/scripts/check-commit-warnings.test.sh b/.github/scripts/check-commit-warnings.test.shnew file mode 100755index 000000000000..68a675c0351b--- /dev/null+++ b/.github/scripts/check-commit-warnings.test.sh@@ -0,0 +1,58 @@+#!/usr/bin/env bash+# Covers the two warn-only pre-commit scripts.+set -euo pipefail++index="$(mktemp)"+trap 'rm -f "$index"' EXIT++blob="$(git rev-parse HEAD:.gitignore)"++stage() {+ printf '100644 %s\t%s\n' "$blob" "$1" | GIT_INDEX_FILE="$index" git update-index --index-info+}++from_head() {+ rm -f "$index"+ GIT_INDEX_FILE="$index" git read-tree HEAD+}++run() {+ GIT_INDEX_FILE="$index" "$1"+}++fail() {+ echo "FAIL: $1" >&2+ exit 1+}++# An empty index makes every tracked file read as deleted, so the staged list runs to+# thousands of paths. A match early in a list that long can close the pipe before git+# finishes writing it, and under pipefail that has to still produce the warning.+rm -f "$index"+stage .claude/hooks/session-start.sh+output="$(run .github/scripts/check-claude-hooks.sh)"+case "$output" in+ *"reserved for env bootstrapping"*) ;;+ *) fail "a long staged list lost the .claude/hooks warning" ;;+esac++from_head+stage packages/quill/packages/primitives/src/Button.tsx+output="$(run .github/scripts/check-quill-agents-md.sh)"+case "$output" in+ *"without an AGENTS.md update"*) ;;+ *) fail "staged quill source produced no warning" ;;+esac++stage packages/quill/packages/primitives/AGENTS.md+output="$(run .github/scripts/check-quill-agents-md.sh)"+[ -z "$output" ] || fail "quill warning fired even though AGENTS.md was staged too"++from_head+stage posthog/models/team/team.py+output="$(run .github/scripts/check-claude-hooks.sh)"+[ -z "$output" ] || fail "hooks warning fired on an unrelated path"+output="$(run .github/scripts/check-quill-agents-md.sh)"+[ -z "$output" ] || fail "quill warning fired on an unrelated path"++echo "ok"diff --git a/.github/scripts/check-quill-agents-md.sh b/.github/scripts/check-quill-agents-md.shnew file mode 100755index 000000000000..1c9024aa814a--- /dev/null+++ b/.github/scripts/check-quill-agents-md.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+# Warn when quill component sources change without an AGENTS.md update. The consumer+# guide is how other teams pick the right component, so it goes stale silently.+# Never blocks: not every source change alters the consumer contract.+#+# A warn-only check has to live in the pre-commit hook body. As a lint-staged task it+# would print nothing, because lint-staged discards the output of every task that+# exits 0.+set -uo pipefail++# The staged list is captured before it is matched. Piping it into `grep -q` lets grep+# exit at the first match, which can leave the writer with SIGPIPE, and under pipefail+# the whole pipeline then reads as failed and the warning never prints.+staged=$(git diff --cached --name-only)++if grep -qE '^packages/quill/packages/[^/]+/src/.*\.(ts|tsx|css)$' <<< "$staged" \+ && ! grep -qE '^packages/quill/.*AGENTS\.md$' <<< "$staged"; then+ printf "\n\033[33mWarning: quill component sources changed without an AGENTS.md update.\n"+ printf "If variants, composition, or spacing changed, update the consumer guide\n"+ printf "(packages/quill/packages/<pkg>/AGENTS.md) in the same PR.\033[0m\n\n"+fidiff --git a/.github/workflows/shellcheck.yml b/.github/workflows/shellcheck.ymlindex 35670dfd7370..b1ed4a5f8e57 100644--- a/.github/workflows/shellcheck.yml+++ b/.github/workflows/shellcheck.yml@@ -44,6 +44,16 @@ jobs:shellcheck .github/scripts/prepare-product-junit-for-trunk.sh .github/scripts/prepare-product-junit-for-trunk.test.shbash .github/scripts/prepare-product-junit-for-trunk.test.sh+ - name: Check commit-time warning scripts+ run: |+ # An open PR that has not rebased onto this commit does not carry these+ # scripts, so the step skips rather than failing before its own tests run.+ [ -f .github/scripts/check-commit-warnings.test.sh ] || exit 0+ shellcheck .github/scripts/check-claude-hooks.sh \+ .github/scripts/check-quill-agents-md.sh \+ .github/scripts/check-commit-warnings.test.sh+ .github/scripts/check-commit-warnings.test.sh+# Runs here, not in a path-gated ci-* job, so AGENTS/CLAUDE changes# anywhere in the repo are validated on every PR.- name: Check AGENTS.md / CLAUDE.md symlinksdiff --git a/.husky/pre-commit b/.husky/pre-commitindex 3463d01f6f42..7e7932b3f111 100755--- a/.husky/pre-commit+++ b/.husky/pre-commit@@ -40,6 +40,17 @@ if [ -x .github/scripts/check-product-scaffold.sh ]; then.github/scripts/check-product-scaffold.sh || truefi+# Same deal for hooks under .claude/ and for quill sources changed without their+# consumer guide. A warn-only check has to run here rather than as a lint-staged+# task, because lint-staged discards the output of every task that exits 0.+if [ -x .github/scripts/check-claude-hooks.sh ]; then+ .github/scripts/check-claude-hooks.sh || true+fi++if [ -x .github/scripts/check-quill-agents-md.sh ]; then+ .github/scripts/check-quill-agents-md.sh || true+fi+# Activate Flox environment if available and not already active# This ensures lint-staged commands work in GUI Git clients (GitHub Desktop, etc.)if command -v flox > /dev/null 2>&1 && [ -d ".flox/cache" ] && [ -z "$FLOX_ENV" ]; thendiff --git a/AGENTS.md b/AGENTS.mdindex 5ed535eb41c8..f49ef6c26386 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -252,7 +252,9 @@ When automating a convention, try these in order — only fall back to the next3. **Skills** (`.agents/skills/`) — scaffold with `hogli init:skill`4. **AGENTS.md / CLAUDE.md instructions** — when automated enforcement isn't suitable-Claude Code hooks are reserved for environment bootstrapping (`SessionStart` only) — do not add `PreToolUse`, `PostToolUse`, or `Notification` hooks as they add latency and are fragile. Changes to `.claude/hooks/` trigger a lint-staged warning; changes to `.claude/settings.json` are blocked outright.+Claude Code hooks are reserved for environment bootstrapping (`SessionStart` only) — do not add `PreToolUse`, `PostToolUse`, or `Notification` hooks as they add latency and are fragile.+Changes to `.claude/hooks/` trigger a warning from the `pre-commit` hook; changes to `.claude/settings.json` are blocked outright by lint-staged.+A warn-only check belongs in the `pre-commit` hook body rather than in a lint-staged task, because lint-staged discards the output of every task that exits 0.### Mandatory skill invocationdiff --git a/hogli.yaml b/hogli.yamlindex cdd8ff1bebaf..d4e4b347f823 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -865,6 +865,9 @@ quality:lint:complexity:click: hogli_commands.complexity_lint:cmd_lint_complexitydescription: Check cyclomatic complexity of changed Python/TypeScript files (warn-only; test files get a relaxed limit)+ lint:size:+ click: hogli_commands.size_lint:cmd_lint_size+ description: Check the size of changed Python/TypeScript files (warn-only, crossing 1000 lines)lint:workflows:click: hogli_commands.workflow_lint.cli:cmd_lint_workflowsdescription: Lint .github/workflows/** for repo conventionsdiff --git a/package.json b/package.jsonindex e4d74eb80b4e..c363f4be1595 100644--- a/package.json+++ b/package.json@@ -85,9 +85,7 @@},"lint-staged": {".claude/settings.json": "sh -c 'printf \"\\n\\033[31mDo not commit .claude/settings.json — personal permissions belong in .claude/settings.local.json (gitignored).\\nUnstage with: git restore --staged .claude/settings.json\\033[0m\\n\\n\" >&2 && exit 1'",- ".claude/hooks/**": "sh -c 'printf \"\\n\\033[33mWarning: hooks in .claude/ are reserved for env bootstrapping (SessionStart only).\\nPrefer skills, AGENTS.md instructions, or lint-staged rules. See Agent automation in AGENTS.md.\\033[0m\\n\\n\"'","**/{AGENTS,CLAUDE}.md": "sh -c '.github/scripts/check-agents-md-symlinks.sh'",- "packages/quill/packages/*/src/**/*.{ts,tsx,css}": "sh -c 'git diff --cached --name-only | grep -q \"^packages/quill/.*AGENTS\\\\.md$\" || printf \"\\n\\033[33mWarning: quill component sources changed without an AGENTS.md update.\\nIf variants, composition, or spacing changed, update the consumer guide (packages/quill/packages/<pkg>/AGENTS.md) in the same PR.\\033[0m\\n\\n\"'","frontend/public/services/*.{png,jpg,jpeg,gif}": "node frontend/bin/check-service-icon-size.mjs","products/**/manifest.tsx": ["bin/hogli format:js",diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex f4b453fb0b16..cc6d4d1f89ce 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -48,6 +48,7 @@ from hogli_commands.build import (from hogli_commands.change_detection import changed_files, matches_globsfrom hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIPT_SCOPE, WARN_ATfrom hogli_commands.devenv.generator import TRACKED_MPROCS_FILES+from hogli_commands.size_lint import SCOPE as SIZE_SCOPERequirement = Literal["node", "desktop-node", "stack", "clickhouse"]@@ -65,6 +66,10 @@ class DiffCheck:advice: str | None = None # nudge-only: preflight never runs this check, it just says what to runrequires: tuple[Requirement, ...] = () # capabilities the check needs, else it skipstakes_files: bool = False # append matched files to the command+ # Append `--against <base>`, plus `--committed` when the run is scoped to commits.+ # A check that measures file content has to agree with preflight on both which base+ # to compare against and which copy of the file to read.+ takes_diff_scope: bool = False# Run once per pnpm workspace containing matched files (cwd = that workspace),# so nested workspaces like products/desktop validate their own lockfile instead# of the root one. Capability (node_modules present) is checked per workspace.@@ -136,6 +141,16 @@ DIFF_CHECKS: list[DiffCheck] = [takes_files=True,soft=True,),+ DiffCheck(+ key="size",+ label="file size (warn >1000 lines)",+ # From size_lint.py so preflight and the command can't drift on scope.+ triggers=[*SIZE_SCOPE],+ verify=["hogli", "lint:size"],+ takes_files=True,+ takes_diff_scope=True,+ soft=True,+ ),DiffCheck(key="ruff-format",label="Python format (ruff format)",@@ -376,7 +391,7 @@ def _run_workspace_scoped(chk: DiffCheck, do_fix: bool) -> tuple[Status, str]:return overall, " · ".join(parts)-def _run_diff_check(chk: DiffCheck, do_fix: bool) -> tuple[Status, str]:+def _run_diff_check(chk: DiffCheck, do_fix: bool, against: str | None, strict: bool) -> tuple[Status, str]:if chk.advice is not None:# Nudge-only: nothing to run, nothing to auto-fix — the advisory *is* the check.return "advisory", chk.advice@@ -397,6 +412,16 @@ def _run_diff_check(chk: DiffCheck, do_fix: bool) -> tuple[Status, str]:return "skipped", f"needs {', '.join(unmet)}"else:cmd = list(chk.verify)+ if chk.takes_diff_scope:+ # Forward only an explicit base. Passing a default would pin the child to+ # `origin/master` while `changed_files` falls back to local `master`, and the two+ # would then disagree in a clone that has no remote ref. Strict runs also pass+ # `--committed`, because only commits are about to be pushed; advisory runs keep+ # the working tree in scope and so must be measured from it.+ if against is not None:+ cmd += ["--against", against]+ if strict:+ cmd.append("--committed")if chk.takes_files:# Drop deleted paths: ruff (and friends) error E902 on a path that no longer exists.present = [f for f in chk.matched if (REPO_ROOT / f).exists()]@@ -703,7 +728,7 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)click.echo(f" {detail}")for chk in triggered:- status, detail = _run_diff_check(chk, do_fix)+ status, detail = _run_diff_check(chk, do_fix, against, strict)failures += status == "fail"# Nudges say "consider this", not "this is drift" — counting them would cry wolf in# the footer on every matching push and cost the detected advisories their weight.diff --git a/tools/hogli-commands/hogli_commands/size_lint.py b/tools/hogli-commands/hogli_commands/size_lint.pynew file mode 100644index 000000000000..5e38414c7e0f--- /dev/null+++ b/tools/hogli-commands/hogli_commands/size_lint.py@@ -0,0 +1,244 @@+"""File-size nudge, scoped to changed files.++An agent reads a file, never a function, so file length is what decides how many+tokens a change costs to make. This reports two things and never fails a build:++* a warning when the diff itself pushed a file past ``CROSSED_AT``, which is the+ only case the author can act on in the change they are making.+* a single note when the diff touches a file already past ``NOTE_AT``, so the+ reading cost is visible without repeating it for every such file.++Reporting every oversized file instead would fire on about three quarters of+commits, which is how a warning turns into wallpaper.++ hogli lint:size # changed files vs origin/master+ hogli lint:size path/to/file.py # explicit files+ hogli lint:size --against <ref> # explicit diff base+"""++from __future__ import annotations++import os+import json+import subprocess+from dataclasses import asdict, dataclass+from typing import Final++import click+from hogli.manifest import REPO_ROOT++from hogli_commands.change_detection import changed_files, matches_globs++CROSSED_AT: Final = 1000+NOTE_AT: Final = 1500++# Code in this repo tokenizes at roughly 11 to 13 tokens per line. The estimate only+# has to be good enough to tell a 3k-token file from a 60k-token one.+TOKENS_PER_LINE: Final = 12++SCOPE: Final = (+ "posthog/*.py",+ "ee/*.py",+ "products/*.py",+ "frontend/*.ts",+ "frontend/*.tsx",+ "ee/*.ts",+ "ee/*.tsx",+ "products/*.ts",+ "products/*.tsx",+)++# Generated and vendored trees have no author to nudge, and splitting them is wrong.+# products/desktop is linted by its own Biome setup.+EXCLUDED: Final = (+ "*/migrations/*",+ "*/generated/*",+ "*/node_modules/*",+ "*.d.ts",+ "products/desktop/*",+ "posthog/schema.py",+ "posthog/schema_enums.py",+)+++@dataclass(frozen=True, kw_only=True, slots=True)+class RenameMaps:+ """Where a path came from, one hop per namespace.++ The two maps stay apart because they describe different namespaces. Merging them+ would join two unrelated files whenever a rename reuses a pathname another rename+ just vacated.+ """++ staged: dict[str, str] # index path -> its name at HEAD+ committed: dict[str, str] # HEAD path -> its name at the merge base++ def path_at_base(self, path: str) -> str:+ at_head = self.staged.get(path, path)+ return self.committed.get(at_head, at_head)+++@dataclass(frozen=True, kw_only=True, slots=True)+class Finding:+ file: str+ lines: int+ was: int # line count at the merge base; 0 when the file is new there+ crossed: bool+++def _git(*args: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True)+++def _merge_base(against: str | None) -> str | None:+ """The commit the branch forked from, or None when no base ref is available.++ Without a base there is no "before" size, so the crossed check cannot run. That+ happens in single-branch clones and bare sandboxes.+ """+ for ref in [against] if against is not None else ["origin/master", "master"]:+ result = _git("merge-base", ref, "HEAD")+ if result.returncode == 0 and result.stdout.strip():+ return result.stdout.strip()+ return None+++def _rename_map(*diff_args: str) -> dict[str, str]:+ result = _git("diff", "-M", "--name-status", "-z", *diff_args)+ if result.returncode != 0:+ return {}+ fields = [field for field in result.stdout.split("\0") if field]+ sources: dict[str, str] = {}+ index = 0+ while index < len(fields):+ # Renames and copies carry two paths; every other status carries one.+ if fields[index].startswith(("R", "C")) and index + 2 < len(fields):+ sources[fields[index + 2]] = fields[index + 1]+ index += 3+ else:+ index += 2+ return sources+++def _rename_maps(base: str) -> RenameMaps:+ """Rename sources for the two hops between the merge base and the index.++ Nearly half of all threshold crossings are file moves. Without them, relocating a+ large file reads as creating one, and every product migration gets nudged for+ tidying up. The index is read as well as the committed range, because a staged+ `git mv` has no committed rename to find yet. A move that is neither committed nor+ staged stays undetectable, because git has no rename to report until one side is+ recorded.+ """+ return RenameMaps(staged=_rename_map("--cached", "HEAD"), committed=_rename_map(f"{base}...HEAD"))+++def _lines_at(rev: str, path: str) -> int:+ result = _git("show", f"{rev}:{path}")+ return 0 if result.returncode != 0 else len(result.stdout.splitlines())+++def _line_count(path: str, rev: str | None) -> int:+ """Size of *path*, read from *rev* when one is named and from disk otherwise.++ Which copy to read follows the caller's scope. A pre-push run carries only commits,+ so it reads the commit and an uncommitted edit cannot move the number away from+ what gets pushed. A run that includes the working tree measures the working tree,+ so growth that is not committed yet is still reported. A path with no blob at *rev*+ is not committed at all, so it counts as zero and drops out rather than falling+ back to disk, which would report content the caller did not ask about.+ """+ if rev is not None:+ result = _git("show", f"{rev}:{path}")+ return 0 if result.returncode != 0 else len(result.stdout.splitlines())+ return len((REPO_ROOT / path).read_text(errors="replace").splitlines())+++def _findings(files: list[str], base: str | None, rev: str | None = None) -> list[Finding]:+ """Every crossing, plus at most one note for the largest already-oversized file."""+ renames = _rename_maps(base) if base is not None else RenameMaps(staged={}, committed={})+ crossings: list[Finding] = []+ already_large: list[Finding] = []+ for path in files:+ lines = _line_count(path, rev)+ # CROSSED_AT is the lower of the two thresholds, so nothing under it is reportable.+ if lines <= CROSSED_AT:+ continue+ was = _lines_at(base, renames.path_at_base(path)) if base is not None else 0+ # Without a base there is no "before" size, so nothing can be called a crossing.+ if base is not None and was <= CROSSED_AT:+ crossings.append(Finding(file=path, lines=lines, was=was, crossed=True))+ elif lines > NOTE_AT:+ already_large.append(Finding(file=path, lines=lines, was=was, crossed=False))+ worst = max(already_large, key=lambda finding: finding.lines, default=None)+ return crossings + ([worst] if worst is not None else [])+++def _tokens(lines: int) -> str:+ tokens = lines * TOKENS_PER_LINE+ return f"~{tokens // 1000}k tokens" if tokens >= 1000 else f"~{tokens} tokens"+++def _message(finding: Finding) -> str:+ # The path is already in the `file:line:col:` prefix, so it is not repeated here.+ if not finding.crossed:+ return f"{finding.lines} lines ({_tokens(finding.lines)} to read)"+ grew = "new file" if finding.was == 0 else f"up from {finding.was}"+ return (+ f"now {finding.lines} lines ({grew}), past {CROSSED_AT} ({_tokens(finding.lines)} to read). "+ "Consider splitting it: /splitting-oversized-modules"+ )+++def _report(finding: Finding) -> None:+ label = "warning" if finding.crossed else "note"+ message = _message(finding)+ click.echo(f"{finding.file}:1:1: {label}: {message}")+ # Only a crossing is this diff's doing, so only a crossing annotates the diff.+ if finding.crossed and os.environ.get("GITHUB_ACTIONS") == "true":+ click.echo(f"::warning file={finding.file},line=1,col=1,title=lint:size::{message}")++[email protected](name="lint:size", help="Check the size of changed Python/TypeScript files (warn-only).")[email protected]("files", nargs=-1)[email protected]("--against", default=None, help="Diff against this base ref instead of the branch default.")+ "--committed",+ is_flag=True,+ help="Measure the committed file at HEAD instead of the working tree, for pre-push checks.",+)+ "--report",+ "report_path",+ type=click.Path(dir_okay=False, writable=True),+ default=None,+ help="Also write the findings as JSON to this path (used by the CI report poster).",+)+def cmd_lint_size(files: tuple[str, ...], against: str | None, committed: bool, report_path: str | None) -> None:+ base = _merge_base(against)+ # Explicit files skip changed_files, which is what would otherwise reject a bad ref.+ # Degrading here instead would turn crossing detection off without saying so, and a+ # ref that resolves but shares no history fails the same way a typo does.+ if against is not None and base is None:+ raise click.UsageError(f"no merge base with {against!r}: check the ref exists and shares history")+ # Committed-only mode must not discover uncommitted work either, or a staged file+ # would be selected and then measured as zero, which reads as a silent skip.+ paths = list(files) if files else changed_files(against, include_worktree=not committed)+ in_scope = [+ path+ for path in paths+ if (REPO_ROOT / path).is_file() and matches_globs(path, SCOPE) and not matches_globs(path, EXCLUDED)+ ]++ if in_scope and base is None:+ # Printed to stdout so a soft preflight check reports a degraded run as a+ # warning rather than a silent pass.+ click.echo(f"size: no base ref, so only files over {NOTE_AT} lines are reported")++ findings = _findings(in_scope, base, rev="HEAD" if committed else None)+ for finding in findings:+ _report(finding)+ click.echo(f"size: {len(in_scope)} file(s) checked, {len(findings)} finding(s)", err=True)+ if report_path is not None:+ with open(report_path, "w") as report_file:+ json.dump([asdict(finding) for finding in findings], report_file)diff --git a/tools/hogli-commands/hogli_commands/tests/test_size_lint.py b/tools/hogli-commands/hogli_commands/tests/test_size_lint.pynew file mode 100644index 000000000000..47dc4d3a537d--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_size_lint.py@@ -0,0 +1,268 @@+from __future__ import annotations++import subprocess+from pathlib import Path++import pytest+from unittest.mock import MagicMock, patch++from click.testing import CliRunner+from hogli.cli import cli+from hogli_commands import change_detection, ci_preflight, size_lint+from hogli_commands.size_lint import CROSSED_AT, NOTE_AT, _findings, _merge_base++runner = CliRunner()+++def _git(repo: Path, *args: str) -> None:+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)+++def _write(repo: Path, path: str, lines: int) -> None:+ target = repo / path+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text("x = 1\n" * lines)+++def repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ _git(tmp_path, "init", "-q", "-b", "master")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "test")+ _write(tmp_path, "posthog/seed.py", 1)+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "base")+ monkeypatch.setattr(size_lint, "REPO_ROOT", tmp_path)+ # File discovery reads the repo through its own module-level root.+ monkeypatch.setattr(change_detection, "REPO_ROOT", tmp_path)+ return tmp_path+++def _commit_on_branch(repo: Path) -> None:+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "change")+++class TestSizeLint:+ @pytest.mark.parametrize(+ ("before", "after", "expected"),+ [+ pytest.param(CROSSED_AT - 100, CROSSED_AT + 100, [("posthog/big.py", True)], id="crossing_warns"),+ # The whole point of the crossed framing: touching a file that was already+ # over the line is not this change's doing, so it stays quiet.+ pytest.param(CROSSED_AT + 200, CROSSED_AT + 300, [], id="already_over_stays_quiet"),+ pytest.param(CROSSED_AT - 100, CROSSED_AT - 50, [], id="staying_under_is_quiet"),+ pytest.param(None, CROSSED_AT + 100, [("posthog/big.py", True)], id="new_file_over_the_line_warns"),+ pytest.param(NOTE_AT + 100, NOTE_AT + 200, [("posthog/big.py", False)], id="already_huge_gets_a_note"),+ ],+ )+ def test_only_this_change_s_crossings_warn(+ self, repo: Path, before: int | None, after: int, expected: list[tuple[str, bool]]+ ) -> None:+ if before is not None:+ _write(repo, "posthog/big.py", before)+ _commit_on_branch(repo)+ _git(repo, "checkout", "-qb", "feature")+ _write(repo, "posthog/big.py", after)+ _commit_on_branch(repo)++ findings = _findings(["posthog/big.py"], _merge_base(None))++ assert [(finding.file, finding.crossed) for finding in findings] == expected++ @pytest.mark.parametrize("commit_the_move", [True, False], ids=["committed", "staged"])+ def test_a_moved_file_is_not_a_new_one(self, repo: Path, commit_the_move: bool) -> None:+ # Nearly half of all crossings are moves. Reading the destination path at the+ # base gives nothing, so without rename detection a relocated file reads as+ # newly created and every product migration gets nudged. The staged case needs+ # the index as a second rename source, because there is no committed rename yet.+ _write(repo, "posthog/big.py", CROSSED_AT + 100)+ _commit_on_branch(repo)+ _git(repo, "checkout", "-qb", "feature")+ _git(repo, "mv", "posthog/big.py", "posthog/moved.py")+ if commit_the_move:+ _commit_on_branch(repo)++ findings = _findings(["posthog/moved.py"], _merge_base(None))++ assert findings == []++ def test_a_named_base_measures_committed_content(self, repo: Path) -> None:+ # Strict preflight scopes to the committed diff because a push carries only+ # commits, so an uncommitted edit must not move the reported size away from+ # what is about to be pushed.+ _git(repo, "checkout", "-qb", "feature")+ _write(repo, "posthog/big.py", CROSSED_AT + 100)+ _commit_on_branch(repo)+ _write(repo, "posthog/big.py", 10)++ from_worktree = _findings(["posthog/big.py"], _merge_base(None))+ from_head = _findings(["posthog/big.py"], _merge_base(None), rev="HEAD")++ assert from_worktree == []+ assert [finding.crossed for finding in from_head] == [True]++ def test_a_file_moved_twice_is_still_not_a_new_one(self, repo: Path) -> None:+ # A commit rename and a staged rename come back as two separate records, so one+ # lookup lands on the intermediate name, which does not exist at the base. That+ # reads as a new file and blames the move for a crossing it did not cause.+ _write(repo, "posthog/big.py", CROSSED_AT + 100)+ _commit_on_branch(repo)+ _git(repo, "checkout", "-qb", "feature")+ _git(repo, "mv", "posthog/big.py", "posthog/middle.py")+ _commit_on_branch(repo)+ _git(repo, "mv", "posthog/middle.py", "posthog/final.py")++ findings = _findings(["posthog/final.py"], _merge_base(None))++ assert findings == []++ def test_a_reused_pathname_does_not_join_two_files(self, repo: Path) -> None:+ # One rename frees a pathname and another takes it. The two records describe+ # different files, so resolving through the shared name would compare the large+ # file against the small one's baseline and invent a crossing.+ _write(repo, "posthog/big.py", CROSSED_AT + 100)+ _write(repo, "posthog/small.py", 1)+ _commit_on_branch(repo)+ _git(repo, "checkout", "-qb", "feature")+ _git(repo, "mv", "posthog/big.py", "posthog/final.py")+ _commit_on_branch(repo)+ _git(repo, "mv", "posthog/small.py", "posthog/big.py")++ findings = _findings(["posthog/final.py"], _merge_base(None))++ assert findings == []++ def test_at_most_one_note_for_files_that_were_already_huge(self, repo: Path) -> None:+ # Reporting every oversized file fires on most commits. One note keeps the+ # reading cost visible without burning context on a list.+ for name, lines in (("posthog/huge.py", NOTE_AT + 500), ("posthog/bigger.py", NOTE_AT + 900)):+ _write(repo, name, lines)+ _commit_on_branch(repo)+ _git(repo, "checkout", "-qb", "feature")+ _write(repo, "posthog/huge.py", NOTE_AT + 501)+ _write(repo, "posthog/bigger.py", NOTE_AT + 901)+ _commit_on_branch(repo)++ findings = _findings(["posthog/huge.py", "posthog/bigger.py"], _merge_base(None))++ assert [finding.file for finding in findings] == ["posthog/bigger.py"]++ def test_uncommitted_growth_is_reported_unless_the_run_is_scoped_to_commits(self, repo: Path) -> None:+ # Advisory preflight keeps the working tree in scope, so reading HEAD there would+ # hide a crossing the author just created. The pre-push run wants the opposite,+ # because only commits get pushed. The base is the same in both.+ _git(repo, "checkout", "-qb", "feature")+ _write(repo, "posthog/big.py", CROSSED_AT - 100)+ _commit_on_branch(repo)+ _write(repo, "posthog/big.py", CROSSED_AT + 100)++ worktree = runner.invoke(cli, ["lint:size", "--against", "master", "posthog/big.py"])+ commits = runner.invoke(cli, ["lint:size", "--against", "master", "--committed", "posthog/big.py"])++ assert "warning" in worktree.output+ assert "warning" not in commits.output++ def test_an_unresolvable_base_is_rejected_rather_than_disabling_the_check(self, repo: Path) -> None:+ # Explicit files bypass change detection, which is the code that normally rejects+ # a bad ref. Without its own check a typo would read as "no base" and silently+ # turn crossing detection off.+ _git(repo, "checkout", "-qb", "feature")+ _write(repo, "posthog/big.py", CROSSED_AT + 100)+ _commit_on_branch(repo)++ unresolvable = runner.invoke(cli, ["lint:size", "--against", "no-such-ref", "posthog/big.py"])+ assert unresolvable.exit_code != 0+ assert "no-such-ref" in unresolvable.output++ # A ref that resolves but shares no history fails the same way, because it also+ # leaves nothing to compare against.+ _git(repo, "checkout", "-q", "--orphan", "unrelated")+ _write(repo, "posthog/other.py", 1)+ _commit_on_branch(repo)+ _git(repo, "checkout", "-q", "feature")++ unrelated = runner.invoke(cli, ["lint:size", "--against", "unrelated", "posthog/big.py"])+ assert unrelated.exit_code != 0+ assert "unrelated" in unrelated.output++ def test_committed_mode_does_not_discover_uncommitted_work(self, repo: Path) -> None:+ # Discovery has to match the promise of the flag. Selecting a staged file and then+ # measuring it at HEAD, where it does not exist, would read as a silent skip.+ _git(repo, "checkout", "-qb", "feature")+ _write(repo, "posthog/staged.py", CROSSED_AT + 100)+ _git(repo, "add", "posthog/staged.py")++ result = runner.invoke(cli, ["lint:size", "--against", "master", "--committed"])++ # The count is the assertion: measuring the file at HEAD would also produce no+ # finding, so only the number of files selected separates the two behaviors.+ assert result.exit_code == 0+ assert "0 file(s) checked" in result.output++ def test_cli_reports_findings_without_failing(self, repo: Path, tmp_path: Path) -> None:+ # The check is advisory, and preflight reads a soft check as a warning only when+ # it exits 0 with output on stdout.+ _git(repo, "checkout", "-qb", "feature")+ _write(repo, "posthog/big.py", CROSSED_AT + 100)+ _commit_on_branch(repo)+ report_path = tmp_path / "findings.json"++ result = runner.invoke(cli, ["lint:size", "posthog/big.py", "--report", str(report_path)])++ assert result.exit_code == 0+ assert "warning" in result.output+ assert "posthog/big.py" in report_path.read_text()++ def test_out_of_scope_and_generated_files_are_skipped(self, repo: Path) -> None:+ _git(repo, "checkout", "-qb", "feature")+ for name in ("posthog/schema.py", "products/desktop/huge.ts", "tools/thing.py"):+ _write(repo, name, NOTE_AT + 900)+ _commit_on_branch(repo)++ result = runner.invoke(cli, ["lint:size", "posthog/schema.py", "products/desktop/huge.ts", "tools/thing.py"])++ assert result.exit_code == 0+ assert "0 file(s) checked" in result.output+++class TestPreflightForwardsDiffScope:+ @pytest.mark.parametrize(+ ("against", "strict", "expected"),+ [+ # No explicit base: the child repeats change detection's own origin/master+ # then master fallback. Forwarding a default would pin it to a ref a clone+ # may not have, and the check would silently find nothing.+ pytest.param(None, False, [], id="default_base_stays_with_the_child"),+ pytest.param(None, True, ["--committed"], id="strict_measures_commits"),+ pytest.param("abc123", True, ["--against", "abc123", "--committed"], id="explicit_base_forwarded"),+ ],+ )+ def test_only_an_explicit_base_is_forwarded(self, against: str | None, strict: bool, expected: list[str]) -> None:+ check = ci_preflight.DiffCheck(+ key="size",+ label="file size",+ triggers=["posthog/*.py"],+ verify=["hogli", "lint:size"],+ takes_files=True,+ takes_diff_scope=True,+ soft=True,+ )+ check.matched = ["posthog/api/team.py"]++ with (+ patch.object(ci_preflight.shutil, "which", return_value="/usr/bin/hogli"),+ patch.object(+ ci_preflight.subprocess, "run", return_value=MagicMock(returncode=0, stdout="", stderr="")+ ) as run,+ ):+ ci_preflight._run_diff_check(check, False, against, strict)++ command = run.call_args[0][0]+ assert command[:2] == ["hogli", "lint:size"]+ assert command[2:-1] == expected+ assert command[-1] == "posthog/api/team.py"++ def test_the_registered_size_check_opts_into_diff_scope(self) -> None:+ registered = next(check for check in ci_preflight.DIFF_CHECKS if check.key == "size")+ assert registered.takes_diff_scope