: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(ci): lint required-check gate hygiene (#72393)
Raúl Negrón-Otero7673382a535f
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.mdindex 35b9e77f853c..3c21d647a49e 100644--- a/.agents/skills/authoring-ci-workflows/SKILL.md+++ b/.agents/skills/authoring-ci-workflows/SKILL.md@@ -26,7 +26,7 @@ The linters own the mechanical rules (below); this skill is the **judgment calls## What the linters already enforceRun `bin/hogli lint:workflows` and `actionlint` before pushing — they gate CI, and they (not this list) are the source of truth for what's enforced.-Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).+Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, required-check gate hygiene, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).Third-party action digests are bumped by Renovate.## The dispatch budget (500 runs / 10s / repo)@@ -83,6 +83,42 @@ concurrency:group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.head_ref || github.ref }}```+## Required-check gates++The "gate" is the collate job that emits the required status check by reading `needs.*.result`.+By convention its display name ends in `Pass` (`Django Tests Pass`, `Visual regression tests pass`), but `WF007` also finds gates structurally when a step reads `needs.<dep>.result`, because the convention is not universally followed.+A job that inspects results without gating anything opts out with `# hogli-lint: not-a-required-gate — <reason>` above the job key.+Gates and the workers they inspect need **opposite** conditions:++| Job | Condition | Why |+| ------- | ------------------ | ----------------------------------------------------------------------------- |+| Gate | `if: always()` | It must run and emit an explicit verdict, even when everything upstream died. |+| Workers | `if: !cancelled()` | So a superseded run actually stops instead of holding the concurrency slot. |++The gate condition must be exactly `always()`, with optional `${{ }}` wrapping.+Adding another predicate can skip the required check, so `always() && <condition>` is rejected.++`!cancelled()` is identical to `always()` on any run that is not cancelled, so failure-path reporting still works; only cancelled runs skip.+Measured on a live superseded run ([evidence](https://github.com/PostHog/posthog/actions/runs/29765284128)): an `always()` worker dispatched and ran to completion _after_ the cancel, while the `!cancelled()` worker never started and reported `cancelled` (not `skipped`), so the gate still fails closed.++Four rules for the gate body:++1. **Allowlist every dependency, never denylist.** Assert `success`/`skipped` and fail everything else.+ A dependency tested only against `== 'failure'` lets `cancelled` through, and one bad dependency is enough — a gate that clears four correctly and one with a bare `failure` test is still wrong.+ The trap is the `changes` detector: clearing it with `== 'failure'` and then reading `needs.changes.outputs.*` reports green on cancellation, because those outputs are empty and the gate takes its "nothing to test" exit.+2. **`needs` every job that produces coverage.**+ If a job's failure would only cascade into a downstream job being _skipped_, the gate reads that as a pass and you get a green check with zero tests run.+ Name the upstream job explicitly.+3. **Legitimate skips must still pass.** A frontend-only PR skips backend jobs by design.+4. **Every dependency's result must reach a fail-closed allowlist guard.**+ One inline `if` per dependency is the clearest form, but a shared shell helper or an `env:` block is equally fine: `WF007` traces each result through assignments, `${!var}` indirection, and helper argument positions within that step.+ The guard must compare with `!=`, join multiple allowed values with `&&`, and unconditionally `exit 1` when entered.+ Comparisons in another step, comments, logs, or branches that do not exit nonzero prove nothing and are rejected.+ A result whose guard `WF007` cannot follow is reported rather than assumed safe, so an unusual routing may need the checks moved inline.++`WF007` enforces 1, 4, and the `always()` condition, and it takes the dependency list from `needs:` as well as the step body, so a job you wired into `needs:` and then forgot to test is reported rather than silently trusted.+The half of rule 2 it cannot check is whether you named the right jobs in `needs:` to begin with: "reporting job" and "coverage job" look identical to a linter, so that one is on you and the reviewer.+## Checkout / clone — shallow by defaultFull clones are slow and hang on degraded runners; blobs dominate clone size and are lazily fetchable.diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 43fbcbbbd0b1..ffc14d5db4b4 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -552,6 +552,7 @@ jobs:# trusted on a draft (legacy graph impact, turbo-discover or selector failure,# a selector full-run signal), the draft skips the heavy matrices entirely —# the pre-selection draft behavior — and defers to the ready full run.+ # hogli-lint: not-a-required-gate - selects draft coverage and emits no required check.## Depot shadow note: canonical uploads /tmp/selection.json for its# test-selection-verdict job. The depot shadow strips that job (and all@@ -2089,17 +2090,10 @@ jobs:local label="$1"local result="$2"- if [[ "$result" == "success" || "$result" == "skipped" ]]; then- return+ if [[ "$result" != "success" && "$result" != "skipped" ]]; then+ echo "::error::$label did not succeed (result: '$result')."+ exit 1fi-- if [[ "$result" == "cancelled" ]]; then- echo "::error::$label was cancelled or timed out."- else- echo "::error::$label failed with result '$result'."- fi-- exit 1}# Upstream jobs whose failure would otherwise only cascade into djangodiff --git a/.github/workflows/cd-sandbox-base-image.yml b/.github/workflows/cd-sandbox-base-image.ymlindex 8794fadbda4c..1111855c4032 100644--- a/.github/workflows/cd-sandbox-base-image.yml+++ b/.github/workflows/cd-sandbox-base-image.yml@@ -293,9 +293,9 @@ jobs:steps:- name: Check all sandbox image jobsrun: |- # Fail if change detection itself failed- if [[ "${{ needs.changes.result }}" == "failure" ]]; then- echo "Change detection job failed."+ # Fail if change detection failed or was cancelled (both build jobs skip then, so the exit below would report green).+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ echo "Change detection did not succeed (result: ${{ needs.changes.result }})."exit 1fidiff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 25cb21ca3394..5e4209b591d4 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -510,6 +510,7 @@ jobs:# trusted on a draft (legacy graph impact, turbo-discover or selector failure,# a selector full-run signal), the draft skips the heavy matrices entirely —# the pre-selection draft behavior — and defers to the ready full run.+ # hogli-lint: not-a-required-gate - selects draft coverage and emits no required check.select-tests:name: Select testsneeds: [changes, turbo-discover]@@ -3421,44 +3422,22 @@ jobs:print(f"::error {loc}title={title}::{body}")PY- deterministic_failure=false- failed=false-if [[ "${{ needs.repo-checks.outputs.deterministic_failure }}" == "true" ]]; thenecho "::error title=Repo checks failed deterministically::Open the repo checks job for the root failure. Backend CI cancelled downstream jobs to save runners; retrying will not fix this."- deterministic_failure=truefiif [[ "${{ needs.check-openapi-types.outputs.deterministic_failure }}" == "true" ]]; thenecho "::error title=OpenAPI type checks failed deterministically::Open the OpenAPI type check job for the root failure. Backend CI cancelled downstream jobs to save runners; retrying will not fix this."- deterministic_failure=truefi- # cancel_ok tolerates a bare 'cancelled' result (the optional snapshot commit job);- # required jobs treat an unexpected cancel as a failure.check_required_result() {local label="$1"local result="$2"- local cancel_ok="${3:-false}"-- if [[ "$result" == "success" || "$result" == "skipped" ]]; then- return- fi- if [[ "$result" == "cancelled" ]]; then- if [[ "$deterministic_failure" == "true" ]]; then- echo "::notice::$label was cancelled after a deterministic failure."- return- fi- if [[ "$cancel_ok" == "true" ]]; then- return- fi- echo "::error::$label was cancelled or timed out."- else- echo "::error::$label failed with result '$result'."+ if [[ "$result" != "success" && "$result" != "skipped" ]]; then+ echo "::error::$label did not succeed (result: '$result')."+ exit 1fi-- failed=true}check_required_result "Repo checks" "${{ needs.repo-checks.result }}"@@ -3475,11 +3454,7 @@ jobs:check_required_result "Turbo discover" "${{ needs.turbo-discover.result }}"check_required_result "Product test matrix build" "${{ needs.build-product-test-matrix.result }}"check_required_result "Product/Turbo tests" "${{ needs.turbo-tests.result }}"- check_required_result "Snapshot commit job" "${{ needs.handle-snapshots.result }}" true-- if [[ "$deterministic_failure" == "true" || "$failed" == "true" ]]; then- exit 1- fi+ check_required_result "Snapshot commit job" "${{ needs.handle-snapshots.result }}"echo "All backend and product checks passed."diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.ymlindex eaab056c5919..00c7359e91aa 100644--- a/.github/workflows/ci-e2e-playwright.yml+++ b/.github/workflows/ci-e2e-playwright.yml@@ -1044,6 +1044,7 @@ jobs:echo "Skipping Playwright section — script not present on this checkout"fi+ # hogli-lint: not-a-required-gate - records telemetry and emits no required check.capture-run-time:name: Capture run timeruns-on: ubuntu-latestdiff --git a/.github/workflows/ci-mcp-ui-apps.yml b/.github/workflows/ci-mcp-ui-apps.ymlindex 29e824fc12eb..3ba47b405c98 100644--- a/.github/workflows/ci-mcp-ui-apps.yml+++ b/.github/workflows/ci-mcp-ui-apps.yml@@ -132,8 +132,9 @@ jobs:steps:- name: Check resultsrun: |- if [[ "${{ needs.changes.result }}" == "failure" ]]; then- echo "Change detection job failed."+ # Block cancelled too: outputs are empty then, so the exit below would report green.+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ echo "Change detection did not succeed (result: ${{ needs.changes.result }})."exit 1fidiff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.ymlindex bb97913692f0..7892c40cf9f0 100644--- a/.github/workflows/ci-mcp.yml+++ b/.github/workflows/ci-mcp.yml@@ -723,9 +723,9 @@ jobs:steps:- name: Check all MCP jobsrun: |- # Fail if change detection itself failed- if [[ "${{ needs.changes.result }}" == "failure" ]]; then- echo "Change detection job failed."+ # Fail if change detection failed or was cancelled (outputs are empty on cancel, so the exit below would report green).+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ echo "Change detection did not succeed (result: ${{ needs.changes.result }})."exit 1fi@@ -735,23 +735,23 @@ jobs:exit 0fi- if [[ "${{ needs.build.result }}" == "failure" ]]; then- echo "MCP build failed."+ if [[ "${{ needs.build.result }}" != "success" && "${{ needs.build.result }}" != "skipped" ]]; then+ echo "MCP build did not succeed (result: ${{ needs.build.result }})."exit 1fi- if [[ "${{ needs.unit-tests.result }}" == "failure" ]]; then- echo "MCP unit tests failed."+ if [[ "${{ needs.unit-tests.result }}" != "success" && "${{ needs.unit-tests.result }}" != "skipped" ]]; then+ echo "MCP unit tests did not succeed (result: ${{ needs.unit-tests.result }})."exit 1fi- if [[ "${{ needs.integration-tests.result }}" == "failure" ]]; then- echo "MCP integration tests failed."+ if [[ "${{ needs.integration-tests.result }}" != "success" && "${{ needs.integration-tests.result }}" != "skipped" ]]; then+ echo "MCP integration tests did not succeed (result: ${{ needs.integration-tests.result }})."exit 1fi- if [[ "${{ needs.handle-snapshots.result }}" == "failure" ]]; then- echo "MCP snapshot commit job failed."+ if [[ "${{ needs.handle-snapshots.result }}" != "success" && "${{ needs.handle-snapshots.result }}" != "skipped" ]]; then+ echo "MCP snapshot commit job did not succeed (result: ${{ needs.handle-snapshots.result }})."exit 1fidiff --git a/.github/workflows/ci-oauth-proxy.yml b/.github/workflows/ci-oauth-proxy.ymlindex bf9426483c31..520ca9cb89f3 100644--- a/.github/workflows/ci-oauth-proxy.yml+++ b/.github/workflows/ci-oauth-proxy.yml@@ -69,8 +69,9 @@ jobs:steps:- name: Check all oauth-proxy jobsrun: |- if [[ "${{ needs.changes.result }}" == "failure" ]]; then- echo "Change detection job failed."+ # Fail if change detection failed or was cancelled (outputs are empty on cancel, so the exit below would report green).+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ echo "Change detection did not succeed (result: ${{ needs.changes.result }})."exit 1fidiff --git a/.github/workflows/ci-proto.yml b/.github/workflows/ci-proto.ymlindex 01ebba3f00ac..b5f80833f89c 100644--- a/.github/workflows/ci-proto.yml+++ b/.github/workflows/ci-proto.yml@@ -127,8 +127,9 @@ jobs:steps:- name: Check all proto jobsrun: |- if [[ "${{ needs.changes.result }}" == "failure" ]]; then- echo "Change detection job failed."+ # Fail if change detection failed or was cancelled (outputs are empty on cancel, so the exit below would report green).+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ echo "Change detection did not succeed (result: ${{ needs.changes.result }})."exit 1fidiff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex cc3dd5fd1869..be85395cf7af 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -265,9 +265,9 @@ jobs:steps:- name: Check Python CI statusrun: |- # Fail if change detection itself failed- if [[ "${{ needs.changes.result }}" == "failure" ]]; then- echo "Change detection job failed."+ # Block cancelled too: outputs are empty then, so the exit below would report green.+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ echo "Change detection did not succeed (result: ${{ needs.changes.result }})."exit 1fidiff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 8be4a491b6b2..0de4e371679f 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -753,9 +753,9 @@ jobs:steps:- name: Check all Rust jobsrun: |- # Fail if change detection or affected computation failed- if [[ "${{ needs.changes.result }}" == "failure" ]]; then- echo "Change detection job failed."+ # Fail if change detection failed, affected computation failed, or either was cancelled (outputs are empty on cancel, so the exit below would report green).+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ echo "Change detection did not succeed (result: ${{ needs.changes.result }})."exit 1fi@@ -765,8 +765,8 @@ jobs:exit 0fi- if [[ "${{ needs.affected.result }}" == "failure" ]]; then- echo "Affected crate computation failed."+ if [[ "${{ needs.affected.result }}" != "success" && "${{ needs.affected.result }}" != "skipped" ]]; then+ echo "Affected crate computation did not succeed (result: ${{ needs.affected.result }})."exit 1fidiff --git a/.github/workflows/pr-approval-agent.yml b/.github/workflows/pr-approval-agent.ymlindex a7807dabe452..8f328124f189 100644--- a/.github/workflows/pr-approval-agent.yml+++ b/.github/workflows/pr-approval-agent.yml@@ -321,6 +321,8 @@ jobs:gh pr comment "$PR" --repo "$REPO" \--body "Retaining stamphog approval — delta since last review classified as \`$REASON\`."+ # hogli-lint: not-a-required-gate — branches on decide-delta's result to decide+ # whether to dismiss a stale approval; it emits no required status check.dismiss:needs: decide-delta# Fail closed on three cases:diff --git a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.pyindex 3741d53d926a..7ee7a0dd6935 100644--- a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py@@ -26,6 +26,7 @@ from hogli_commands.workflow_lint.checks.checkout_full_depth import CheckoutFullfrom hogli_commands.workflow_lint.checks.dorny_negation import DornyNegationCheckfrom hogli_commands.workflow_lint.checks.job_timeouts import JobTimeoutsCheckfrom hogli_commands.workflow_lint.checks.pr_concurrency import PrConcurrencyCheck+from hogli_commands.workflow_lint.checks.required_gates import RequiredGateCheckfrom hogli_commands.workflow_lint.checks.semgrep_services_coverage import SemgrepServicesCoverageCheckfrom hogli_commands.workflow_lint.model import PR_TRIGGERS, Workflow, WorkflowParseError, read_workflows@@ -875,6 +876,374 @@ class TestRegistry:assert isinstance(result, CheckResult)+# The shape these fixtures guard against: a `changes` detector cleared with a bare+# `== "failure"`, then its outputs read to decide "nothing to test". Those outputs+# are empty on a cancelled job, so the gate exits 0 green with no tests run.+def _gate(body: str, condition: str = "always()") -> str:+ return f"""+ name: ci-thing+ on: pull_request+ jobs:+ changes:+ timeout-minutes: 5+ steps:+ - run: echo detect+ build:+ timeout-minutes: 5+ steps:+ - run: echo build+ thing_tests:+ name: Thing Tests Pass+ needs: [changes, build]+ timeout-minutes: 5+ if: {condition}+ steps:+ - run: |+{textwrap.indent(textwrap.dedent(body).strip(), " " * 14)}+"""+++SAFE_BODY = """+ if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then+ exit 1+ fi+ if [[ "${{ needs.changes.outputs.thing }}" != "true" ]]; then+ exit 0+ fi+ if [[ "${{ needs.build.result }}" != "success" && "${{ needs.build.result }}" != "skipped" ]]; then+ exit 1+ fi+"""++# One dependency allowlisted, one denylisted — the shape a global scan for+# result words calls clean.+MIXED_BODY = SAFE_BODY.replace(+ """if [[ "${{ needs.changes.result }}" != "success" && "${{ needs.changes.result }}" != "skipped" ]]; then""",+ """if [[ "${{ needs.changes.result }}" == "failure" ]]; then""",+)++# Two dependencies denylisted while the rest are allowlisted.+TWO_BAD_BODY = MIXED_BODY.replace(+ """if [[ "${{ needs.changes.outputs.thing }}" != "true" ]]; then""",+ """if [[ "${{ needs.affected.result }}" == "failure" ]]; then+ exit 1+ fi+ if [[ "${{ needs.changes.outputs.thing }}" != "true" ]]; then""",+)++# Some gates route every result through one shell function, so no guard sits+# next to `needs.<dep>.result`.+HELPER_BODY = """+ check() {+ if [[ "$2" != "success" && "$2" != "skipped" ]]; then+ exit 1+ fi+ }+ check "Changes" "${{ needs.changes.result }}"+ check "Build" "${{ needs.build.result }}"+"""++UNSAFE_HELPER_BODY = HELPER_BODY.replace(+ """if [[ "$2" != "success" && "$2" != "skipped" ]]; then""",+ """if [[ "$2" == "failure" ]]; then""",+)++# The positional is bound to a local before being tested, so the trace has to+# follow the assignment as well as the call site to reach the guard.+LOCAL_ALIAS_HELPER_BODY = """+ check() {+ local result="$2"+ if [[ "$result" != "success" && "$result" != "skipped" ]]; then+ exit 1+ fi+ }+ check "Changes" "${{ needs.changes.result }}"+ check "Build" "${{ needs.build.result }}"+"""++# Guard-shaped text in a comment or log line asserts nothing. The only executed+# test in these fixtures still clears everything but `failure`.+DECOY_COMMENT_BODY = UNSAFE_HELPER_BODY.replace(+ """ check() {""",+ """ check() {+ # if [[ "$2" != "success" && "$2" != "skipped" ]]; then exit 1; fi""",+)++DECOY_ECHO_BODY = UNSAFE_HELPER_BODY.replace(+ """ exit 1""",+ """ echo 'if [[ "$2" != "success" && "$2" != "skipped" ]]; then exit 1; fi'+ exit 1""",+)++NON_FAILING_ALLOWLIST_BODY = """+ check() {+ if [[ "$2" != "success" && "$2" != "skipped" ]]; then+ echo "dependency did not succeed"+ fi+ }+ check "Changes" "${{ needs.changes.result }}"+ check "Build" "${{ needs.build.result }}"+"""++INVERTED_ALLOWLIST_BODY = """+ check() {+ if [[ "$2" == "success" ]]; then+ exit 1+ fi+ }+ check "Changes" "${{ needs.changes.result }}"+ check "Build" "${{ needs.build.result }}"+"""++# Results that are only ever logged reach no comparison at all, which has to fail+# closed: the absence of a test is not evidence of a safe one.+LOGGED_ONLY_BODY = """+ echo "changes: ${{ needs.changes.result }}"+ echo "build: ${{ needs.build.result }}"+"""++BUILD_CALL = """ check "Build" "${{ needs.build.result }}\""""++# Helper calls whose trailing comment or label contains `()`. Discarding those lines+# loses the argument binding, which reports a gate that does allowlist its results.+COMMENTED_CALL_BODY = HELPER_BODY.replace(BUILD_CALL, f"{BUILD_CALL} # see check() above")+PAREN_LABEL_CALL_BODY = HELPER_BODY.replace(BUILD_CALL, """ check "Build ()" "${{ needs.build.result }}\"""")++# A job wired into `needs:` that the gate never tests. Judging only the results the+# body mentions would approve the two assertions that are here and say nothing+# about the dependency whose assertion was forgotten.+UNTESTED_DEPENDENCY_GATE = (+ _gate(SAFE_BODY)+ .replace(+ " build:",+ " lint:\n timeout-minutes: 5\n steps:\n - run: echo lint\n build:",+ )+ .replace("needs: [changes, build]", "needs: [changes, build, lint]")+)++# The env-loop form maps results into env and loops over the variable names.+ENV_LOOP_GATE = """+ name: ci-thing+ on: pull_request+ jobs:+ build:+ timeout-minutes: 5+ steps:+ - run: echo build+ thing_tests:+ name: Thing Tests Pass+ needs: [build]+ timeout-minutes: 5+ if: always()+ steps:+ - name: Check outcomes+ env:+ BUILD: ${{ needs.build.result }}+ run: |+ for var in BUILD; do+ val="${!var}"+ if [[ "$val" != "success" && "$val" != "skipped" ]]; then+ exit 1+ fi+ done+"""++CROSS_STEP_ENV_GATE = """+ name: ci-thing+ on: pull_request+ jobs:+ build:+ timeout-minutes: 5+ steps:+ - run: echo build+ thing_tests:+ name: Thing Tests Pass+ needs: [build]+ timeout-minutes: 5+ if: always()+ steps:+ - name: Log outcome+ env:+ RESULT: ${{ needs.build.result }}+ run: echo "$RESULT"+ - name: Check unrelated value+ env:+ RESULT: success+ run: |+ if [[ "$RESULT" != "success" && "$RESULT" != "skipped" ]]; then+ exit 1+ fi+"""+++# A gate whose display name doesn't end in "Pass", so only structural detection finds it.+def _off_convention_gate(marker: str = "", condition: str = "always()") -> str:+ yaml_ = _gate(MIXED_BODY, condition=condition).replace("Thing Tests Pass", "Thing decision")+ if marker:+ yaml_ = yaml_.replace(" thing_tests:", f" # {marker}\n thing_tests:")+ return yaml_+++def _off_convention_env_gate() -> str:+ return ENV_LOOP_GATE.replace("Thing Tests Pass", "Thing decision").replace(+ 'if [[ "$val" != "success" && "$val" != "skipped" ]]; then',+ 'if [[ "$val" == "failure" ]]; then',+ )+++def _nested_allow_marker_gate() -> str:+ return _off_convention_gate().replace(+ " changes:\n",+ """ changes:+ env:+ # hogli-lint: not-a-required-gate - nested keys cannot exempt a job+ thing_tests:+""",+ )+++class TestRequiredGateCheck:+ @pytest.mark.parametrize(+ "content",+ [+ _gate(SAFE_BODY),+ _gate(SAFE_BODY, condition="${{ always() }}"),+ _gate(HELPER_BODY),+ _gate(LOCAL_ALIAS_HELPER_BODY),+ _gate(COMMENTED_CALL_BODY),+ _gate(PAREN_LABEL_CALL_BODY),+ ENV_LOOP_GATE,+ ],+ ids=[+ "inline-allowlist",+ "wrapped-always",+ "shared-helper",+ "helper-via-local",+ "helper-call-with-trailing-comment",+ "helper-call-with-parens-in-label",+ "env-block-loop",+ ],+ )+ def test_passes_when_every_dependency_is_allowlisted(self, tmp_path: Path, content: str) -> None:+ _write(tmp_path, "ci-thing.yml", content)+ assert RequiredGateCheck().run(_read_all(tmp_path)).issues == []++ @pytest.mark.parametrize(+ "body,expected_deps",+ [(MIXED_BODY, ["changes"]), (TWO_BAD_BODY, ["affected", "changes"])],+ ids=["one-denylisted-among-allowlisted", "two-denylisted-among-allowlisted"],+ )+ def test_flags_exactly_the_denylisted_dependencies(+ self, tmp_path: Path, body: str, expected_deps: list[str]+ ) -> None:+ _write(tmp_path, "ci-thing.yml", _gate(body))+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert sorted(i.message.split("'")[1] for i in issues) == expected_deps++ @pytest.mark.parametrize(+ "condition",+ ["${{ !cancelled() }}", "${{ always() && false }}", "${{ !always() }}"],+ ids=["cancelled-condition", "conditional-always", "negated-always"],+ )+ def test_flags_gate_that_can_skip_itself(self, tmp_path: Path, condition: str) -> None:+ _write(tmp_path, "ci-thing.yml", _gate(SAFE_BODY, condition=condition))+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert len(issues) == 1+ assert "always()" in issues[0].message++ # Every fixture can exit zero for a cancelled dependency despite mentioning+ # the expected statuses or guard shape.+ @pytest.mark.parametrize(+ "body",+ [+ UNSAFE_HELPER_BODY,+ DECOY_COMMENT_BODY,+ DECOY_ECHO_BODY,+ NON_FAILING_ALLOWLIST_BODY,+ INVERTED_ALLOWLIST_BODY,+ LOGGED_ONLY_BODY,+ ],+ ids=[+ "failure-only-helper",+ "allowlist-guard-in-comment",+ "allowlist-guard-in-echo",+ "non-failing-allowlist",+ "inverted-allowlist",+ "results-only-logged",+ ],+ )+ def test_flags_gate_whose_results_reach_no_fail_closed_guard(self, tmp_path: Path, body: str) -> None:+ _write(tmp_path, "ci-thing.yml", _gate(body))+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert sorted(i.message.split("'")[1] for i in issues) == ["build", "changes"]+ assert all("fail-closed guard" in i.message for i in issues)++ def test_flags_dependency_declared_in_needs_but_never_tested(self, tmp_path: Path) -> None:+ _write(tmp_path, "ci-thing.yml", UNTESTED_DEPENDENCY_GATE)+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert [i.message.split("'")[1] for i in issues] == ["lint"]+ assert "never reaches" in issues[0].message++ def test_ignores_non_gate_jobs(self, tmp_path: Path) -> None:+ # Worker jobs *should* use !cancelled() so they stop when superseded;+ # only the collate gate is held to always().+ _write(+ tmp_path,+ "ci-thing.yml",+ """+ name: ci-thing+ on: pull_request+ jobs:+ shards:+ timeout-minutes: 5+ if: ${{ !cancelled() }}+ steps:+ - run: echo test+ """,+ )+ assert RequiredGateCheck().run(_read_all(tmp_path)).issues == []++ # A gate named off-convention is still a gate, so detection can't key on the+ # name alone.+ def test_finds_gate_not_named_pass(self, tmp_path: Path) -> None:+ _write(tmp_path, "ci-thing.yml", _off_convention_gate())+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert [i.message.split("'")[1] for i in issues] == ["changes"]++ def test_finds_off_convention_gate_without_always(self, tmp_path: Path) -> None:+ _write(tmp_path, "ci-thing.yml", _off_convention_gate(condition="${{ !cancelled() }}"))+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert any("unconditional `if: always()`" in issue.message for issue in issues)+ assert [issue.message.split("'")[1] for issue in issues if "dependency" in issue.message] == ["changes"]++ def test_finds_env_routed_gate_not_named_pass(self, tmp_path: Path) -> None:+ _write(tmp_path, "ci-thing.yml", _off_convention_env_gate())+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert [issue.message.split("'")[1] for issue in issues] == ["build"]++ def test_does_not_trace_step_env_into_another_step(self, tmp_path: Path) -> None:+ _write(tmp_path, "ci-thing.yml", CROSS_STEP_ENV_GATE)+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert [issue.message.split("'")[1] for issue in issues] == ["build"]++ @pytest.mark.parametrize(+ "marker,exempted",+ [+ ("hogli-lint: not-a-required-gate", False),+ ("hogli-lint: not-a-required-gate — decides a side effect, emits no check", True),+ ],+ ids=["without-reason", "with-reason"],+ )+ def test_allow_marker_needs_a_reason_to_exempt(self, tmp_path: Path, marker: str, exempted: bool) -> None:+ _write(tmp_path, "ci-thing.yml", _off_convention_gate(marker))+ assert (RequiredGateCheck().run(_read_all(tmp_path)).issues == []) is exempted++ def test_nested_allow_marker_does_not_exempt_job(self, tmp_path: Path) -> None:+ _write(tmp_path, "ci-thing.yml", _nested_allow_marker_gate())+ issues = RequiredGateCheck().run(_read_all(tmp_path)).issues+ assert [issue.message.split("'")[1] for issue in issues] == ["changes"]++class TestLiveTreeSmoke:"""Smoke test against the live ``.github/workflows/`` tree.diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.pyindex 4df3110b329b..5e0850f9894f 100644--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py@@ -17,6 +17,7 @@ from .checkout_full_depth import CheckoutFullDepthCheckfrom .dorny_negation import DornyNegationCheckfrom .job_timeouts import JobTimeoutsCheckfrom .pr_concurrency import PrConcurrencyCheck+from .required_gates import RequiredGateCheckfrom .semgrep_services_coverage import SemgrepServicesCoverageCheckCHECKS: list[WorkflowCheck] = [@@ -26,6 +27,7 @@ CHECKS: list[WorkflowCheck] = [SemgrepServicesCoverageCheck(),CheckoutFullDepthCheck(),CacheWriteGateCheck(),+ RequiredGateCheck(),]diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/required_gates.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/required_gates.pynew file mode 100644index 000000000000..67e5c77fcfd2--- /dev/null+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/required_gates.py@@ -0,0 +1,375 @@+"""Collate gates must run unconditionally and fail closed on every dependency.++A "collate gate" is the job that emits a required status check by inspecting its+dependencies' ``needs.*.result``. Two properties keep it honest:++1. ``if: always()`` — the gate must run and emit an explicit verdict. Worker jobs+ should use ``!cancelled()`` so they actually stop when a run is superseded, but+ the gate itself is what branch protection reads, so it has to report.++2. Allowlist **per dependency** — assert ``success``/``skipped`` and block+ everything else. One bad dependency is enough, so judging the step as a whole+ would call a mostly-correct gate clean. The trap is a ``changes`` detector+ cleared with a bare ``== 'failure'`` test: ``cancelled`` passes it, the gate+ then reads ``needs.changes.outputs.*``, which is empty on a cancelled job, and+ takes its "nothing to test" exit — green, with zero tests run.++Gates are found two ways, because the "name it ``… Pass``" convention is not+universally followed: by that name, and structurally when a step reads+``needs.<dep>.result`` in its shell or environment. Detection is independent of+the job condition so a gate missing ``always()`` cannot disappear from the rule.+Jobs that inspect results without gating anything opt out with ``ALLOW_MARKER``+plus a reason.++Results reach a fail-closed guard directly or indirectly, by way of a step+``env:`` block or a shared shell function. Both forms are judged the same way:+within each step, every dependency's result is traced through assignments,+``${!var}`` indirection, and helper-call argument positions to a canonical guard.+That guard must allowlist one or both safe states with ``!=`` comparisons joined+by ``&&``, then unconditionally exit nonzero. This keeps comparisons in comments,+logs, other steps, and non-failing branches from certifying a dependency.+"""++from __future__ import annotations++import re+from collections.abc import Iterable, Iterator+from dataclasses import dataclass+from pathlib import Path++from ..check import CheckResult, Issue, WorkflowCheck+from ..model import Job, Step, Workflow++ALLOW_MARKER = "hogli-lint: not-a-required-gate"++GATE_NAME = re.compile(r"\bpass$", re.IGNORECASE)+ALWAYS = re.compile(r"always\s*\(\s*\)")+READS_RESULT = re.compile(r"needs\.(?P<dep>[A-Za-z0-9_\-]+)\.result")++# `foo() {` / `function foo() {`, whose body ends at the first `}` sitting at or+# left of the definition's own indentation. Brace counting would be the general+# answer, but gate steps embed brace groups and Python heredocs, so the+# conventional shell layout is the more reliable signal.+FUNC_DEF = re.compile(r"^(?P<indent>[ \t]*)(?:function\s+)?(?P<name>[A-Za-z_][A-Za-z0-9_]*)\s*\(\s*\)\s*\{\s*$")++OPERAND = r"""\$\{\{[^}]*\}\}|\$\{!?[A-Za-z_0-9]+\}|\$[A-Za-z_0-9]+"""+IF_TEST = re.compile(r"^\s*if\s+\[\[\s*(?P<condition>.*?)\s*\]\]\s*;\s*then\s*(?:#.*)?$")+NOT_SAFE_STATUS = re.compile(rf"""["']?(?P<operand>{OPERAND})["']?\s*!=\s*["']?(?P<literal>success|skipped)["']?""")+NONZERO_EXIT = re.compile(r"exit\s+[1-9][0-9]*\s*(?:#.*)?$")+SIMPLE_LOG = re.compile(r"(?:echo|printf)\s+(?:\"[^\"]*\"|'[^']*')\s*$")+HEREDOC = re.compile(r"<<-?\s*[\"']?(?P<delimiter>[A-Za-z_][A-Za-z0-9_]*)[\"']?")++# `local result="$2"` / `val="${!var}"`, which is how a positional or an env value+# picks up the name that the comparison further down actually tests.+ASSIGNMENT = re.compile(+ rf"""^\s*(?:local\s+|declare\s+|export\s+)?(?P<target>[A-Za-z_][A-Za-z_0-9]*)=["']?(?P<source>{OPERAND})["']?"""+)++# `for var in BUILD DEPLOY; do`, giving the candidate names a later `${!var}` can hold.+FOR_LOOP = re.compile(r"^\s*for\s+(?P<var>[A-Za-z_][A-Za-z_0-9]*)\s+in\s+(?P<names>[^;]+?)\s*;?\s*do\b")++IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z_0-9]*$")+ARGUMENT = re.compile(r"""\"[^\"]*\"|'[^']*'|\S+""")+VAR_OPERAND = re.compile(r"^\$\{?(?P<indirect>!)?(?P<name>[A-Za-z_0-9]+)\}?$")+++@dataclass(frozen=True, slots=True)+class _Scope:+ """A shell body with its own positional parameters: one function, or the step itself."""++ name: str # "" for the step body outside any function+ body: str+++def _env(block: object) -> dict[str, str]:+ if not isinstance(block, dict):+ return {}+ return {name: value for name, value in block.items() if isinstance(name, str) and isinstance(value, str)}+++def _effective_env(job: Job, step: Step) -> dict[str, str]:+ return _env(job.raw.get("env")) | _env(step.raw.get("env"))+++def _result_sources(job: Job) -> Iterator[str]:+ yield from _env(job.raw.get("env")).values()+ for step in job.steps:+ if step.run:+ yield step.run+ condition = step.raw.get("if")+ if isinstance(condition, str):+ yield condition+ yield from _env(step.raw.get("env")).values()+++def _exempt_jobs(path: Path, job_names: frozenset[str]) -> frozenset[str]:+ """Job ids carrying an allow marker, with a reason, in the comments above them."""+ lines = path.read_text(encoding="utf-8").splitlines()+ candidates: list[tuple[int, int, str]] = []+ for index, line in enumerate(lines):+ match = re.match(r"^(?P<indent>\s*)(?P<job>[A-Za-z0-9_\-]+):\s*$", line)+ if match is not None and match.group("job") in job_names:+ candidates.append((index, len(match.group("indent")), match.group("job")))+ if not candidates:+ return frozenset()++ exempt: set[str] = set()+ job_indent = min(indent for _, indent, _ in candidates)+ for index, indent, job in candidates:+ if indent != job_indent:+ continue+ for above in reversed(lines[:index]):+ comment = re.match(r"^(?P<indent>\s*)#(?P<body>.*)$", above)+ if comment is None or len(comment.group("indent")) != job_indent:+ break+ _, marker, reason = comment.group("body").partition(ALLOW_MARKER)+ if marker and reason.strip(" -—:"):+ exempt.add(job)+ break+ return frozenset(exempt)+++def _is_gate(job: Job) -> bool:+ name = job.raw.get("name")+ display = name if isinstance(name, str) else job.name+ if GATE_NAME.search(display.strip()):+ return True+ return any(READS_RESULT.search(source) for source in _result_sources(job))+++def _uses_only_always(condition: object) -> bool:+ if not isinstance(condition, str):+ return False+ normalized = condition.strip()+ if normalized.startswith("${{") or normalized.endswith("}}"):+ if not (normalized.startswith("${{") and normalized.endswith("}}")):+ return False+ normalized = normalized[3:-2].strip()+ return ALWAYS.fullmatch(normalized) is not None+++def _without_heredocs(bash: str) -> str:+ lines: list[str] = []+ delimiter: str | None = None+ for line in bash.splitlines():+ if delimiter is not None:+ if line.strip() == delimiter:+ delimiter = None+ lines.append("")+ continue+ lines.append(line)+ match = HEREDOC.search(line)+ if match is not None:+ delimiter = match.group("delimiter")+ return "\n".join(lines)+++def _scopes(bash: str) -> list[_Scope]:+ lines = _without_heredocs(bash).splitlines()+ top: list[str] = []+ scopes: list[_Scope] = []++ idx = 0+ while idx < len(lines):+ match = FUNC_DEF.match(lines[idx])+ if match is None:+ top.append(lines[idx])+ idx += 1+ continue+ indent = len(match.group("indent"))+ body: list[str] = []+ idx += 1+ while idx < len(lines):+ line = lines[idx]+ idx += 1+ if line.strip() == "}" and len(line) - len(line.lstrip()) <= indent:+ break+ body.append(line)+ scopes.append(_Scope(match.group("name"), "\n".join(body)))++ scopes.append(_Scope("", "\n".join(top)))+ return scopes+++def _loop_names(body: str) -> dict[str, set[str]]:+ """Loop variable to the identifiers it iterates over, so `${!var}` can be resolved."""+ loops: dict[str, set[str]] = {}+ for line in body.splitlines():+ match = FOR_LOOP.match(line)+ if match is None:+ continue+ names = {word for word in match.group("names").split() if IDENTIFIER.match(word)}+ if names:+ loops.setdefault(match.group("var"), set()).update(names)+ return loops+++def _operands(scope: _Scope, token: str, loops: dict[str, set[str]]) -> list[str]:+ """Every operand key a shell token can stand for.++ `${{ needs.x.result }}` is global; `$2` and `$result` are local to their+ scope; `${!var}` stands for whichever names the enclosing loop supplies.+ """+ token = token.strip().strip('"').strip("'")+ if "needs." in token:+ match = READS_RESULT.search(token)+ return [f"needs:{match.group('dep')}"] if match else []++ match = VAR_OPERAND.match(token)+ if match is None:+ return []+ name = match.group("name")+ if match.group("indirect"):+ return [f"{scope.name}|var:{held}" for held in sorted(loops.get(name, ()))]+ kind = "arg" if name.isdigit() else "var"+ return [f"{scope.name}|{kind}:{name}"]+++def _guard_operand(lines: list[str], index: int) -> str | None:+ match = IF_TEST.match(lines[index])+ if match is None:+ return None++ comparisons: list[re.Match[str]] = []+ for term in re.split(r"\s*&&\s*", match.group("condition")):+ comparison = NOT_SAFE_STATUS.fullmatch(term.strip())+ if comparison is None:+ return None+ comparisons.append(comparison)++ operands = {comparison.group("operand") for comparison in comparisons}+ if len(operands) != 1:+ return None++ for body_line in lines[index + 1 :]:+ stripped = body_line.strip()+ if not stripped or stripped.startswith("#") or SIMPLE_LOG.fullmatch(stripped):+ continue+ if NONZERO_EXIT.fullmatch(stripped):+ return operands.pop()+ return None+ return None+++def _trace_step(job: Job, step: Step) -> tuple[set[str], dict[str, set[str]]]:+ """Resolve one shell step into guarded operands and alias edges.++ An edge ``a -> b`` means a result held by ``a`` also flows into ``b``, so a+ fail-closed guard on ``b`` gates ``a``. Steps stay isolated because their+ shells and step-level environments do not persist into later steps.+ """+ scopes = _scopes(step.run or "")+ functions = {scope.name for scope in scopes if scope.name}++ guarded: set[str] = set()+ edges: dict[str, set[str]] = {}++ for name, value in _effective_env(job, step).items():+ for source in _operands(_Scope("", ""), value, {}):+ edges.setdefault(source, set()).add(f"|var:{name}")++ for scope in scopes:+ loops = _loop_names(scope.body)+ lines = scope.body.splitlines()++ if step.raw.get("if") is None or _uses_only_always(step.raw.get("if")):+ for index in range(len(lines)):+ guard_operand = _guard_operand(lines, index)+ if guard_operand is not None:+ guarded.update(_operands(scope, guard_operand, loops))++ for line in lines:+ assignment = ASSIGNMENT.match(line)+ if assignment is not None:+ target = f"{scope.name}|var:{assignment.group('target')}"+ for source in _operands(scope, assignment.group("source"), loops):+ edges.setdefault(source, set()).add(target)++ # A helper call binds each argument to that function's positional parameter.+ # Only a nested definition is skipped here, matched as such rather than by+ # looking for `()` anywhere, which also discards real calls whose arguments+ # or trailing comment happen to contain those two characters.+ call = line.strip()+ if FUNC_DEF.match(call):+ continue+ name, _, rest = call.partition(" ")+ if name not in functions or not rest.strip():+ continue+ for position, argument in enumerate(ARGUMENT.findall(rest), start=1):+ for source in _operands(scope, argument, loops):+ edges.setdefault(source, set()).add(f"{name}|arg:{position}")++ return guarded, edges+++def _reachable(start: str, edges: dict[str, set[str]]) -> Iterable[str]:+ seen = {start}+ queue = [start]+ while queue:+ node = queue.pop()+ yield node+ for nxt in edges.get(node, ()):+ if nxt not in seen:+ seen.add(nxt)+ queue.append(nxt)+++def _dependencies(job: Job) -> set[str]:+ """Every dependency the gate is answerable for.++ Taken from ``needs:`` as well as the step body, because a job wired into+ ``needs:`` and then never tested is the drift this check exists to catch:+ reading only the body would judge the assertions that were written and stay+ silent about the one that was forgotten.+ """+ declared = job.raw.get("needs") or []+ declared = [declared] if isinstance(declared, str) else declared+ named = {dep for dep in declared if isinstance(dep, str)}+ referenced = {dep for source in _result_sources(job) for dep in READS_RESULT.findall(source)}+ return named | referenced+++def _problems(job: Job) -> Iterator[str]:+ if not _uses_only_always(job.raw.get("if")):+ yield "required-check gate must use unconditional `if: always()` so it always emits a verdict"++ step_traces = [_trace_step(job, step) for step in job.steps]+ for dep in sorted(_dependencies(job)):+ if not any(+ any(operand in guarded for operand in _reachable(f"needs:{dep}", edges)) for guarded, edges in step_traces+ ):+ yield (+ f"dependency '{dep}' result never reaches a fail-closed guard, so nothing blocks a "+ f'cancelled \'{dep}\'. Test `!= "success" && != "skipped"`, then exit nonzero'+ )+++class RequiredGateCheck(WorkflowCheck):+ id = "WF007-required-check-gates"+ label = "required-check gates"+ description = "collate gates use always() and allowlist each dependency's result"++ @property+ def fix_hint(self) -> str | None:+ return (+ "Use only `if: always()` on the gate, and test every dependency as "+ '`!= "success" && != "skipped"` rather than `== "failure"`. Inline tests, an `env:` '+ "block and a shared shell helper all work, so long as the failing branch exits nonzero. "+ "A job that reads results without gating anything opts out with "+ f"`# {ALLOW_MARKER} — <reason>`. See .agents/skills/authoring-ci-workflows/SKILL.md."+ )++ def run(self, workflows: list[Workflow]) -> CheckResult:+ result = CheckResult()+ for wf in workflows:+ gates = [job for job in wf.jobs if not job.is_reusable_call and _is_gate(job)]+ if not gates:+ continue+ # Only worth re-reading the file once we know there's a gate to exempt.+ exempt = _exempt_jobs(wf.path, frozenset(job.name for job in wf.jobs))+ for job in gates:+ if job.name in exempt:+ continue+ for message in _problems(job):+ result.issues.append(Issue(workflow=wf.path.name, job=job.name, message=message, file=str(wf.path)))+ return result