: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
feat(hogli): add ci:preflight pre-push hook, checks, and telemetry (#65581)
Raúl Negrón-Otero8d91b3679b42
diff --git a/.agents/skills/running-ci-preflight/SKILL.md b/.agents/skills/running-ci-preflight/SKILL.mdnew file mode 100644index 000000000000..e00c7ed530fe--- /dev/null+++ b/.agents/skills/running-ci-preflight/SKILL.md@@ -0,0 +1,44 @@+---+name: running-ci-preflight+description: >+ Catch the deterministic CI failures reachable from your diff before pushing, with `hogli ci:preflight`.+ Use when the pre-push hook blocks a push, before reporting a task done, or after editing Python,+ serializers, migrations, workflows, or dependency manifests — to avoid burning a CI matrix on a failure+ you could catch locally (formatting, lint, broken lockfiles, OpenAPI drift, migration conflict, stale branch).+ Trigger terms: ci:preflight, preflight, pre-push checks, pre-push hook failed, "will this break CI".+---++# Running ci:preflight++`hogli ci:preflight` scopes a curated set of checks to the files your branch touched — each mapped to a+CI failure class that has taken master down — plus an always-on branch-freshness check. It is the+pre-push counterpart to `hogli ci:insights` (what is _already_ broken on master).++The pre-push hook runs `ci:preflight --strict` automatically and blocks the push on failed checks.+**Never bypass it with `--no-verify`** — fix what it reports instead.++## The loop (when the hook blocks, or before reporting done)++```sh+hogli ci:preflight --fix+```++1. Run with `--fix` — it formats, lints, and auto-fixes what is safe.+2. Read each line: `✓ pass`, `✗ fail`, `→ advisory` (do it yourself), `· skipped` (capability absent).+3. Resolve every `✗ fail` — these are what `--fix` could not (real lint error, broken lockfile, migration conflict). These block the push.+4. Act on every `→ advisory` — e.g. `openapi` advisory → run `hogli build:openapi` and commit the drift; `staleness` advisory → `git merge origin/master`. Advisories never block, but ignoring them ships the failure to CI.+5. Re-run until clean, then push.++## Notes++- **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.+- **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 stack/node)`** is expected on a bare checkout or sandbox. Start the stack with `hogli start` to run those, or let CI cover them. 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.+- **Kill switch.** `HOGLI_PREFLIGHT_DISABLED=1` makes the command (and the hook) a no-op with exit 0. It is a rollout/emergency lever — respect it; never unset it to force a run.++## Why it matters++Drafts already run a trimmed CI subset; the expensive waste is a ready PR that fails the full matrix on+something deterministic, gets fixed, and re-runs the whole matrix. Catching that locally is the cheapest+CI saving available.diff --git a/.github/scripts/ci_flake_overseer.py b/.github/scripts/ci_flake_overseer.pyindex eee592f24c8a..53a3b045d2d6 100644--- a/.github/scripts/ci_flake_overseer.py+++ b/.github/scripts/ci_flake_overseer.py@@ -30,33 +30,40 @@ def compile_patterns(*patterns: str) -> tuple[re.Pattern[str], ...]:return tuple(re.compile(pattern, re.IGNORECASE) for pattern in patterns)+def compile_classified(*rules: tuple[str, str]) -> tuple[tuple[re.Pattern[str], str], ...]:+ return tuple((re.compile(pattern, re.IGNORECASE), failure_class) for pattern, failure_class in rules)++# Jobs/steps whose failures a rerun can't fix — excluded from the flake measurement.-DETERMINISTIC_JOB_PATTERNS = compile_patterns(- r"\brepo checks?\b",- r"\bopenapi\b",- r"\bmigrations?\b",- r"\blint\b",- r"\btype ?check\b",- r"\btypescript\b",- r"\bvisual\b",- r"\bsnapshot\b",- r"\bstorybook\b",- r"\btach\b",- r"\bimport-linter\b",+# Each rule carries a stable failure-class key (matching `hogli ci:preflight` check+# keys where the two overlap) so dashboards can group deterministic failures that+# reached CI and join them against local preflight interceptions.+DETERMINISTIC_JOB_RULES = compile_classified(+ (r"\brepo checks?\b", "repo-checks"),+ (r"\bopenapi\b", "openapi"),+ (r"\bmigrations?\b", "migrations"),+ (r"\blint\b", "lint"),+ (r"\btype ?check\b", "typecheck"),+ (r"\btypescript\b", "typecheck"),+ (r"\bvisual\b", "visual-review"),+ (r"\bsnapshot\b", "snapshot"),+ (r"\bstorybook\b", "storybook"),+ (r"\btach\b", "module-boundaries"),+ (r"\bimport-linter\b", "module-boundaries"),)-DETERMINISTIC_STEP_PATTERNS = compile_patterns(- r"\bcheck module boundaries\b",- r"\bproduct facade enforcement\b",- r"\bopenapi\b",- r"\bmigrations?\b",- r"\blint\b",- r"\btype ?check\b",- r"\btypescript\b",- r"\bvisual review\b",- r"\bsnapshot\b",- r"\bverify changed playwright tests are stable\b",- r"\bverify new snapshots\b",+DETERMINISTIC_STEP_RULES = compile_classified(+ (r"\bcheck module boundaries\b", "module-boundaries"),+ (r"\bproduct facade enforcement\b", "module-boundaries"),+ (r"\bopenapi\b", "openapi"),+ (r"\bmigrations?\b", "migrations"),+ (r"\blint\b", "lint"),+ (r"\btype ?check\b", "typecheck"),+ (r"\btypescript\b", "typecheck"),+ (r"\bvisual review\b", "visual-review"),+ (r"\bsnapshot\b", "snapshot"),+ (r"\bverify changed playwright tests are stable\b", "playwright-stability"),+ (r"\bverify new snapshots\b", "snapshot"),)TEST_STEP_PATTERNS = compile_patterns(@@ -112,6 +119,8 @@ class WorkflowRun:html_url: strhead_branch: str = ""event: str = ""+ # Empty `pull_requests` (e.g. fork PRs) collapses to None; head_branch stays the primary join key.+ pr_number: int | None = None@dataclass(frozen=True)@@ -121,6 +130,8 @@ class Decision:job: Job# Which signal classified an `observe`: the job name or a failed step. Surfaces silent allowlist drift.classified_via: str | None = None+ # Canonical failure-class key for `skip deterministic` decisions (see the rule tables above).+ failure_class: str | None = Nonedef as_str(value: object) -> str | None:@@ -166,6 +177,11 @@ def gh_json(repo: str, path: str) -> JsonObject:return parsed if isinstance(parsed, dict) else {}+def pr_number_from_object(raw: JsonObject) -> int | None:+ pulls = as_object_list(raw.get("pull_requests"))+ return as_int(pulls[0].get("number")) if pulls else None++def workflow_run_from_object(raw: JsonObject) -> WorkflowRun:return WorkflowRun(id=as_int(raw.get("id")) or 0,@@ -177,6 +193,7 @@ def workflow_run_from_object(raw: JsonObject) -> WorkflowRun:html_url=as_str(raw.get("html_url")) or "",head_branch=as_str(raw.get("head_branch")) or "",event=as_str(raw.get("event")) or "",+ pr_number=pr_number_from_object(raw),)@@ -227,14 +244,14 @@ def fetch_jobs(repo: str, run_id: int, run_attempt: int, *, strict: bool = Falsepage += 1-def deterministic_reason(job: Job) -> str | None:- for pattern in DETERMINISTIC_JOB_PATTERNS:+def deterministic_match(job: Job) -> tuple[str, str] | None:+ for pattern, failure_class in DETERMINISTIC_JOB_RULES:if pattern.search(job.name):- return f"job name matches deterministic rule `{pattern.pattern}`"+ return f"job name matches deterministic rule `{pattern.pattern}`", failure_classfor step_name in job.failed_step_names():- for pattern in DETERMINISTIC_STEP_PATTERNS:+ for pattern, failure_class in DETERMINISTIC_STEP_RULES:if pattern.search(step_name):- return f"failed step `{step_name}` matches deterministic rule `{pattern.pattern}`"+ return f"failed step `{step_name}` matches deterministic rule `{pattern.pattern}`", failure_classreturn None@@ -251,9 +268,10 @@ def is_test_job_failure(job: Job) -> bool:def classify_job(job: Job) -> Decision:- deterministic = deterministic_reason(job)+ deterministic = deterministic_match(job)if deterministic is not None:- return Decision(action="skip deterministic", reason=deterministic, job=job)+ reason, failure_class = deterministic+ return Decision(action="skip deterministic", reason=reason, job=job, failure_class=failure_class)source = test_failure_source(job)if source is None:return Decision(action="skip non-test", reason="failed job or step is not an allowlisted test runner", job=job)@@ -276,6 +294,7 @@ def base_event_properties(repo: str, workflow_run: WorkflowRun) -> JsonObject:"run_url": workflow_run.html_url,"head_sha": workflow_run.head_sha,"head_branch": workflow_run.head_branch,+ "pr_number": workflow_run.pr_number,# Master failures block the deploy gate; PR failures only annoy the author — keep them separable."is_master": workflow_run.head_branch in {"master", "main"},"trigger_event": workflow_run.event,@@ -294,6 +313,7 @@ def build_decision_events(repo: str, workflow_run: WorkflowRun, decisions: tuple"action": decision.action,"reason": decision.reason,"classified_via": decision.classified_via,+ "failure_class": decision.failure_class,"job_name": job.name,"job_id": job.id,"job_url": job.html_url,diff --git a/.github/scripts/test_ci_flake_overseer.py b/.github/scripts/test_ci_flake_overseer.pyindex 26b7cdd57628..fc3ad7e0de53 100644--- a/.github/scripts/test_ci_flake_overseer.py+++ b/.github/scripts/test_ci_flake_overseer.py@@ -18,6 +18,7 @@ from ci_flake_overseer import (is_test_job_failure,report_rerun_outcomes,rerun_outcome_label,+ workflow_run_from_object,)@@ -40,7 +41,9 @@ def make_job()-def make_workflow_run(run_attempt: int = 1, *, head_branch: str = "", event: str = "pull_request") -> WorkflowRun:+def make_workflow_run(+ run_attempt: int = 1, *, head_branch: str = "", event: str = "pull_request", pr_number: int | None = 12345+) -> WorkflowRun:return WorkflowRun(id=999,workflow_id=42,@@ -51,55 +54,72 @@ def make_workflow_run(run_attempt: int = 1, *, head_branch: str = "", event: strhtml_url="https://github.com/PostHog/posthog/actions/runs/999",head_branch=head_branch,event=event,+ pr_number=pr_number,)@pytest.mark.parametrize(- ("job", "expected_action", "expected_reason_fragment"),+ ("job", "expected_action", "expected_reason_fragment", "expected_failure_class"),[pytest.param(make_job("Repo checks (depot-ubuntu-latest)", failed_step="Check module boundaries (tach)"),"skip deterministic","deterministic",+ "repo-checks",id="deterministic-repo-checks",),pytest.param(make_job("Validate OpenAPI types", failed_step="Check and update OpenAPI types"),"skip deterministic","deterministic",+ "openapi",id="deterministic-openapi",),pytest.param(make_job("Frontend lint", failed_step="Lint with Oxlint"),"skip deterministic","deterministic",+ "lint",id="deterministic-lint",),pytest.param(make_job("Validate migrations", failed_step="Check migrations"),"skip deterministic","deterministic",+ "migrations",id="deterministic-migrations",),+ pytest.param(+ make_job("Django tests", failed_step="Product facade enforcement"),+ "skip deterministic",+ "deterministic",+ "module-boundaries",+ id="deterministic-via-step-rule",+ ),pytest.param(make_job("Build and deploy", failed_step="Compile assets"),"skip non-test","not an allowlisted test runner",+ None,id="non-test-job",),pytest.param(make_job("Django tests - Temporal (1/1)", failed_step="Run Temporal tests"),"observe","test job failure",+ None,id="observed-test-job",),],)-def test_classify_job(job: Job, expected_action: str, expected_reason_fragment: str) -> None:+def test_classify_job(+ job: Job, expected_action: str, expected_reason_fragment: str, expected_failure_class: str | None+) -> None:decision = classify_job(job)assert decision.action == expected_actionassert expected_reason_fragment in decision.reason+ assert decision.failure_class == expected_failure_class@pytest.mark.parametrize(@@ -121,11 +141,12 @@ def test_build_decision_events_one_event_per_decision() -> None:decisions = (classify_job(make_job("Django tests - Temporal (1/1)")),classify_job(make_job("Build and deploy", failed_step="Compile assets")),+ classify_job(make_job("Validate OpenAPI types", failed_step="Check and update OpenAPI types")),)events = build_decision_events("PostHog/posthog", make_workflow_run(), decisions)- assert [event["event"] for event in events] == [DECISION_EVENT, DECISION_EVENT]+ assert [event["event"] for event in events] == [DECISION_EVENT, DECISION_EVENT, DECISION_EVENT]assert all(event["distinct_id"] == "PostHog/posthog" for event in events)first = events[0]["properties"]assert first["action"] == "observe"@@ -133,11 +154,31 @@ def test_build_decision_events_one_event_per_decision() -> None:assert first["job_name"] == "Django tests - Temporal (1/1)"assert first["$groups"] == {"workflow_run": "999"}assert first["classified_via"] == "job_name"+ assert first["failure_class"] is None+ assert first["pr_number"] == 12345assert first["job_conclusion"] == "failure"assert first["failed_steps"] == ["Run Core tests"]assert first["$insert_id"] == "decision:999:1:123"assert events[1]["properties"]["action"] == "skip non-test"assert events[1]["properties"]["classified_via"] is None+ assert events[2]["properties"]["action"] == "skip deterministic"+ assert events[2]["properties"]["failure_class"] == "openapi"+++ ("pull_requests", "expected"),+ [+ pytest.param([{"number": 65581}], 65581, id="same-repo-pr"),+ pytest.param([], None, id="fork-pr-empty-list"),+ pytest.param(None, None, id="field-absent"),+ ],+)+def test_workflow_run_pr_number(pull_requests: list[dict[str, object]] | None, expected: int | None) -> None:+ raw: dict[str, object] = {"id": 1, "workflow_id": 2, "name": "Backend CI"}+ if pull_requests is not None:+ raw["pull_requests"] = pull_requests++ assert workflow_run_from_object(raw).pr_number == expected@pytest.mark.parametrize(diff --git a/.husky/pre-push b/.husky/pre-pushindex b7b1e06d781b..341e423203e7 100755--- a/.husky/pre-push+++ b/.husky/pre-push@@ -8,6 +8,16 @@ if [ $protected_branch = $current_branch ]thenecho "Pushing to $protected_branch is a sin! Instead, create a pull request and repent."exit 1 # push will not execute-else- exit 0 # push will executefi++# Catch deterministic CI failures before this push burns a CI matrix.+# Advisories never block; HOGLI_PREFLIGHT_DISABLED=1 makes it a no-op; no hogli → skip.+if command -v hogli >/dev/null 2>&1+then+ hogli ci:preflight --strict || {+ echo "pre-push: ci:preflight found failures — run 'hogli ci:preflight --fix', resolve, and push again."+ exit 1+ }+fi++exit 0diff --git a/AGENTS.md b/AGENTS.mdindex 08a3fb4a5a53..f4ba25ef6693 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -72,6 +72,12 @@ NEVER share sensitive information in a PR description. Users may share sensitiveOnce a branch already has an open PR, push incremental changes and fixes to it without waiting for human guidance — keeping the PR current is part of the work.Pushes still trigger CI, which burns runner credits, so batch related commits and push once the increment is ready rather than after every change.+#### Pre-push checks — ci:preflight++A pre-push hook runs `hogli ci:preflight --strict`, failing the push on deterministic CI breakage reachable from your diff (lint, lockfiles, migration conflicts). Never bypass it (`--no-verify`).+If it blocks the push, run `hogli ci:preflight --fix`, resolve the remaining `✗ fail` lines, act on the `→ advisory` ones (regenerate OpenAPI types, merge master in), and push again.+In environments without hooks (no `node_modules`), run `hogli ci:preflight --fix` yourself before pushing or reporting a task done. If the command reports it is disabled, that's intentional — proceed.+### Public open source repo guidanceThis repository is public and all commit messages, pull request titles, and pull request descriptions must be safe for public readers.diff --git a/hogli.yaml b/hogli.yamlindex 9c742426eb4f..fc4c42436ee4 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -988,6 +988,9 @@ tools:ci:insights:click: hogli_commands.ci_insights:ci_insightsdescription: Show CI insights for the current repo + branch (search/view/plan subcommands)+ ci:preflight:+ click: hogli_commands.ci_preflight:ci_preflight+ description: Catch deterministic CI failures reachable from your diff before you push (advisory; --fix, --strict)utilities:nuke:steps:diff --git a/tools/hogli-commands/hogli_commands/build.py b/tools/hogli-commands/hogli_commands/build.pyindex ceffe600fbe0..6662152b3b6b 100644--- a/tools/hogli-commands/hogli_commands/build.py+++ b/tools/hogli-commands/hogli_commands/build.py@@ -2,12 +2,14 @@from __future__ import annotations-import fnmatchimport subprocess+from collections.abc import Iterableimport clickfrom hogli.manifest import REPO_ROOT+from hogli_commands.change_detection import changed_files, matches_globs+# command -> file globs that should trigger itTRIGGERS: dict[str, tuple[str, ...]] = {"build:schema": (@@ -32,54 +34,9 @@ TRIGGERS: dict[str, tuple[str, ...]] = {}-def _get_changed_files() -> set[str]:- """Get all files changed on the current branch vs master, plus uncommitted changes."""- changed: set[str] = set()-- # Branch changes vs merge-base with master- try:- merge_base = subprocess.check_output(- ["git", "merge-base", "HEAD", "master"],- cwd=REPO_ROOT,- text=True,- stderr=subprocess.DEVNULL,- ).strip()- branch_diff = subprocess.check_output(- ["git", "diff", "--name-only", f"{merge_base}...HEAD"],- cwd=REPO_ROOT,- text=True,- stderr=subprocess.DEVNULL,- ).strip()- if branch_diff:- changed.update(branch_diff.splitlines())- except subprocess.CalledProcessError:- pass-- # Working tree: staged + unstaged + untracked in one call- try:- status = subprocess.check_output(- ["git", "status", "--porcelain", "--no-renames"],- cwd=REPO_ROOT,- text=True,- stderr=subprocess.DEVNULL,- )- for line in status.splitlines():- if len(line) > 3:- # Porcelain format: "XY filename" — 2-char status + space + path- changed.add(line[3:])- except subprocess.CalledProcessError:- pass-- return changed---def _match_commands(changed_files: set[str]) -> list[str]:- """Return commands whose trigger globs match any changed file."""- return [- cmd- for cmd, globs in TRIGGERS.items()- if any(fnmatch.fnmatch(path, glob) for path in changed_files for glob in globs)- ]+def _match_commands(changed: Iterable[str]) -> list[str]:+ """Return build commands whose trigger globs match any changed file."""+ return [cmd for cmd, globs in TRIGGERS.items() if any(matches_globs(p, globs) for p in changed)]@click.command(name="build", help="Run code generation pipelines (smart change detection by default)")@@ -99,7 +56,7 @@ def build(force: bool, dry_run: bool, list_all: bool) -> None:if force:commands = list(TRIGGERS)else:- changed = _get_changed_files()+ changed = changed_files()if not changed:click.echo("Nothing to rebuild -- no changes detected.")returndiff --git a/tools/hogli-commands/hogli_commands/change_detection.py b/tools/hogli-commands/hogli_commands/change_detection.pynew file mode 100644index 000000000000..87e55e47fec9--- /dev/null+++ b/tools/hogli-commands/hogli_commands/change_detection.py@@ -0,0 +1,51 @@+"""Changed-file detection shared by the hogli dev commands.++A thin wrapper over ``git diff`` + ``git status`` so ``hogli build``, ``ci:preflight``,+and ``test --changed`` agree on "what changed" instead of each rolling its own.+``matches_globs`` is the shared fnmatch predicate. CI computes affectedness its own+way (Turbo, snob); this is just the local dev-CLI helper, not a repo-wide authority.+"""++from __future__ import annotations++import fnmatch+import subprocess+from collections.abc import Iterable++import click+from hogli.manifest import REPO_ROOT+++def _git(*args: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(["git", *args], cwd=REPO_ROOT, capture_output=True, text=True)+++def changed_files(against: str | None = None) -> list[str]:+ """Files the branch touches vs a base ref (merge-base), plus uncommitted/untracked work.++ An explicit *against* raises on a bad ref so a typo can't masquerade as a clean+ diff. The default base tries ``origin/master`` then ``master`` (origin/master is+ what CI diffs against and what the staleness check compares to) and degrades to+ working-tree-only detection when neither exists (single-branch clones, bare+ sandboxes). ``-z`` output keeps paths with spaces/non-ASCII unquoted, and+ ``--untracked-files=all`` lists files inside brand-new directories.+ """+ files: set[str] = set()+ for base in [against] if against is not None else ["origin/master", "master"]:+ diff = _git("diff", "--name-only", "-z", f"{base}...HEAD")+ if diff.returncode == 0:+ files.update(path for path in diff.stdout.split("\0") if path)+ break+ if against is not None:+ raise click.UsageError(f"git diff against {against!r} failed: {diff.stderr.strip()}")+ status = _git("status", "--porcelain", "-z", "--no-renames", "--untracked-files=all")+ if status.returncode != 0:+ # A failed status (e.g. index.lock contention) must not read as "no uncommitted work".+ raise click.UsageError(f"git status failed: {status.stderr.strip()}")+ files.update(entry[3:] for entry in status.stdout.split("\0") if len(entry) > 3)+ return sorted(files)+++def matches_globs(path: str, globs: Iterable[str]) -> bool:+ """True if *path* matches any fnmatch glob (``*`` spans ``/``, matching build & CI)."""+ return any(fnmatch.fnmatch(path, glob) for glob in globs)diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pynew file mode 100644index 000000000000..b908334b0e3c--- /dev/null+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -0,0 +1,485 @@+"""Catch the deterministic CI failures reachable from your diff before you push.++``ci:preflight`` is the pre-push counterpart to ``ci:insights``: insights tells+you what's broken on master, preflight stops you from being the one who breaks+it. It scopes a curated set of checks to the files your branch actually touched,+each mapped to a CI failure class we've seen take master down, plus an always-on+branch-freshness check that flags concrete merge risks (textual conflicts,+migration collisions, generated-file drift, CI changes on master).++ hogli ci:preflight # report what your diff could break in CI+ hogli ci:preflight --fix # auto-remediate what's safe, report the rest+ hogli ci:preflight --strict # exit non-zero on failed checks (the pre-push hook)+ hogli ci:preflight --against origin/master # diff against an explicit base++``HOGLI_PREFLIGHT_DISABLED=1`` makes the command (and thus the pre-push hook) a+no-op — the rollout/emergency kill switch (still emits a run event so opt-out+prevalence is measurable).++Checks declare what they need (``node`` modules, the dev ``stack``) and skip with+a note when it's absent, so the no-dependency checks always run — even on a bare+checkout or inside an agent sandbox. The pre-push hook runs ``--strict`` (failures+block, advisories never do); the fix loop is ``--fix`` — see the running-ci-preflight skill.+"""++from __future__ import annotations++import os+import json+import time+import shutil+import socket+import subprocess+from dataclasses import dataclass, field+from datetime import datetime+from pathlib import Path+from typing import Any, Literal++import click+from hogli import telemetry+from hogli.hooks import telemetry_property_hooks+from hogli.manifest import REPO_ROOT++from hogli_commands.build import (+ TRIGGERS as BUILD_TRIGGERS,+ _match_commands,+)+from hogli_commands.change_detection import changed_files, matches_globs++Requirement = Literal["node", "stack", "clickhouse"]+++@dataclass+class DiffCheck:+ """A CI failure class triggered by file globs in the diff, and how to catch it locally.+ The always-on branch-freshness check is a different shape — see ``_staleness``."""++ key: str+ label: str # the CI failure class this intercepts+ triggers: list[str] # fnmatch globs against changed paths (`*` spans `/`, as in build.py)+ verify: list[str] | None # advisory command; None = guidance only (no runnable local check)+ fix: list[str] | None = None # remediation for --fix+ requires: tuple[Requirement, ...] = () # capabilities the check needs, else it skips+ takes_files: bool = False # append matched files to the command+ matched: list[str] = field(default_factory=list)+++# Ordered cheapest-first. Grounded in failure classes seen in `hogli ci:insights`:+# broken lockfile blocking all CI, OpenAPI drift, formatting/lint, flag sort,+# workflow-convention failures, migration conflicts.+DIFF_CHECKS: list[DiffCheck] = [+ DiffCheck(+ key="lockfile",+ label="broken pnpm-lock.yaml (blocks ALL CI)",+ # pnpm-workspace.yaml (catalog versions) and patches/* (patchedDependencies+ # hashes) invalidate the lockfile just like a package.json edit.+ triggers=["package.json", "*/package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "patches/*"],+ # --lockfile-only validates manifest/lockfile agreement without touching node_modules.+ verify=["pnpm", "install", "--frozen-lockfile", "--lockfile-only"],+ fix=["pnpm", "install", "--no-frozen-lockfile"],+ requires=("node",),+ ),+ DiffCheck(+ key="uv-lock",+ label="uv.lock out of sync with pyproject.toml (blocks Python CI)",+ triggers=["pyproject.toml", "*/pyproject.toml", "uv.lock"],+ verify=["uv", "lock", "--check"],+ fix=["uv", "lock"],+ ),+ DiffCheck(+ key="ruff-lint",+ label="Python lint (ruff check)",+ triggers=["*.py"],+ verify=["ruff", "check"],+ fix=["ruff", "check", "--fix"],+ takes_files=True,+ ),+ DiffCheck(+ key="ruff-format",+ label="Python format (ruff format)",+ triggers=["*.py"],+ verify=["ruff", "format", "--check"],+ fix=["ruff", "format"],+ takes_files=True,+ ),+ DiffCheck(+ key="markdown-format",+ label="markdown formatting (oxfmt)",+ triggers=["*.md", "*.mdx"],+ # Mirrors lint-staged's `format:markdown`, which agents bypass via --no-verify.+ # --no-error-on-unmatched-pattern: .oxfmtrc.json ignores whole trees (rust/,+ # fixtures, ...) and oxfmt exits 2 when every given file is ignored.+ verify=["pnpm", "exec", "oxfmt", "--check", "--no-error-on-unmatched-pattern"],+ fix=["hogli", "format:markdown"],+ requires=("node",),+ takes_files=True,+ ),+ DiffCheck(+ key="feature-flags",+ label="FEATURE_FLAGS not alphabetically sorted",+ triggers=["frontend/src/lib/constants.tsx"],+ verify=["hogli", "lint:feature-flags"],+ fix=["hogli", "lint:feature-flags:fix"],+ ),+ DiffCheck(+ key="workflow-lint",+ label="workflow-convention failure in .github/workflows",+ triggers=[".github/workflows/*.yml", ".github/workflows/*.yaml"],+ verify=["hogli", "lint:workflows"],+ ),+ DiffCheck(+ key="openapi",+ label="OpenAPI types out of date (frontend/MCP drift)",+ # From build.py so preflight and build:openapi can't drift on which diffs need a regen.+ triggers=list(BUILD_TRIGGERS["build:openapi"]),+ # Drift detection regenerates then diffs — needs the DB. Guidance-only here.+ verify=None,+ fix=["hogli", "build:openapi"],+ requires=("stack",),+ ),+ DiffCheck(+ key="migrations",+ label="migration conflict / orphaned migration",+ triggers=["*/migrations/*.py"],+ # migrations:check declares both postgresql and clickhouse services.+ verify=["hogli", "migrations:check"],+ requires=("stack", "clickhouse"),+ ),+]+++def _has_node_modules() -> bool:+ return (REPO_ROOT / "node_modules" / ".pnpm").exists()+++def _port_open(port: int) -> bool:+ try:+ with socket.create_connection(("localhost", port), timeout=0.3):+ return True+ except OSError:+ return False+++def _capability_met(req: Requirement) -> bool:+ if req == "node":+ return _has_node_modules()+ if req == "stack":+ # Postgres reachable — proxy for "dev stack is running".+ return _port_open(5432)+ return _port_open(8123) # ClickHouse HTTP+++def _unmet(chk: DiffCheck) -> list[Requirement]:+ return [req for req in chk.requires if not _capability_met(req)]+++Status = Literal["pass", "fail", "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+++def _run_diff_check(chk: DiffCheck, do_fix: bool) -> tuple[Status, str]:+ unmet = _unmet(chk)+ if do_fix and chk.fix is not None and not unmet:+ cmd = list(chk.fix)+ elif chk.verify is None:+ # Guidance-only (no runnable local check, or its fix needs an absent capability):+ # advise regardless, so the hint still shows on a bare checkout — even with --fix.+ return "advisory", f"run `{' '.join(chk.fix or [])}` and commit drift"+ elif unmet:+ return "skipped", f"needs {', '.join(unmet)}"+ else:+ cmd = list(chk.verify)+ 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()]+ if not present:+ return "skipped", "only deleted files"+ cmd += present+ if shutil.which(cmd[0]) is None:+ return "skipped", f"{cmd[0]} not found"+ try:+ result = subprocess.run(cmd, cwd=REPO_ROOT, capture_output=True, text=True, timeout=_CHECK_TIMEOUT_SECONDS)+ except subprocess.TimeoutExpired:+ return "fail", f"`{cmd[0]}` timed out after {_CHECK_TIMEOUT_SECONDS}s"+ if result.returncode == 0:+ return "pass", "fixed" if do_fix else "ok"+ lines = (result.stdout or result.stderr).strip().splitlines()+ return "fail", " · ".join(lines[:3]) if lines else f"exit {result.returncode}"+++# Branch-freshness backstop thresholds. The risk signals in ``_staleness_risks``+# are the primary advisory trigger; these are a secondary net for branches old+# enough that generic (undetected) drift is likely. Deliberately aggressive to+# start — master moves fast and we'd rather over-warn and tune down from+# telemetry than under-warn. Advisory only (never auto-merged). Env-tunable.+_MASTER_REF = "origin/master"+_STALE_COMMITS_DEFAULT = 5+_STALE_DAYS_DEFAULT = 2+_FETCH_TTL_SECONDS = 600 # skip re-fetching origin/master if refreshed this recently+++def _git_run(*args: str, timeout: float = 15.0) -> subprocess.CompletedProcess[str] | None:+ """Run a git command in the repo; None on OS error or timeout."""+ try:+ return subprocess.run(["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, timeout=timeout)+ except (OSError, subprocess.SubprocessError):+ return None+++def _git(*args: str, timeout: float = 5.0) -> str | None:+ """Like ``_git_run`` but collapses to trimmed stdout, None on any failure."""+ result = _git_run(*args, timeout=timeout)+ return result.stdout.strip() if result is not None and result.returncode == 0 else None+++def _fetch_marker() -> Path | None:+ """Our own TTL marker — FETCH_HEAD won't do, since fetching *any* ref touches it."""+ raw = _git("rev-parse", "--git-path", "hogli-preflight-fetched")+ if not raw:+ return None+ path = Path(raw)+ return path if path.is_absolute() else REPO_ROOT / raw+++def _fetch_master() -> None:+ """Refresh origin/master for an accurate diff base and behind-count, skipping the+ fetch if done recently (the agent loop reruns preflight often). Offline → keep+ the local ref."""+ marker = _fetch_marker()+ if marker is not None:+ try:+ if time.time() - marker.stat().st_mtime < _FETCH_TTL_SECONDS:+ return+ except OSError:+ pass+ if _git("fetch", "--quiet", "origin", "master", timeout=10.0) is not None and marker is not None:+ marker.touch()+++def _env_int(var: str, default: int) -> int:+ try:+ return int(os.environ.get(var, default))+ except ValueError:+ return default+++def _commit_age_days(ref: str) -> int | None:+ """Whole days since *ref* was committed — how long since the branch last held master's state."""+ iso = _git("show", "-s", "--format=%cI", ref)+ if not iso:+ return None+ try:+ when = datetime.fromisoformat(iso)+ except ValueError:+ return None+ return max(0, (datetime.now(when.tzinfo) - when).days)+++def _merge_conflicts() -> list[str] | None:+ """Files that would conflict if master were merged right now, computed without+ touching the working tree (``git merge-tree``, git >= 2.38). None = can't tell."""+ result = _git_run("merge-tree", "--write-tree", "--name-only", "HEAD", _MASTER_REF)+ if result is None or result.returncode not in (0, 1):+ return None+ # returncode 1 = conflicts; first output line is the merged tree OID.+ return [line for line in result.stdout.splitlines()[1:] if line] if result.returncode == 1 else []+++def _changed_on_master(merge_base: str) -> list[str]:+ result = _git_run("diff", "--name-only", "-z", f"{merge_base}..{_MASTER_REF}")+ if result is None or result.returncode != 0:+ return []+ return [path for path in result.stdout.split("\0") if path]+++_MIGRATION_GLOB = ["*/migrations/*.py"]+++def _staleness_risks(branch_files: list[str], master_files: list[str], conflicts: list[str] | None) -> list[str]:+ """Concrete ways merging master late will break this branch — each a failure+ class that recurs on unrebased PRs: textual conflicts, migration collisions,+ generated-file drift, and CI workflows changing underneath the branch."""+ risks: list[str] = []+ if conflicts:+ risks.append(f"merging master conflicts in {len(conflicts)} file(s) (e.g. {conflicts[0]})")+ branch_apps = {str(Path(f).parent) for f in branch_files if matches_globs(f, _MIGRATION_GLOB)}+ master_apps = {str(Path(f).parent) for f in master_files if matches_globs(f, _MIGRATION_GLOB)}+ collisions = sorted(branch_apps & master_apps)+ if collisions:+ risks.append(f"migrations added on both sides in {', '.join(collisions)}")+ drift = sorted(set(_match_commands(branch_files)) & set(_match_commands(master_files)))+ if drift:+ risks.append(f"master also changed {', '.join(drift)} inputs — regenerate after merging")+ workflows = sum(f.startswith(".github/workflows/") for f in master_files)+ if workflows:+ risks.append(f"CI workflows changed on master ({workflows} file(s))")+ return risks+++def _staleness(branch_files: list[str]) -> tuple[Status, str, dict[str, Any]]:+ """Whether merging master *now* would break this branch. Risk signals are the+ primary advisory trigger; a raw behind-count backstop also fires, aggressively+ by default. On squash-merge master, commits behind ≈ PRs merged.+ Returns (status, detail, telemetry props)."""+ merge_base = _git("merge-base", "HEAD", _MASTER_REF)+ if not merge_base:+ return "skipped", f"no merge-base with {_MASTER_REF}", {"stale": None}++ # Commits on master we don't have = how far behind; 0 means up to date.+ # A failed/timed-out count must not read as "even with master".+ count = _git("rev-list", "--count", f"{merge_base}..{_MASTER_REF}")+ if count is None or not count.isdigit():+ return "skipped", "could not count commits behind master", {"stale": None}+ behind = int(count)+ if behind == 0:+ return "pass", "even with master", {"stale": False, "behind_commits": 0, "branch_age_days": 0}++ age_days = _commit_age_days(merge_base) # merge-base age ≈ time since the branch last synced with master+ conflicts = _merge_conflicts()+ risks = _staleness_risks(branch_files, _changed_on_master(merge_base), conflicts)+ if behind >= _env_int("HOGLI_PREFLIGHT_STALE_COMMITS", _STALE_COMMITS_DEFAULT):+ risks.append(f"{behind} commits (≈ PRs) behind")+ elif age_days is not None and age_days >= _env_int("HOGLI_PREFLIGHT_STALE_DAYS", _STALE_DAYS_DEFAULT):+ risks.append(f"last synced {age_days}d ago")++ props: dict[str, Any] = {+ "stale": bool(risks),+ "behind_commits": behind,+ "branch_age_days": age_days,+ "merge_conflict_files": len(conflicts) if conflicts is not None else None,+ "staleness_risks": len(risks),+ }+ if risks:+ return "advisory", f"{' · '.join(risks)} — merge master in: git merge {_MASTER_REF}", props++ synced = f", synced {age_days}d ago" if age_days is not None else ""+ return "pass", f"{behind} commits behind master{synced} — no conflict or drift risk detected", props+++_ICON: dict[Status, str] = {"pass": "✓", "fail": "✗", "advisory": "→", "skipped": "·"}+_COLOR: dict[Status, str] = {"pass": "green", "fail": "red", "advisory": "yellow", "skipped": "bright_black"}+++def _emit_telemetry(summary: dict[str, Any]) -> None:+ """Emit ``ci_preflight_run`` to measure failures intercepted locally vs. what+ would reach CI. Gated on ``is_active()`` first so an opt-out/CI run doesn't fork+ the ``gh``/``git`` property hooks for an event ``track()`` would drop anyway."""+ if not telemetry.is_active():+ return+ keys = (+ "changed_files",+ "triggered",+ "failures",+ "advisories",+ "mode",+ "stale",+ "behind_commits",+ "branch_age_days",+ "merge_conflict_files",+ "staleness_risks",+ )+ props: dict[str, Any] = {k: summary[k] for k in keys if k in summary}+ props["results"] = {r["check"]: r["status"] for r in summary["results"]}+ # Registries are read directly by design (see hogli.hooks). Merge the same+ # dev-context props the command lifecycle attaches to command_completed+ # (incl. git_branch, so a run ties back to its PR).+ for hook in telemetry_property_hooks:+ try:+ props.update(hook("ci:preflight"))+ except Exception:+ pass+ telemetry.track("ci_preflight_run", props)+++ name="ci:preflight",+ help="Catch the deterministic CI failures reachable from your diff before you push.",+)[email protected]("--fix", "do_fix", is_flag=True, help="Auto-remediate what's safe instead of only reporting.")+ "--strict",+ is_flag=True,+ help="Exit non-zero on any failed check (advisories never block) — for the pre-push hook.",+)[email protected]("--against", default=None, help="Diff against this base ref instead of the branch default.")[email protected]("--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:+ if os.environ.get("HOGLI_PREFLIGHT_DISABLED", "").lower() in {"1", "true"}:+ disabled_summary: dict[str, Any] = {"mode": "disabled", "results": []}+ if as_json:+ click.echo(json.dumps(disabled_summary))+ else:+ click.secho(+ " ci:preflight disabled by operator (HOGLI_PREFLIGHT_DISABLED) — intentional; "+ "do not unset. Nothing to check, CI remains the gate.",+ fg="yellow",+ )+ _emit_telemetry(disabled_summary)+ 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()+ files = changed_files(against)+ base = against or "origin/master"++ triggered: list[DiffCheck] = []+ for chk in DIFF_CHECKS:+ chk.matched = [f for f in files if matches_globs(f, chk.triggers)]+ if chk.matched:+ triggered.append(chk)++ results: list[dict[str, Any]] = []+ failures = 0+ advisories = 0+ if not as_json:+ click.secho(f"\n ci:preflight — {len(files)} changed file(s) vs {base}\n", bold=True)++ # Always-on branch-health check, independent of which files changed: a stale+ # branch breaks CI on merge no matter what the diff touches. Advisory only —+ # it never counts toward `failures` (a merge is the human/agent's call).+ stale_status, stale_detail, stale_props = _staleness(files)+ results.append({"check": "staleness", "status": stale_status, "files": 0, "detail": stale_detail})+ if not as_json:+ click.secho(f" {_ICON[stale_status]} [staleness] branch freshness vs master", fg=_COLOR[stale_status])+ click.echo(f" {stale_detail}")++ for chk in triggered:+ status, detail = _run_diff_check(chk, do_fix)+ failures += status == "fail"+ advisories += status == "advisory"+ results.append({"check": chk.key, "status": status, "files": len(chk.matched), "detail": detail})+ if not as_json:+ click.secho(f" {_ICON[status]} [{chk.key}] {chk.label}", fg=_COLOR[status])+ click.echo(f" {len(chk.matched)} file(s) · {detail}")++ summary = {+ "changed_files": len(files),+ "triggered": [c.key for c in triggered],+ "failures": failures,+ "advisories": advisories,+ "mode": "fix" if do_fix else ("strict" if strict else "advisory"),+ "results": results,+ **stale_props,+ }+ if as_json:+ click.echo(json.dumps(summary))+ else:+ if not triggered:+ click.secho(" ✓ Nothing in this diff maps to a known CI failure class.", fg="green")+ click.echo()+ click.echo(+ f" summary {json.dumps({k: summary[k] for k in ('changed_files', 'triggered', 'failures', 'mode')})}"+ )+ click.echo()++ _emit_telemetry(summary)++ # Advisory by default — --strict turns verified *failures* into a non-zero exit+ # for the pre-push hook. Advisories never block: guidance-only checks can't tell+ # done from not-done, so blocking on them would false-block every matching push.+ # SystemExit so the telemetry wrapper records it.+ raise SystemExit(1 if (strict and failures) else 0)diff --git a/tools/hogli-commands/hogli_commands/telemetry_props.py b/tools/hogli-commands/hogli_commands/telemetry_props.pyindex 715129d48ab0..f979fc39d789 100644--- a/tools/hogli-commands/hogli_commands/telemetry_props.py+++ b/tools/hogli-commands/hogli_commands/telemetry_props.py@@ -113,6 +113,27 @@ def _repo_commit_properties() -> dict[str, str]:return {"repo_sha": commit[0], "repo_commit_date": commit[1]}+def _git_branch() -> str | None:+ """Current branch name — the join key from a hogli run back to its PR.++ "HEAD" (detached) and failures collapse to None so they don't pollute the+ dimension. Cached per process: hogli commands are short-lived, so the branch+ can't change mid-run.+ """+ try:+ result = subprocess.run(+ ["git", "-C", str(REPO_ROOT), "rev-parse", "--abbrev-ref", "HEAD"],+ capture_output=True,+ text=True,+ timeout=2,+ )+ except Exception:+ return None+ branch = result.stdout.strip()+ return branch if result.returncode == 0 and branch and branch != "HEAD" else None++def _infer_process_manager(command: str | None) -> str | None:pm = os.environ.get("HOGLI_PROCESS_MANAGER")if pm:@@ -182,6 +203,7 @@ def _posthog_telemetry_properties(command: str | None = None) -> dict[str, Any]:"is_worktree": (REPO_ROOT / ".git").is_file(),"is_posthog_dev": _is_posthog_dev(),"process_manager": _infer_process_manager(command),+ "git_branch": _git_branch(),**_repo_commit_properties(),}diff --git a/tools/hogli-commands/hogli_commands/test_runner.py b/tools/hogli-commands/hogli_commands/test_runner.pyindex e7b643a5bf81..131b915dbe9d 100644--- a/tools/hogli-commands/hogli_commands/test_runner.py+++ b/tools/hogli-commands/hogli_commands/test_runner.py@@ -18,6 +18,8 @@ import clickfrom hogli.command_types import _runfrom hogli.manifest import REPO_ROOT+from hogli_commands.change_detection import changed_files+_PYTHON_ROOTS = ("posthog/", "ee/", "products/", "common/", "dags/", "tools/", "services/")@@ -523,58 +525,21 @@ def detect_test_type(file_path: str) -> TestRunConfig:# ----------------------------------------------------------------------------def _parse_porcelain_path(line: str) -> str:- """Extract the file path from a ``git status --porcelain`` line.-- Handles renames/copies (``R old -> new``) by taking the destination,- and strips quotes that git adds for paths with special characters.- """- raw = line[3:]- # Renames/copies: "old -> new" — take the destination- if " -> " in raw:- raw = raw.split(" -> ", 1)[1]- # Git quotes paths containing special chars- return raw.strip().strip('"')--def _get_changed_files() -> list[str]:- """Get files changed on the current branch vs master, plus uncommitted changes."""+ """Files changed on the current branch vs master, plus uncommitted changes.++ ``--changed`` is meaningless on master, so guard that here; the diffing itself+ is delegated to the shared change-detection module."""branch = subprocess.run(["git", "branch", "--show-current"],cwd=REPO_ROOT,capture_output=True,text=True,).stdout.strip()-if branch == "master":raise click.UsageError("Cannot use --changed on the master branch.")-- # Files changed between master and HEAD- diff_vs_master = (- subprocess.run(- ["git", "diff", "--name-only", "master...HEAD"],- cwd=REPO_ROOT,- capture_output=True,- text=True,- )- .stdout.strip()- .splitlines()- )-- # Uncommitted / staged changes- porcelain = (- subprocess.run(- ["git", "status", "--porcelain"],- cwd=REPO_ROOT,- capture_output=True,- text=True,- )- .stdout.strip()- .splitlines()- )- uncommitted = [_parse_porcelain_path(line) for line in porcelain if len(line) > 3]-- return sorted(set(diff_vs_master + uncommitted))+ # Drop deleted/renamed-away paths — pytest errors on files that no longer exist.+ return [f for f in changed_files() if (REPO_ROOT / f).exists()]def _detect_all(test_files: list[str]) -> list[tuple[str, TestRunConfig]]:diff --git a/tools/hogli-commands/hogli_commands/tests/test_build.py b/tools/hogli-commands/hogli_commands/tests/test_build.pyindex e128b0c9cb96..f48255a42d4c 100644--- a/tools/hogli-commands/hogli_commands/tests/test_build.py+++ b/tools/hogli-commands/hogli_commands/tests/test_build.py@@ -7,7 +7,7 @@ from unittest.mock import MagicMock, patchfrom click.testing import CliRunnerfrom hogli.cli import cli-from hogli_commands.build import TRIGGERS, _get_changed_files, _match_commands+from hogli_commands.build import TRIGGERS, _match_commandsrunner = CliRunner()@@ -62,36 +62,6 @@ class TestTriggerMatching:assert _match_commands(set()) == []-class TestGetChangedFiles:- @patch("hogli_commands.build.subprocess.check_output")- def test_combines_branch_and_working_tree(self, mock_output: MagicMock) -> None:- mock_output.side_effect = [- "abc123\n", # merge-base- "file_branch.py\n", # branch diff- " M file_modified.py\nA file_staged.py\n?? file_untracked.py\n", # status --porcelain- ]- result = _get_changed_files()- assert result == {"file_branch.py", "file_modified.py", "file_staged.py", "file_untracked.py"}-- @patch("hogli_commands.build.subprocess.check_output")- def test_deduplicates_files(self, mock_output: MagicMock) -> None:- mock_output.side_effect = [- "abc123\n",- "same_file.py\n",- "M same_file.py\n", # same file in working tree- ]- result = _get_changed_files()- assert result == {"same_file.py"}-- @patch("hogli_commands.build.subprocess.check_output")- def test_handles_all_git_failures_gracefully(self, mock_output: MagicMock) -> None:- from subprocess import CalledProcessError-- mock_output.side_effect = CalledProcessError(1, "git")- result = _get_changed_files()- assert result == set()--class TestBuildCommand:def test_list_shows_all_commands(self) -> None:result = runner.invoke(cli, ["build", "--list"])@@ -99,14 +69,14 @@ class TestBuildCommand:for cmd in TRIGGERS:assert cmd in result.output- @patch("hogli_commands.build._get_changed_files")+ @patch("hogli_commands.build.changed_files")def test_no_changes_exits_cleanly(self, mock_changed: MagicMock) -> None:mock_changed.return_value = set()result = runner.invoke(cli, ["build"])assert result.exit_code == 0assert "Nothing to rebuild" in result.output- @patch("hogli_commands.build._get_changed_files")+ @patch("hogli_commands.build.changed_files")def test_unrelated_changes_exits_cleanly(self, mock_changed: MagicMock) -> None:mock_changed.return_value = {"README.md", "docs/foo.md"}result = runner.invoke(cli, ["build"])@@ -121,7 +91,7 @@ class TestBuildCommand:],)@patch("hogli_commands.build.subprocess.run")- @patch("hogli_commands.build._get_changed_files")+ @patch("hogli_commands.build.changed_files")def test_smart_mode_runs_single_matching_pipeline(self, mock_changed: MagicMock, mock_run: MagicMock, changed_file: str, expected_command: str) -> None:@@ -140,7 +110,7 @@ class TestBuildCommand:assert mock_run.call_count == len(TRIGGERS)@patch("hogli_commands.build.subprocess.run")- @patch("hogli_commands.build._get_changed_files")+ @patch("hogli_commands.build.changed_files")def test_dry_run_does_not_execute(self, mock_changed: MagicMock, mock_run: MagicMock) -> None:mock_changed.return_value = {"posthog/api/views.py"}result = runner.invoke(cli, ["build", "--dry-run"])diff --git a/tools/hogli-commands/hogli_commands/tests/test_change_detection.py b/tools/hogli-commands/hogli_commands/tests/test_change_detection.pynew file mode 100644index 000000000000..723fce8caa6f--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_change_detection.py@@ -0,0 +1,86 @@+from __future__ import annotations++import pytest+from unittest.mock import MagicMock, patch++import click+from hogli_commands.change_detection import changed_files, matches_globs+++def _completed(stdout: str = "", returncode: int = 0, stderr: str = "") -> MagicMock:+ return MagicMock(stdout=stdout, stderr=stderr, returncode=returncode)+++class TestChangedFiles:+ @patch("hogli_commands.change_detection.subprocess.run")+ def test_combines_branch_diff_and_working_tree(self, mock_run: MagicMock) -> None:+ mock_run.side_effect = [+ _completed(stdout="file_branch.py\0"),+ _completed(stdout=" M file_modified.py\0A file_staged.py\0?? file_untracked.py\0"),+ ]+ assert changed_files() == ["file_branch.py", "file_modified.py", "file_staged.py", "file_untracked.py"]++ @patch("hogli_commands.change_detection.subprocess.run")+ def test_deduplicates_across_diff_and_working_tree(self, mock_run: MagicMock) -> None:+ mock_run.side_effect = [_completed(stdout="same_file.py\0"), _completed(stdout="M same_file.py\0")]+ assert changed_files() == ["same_file.py"]++ @patch("hogli_commands.change_detection.subprocess.run")+ def test_paths_with_spaces_stay_unquoted(self, mock_run: MagicMock) -> None:+ mock_run.side_effect = [+ _completed(stdout="posthog/migrations/0067_table copy.py\0"),+ _completed(stdout=" M docs/a b.md\0"),+ ]+ assert changed_files() == ["docs/a b.md", "posthog/migrations/0067_table copy.py"]++ @patch("hogli_commands.change_detection.subprocess.run")+ def test_default_base_falls_back_to_local_master(self, mock_run: MagicMock) -> None:+ mock_run.side_effect = [+ _completed(returncode=128, stderr="fatal: bad revision 'origin/master...HEAD'"),+ _completed(stdout="file_branch.py\0"),+ _completed(stdout=""),+ ]+ assert changed_files() == ["file_branch.py"]++ @patch("hogli_commands.change_detection.subprocess.run")+ def test_no_base_ref_degrades_to_working_tree_only(self, mock_run: MagicMock) -> None:+ mock_run.side_effect = [+ _completed(returncode=128, stderr="fatal: bad revision"),+ _completed(returncode=128, stderr="fatal: bad revision"),+ _completed(stdout="?? sandbox_edit.py\0"),+ ]+ assert changed_files() == ["sandbox_edit.py"]++ @patch("hogli_commands.change_detection.subprocess.run")+ def test_explicit_bad_ref_raises_instead_of_reporting_clean(self, mock_run: MagicMock) -> None:+ mock_run.return_value = _completed(returncode=128, stderr="fatal: bad revision 'orgin/master'")+ with pytest.raises(click.UsageError):+ changed_files("orgin/master")++ @patch("hogli_commands.change_detection.subprocess.run")+ def test_status_failure_raises_instead_of_dropping_uncommitted_work(self, mock_run: MagicMock) -> None:+ mock_run.side_effect = [+ _completed(stdout="file_branch.py\0"),+ _completed(returncode=128, stderr="fatal: Unable to create index.lock"),+ ]+ with pytest.raises(click.UsageError):+ changed_files()+++class TestMatchesGlobs:+ @pytest.mark.parametrize(+ "path,globs,expected",+ [+ ("posthog/api/insight.py", ["posthog/api/*"], True),+ ("posthog/api/dashboards/dashboard.py", ["posthog/api/*"], True),+ ("posthog/models/team.py", ["posthog/api/*"], False),+ ("tools/a/b.py", ["*.py"], True),+ ("notes.md", ["*.py"], False),+ ("posthog/migrations/0001_x.py", ["*/migrations/*.py"], True),+ ("pnpm-workspace.yaml", ["pnpm-workspace.yaml"], True),+ ("patches/[email protected]", ["patches/*"], True),+ ("x.py", [], False),+ ],+ )+ def test_matches(self, path: str, globs: list[str], expected: bool) -> None:+ assert matches_globs(path, globs) is expecteddiff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.pynew file mode 100644index 000000000000..d0b8a36a4333--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py@@ -0,0 +1,110 @@+from __future__ import annotations++import json++import pytest+from unittest.mock import MagicMock, patch++from click.testing import CliRunner+from hogli.cli import cli+from hogli_commands.ci_preflight import _staleness_risks++runner = CliRunner()+++class TestKillSwitch:+ @patch("hogli_commands.ci_preflight._emit_telemetry")+ @patch("hogli_commands.ci_preflight.changed_files")+ def test_short_circuits_before_any_git_work(self, mock_changed: MagicMock, mock_emit: MagicMock) -> None:+ result = runner.invoke(cli, ["ci:preflight"], env={"HOGLI_PREFLIGHT_DISABLED": "1"})+ assert result.exit_code == 0+ assert "disabled" in result.output+ mock_changed.assert_not_called()+ assert mock_emit.call_args[0][0]["mode"] == "disabled"++ @patch("hogli_commands.ci_preflight._emit_telemetry")+ @patch("hogli_commands.ci_preflight.changed_files")+ def test_json_output_stays_parseable(self, mock_changed: MagicMock, mock_emit: MagicMock) -> None:+ result = runner.invoke(cli, ["ci:preflight", "--json"], env={"HOGLI_PREFLIGHT_DISABLED": "1"})+ assert result.exit_code == 0+ assert json.loads(result.output)["mode"] == "disabled"+ mock_changed.assert_not_called()+++class TestStrictAndFixContracts:+ @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=["posthog/api/does_not_exist.py"])+ def test_strict_never_blocks_on_advisory(+ self, mock_changed: MagicMock, mock_fetch: MagicMock, mock_stale: MagicMock, mock_emit: MagicMock+ ) -> None:+ result = runner.invoke(cli, ["ci:preflight", "--strict"])+ assert "build:openapi" in result.output+ assert result.exit_code == 0++ @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.shutil.which", return_value="/usr/bin/hogli")+ @patch("hogli_commands.ci_preflight.subprocess.run")+ @patch("hogli_commands.ci_preflight.changed_files", return_value=[".github/workflows/ci-foo.yml"])+ def test_strict_exits_nonzero_on_failure(+ self,+ mock_changed: MagicMock,+ mock_run: MagicMock,+ mock_which: MagicMock,+ mock_fetch: MagicMock,+ mock_stale: MagicMock,+ mock_emit: MagicMock,+ ) -> None:+ mock_run.return_value = MagicMock(returncode=1, stdout="workflow convention violated", stderr="")+ result = runner.invoke(cli, ["ci:preflight", "--strict"])+ assert result.exit_code == 1++ @patch("hogli_commands.ci_preflight._emit_telemetry")+ @patch("hogli_commands.ci_preflight._capability_met", return_value=False)+ @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=["posthog/api/does_not_exist.py"])+ def test_fix_without_stack_still_advises_openapi(+ self,+ mock_changed: MagicMock,+ mock_fetch: MagicMock,+ mock_stale: MagicMock,+ mock_capability: MagicMock,+ mock_emit: MagicMock,+ ) -> None:+ result = runner.invoke(cli, ["ci:preflight", "--fix"])+ assert result.exit_code == 0+ assert "run `hogli build:openapi` and commit drift" in result.output+++class TestStalenessRisks:+ @pytest.mark.parametrize(+ "branch_files,master_files,conflicts,expected_fragments",+ [+ (["posthog/models/team.py"], ["frontend/src/lib/utils.tsx"], [], []),+ (["posthog/models/team.py"], ["frontend/src/lib/utils.tsx"], None, []),+ (["a.py"], ["b.py"], ["posthog/api/insight.py"], ["conflicts in 1 file"]),+ (+ ["posthog/migrations/0700_ours.py"],+ ["posthog/migrations/0700_theirs.py"],+ [],+ ["migrations added on both sides in posthog/migrations"],+ ),+ (["posthog/api/ours.py"], ["posthog/api/theirs.py"], [], ["master also changed build:openapi"]),+ (["a.py"], [".github/workflows/ci-backend.yml"], [], ["CI workflows changed on master (1 file(s))"]),+ ],+ )+ def test_risk_derivation(+ self,+ branch_files: list[str],+ master_files: list[str],+ conflicts: list[str] | None,+ expected_fragments: list[str],+ ) -> None:+ risks = _staleness_risks(branch_files, master_files, conflicts)+ assert len(risks) == len(expected_fragments)+ for fragment, risk in zip(expected_fragments, risks):+ assert fragment in riskdiff --git a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py b/tools/hogli-commands/hogli_commands/tests/test_test_runner.pyindex 87ebe6d7ec53..c676f45cf323 100644--- a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py+++ b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py@@ -14,8 +14,8 @@ from hogli_commands.test_runner import (_batch_find_rs_cfg_test,_detect_all,_find_test_files_for_source,+ _get_changed_files,_is_test_file,- _parse_porcelain_path,_resolve_to_repo_relative,_run_changed,_run_grouped,@@ -335,20 +335,16 @@ class TestIsTestFile:assert not _is_test_file("rust/capture/src/api.rs", rs_cfg_test=set())-class TestParsePorcelainPath:- @parameterized.expand(- [- (" M posthog/api/views.py", "posthog/api/views.py"),- ("?? posthog/new_file.py", "posthog/new_file.py"),- ("A posthog/added.py", "posthog/added.py"),- ("R old/test_foo.py -> new/test_foo.py", "new/test_foo.py"),- ("C src/a.py -> src/b.py", "src/b.py"),- (' M "path with spaces/test_foo.py"', "path with spaces/test_foo.py"),- ('R "old name.py" -> "new name.py"', "new name.py"),+class TestGetChangedFiles:+ @patch("hogli_commands.test_runner.changed_files")+ @patch("hogli_commands.test_runner.subprocess.run")+ def test_drops_paths_missing_from_disk(self, mock_run: MagicMock, mock_changed: MagicMock) -> None:+ mock_run.return_value = MagicMock(stdout="feature-branch\n")+ mock_changed.return_value = [+ "tools/hogli-commands/hogli_commands/test_runner.py",+ "renamed_away/test_gone.py",]- )- def test_parse_porcelain_path(self, line: str, expected: str) -> None:- assert _parse_porcelain_path(line) == expected+ assert _get_changed_files() == ["tools/hogli-commands/hogli_commands/test_runner.py"]class TestFindTestFilesForSource: