: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(ci): catch frontend format, semgrep and baseline drops in preflight (#110891)
Raúl Negrón-Oterodb94b8ac4fb3
diff --git a/.agents/skills/running-ci-preflight/SKILL.md b/.agents/skills/running-ci-preflight/SKILL.mdindex 97787a9479a8..e2552029d3f5 100644--- a/.agents/skills/running-ci-preflight/SKILL.md+++ b/.agents/skills/running-ci-preflight/SKILL.md@@ -34,6 +34,9 @@ hogli ci:preflight --fix- **Strict = failures only.** `--strict` (what the hook runs) exits non-zero only on `✗ fail` — advisories are unverifiable-locally classes, so they warn without blocking. A clean exit means "nothing left to fix", not "CI will pass" — CI stays the authoritative gate. Non-blocking is a mechanism limit, not permission to skip.- **`type-check` is a nudge, not a run.** Only a repo-wide mypy run matches CI (mypy follows imports, so a changed-file subset misses reverse-dependency breakage), and that costs minutes cold — too much to tax every push with. So preflight names the command instead of running it: judge whether your change is type-risky and run it yourself. CI blocks on the same command, so a type error you skip here comes back as a full re-run.- **`complexity` warns only.** Cyclomatic complexity above 10 in a changed file shows as `⚠ warning` and never blocks; CI annotates the same warning and posts it to the CI report comment. Simplify the function when you next touch it rather than gaming the number.+- **`semgrep-devex` advises on findings your branch introduced.** It scans the changed files and their merge-base copies within one 15-second budget. Both scans use the cached version `SEMGREP_IMAGE` pins in `.github/workflows/ci-security.yaml`, with network access disabled. Run `hogli ci:preflight --prepare-semgrep` once with network access to prepare that tool. A missing tool or an incomplete scan skips with a reason, without delaying the push for downloads. A finding already on master is not reported. CI blocks on a new one, so fix it before you push. The advisory prints the command that shows the rule.+- **`snapshot-baselines` advises when `frontend/snapshots.yml` loses entries for stories your branch did not change.** This is what a bad merge-conflict resolution looks like. When the stories still render, the merge queue fails the batch that carries the file. Run the `git diff` the check prints and restore the entries you did not mean to remove. The entries of a story you deleted, renamed or retitled in the same branch pass.+- **`merge-queue-lane` warns only, and the pre-push hook skips it.** It fires when a few cross-cutting files (a CI workflow, a lane script) make the whole PR claim every merge queue lane, which makes the queue merge in series behind it. Move those files to their own PR when the other changes do not need them.- **Staleness is risk-based.** It fires when merging master _now_ would actually break something — textual merge conflicts (computed via `git merge-tree`, working tree untouched), migrations added on both sides, generated-file inputs changed on both sides, or CI workflows changed on master — plus a behind/age backstop, aggressive by default (5 commits / 2 days; env-tunable via `HOGLI_PREFLIGHT_STALE_COMMITS`/`HOGLI_PREFLIGHT_STALE_DAYS`) so we over-warn to start and tune down from telemetry. Merge master in when it fires. Advisory only, never auto-merged.- **`· skipped (needs …)`** is expected on a bare checkout or sandbox. `needs stack`/`needs clickhouse` want a running dev stack (`hogli start`), `needs node` wants `pnpm install`, `needs desktop-node` wants `pnpm --dir products/desktop install` and `needs agent-node` wants `pnpm --dir packages/agent install` (both nested workspaces are excluded from the root install and have their own lockfiles), and `needs python-env` wants `uv sync`, so the synced project environment is the `python` on PATH. Satisfy what you can, or let CI cover the rest. No hooks in your environment (no `node_modules`)? Run the loop yourself before pushing.- **Flags.** `--against <ref>` diffs against an explicit base; `--json` emits a machine-readable summary.diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex 6b5a97bb5715..505d6c90d1b4 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -31,6 +31,7 @@ import timeimport shutilimport socketimport subprocess+from collections.abc import Callable, Sequencefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom pathlib import Path@@ -50,8 +51,22 @@ from hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIPfrom hogli_commands.depot_mirrors import mirror_violationsfrom hogli_commands.devenv.generator import TRACKED_MPROCS_FILESfrom hogli_commands.lockfile_merge import LOCKFILE_GLOBS, missing_resolutions+from hogli_commands.preflight_checks import (+ SEMGREP_SCOPE,+ SNAPSHOT_MANIFEST,+ Outcome,+ Scope,+ Status,+ check_merge_queue_lane,+ check_semgrep_devex,+ check_snapshot_baselines,+ prepare_semgrep,+)from hogli_commands.projections import all_outputs as projection_outputs-from hogli_commands.size_lint import SCOPE as SIZE_SCOPE+from hogli_commands.size_lint import (+ SCOPE as SIZE_SCOPE,+ _merge_base,+)Requirement = Literal["node", "desktop-node", "agent-node", "stack", "clickhouse", "python-env"]@@ -81,6 +96,8 @@ class DiffCheck:# for advisory checks whose findings print on stdout with exit 0. Warnings# never block and never count toward the advisory footer.soft: bool = False+ # A check that reads the diff itself. It replaces `verify` and `fix`, and it has no auto-fix.+ run: Callable[[Scope], Outcome] | None = Nonematched: list[str] = field(default_factory=list)@property@@ -91,7 +108,7 @@ class DiffCheck:as a finding whatever shape it takes: a nudge (``advice``) and aguidance-only check (``verify is None``) are both unmeasured."""- return self.advice is None and self.verify is not None+ return self.run is not None or (self.advice is None and self.verify is not None)# Ordered cheapest-first. Grounded in failure classes seen in `hogli ci:insights`:@@ -233,6 +250,21 @@ DIFF_CHECKS: list[DiffCheck] = [requires=("node",),takes_files=True,),+ DiffCheck(+ key="frontend-format",+ label="frontend formatting (oxfmt)",+ # The trees and extensions `format:frontend:check` covers in CI.+ triggers=[+ f"{tree}/*.{ext}"+ for tree in ("products", "frontend/src", "docs")+ for ext in ("js", "mjs", "ts", "tsx", "json", "yaml", "yml", "css", "scss")+ ],+ # Mirrors lint-staged's `format:js`, which agents bypass via --no-verify.+ verify=["pnpm", "exec", "oxfmt", "--check", "--no-error-on-unmatched-pattern"],+ fix=["pnpm", "exec", "oxfmt", "--no-error-on-unmatched-pattern"],+ requires=("node",),+ takes_files=True,+ ),DiffCheck(key="feature-flags",label="FEATURE_FLAGS not alphabetically sorted",@@ -311,6 +343,28 @@ DIFF_CHECKS: list[DiffCheck] = [verify=["hogli", "migrations:check"],requires=("stack", "clickhouse"),),+ DiffCheck(+ key="snapshot-baselines",+ label="visual baselines dropped from snapshots.yml (fails the merge queue batch)",+ triggers=[SNAPSHOT_MANIFEST],+ verify=None,+ run=check_snapshot_baselines,+ ),+ DiffCheck(+ key="semgrep-devex",+ label="new semgrep findings (devex rules)",+ triggers=SEMGREP_SCOPE,+ verify=None,+ run=check_semgrep_devex,+ ),+ DiffCheck(+ key="merge-queue-lane",+ label="merge queue lane this diff claims",+ triggers=["*"],+ verify=None,+ run=check_merge_queue_lane,+ soft=True,+ ),]@@ -376,8 +430,6 @@ def _unmet(chk: DiffCheck) -> list[Requirement]:return [req for req in chk.requires if not _capability_met(req)]-Status = Literal["pass", "fail", "warning", "advisory", "skipped"]-# Generous: pnpm installs and migrations:check are legitimately slow, but a wedged# command must not hang the agent loop forever (output is captured, not streamed)._CHECK_TIMEOUT_SECONDS = 600@@ -437,7 +489,19 @@ 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, against: str | None, strict: bool) -> tuple[Status, str]:+def _run_diff_check(+ chk: DiffCheck, do_fix: bool, against: str | None, strict: bool, changed: Sequence[str] = ()+) -> tuple[Status, str]:+ if chk.run is not None:+ base = _merge_base(against)+ if base is None:+ return "skipped", "no merge-base to compare against"+ try:+ return chk.run(Scope(files=chk.matched, changed=list(changed), merge_base=base, committed_only=strict))+ except Exception as error:+ # These checks parse the output of other tools. A shape they did not expect+ # must not block the push with a traceback.+ return "skipped", f"check could not run ({type(error).__name__}: {str(error)[:120]})"if chk.advice is not None:# Nudge-only: nothing to run, nothing to auto-fix — the advisory *is* the check.return "advisory", chk.advice@@ -747,7 +811,13 @@ def _emit_telemetry(summary: dict[str, Any]) -> None:)@click.option("--against", default=None, help="Diff against this base ref instead of the branch default.")@click.option("--json", "as_json", is_flag=True, help="Emit the result summary as JSON.")-def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool) -> None:+ "--prepare-semgrep",+ "prepare_semgrep_tool",+ is_flag=True,+ help="Cache the pinned Semgrep tool without running checks.",+)+def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool, prepare_semgrep_tool: bool) -> None:if os.environ.get("HOGLI_PREFLIGHT_DISABLED", "").lower() in {"1", "true"}:disabled_summary: dict[str, Any] = {"mode": "disabled", "results": []}if as_json:@@ -761,6 +831,13 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)_emit_telemetry(disabled_summary)return+ if prepare_semgrep_tool:+ status, detail = prepare_semgrep()+ if status != "pass":+ raise click.ClickException(detail)+ click.echo(detail)+ return+# Fetch first so both the diff base and the staleness check see a fresh# origin/master — a stale local ref would inflate the diff with master's own commits._fetch_master()@@ -774,7 +851,8 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)triggered: list[DiffCheck] = []for chk in DIFF_CHECKS:chk.matched = [f for f in files if matches_globs(f, chk.triggers)]- if chk.matched:+ # A check that can only warn is not worth its run time in the pre-push hook.+ if chk.matched and not (strict and chk.soft and chk.run is not None):triggered.append(chk)shadow_drift_triggered = any(matches_globs(path, SHADOW_DRIFT_TRIGGERS) for path in files)@@ -807,7 +885,7 @@ def ci_preflight(do_fix: bool, strict: bool, against: str | None, as_json: bool)click.echo(f" {drift_detail}")for chk in triggered:- status, detail = _run_diff_check(chk, do_fix, against, strict)+ status, detail = _run_diff_check(chk, do_fix, against, strict, files)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/preflight_checks.py b/tools/hogli-commands/hogli_commands/preflight_checks.pynew file mode 100644index 000000000000..3b1559c0aa42--- /dev/null+++ b/tools/hogli-commands/hogli_commands/preflight_checks.py@@ -0,0 +1,382 @@+"""``ci:preflight`` checks that read the diff itself instead of running one command over it."""++from __future__ import annotations++import os+import re+import json+import time+import shutil+import tempfile+import subprocess+from dataclasses import dataclass+from pathlib import Path+from typing import Literal++import yaml+from hogli.manifest import REPO_ROOT++from hogli_commands.change_detection import matches_globs+from hogli_commands.size_lint import _rename_map++Status = Literal["pass", "fail", "warning", "advisory", "skipped"]+Outcome = tuple[Status, str]+++@dataclass(frozen=True, kw_only=True, slots=True)+class Scope:+ """What a push carries.++ ``files`` are the changed paths that match the check's triggers and ``changed`` is the+ whole diff. ``committed_only`` says to read the HEAD copy of a file instead of the working tree.+ """++ files: list[str]+ changed: list[str]+ merge_base: str+ committed_only: bool+++def _git(*args: str, timeout: float = 20.0) -> bytes | None:+ try:+ result = subprocess.run(["git", "-C", str(REPO_ROOT), *args], capture_output=True, timeout=timeout)+ except (OSError, subprocess.SubprocessError):+ return None+ return result.stdout if result.returncode == 0 else None+++def _head_copy(path: str, committed_only: bool, *, timeout: float = 20.0) -> bytes | None:+ if committed_only:+ return _git("show", f"HEAD:{path}", timeout=timeout)+ target = REPO_ROOT / path+ return target.read_bytes() if target.is_file() else None+++def _renamed_from(scope: Scope, *, timeout: float | None = None) -> dict[str, str]:+ """New path to old path, for every file the branch renamed."""+ return _rename_map(scope.merge_base, *(["HEAD"] if scope.committed_only else []), timeout=timeout)+++SNAPSHOT_MANIFEST = "frontend/snapshots.yml"+STORY_FILES = ["*.stories.*"]+# The Storybook config decides which story files load, so a change there can remove any story.+STORYBOOK_CONFIG = [".storybook/*", "common/storybook/*"]+_STORY_TITLE = re.compile(rb"""^\s*title:\s*(['"`])(.+?)\1""", re.MULTILINE)+++def _snapshot_identifiers(manifest: bytes) -> set[str]:+ return set(yaml.load(manifest, Loader=getattr(yaml, "CSafeLoader", yaml.SafeLoader))["snapshots"])+++def _story_id_prefixes(scope: Scope) -> set[str] | None:+ """Identifier prefixes of the stories this diff changed. None when one cannot be named.++ Storybook builds an identifier as the story file's title, lowercased with every run of+ other characters turned into a dash, then ``--`` and the export name. A story file+ without a literal title takes its identifier from its path, which is not derived here.+ """+ renames = _renamed_from(scope)+ prefixes: set[str] = set()+ for path in scope.changed:+ if not matches_globs(path, STORY_FILES):+ continue+ copies = (_git("show", f"{scope.merge_base}:{renames.get(path, path)}"), _head_copy(path, scope.committed_only))+ for content in copies:+ if content is None:+ continue+ title = _STORY_TITLE.search(content)+ if title is None:+ return None+ prefixes.add(re.sub(r"[^a-z0-9]+", "-", title.group(2).decode(errors="replace").lower()).strip("-"))+ return prefixes+++def check_snapshot_baselines(scope: Scope) -> Outcome:+ before = _git("show", f"{scope.merge_base}:{SNAPSHOT_MANIFEST}")+ after = _head_copy(SNAPSHOT_MANIFEST, scope.committed_only)+ if before is None or after is None:+ return "skipped", f"could not read {SNAPSHOT_MANIFEST} on both sides"+ removed = sorted(_snapshot_identifiers(before) - _snapshot_identifiers(after))+ if not removed:+ return "pass", "no baseline entries removed"+ if any(matches_globs(path, STORYBOOK_CONFIG) for path in scope.changed):+ return "pass", "the Storybook config changed in this diff, so removed entries are expected"+ prefixes = _story_id_prefixes(scope)+ if prefixes is None:+ return "pass", "a story without a literal title changed, so removed entries cannot be attributed"+ removed = [entry for entry in removed if not any(entry.startswith(f"{prefix}--") for prefix in prefixes)]+ if not removed:+ return "pass", "every removed baseline entry belongs to a story this diff changed"+ # An advisory and not a failure, because a branch can remove the entries of a story that+ # an earlier PR deleted, and nothing here can tell that apart from a bad conflict resolution.+ return (+ "advisory",+ f"{len(removed)} baseline {'entry' if len(removed) == 1 else 'entries'} removed "+ f"for stories this diff did not change (e.g. {removed[0]}). "+ "If the stories still render, the merge queue fails the batch that carries this file. "+ f"Compare with `git diff {scope.merge_base[:12]} -- {SNAPSHOT_MANIFEST}` "+ "and restore the entries you did not mean to remove",+ )+++SEMGREP_RULES = ".semgrep/rules/devex"+# The `SEMGREP_IMAGE` value in this workflow is the one semgrep version pin in the repository.+SEMGREP_WORKFLOW = ".github/workflows/ci-security.yaml"+# The directories the `semgrep-devex` CI job scans.+SEMGREP_SCOPE = [+ f"{root}/*"+ for root in (+ "bin",+ "common",+ "docs/onboarding",+ "ee",+ "frontend",+ "packages",+ "posthog",+ "products",+ "services",+ "tools",+ )+]+# CI excludes this tree from its blocking pass over ERROR rules, and from no other pass.+SEMGREP_ERROR_EXCLUDED = ["products/desktop/*"]+_SEMGREP_TIMEOUT_SECONDS = 15++# The rule, the file, and the source text the rule matched.+Finding = tuple[str, str, str]+++def _semgrep_command(*, offline: bool = True) -> list[str] | None:+ """The command that runs the semgrep version CI pins. None when it cannot be built.++ uv runs that version from its cache, in an environment of its own, so the scan does not+ depend on a semgrep the developer installed. Only preparation downloads the package.+ """+ if shutil.which("uv") is None:+ return None+ try:+ workflow = (REPO_ROOT / SEMGREP_WORKFLOW).read_text()+ except OSError:+ return None+ pin = re.search(r"^\s*SEMGREP_IMAGE:\s*semgrep/semgrep:(\d+\.\d+\.\d+)@", workflow, re.MULTILINE)+ if pin is None:+ return None+ return ["uv", "tool", "run", *(["--offline"] if offline else []), "--from", f"semgrep=={pin.group(1)}", "semgrep"]+++class SemgrepUnavailable(RuntimeError):+ pass+++def _semgrep_remaining(deadline: float) -> float:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise SemgrepUnavailable(+ f"semgrep exceeded the {_SEMGREP_TIMEOUT_SECONDS}s check budget; CI will run the check"+ )+ return remaining+++def _run_semgrep(command: list[str], *, cwd: Path, timeout: float) -> subprocess.CompletedProcess[str]:+ with tempfile.TemporaryDirectory() as state:+ try:+ result = subprocess.run(+ command,+ cwd=cwd,+ env={+ **os.environ,+ "UV_TOOL_DIR": str(REPO_ROOT / ".flox/cache/uv-tools"),+ "SEMGREP_LOG_FILE": str(Path(state) / "semgrep.log"),+ "SEMGREP_SETTINGS_FILE": str(Path(state) / "settings.yml"),+ "SEMGREP_ENABLE_VERSION_CHECK": "false",+ },+ capture_output=True,+ text=True,+ timeout=timeout,+ )+ except subprocess.TimeoutExpired as error:+ raise SemgrepUnavailable("semgrep timed out; CI will run the check") from error+ except OSError as error:+ raise SemgrepUnavailable(f"semgrep could not start: {error}") from error+ if result.returncode != 0:+ lines = [line.strip() for line in result.stderr.splitlines() if line.strip()]+ detail = " · ".join(lines[-2:])[:240].rstrip(".") or f"exit {result.returncode}"+ raise SemgrepUnavailable(f"{detail}. Run `hogli ci:preflight --prepare-semgrep` to prepare the pinned tool")+ return result+++def prepare_semgrep() -> Outcome:+ command = _semgrep_command(offline=False)+ if command is None:+ return "skipped", f"uv is not on PATH, or {SEMGREP_WORKFLOW} pins no semgrep version"+ try:+ result = _run_semgrep([*command, "--version"], cwd=REPO_ROOT, timeout=120)+ except SemgrepUnavailable as error:+ return "skipped", str(error)+ return "pass", f"semgrep {result.stdout.strip()} is cached for offline preflight checks"+++def _semgrep_findings(contents: dict[str, bytes], command: list[str], *, deadline: float) -> dict[Finding, list[int]]:+ """Findings in *contents* (path to file content), each with the lines it starts on.++ Raises SemgrepUnavailable when the scan did not complete. The scan targets a temporary+ directory containing the files. Semgrep applies its default ignore list+ (``tests/``, ``node_modules/``, minified files) to a directory it walks, which is how+ CI scans, and skips that list for a file named on the command line.+ """+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ for path, content in contents.items():+ target = root / path+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(content)+ result = _run_semgrep(+ [+ *command,+ "--config",+ str(REPO_ROOT / SEMGREP_RULES),+ "--severity=WARNING",+ "--severity=ERROR",+ "--metrics=off",+ "--quiet",+ "--json",+ ".",+ ],+ cwd=root,+ timeout=_semgrep_remaining(deadline),+ )+ report = json.loads(result.stdout)+ # Semgrep can exit zero and still list a failure. A file it parsed only in part is listed+ # at "warn" level on ordinary TypeScript, and its other findings are still valid.+ if any(error.get("level") == "error" for error in report.get("errors", [])):+ raise SemgrepUnavailable("semgrep reported an incomplete scan; CI will run the check")+ findings: dict[Finding, list[int]] = {}+ for item in report["results"]:+ path = item["path"]+ if item["extra"]["severity"] == "ERROR" and matches_globs(path, SEMGREP_ERROR_EXCLUDED):+ continue+ start, end = item["start"]["line"], item["end"]["line"]+ lines = contents[path].decode(errors="replace").splitlines()[start - 1 : end]+ # The id prefix encodes the rule file's path relative to the working directory.+ # The last segment is the rule's own id.+ rule = item["check_id"].rsplit(".", 1)[-1]+ findings.setdefault((rule, path, "\n".join(line.strip() for line in lines)), []).append(start)+ return findings+++def _check_semgrep_devex(scope: Scope, command: list[str], *, deadline: float) -> Outcome:+ # Semgrep cannot scan a binary, and a snapshot update can carry hundreds of them.+ after_contents = {+ path: content+ for path in scope.files+ if (content := _head_copy(path, scope.committed_only, timeout=_semgrep_remaining(deadline))) is not None+ and b"\0" not in content[:8000]+ }+ _semgrep_remaining(deadline)+ if not after_contents:+ return "skipped", "no file to scan"+ after = _semgrep_findings(after_contents, command, deadline=deadline)+ _semgrep_remaining(deadline)+ if not after:+ return "pass", "no new findings"++ # CI blocks only on findings the branch introduced, and gets them from `--baseline-commit`.+ # That flag is not usable here: on a clean checkout semgrep runs `git reset --hard` to the+ # baseline and back, and otherwise it checks the whole repository out again. Scanning the+ # merge-base copies of the flagged files gives the same comparison without touching the checkout.+ renames = _renamed_from(scope, timeout=_semgrep_remaining(deadline))+ before_contents = {+ path: content+ for path in {path for _, path, _ in after}+ if (+ content := _git(+ "show", f"{scope.merge_base}:{renames.get(path, path)}", timeout=_semgrep_remaining(deadline)+ )+ )+ is not None+ }+ _semgrep_remaining(deadline)+ before = _semgrep_findings(before_contents, command, deadline=deadline) if before_contents else {}+ _semgrep_remaining(deadline)++ introduced = [+ f"{rule} at {path}:{line}"+ for (rule, path, matched), lines in sorted(after.items())+ for line in lines[len(before.get((rule, path, matched), [])) :]+ ]+ if not introduced:+ return "pass", "no new findings"+ more = f" (+{len(introduced) - 3} more)" if len(introduced) > 3 else ""+ # An advisory and not a failure: this comparison is a reconstruction of CI's baseline scan,+ # so a mismatch between the two must not block a push.+ return (+ "advisory",+ f"{len(introduced)} new finding(s) that the semgrep-devex CI job blocks on: "+ f"{' · '.join(introduced[:3])}{more}. "+ f"Run `{' '.join(command)} --config {SEMGREP_RULES} <file>` to read the rule",+ )+++def check_semgrep_devex(scope: Scope) -> Outcome:+ command = _semgrep_command()+ if command is None:+ return "skipped", f"uv is not on PATH, or {SEMGREP_WORKFLOW} pins no semgrep version"+ deadline = time.monotonic() + _SEMGREP_TIMEOUT_SECONDS+ try:+ return _check_semgrep_devex(scope, command, deadline=deadline)+ except SemgrepUnavailable as error:+ return "skipped", str(error)+ except subprocess.TimeoutExpired:+ return "skipped", f"semgrep exceeded the {_SEMGREP_TIMEOUT_SECONDS}s check budget; CI will run the check"+++LANE_TARGETS_SCRIPT = ".github/scripts/trunk-impacted-targets.js"+LANE_SUMMARY_SCRIPT = ".github/scripts/trunk-lane-telemetry.js"+_LANE_TIMEOUT_SECONDS = 120+++def _node(script: str, files: list[str], env: dict[str, str]) -> object:+ result = subprocess.run(+ ["node", script],+ cwd=REPO_ROOT,+ env=env,+ input="\n".join(files),+ capture_output=True,+ text=True,+ timeout=_LANE_TIMEOUT_SECONDS,+ )+ return json.loads(result.stdout)+++def check_merge_queue_lane(scope: Scope) -> Outcome:+ if shutil.which("node") is None:+ return "skipped", "node not found"+ # CI lists a rename as its old path and its new one, and the old path can widen the lane.+ changed = sorted({*scope.changed, *_renamed_from(scope).values()})+ env = {**os.environ, "LANE_MERGE_BASE": scope.merge_base}+ targets = _node(LANE_TARGETS_SCRIPT, changed, env)+ lane = _node(LANE_SUMMARY_SCRIPT, changed, {**env, "IMPACTED_TARGETS": json.dumps({"impactedTargets": targets})})+ if not isinstance(lane, dict) or not isinstance(targets, list):+ return "skipped", "could not compute the merge queue lane"+ if not lane.get("is_all"):+ return "pass", f"claims {len(targets)} merge queue lane target(s)"++ unsplittable: Outcome = ("pass", "claims every merge queue lane, and a split would not narrow it much")+ # The summary names the files that some widening rule matched, which is not proof of cause.+ # Recomputing the lane without the whole set shows what a split would gain. The summary cuts+ # its file list off, and its per-domain counts say how many files the full list holds.+ suspects = sorted(lane.get("tripwire_files") or [])+ rest = [path for path in changed if path not in suspects]+ if not suspects or not rest or len(suspects) != sum((lane.get("tripwire_domains") or {}).values()):+ return unsplittable+ narrowed = _node(LANE_TARGETS_SCRIPT, rest, env)+ # A split that still claims most lanes leaves the queue as serial as before.+ if not isinstance(narrowed, list) or len(narrowed) * 2 > len(targets):+ return unsplittable+ more = f" (+{len(suspects) - 3} more)" if len(suspects) > 3 else ""+ return (+ "warning",+ "claims every merge queue lane, so the whole queue merges in series behind this PR. "+ f"Without these {len(suspects)} file(s) the other changes claim {len(narrowed)} of {len(targets)} "+ f"lane targets: {', '.join(suspects[:3])}{more}",+ )diff --git a/tools/hogli-commands/hogli_commands/size_lint.py b/tools/hogli-commands/hogli_commands/size_lint.pyindex 5e38414c7e0f..cf45a7ac2f98 100644--- a/tools/hogli-commands/hogli_commands/size_lint.py+++ b/tools/hogli-commands/hogli_commands/size_lint.py@@ -86,8 +86,8 @@ class Finding:crossed: bool-def _git(*args: str) -> subprocess.CompletedProcess[str]:- return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True)+def _git(*args: str, timeout: float | None = None) -> subprocess.CompletedProcess[str]:+ return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True, timeout=timeout)def _merge_base(against: str | None) -> str | None:@@ -103,8 +103,8 @@ def _merge_base(against: str | None) -> str | None:return None-def _rename_map(*diff_args: str) -> dict[str, str]:- result = _git("diff", "-M", "--name-status", "-z", *diff_args)+def _rename_map(*diff_args: str, timeout: float | None = None) -> dict[str, str]:+ result = _git("diff", "-M", "--name-status", "-z", *diff_args, timeout=timeout)if result.returncode != 0:return {}fields = [field for field in result.stdout.split("\0") if field]diff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.pyindex 5b065f9a9029..a8362b5119d3 100644--- a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+from collections.abc import Iteratorimport pytestfrom unittest.mock import MagicMock, patch@@ -9,11 +10,59 @@ from click.testing import CliRunnerfrom hogli.cli import clifrom hogli.manifest import REPO_ROOTfrom hogli_commands.change_detection import matches_globs-from hogli_commands.ci_preflight import DIFF_CHECKS, _pnpm_workspace_root, _run_workspace_scoped, _staleness_risks+from hogli_commands.ci_preflight import (+ DIFF_CHECKS,+ DiffCheck,+ _pnpm_workspace_root,+ _run_workspace_scoped,+ _staleness_risks,+)+from hogli_commands.preflight_checks import Scope, Statusrunner = CliRunner()[email protected](autouse=True)+def no_diff_reading_checks() -> Iterator[None]:+ # The real ones shell out to node and semgrep on any changed path.+ with patch("hogli_commands.ci_preflight.DIFF_CHECKS", [chk for chk in DIFF_CHECKS if chk.run is None]):+ yield+++class TestDiffReadingChecks:+ @pytest.mark.parametrize(+ "status,warn_only,expected_exit",+ [("fail", False, 1), ("advisory", False, 0), (None, False, 0), ("warning", True, 0)],+ )+ @patch("hogli_commands.ci_preflight._merge_base", return_value="abc123")+ @patch("hogli_commands.ci_preflight._emit_telemetry")+ @patch("hogli_commands.ci_preflight._staleness", return_value=("pass", "even with master", {}))+ @patch("hogli_commands.ci_preflight._fetch_master")+ @patch("hogli_commands.ci_preflight.changed_files", return_value=["frontend/snapshots.yml"])+ def test_only_a_failed_check_blocks_the_push_and_a_warn_only_check_is_skipped(+ self,+ mock_changed: MagicMock,+ mock_fetch: MagicMock,+ mock_stale: MagicMock,+ mock_emit: MagicMock,+ mock_merge_base: MagicMock,+ status: Status | None,+ warn_only: bool,+ expected_exit: int,+ ) -> None:+ def run(scope: Scope) -> tuple[Status, str]:+ if status is None:+ raise KeyError("unexpected tool output")+ return status, "detail"++ check = DiffCheck(key="probe", label="probe", triggers=["frontend/*"], verify=None, run=run, soft=warn_only)+ with patch("hogli_commands.ci_preflight.DIFF_CHECKS", [check]):+ result = runner.invoke(cli, ["ci:preflight", "--strict"])++ assert result.exit_code == expected_exit+ assert ("[probe]" in result.output) != warn_only++class TestKillSwitch:@patch("hogli_commands.ci_preflight._emit_telemetry")@patch("hogli_commands.ci_preflight.changed_files")diff --git a/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py b/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.pynew file mode 100644index 000000000000..7cd8bea44b40--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_preflight_checks.py@@ -0,0 +1,288 @@+from __future__ import annotations++import re+import json+import subprocess+from collections.abc import Callable+from pathlib import Path++import pytest+from unittest.mock import MagicMock, patch++from hogli_commands.preflight_checks import (+ Finding,+ Scope,+ SemgrepUnavailable,+ check_merge_queue_lane,+ check_semgrep_devex,+ check_snapshot_baselines,+)++MANIFEST = """version: 1+config:+ api: https://example.com+snapshots:+ scenes-app-a--default--dark:+ hash: v1.aaa+ scenes-app-b--default--dark:+ hash: v1.bbb+ ? scenes-app-c--default--dark+ : hash: v1.ccc+"""+MANIFEST_WITHOUT_B = MANIFEST.replace(" scenes-app-b--default--dark:\n hash: v1.bbb\n", "")+MANIFEST_WITHOUT_C = MANIFEST.replace(" ? scenes-app-c--default--dark\n : hash: v1.ccc\n", "")+MANIFEST_B_REHASHED = MANIFEST.replace("v1.bbb", "v1.ddd")+++def _scope(changed: list[str]) -> Scope:+ return Scope(files=changed, changed=changed, merge_base="abc123", committed_only=True)+++def _git_show(blobs: dict[str, bytes]) -> Callable[..., bytes | None]:+ return lambda _show, ref, timeout=20.0: blobs.get(ref)+++class TestSnapshotBaselines:+ @pytest.mark.parametrize(+ "after,stories,expected_status,removed",+ [+ (MANIFEST_WITHOUT_B, {}, "advisory", "scenes-app-b"),+ (MANIFEST_WITHOUT_C, {}, "advisory", "scenes-app-c"),+ (MANIFEST_WITHOUT_B, {"abc123:x/B.stories.tsx": b" title: 'Scenes-App/B',"}, "pass", None),+ (MANIFEST_WITHOUT_B, {"HEAD:x/A.stories.tsx": b" title: 'Scenes-App/A',"}, "advisory", "scenes-app-b"),+ (MANIFEST_WITHOUT_B, {"HEAD:x/A.stories.tsx": b"const meta = { title: makeTitle() }"}, "pass", None),+ (MANIFEST_B_REHASHED, {}, "pass", None),+ ],+ )+ @patch("hogli_commands.preflight_checks._renamed_from", return_value={})+ def test_removal_is_flagged_unless_its_own_story_changed(+ self,+ mock_renames: MagicMock,+ after: str,+ stories: dict[str, bytes],+ expected_status: str,+ removed: str | None,+ ) -> None:+ blobs = {+ "abc123:frontend/snapshots.yml": MANIFEST.encode(),+ "HEAD:frontend/snapshots.yml": after.encode(),+ **stories,+ }+ changed = ["frontend/snapshots.yml", *(ref.split(":", 1)[1] for ref in stories)]+ with patch("hogli_commands.preflight_checks._git", side_effect=_git_show(blobs)):+ status, detail = check_snapshot_baselines(_scope(changed))++ assert status == expected_status+ if removed:+ assert removed in detail+++def _every_line_is_a_finding(+ contents: dict[str, bytes], command: list[str], *, deadline: float+) -> dict[Finding, list[int]]:+ found: dict[Finding, list[int]] = {}+ for path, content in contents.items():+ for number, line in enumerate(content.decode().splitlines(), start=1):+ if line:+ found.setdefault(("prefer-frozen-dataclasses", path, line), []).append(number)+ return found+++class TestSemgrepDevex:+ @pytest.mark.parametrize(+ "blobs,renames,changed,expected_status,expected_fragment",+ [+ (+ {"abc123:posthog/a.py": b"old", "HEAD:posthog/a.py": b"\nold"},+ {},+ ["posthog/a.py"],+ "pass",+ "no new findings",+ ),+ (+ {"abc123:posthog/a.py": b"old", "HEAD:posthog/a.py": b"old\nnew"},+ {},+ ["posthog/a.py"],+ "advisory",+ "posthog/a.py:2",+ ),+ (+ {"abc123:posthog/a.py": b"old", "HEAD:posthog/a.py": b"old\nold"},+ {},+ ["posthog/a.py"],+ "advisory",+ "posthog/a.py:2",+ ),+ (+ {"abc123:posthog/a.py": b"old", "HEAD:posthog/moved/a.py": b"old"},+ {"posthog/moved/a.py": "posthog/a.py"},+ ["posthog/moved/a.py"],+ "pass",+ "no new findings",+ ),+ ({"HEAD:posthog/new.py": b"new"}, {}, ["posthog/new.py"], "advisory", "posthog/new.py:1"),+ ({"HEAD:frontend/a.png": b"\x89PNG\0\0"}, {}, ["frontend/a.png"], "skipped", "no file to scan"),+ ],+ )+ @patch("hogli_commands.preflight_checks._semgrep_findings", side_effect=_every_line_is_a_finding)+ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/uv")+ def test_only_findings_the_branch_introduced_are_reported(+ self,+ mock_which: MagicMock,+ mock_findings: MagicMock,+ blobs: dict[str, bytes],+ renames: dict[str, str],+ changed: list[str],+ expected_status: str,+ expected_fragment: str,+ ) -> None:+ with (+ patch("hogli_commands.preflight_checks._git", side_effect=_git_show(blobs)),+ patch("hogli_commands.preflight_checks._renamed_from", return_value=renames),+ ):+ status, detail = check_semgrep_devex(_scope(changed))++ assert status == expected_status+ assert expected_fragment in detail++ @patch(+ "hogli_commands.preflight_checks._semgrep_findings", side_effect=SemgrepUnavailable("tool cache unavailable")+ )+ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/uv")+ def test_an_incomplete_scan_skips_instead_of_reporting(+ self, mock_which: MagicMock, mock_findings: MagicMock+ ) -> None:+ with patch("hogli_commands.preflight_checks._git", side_effect=_git_show({"HEAD:posthog/a.py": b"new"})):+ status, detail = check_semgrep_devex(_scope(["posthog/a.py"]))++ assert status == "skipped"+ assert "tool cache unavailable" in detail++ @patch("hogli_commands.preflight_checks._semgrep_findings", return_value={})+ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/uv")+ def test_the_scan_runs_the_semgrep_version_ci_pins(self, mock_which: MagicMock, mock_findings: MagicMock) -> None:+ with patch("hogli_commands.preflight_checks._git", side_effect=_git_show({"HEAD:posthog/a.py": b"new"})):+ status, _ = check_semgrep_devex(_scope(["posthog/a.py"]))++ assert status == "pass"+ command = mock_findings.call_args.args[1]+ assert re.fullmatch(r"semgrep==\d+\.\d+\.\d+", command[command.index("--from") + 1])+ assert "--offline" in command++ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/uv")+ def test_baseline_scan_uses_only_the_remaining_check_budget(self, mock_which: MagicMock) -> None:+ clock = [100.0]+ scans = 0+ finding = {+ "check_id": "rule",+ "path": "posthog/a.py",+ "start": {"line": 1},+ "end": {"line": 1},+ "extra": {"severity": "WARNING"},+ }++ def run(+ command: list[str],+ *,+ timeout: float,+ cwd: Path,+ capture_output: bool,+ text: bool,+ env: dict[str, str] | None = None,+ ) -> subprocess.CompletedProcess[str]:+ nonlocal scans+ if command[0] == "git":+ return subprocess.CompletedProcess(command, 0, stdout="", stderr="")+ scans += 1+ duration = 14.0 if scans == 1 else 2.0+ clock[0] += min(duration, timeout)+ if duration > timeout:+ raise subprocess.TimeoutExpired(command, timeout)+ return subprocess.CompletedProcess(command, 0, stdout=json.dumps({"results": [finding]}), stderr="")++ with (+ patch("hogli_commands.preflight_checks.time.monotonic", side_effect=lambda: clock[0]),+ patch("hogli_commands.preflight_checks.subprocess.run", side_effect=run),+ patch(+ "hogli_commands.preflight_checks._git",+ side_effect=_git_show({"HEAD:posthog/a.py": b"old", "abc123:posthog/a.py": b"old"}),+ ),+ ):+ status, detail = check_semgrep_devex(_scope(["posthog/a.py"]))++ assert status == "skipped"+ assert "timed out" in detail+ assert clock[0] == 115.0++ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/uv")+ def test_scan_uses_writable_state_when_home_paths_are_unavailable(+ self, mock_which: MagicMock, tmp_path: Path+ ) -> None:+ (tmp_path / ".github/workflows").mkdir(parents=True)+ (tmp_path / ".github/workflows/ci-security.yaml").write_text(+ "SEMGREP_IMAGE: semgrep/semgrep:1.175.0@sha256:test\n"+ )+ (tmp_path / "posthog").mkdir()+ (tmp_path / "posthog/a.py").write_text("value = 1\n")++ def run(command: list[str], *, env: dict[str, str], **kwargs: object) -> subprocess.CompletedProcess[str]:+ tools = Path(env.get("UV_TOOL_DIR", "/home-paths-forbidden/uv-tools"))+ tools.mkdir(parents=True, exist_ok=True)+ for key in ("SEMGREP_LOG_FILE", "SEMGREP_SETTINGS_FILE"):+ Path(env.get(key, "/home-paths-forbidden/semgrep")).touch()+ return subprocess.CompletedProcess(command, 0, stdout='{"results": []}', stderr="")++ with (+ patch("hogli_commands.preflight_checks.REPO_ROOT", tmp_path),+ patch("hogli_commands.preflight_checks.subprocess.run", side_effect=run),+ ):+ scope = Scope(files=["posthog/a.py"], changed=["posthog/a.py"], merge_base="abc123", committed_only=False)+ status, detail = check_semgrep_devex(scope)++ assert status == "pass"+ assert detail == "no new findings"+++WORKFLOW = ".github/workflows/ci-backend.yml"+PRODUCT_FILE = "products/x/backend/api.py"+EVERY_LANE = ["fe:core", "py:core", "rust:core"]+++def _node_output(payload: object) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(args=[], returncode=0, stdout=json.dumps(payload), stderr="")+++def _widened(listed: int, total: int) -> dict[str, object]:+ files = [WORKFLOW, *(f".github/workflows/{n}.yml" for n in range(listed - 1))]+ return {"is_all": True, "tripwire_files": files, "tripwire_domains": {"universal": total}}+++class TestMergeQueueLane:+ @pytest.mark.parametrize(+ "changed,summary,narrowed,expected_status",+ [+ ([WORKFLOW, PRODUCT_FILE], _widened(1, 1), ["py:core"], "warning"),+ ([WORKFLOW, "common/new/x.py"], _widened(1, 1), EVERY_LANE, "pass"),+ ([WORKFLOW], _widened(1, 1), None, "pass"),+ ([WORKFLOW, PRODUCT_FILE], _widened(20, 25), ["py:core"], "pass"),+ ([PRODUCT_FILE], {"is_all": False, "tripwire_files": []}, None, "pass"),+ ],+ )+ @patch("hogli_commands.preflight_checks._renamed_from", return_value={})+ @patch("hogli_commands.preflight_checks.shutil.which", return_value="/usr/bin/node")+ def test_warns_only_when_splitting_the_pr_would_narrow_the_lane(+ self,+ mock_which: MagicMock,+ mock_renames: MagicMock,+ changed: list[str],+ summary: dict[str, object],+ narrowed: list[str] | None,+ expected_status: str,+ ) -> None:+ runs = [_node_output(EVERY_LANE), _node_output(summary), _node_output(narrowed)]+ with patch("hogli_commands.preflight_checks.subprocess.run", side_effect=runs):+ status, detail = check_merge_queue_lane(_scope(changed))++ assert status == expected_status+ if expected_status == "warning":+ assert WORKFLOW in detail