Skip to content

: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.

feat(devex): consolidate workflow linters into hogli lint:workflows (#56972)

Raúl Negrón-Oterod46c9b4f666c
diff --git a/.github/scripts/check-ci-concurrency.py b/.github/scripts/check-ci-concurrency.py
deleted file mode 100644
index 1f201c675f0d..000000000000
--- a/.github/scripts/check-ci-concurrency.py
+++ /dev/null
@@ -1,141 +0,0 @@
-#!/usr/bin/env python3
-# /// script
-# requires-python = ">=3.11"
-# dependencies = ["pyyaml"]
-# ///
-# ruff: noqa: T201 allow print statements
-"""
-CI script to verify GitHub Actions workflow concurrency is configured correctly.
-
-Two checks:
-
-1. PR-triggered workflows must declare a top-level `concurrency:` block — without it,
- every push to a PR branch starts a fresh run while the in-flight one keeps burning
- minutes.
-
-2. The concurrency group must not fall back to `github.run_id` — `github.head_ref` is
- empty on `push` events, so `head_ref || run_id` makes every push run land in its own
- unique group, silently disabling dedup. Use `github.ref` as the fallback instead.
- See PR #53194 (the agent-skills release race) for the failure mode.
-
-Repo convention:
-
- concurrency:
- group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
- cancel-in-progress: ${{ github.event_name == 'pull_request' }}
-
-Usage:
- uv run .github/scripts/check-ci-concurrency.py
-"""
-
-import re
-import sys
-from pathlib import Path
-
-import yaml
-
-WORKFLOWS_DIR = Path(__file__).resolve().parent.parent / "workflows"
-
-BAD_FALLBACK = re.compile(r"head_ref\s*\|\|\s*github\.run_id")
-
-# Workflows intentionally exempt from concurrency cancellation.
-# Each entry has a one-line reason so the next reader knows why.
-SKIP = {
- # Telemetry / shadow measurement — cancelling stale runs may drop data.
- "ci-test-selection-shadow.yml",
- # Schedule-dominant; PR trigger filtered to a single script — cosmetic gain.
- "ci-backend-update-test-timing.yml",
- # Migration enforcement; arguably wants to complete on every PR state.
- "ci-migrations-service-separation-check.yml",
-}
-
-PR_TRIGGERS = {"pull_request", "pull_request_target"}
-
-
-def is_pr_triggered(triggers: object) -> bool:
- if isinstance(triggers, str):
- return triggers in PR_TRIGGERS
- if isinstance(triggers, list):
- return any(t in PR_TRIGGERS for t in triggers)
- if isinstance(triggers, dict):
- return any(t in PR_TRIGGERS for t in triggers)
- return False
-
-
-def check_concurrency() -> tuple[list[str], list[str], list[str]]:
- parse_errors: list[str] = []
- missing: list[str] = []
- bad_group: list[str] = []
- for workflow_file in sorted(WORKFLOWS_DIR.glob("*.y*ml")):
- with open(workflow_file) as f:
- try:
- data = yaml.safe_load(f)
- except yaml.YAMLError as e:
- parse_errors.append(f"{workflow_file.name}: failed to parse YAML: {e}")
- continue
-
- if not isinstance(data, dict):
- continue
-
- concurrency = data.get("concurrency")
- # Concurrency can be either a string (group only) or a mapping (group + cancel-in-progress).
- group_expr = ""
- if isinstance(concurrency, dict):
- group_expr = concurrency.get("group") or ""
- elif isinstance(concurrency, str):
- group_expr = concurrency
- if isinstance(group_expr, str) and BAD_FALLBACK.search(group_expr):
- bad_group.append(workflow_file.name)
-
- # PyYAML parses the top-level `on:` key as boolean True.
- triggers = data.get(True, data.get("on"))
- if not is_pr_triggered(triggers):
- continue
- if workflow_file.name.startswith("ci-") and workflow_file.name not in SKIP and concurrency is None:
- missing.append(f"{workflow_file.name}: missing top-level concurrency block")
-
- return parse_errors, missing, bad_group
-
-
-def main() -> None:
- parse_errors, missing, bad_group = check_concurrency()
- failed = False
-
- if parse_errors:
- failed = True
- print(f"Found {len(parse_errors)} workflow file(s) with YAML parse errors:\n")
- for error in parse_errors:
- print(f" - {error}")
- print()
-
- if bad_group:
- failed = True
- print(f"Found {len(bad_group)} workflow(s) with broken concurrency group fallback:\n")
- for name in bad_group:
- print(f" - {name}")
- print(
- "\n`github.head_ref` is empty on push events — the `|| github.run_id` fallback gives every push run its\n"
- "own unique group, silently disabling dedup. Use `github.ref` as the fallback instead:\n"
- )
- print(" group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}")
- print("\nSee PR #53194 (agent-skills release race) for the failure mode.\n")
-
- if missing:
- failed = True
- print(f"Found {len(missing)} PR-triggered workflow(s) missing concurrency:\n")
- for error in missing:
- print(f" - {error}")
- print("\nFix by adding this block after `on:`:\n")
- print("concurrency:")
- print(" group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}")
- print(" cancel-in-progress: ${{ github.event_name == 'pull_request' }}")
- print("\nOr, if cancelling stale runs would lose data (telemetry, schedule-only PR triggers, etc.),")
- print(f"add the filename to the SKIP set in {Path(__file__).name} with a one-line reason.")
-
- if failed:
- sys.exit(1)
- print("All workflow concurrency configurations look good.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/.github/scripts/check-ci-timeouts.py b/.github/scripts/check-ci-timeouts.py
deleted file mode 100644
index 1c775e3877a3..000000000000
--- a/.github/scripts/check-ci-timeouts.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env python3
-# /// script
-# requires-python = ">=3.11"
-# dependencies = ["pyyaml"]
-# ///
-# ruff: noqa: T201 allow print statements
-"""
-CI script to verify all GitHub Actions jobs declare timeout-minutes.
-
-Without explicit timeout-minutes, jobs default to a 6-hour execution limit,
-meaning stuck runners silently burn CI credits.
-
-Usage:
- uv run .github/scripts/check-ci-timeouts.py
-"""
-
-import sys
-from pathlib import Path
-
-import yaml
-
-WORKFLOWS_DIR = Path(__file__).resolve().parent.parent / "workflows"
-
-
-def check_timeouts() -> list[str]:
- errors: list[str] = []
- for workflow_file in sorted(WORKFLOWS_DIR.glob("*.y*ml")):
- with open(workflow_file) as f:
- try:
- data = yaml.safe_load(f)
- except yaml.YAMLError as e:
- errors.append(f"{workflow_file.name}: failed to parse YAML: {e}")
- continue
-
- if not isinstance(data, dict):
- continue
-
- jobs = data.get("jobs")
- if not isinstance(jobs, dict):
- continue
-
- for job_name, job_config in jobs.items():
- if not isinstance(job_config, dict):
- continue
- # Reusable workflow calls (jobs with `uses:`) don't support
- # timeout-minutes at the job level — timeouts are set inside
- # the called workflow.
- if "uses" in job_config:
- continue
- if "timeout-minutes" not in job_config:
- errors.append(f"{workflow_file.name}: job '{job_name}' is missing timeout-minutes")
-
- return errors
-
-
-def main() -> None:
- errors = check_timeouts()
- if errors:
- print(f"Found {len(errors)} job(s) missing timeout-minutes:\n")
- for error in errors:
- print(f" - {error}")
- sys.exit(1)
- else:
- print("All jobs have timeout-minutes set.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/.github/scripts/check-dorny-paths-filter.py b/.github/scripts/check-dorny-paths-filter.py
deleted file mode 100755
index 4812a215671e..000000000000
--- a/.github/scripts/check-dorny-paths-filter.py
+++ /dev/null
@@ -1,172 +0,0 @@
-#!/usr/bin/env python3
-# /// script
-# requires-python = ">=3.11"
-# dependencies = ["pyyaml"]
-# ///
-# ruff: noqa: T201 allow print statements
-"""
-CI script to verify dorny/paths-filter negation patterns are guarded.
-
-With dorny's default predicate-quantifier ('some'), each filter rule is OR'd
-independently. A '!path' rule then matches every file NOT at that path — which
-silently inverts the intended exclusion. Using '!' patterns is only safe when
-the step also sets `predicate-quantifier: 'every'`.
-
-Docs: https://github.com/dorny/paths-filter#advanced-options
-
-Usage:
- uv run .github/scripts/check-dorny-paths-filter.py
-"""
-
-import sys
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-
-import yaml
-
-WORKFLOWS_DIR = Path(__file__).resolve().parent.parent / "workflows"
-DORNY_PREFIX = "dorny/paths-filter@"
-DOCS_URL = "https://github.com/dorny/paths-filter#advanced-options"
-
-
-@dataclass(slots=True)
-class CheckResult:
- parse_errors: list[str]
- negation_errors: list[str]
- workflow_count: int
- step_count: int
-
-
-def parse_filters(raw: Any) -> dict[str, list[str]] | None:
- """Return the filter dict, or None if it's an unparseable external path ref."""
- if isinstance(raw, dict):
- return raw
- if not isinstance(raw, str):
- return None
- # dorny also accepts a path to an external filters file; those are
- # single-line strings without the block scalar's newline structure.
- if "\n" not in raw and ":" not in raw:
- return None
- try:
- parsed = yaml.safe_load(raw)
- except yaml.YAMLError:
- return None
- return parsed if isinstance(parsed, dict) else None
-
-
-def negation_patterns(filters: dict[str, list[str]]) -> list[tuple[str, str]]:
- """Return (filter_name, pattern) pairs for every '!' pattern found."""
- hits: list[tuple[str, str]] = []
- for name, patterns in filters.items():
- if not isinstance(patterns, list):
- continue
- for pattern in patterns:
- if isinstance(pattern, str) and pattern.startswith("!"):
- hits.append((name, pattern))
- return hits
-
-
-def check_workflows(workflows_dir: Path | None = None) -> CheckResult:
- workflows_dir = workflows_dir or WORKFLOWS_DIR
- parse_errors: list[str] = []
- negation_errors: list[str] = []
- workflow_count = 0
- step_count = 0
-
- for workflow_file in sorted(workflows_dir.glob("*.y*ml")):
- workflow_count += 1
- with open(workflow_file, encoding="utf-8") as f:
- try:
- data = yaml.safe_load(f)
- except yaml.YAMLError as e:
- parse_errors.append(f"{workflow_file.name}: failed to parse YAML: {e}")
- continue
-
- if not isinstance(data, dict):
- continue
-
- jobs = data.get("jobs")
- if not isinstance(jobs, dict):
- continue
-
- for job_name, job_config in jobs.items():
- if not isinstance(job_config, dict):
- continue
- steps = job_config.get("steps")
- if not isinstance(steps, list):
- continue
-
- for idx, step in enumerate(steps):
- if not isinstance(step, dict):
- continue
- uses = step.get("uses")
- if not isinstance(uses, str) or not uses.startswith(DORNY_PREFIX):
- continue
-
- step_count += 1
- with_block = step.get("with")
- if not isinstance(with_block, dict):
- continue
-
- filters = parse_filters(with_block.get("filters"))
- if filters is None:
- continue
-
- negations = negation_patterns(filters)
- if not negations:
- continue
-
- quantifier = with_block.get("predicate-quantifier")
- if quantifier == "every":
- continue
-
- step_ref = f"step id '{step['id']}'" if step.get("id") else f"step[{idx}]"
- for filter_name, pattern in negations:
- negation_errors.append(
- f"{workflow_file.name}: job '{job_name}' ({step_ref}): "
- f"filter '{filter_name}' uses negation '{pattern}' without "
- f"`predicate-quantifier: 'every'` — with the default "
- f"'some' quantifier, '!' rules match every file NOT at the "
- f"path (including unrelated changes). See {DOCS_URL}."
- )
-
- return CheckResult(
- parse_errors=parse_errors,
- negation_errors=negation_errors,
- workflow_count=workflow_count,
- step_count=step_count,
- )
-
-
-def main(workflows_dir: Path | None = None) -> None:
- result = check_workflows(workflows_dir)
- if result.parse_errors or result.negation_errors:
- if result.parse_errors:
- print(f"Found {len(result.parse_errors)} workflow parse error(s):\n")
- for error in result.parse_errors:
- print(f" - {error}")
- print("\nFix the malformed workflow YAML and rerun this check.")
-
- if result.parse_errors and result.negation_errors:
- print()
-
- if result.negation_errors:
- print(f"Found {len(result.negation_errors)} unsafe dorny/paths-filter negation(s):\n")
- for error in result.negation_errors:
- print(f" - {error}")
- print(
- "\nFix: either remove the '!' patterns and use positive filters "
- "with count comparison, or add `predicate-quantifier: 'every'` "
- f"to the step's `with:` block. See {DOCS_URL}."
- )
-
- sys.exit(1)
- print(
- f"Checked {result.workflow_count} workflow(s); {result.step_count} dorny/paths-filter "
- f"step(s); all negation usages guarded by predicate-quantifier: 'every'."
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/.github/scripts/check-semgrep-services-coverage.py b/.github/scripts/check-semgrep-services-coverage.py
deleted file mode 100644
index c1f849aba49f..000000000000
--- a/.github/scripts/check-semgrep-services-coverage.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/env python3
-# /// script
-# requires-python = ">=3.11"
-# dependencies = ["pyyaml"]
-# ///
-# ruff: noqa: T201 allow print statements
-"""
-CI script to verify every services/<name>/ is covered by a language-specific
-Semgrep job in .github/workflows/ci-security.yaml.
-
-The repo-wide semgrep-general job excludes services/, so a new service added
-without updating semgrep-python or semgrep-js silently drops out of SAST.
-
-Usage:
- uv run .github/scripts/check-semgrep-services-coverage.py
-"""
-
-import sys
-from pathlib import Path
-
-import yaml
-
-REPO_ROOT = Path(__file__).resolve().parent.parent.parent
-SERVICES_DIR = REPO_ROOT / "services"
-SECURITY_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "ci-security.yaml"
-COVERING_JOBS = ("semgrep-python", "semgrep-js")
-
-
-def services_subdirs() -> list[str]:
- return sorted(p.name for p in SERVICES_DIR.iterdir() if p.is_dir() and not p.name.startswith("."))
-
-
-def covering_run_text() -> str:
- with open(SECURITY_WORKFLOW) as f:
- data = yaml.safe_load(f)
-
- jobs = data.get("jobs", {})
- parts: list[str] = []
- for job_name in COVERING_JOBS:
- job = jobs.get(job_name)
- if not isinstance(job, dict):
- raise SystemExit(f"{SECURITY_WORKFLOW.name}: expected job '{job_name}'")
- for step in job.get("steps", []) or []:
- run = step.get("run") if isinstance(step, dict) else None
- if isinstance(run, str):
- parts.append(run)
- return "\n".join(parts)
-
-
-def main() -> None:
- text = covering_run_text()
- all_services = services_subdirs()
- missing = [name for name in all_services if f"services/{name}/" not in text]
-
- if missing:
- print(
- f"Found {len(missing)} service(s) not covered by {' or '.join(COVERING_JOBS)} "
- f"in {SECURITY_WORKFLOW.name}:\n"
- )
- for name in missing:
- print(f" - services/{name}/")
- print("\nAdd each to the matching job's target list in ci-security.yaml.")
- sys.exit(1)
-
- print(f"All {len(all_services)} service(s) covered by Semgrep scans.")
-
-
-if __name__ == "__main__":
- main()
diff --git a/.github/workflows/ci-lint-workflows.yml b/.github/workflows/ci-lint-workflows.yml
index de6f02f5e513..2e2a5b7d6235 100644
--- a/.github/workflows/ci-lint-workflows.yml
+++ b/.github/workflows/ci-lint-workflows.yml
@@ -4,8 +4,9 @@ on:
pull_request:
paths:
- .github/workflows/**
- - .github/scripts/**
- services/**
+ - tools/hogli-commands/hogli_commands/workflow_lint/**
+ - hogli.yaml
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
@@ -15,42 +16,27 @@ permissions:
contents: read
jobs:
- check-timeouts:
+ lint-workflows:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v6
- - uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
- with:
- version: '0.10.2'
- - run: uv run .github/scripts/check-ci-timeouts.py
- check-semgrep-services-coverage:
- runs-on: ubuntu-latest
- timeout-minutes: 5
- steps:
- - uses: actions/checkout@v6
- - uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
+ - name: Set up Python
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
- version: '0.10.2'
- - run: uv run .github/scripts/check-semgrep-services-coverage.py
+ python-version-file: 'pyproject.toml'
- check-dorny-paths-filter:
- runs-on: ubuntu-latest
- timeout-minutes: 5
- steps:
- - uses: actions/checkout@v6
- - uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
+ - name: Install uv
+ uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
with:
- version: '0.10.2'
- - run: uv run .github/scripts/check-dorny-paths-filter.py
+ version: '0.10.2' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
+ enable-cache: true
+ cache-dependency-glob: uv.lock
+ save-cache: ${{ github.ref == 'refs/heads/master' }}
- check-concurrency:
- runs-on: ubuntu-latest
- timeout-minutes: 5
- steps:
- - uses: actions/checkout@v6
- - uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
- with:
- version: '0.10.2'
- - run: uv run .github/scripts/check-ci-concurrency.py
+ - name: Install python dependencies
+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
+
+ - name: Lint workflows
+ run: ./bin/hogli lint:workflows
diff --git a/hogli.yaml b/hogli.yaml
index 8664758e4196..c893039b7393 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -750,6 +750,9 @@ quality:
lint:feature-flags:fix:
cmd: node bin/lint-feature-flag-sorting.mjs --fix
description: Auto-sort FEATURE_FLAGS in constants.tsx alphabetically
+ lint:workflows:
+ click: hogli_commands.workflow_lint.cli:cmd_lint_workflows
+ description: Lint .github/workflows/** for repo conventions
format:mcp:
cmd: pnpm run --filter @posthog/mcp format
description: Format MCP files
diff --git a/posthog/test/test_check_dorny_paths_filter.py b/posthog/test/test_check_dorny_paths_filter.py
deleted file mode 100644
index c8789d4b8da5..000000000000
--- a/posthog/test/test_check_dorny_paths_filter.py
+++ /dev/null
@@ -1,88 +0,0 @@
-import sys
-import importlib.util
-from pathlib import Path
-from types import ModuleType
-
-import pytest
-
-
-def load_script_module() -> ModuleType:
- script_path = Path(__file__).resolve().parents[2] / ".github/scripts/check-dorny-paths-filter.py"
- spec = importlib.util.spec_from_file_location("check_dorny_paths_filter", script_path)
- assert spec is not None
- assert spec.loader is not None
-
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- spec.loader.exec_module(module)
- return module
-
-
- ("workflow_contents", "expected_text", "unexpected_text"),
- [
- (
- "name: Broken workflow\njobs:\n test: [\n",
- "Found 1 workflow parse error(s):",
- "unsafe dorny/paths-filter negation",
- ),
- (
- """name: Dorny workflow
-jobs:
- test:
- steps:
- - uses: dorny/paths-filter@v3
- with:
- filters: |
- docs:
- - 'docs/**'
- - '!docs/private/**'
-""",
- "Found 1 unsafe dorny/paths-filter negation(s):",
- "workflow parse error",
- ),
- ],
-)
-def test_main_reports_failure_category(
- workflow_contents: str, expected_text: str, unexpected_text: str, tmp_path: Path, monkeypatch, capsys
-) -> None:
- module = load_script_module()
-
- (tmp_path / "test.yml").write_text(workflow_contents)
-
- with pytest.raises(SystemExit, match="1"):
- module.main(tmp_path)
-
- output = capsys.readouterr().out
- assert expected_text in output
- assert unexpected_text not in output
-
-
-def test_main_reports_all_negation_patterns(tmp_path: Path, capsys) -> None:
- module = load_script_module()
-
- (tmp_path / "test.yml").write_text(
- """name: Dorny workflow
-jobs:
- test:
- steps:
- - id: changes
- uses: dorny/paths-filter@v3
- with:
- filters: |
- docs:
- - 'docs/**'
- - '!docs/private/**'
- backend:
- - 'posthog/**'
- - '!posthog/test/**'
-""",
- encoding="utf-8",
- )
-
- with pytest.raises(SystemExit, match="1"):
- module.main(tmp_path)
-
- output = capsys.readouterr().out
- assert "filter 'docs' uses negation '!docs/private/**'" in output
- assert "filter 'backend' uses negation '!posthog/test/**'" in output
diff --git a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
new file mode 100644
index 000000000000..bcdf2310a98e
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py
@@ -0,0 +1,546 @@
+"""Tests for the workflow_lint package.
+
+These tests are fully isolated — each rule gets a passing fixture and a
+failing fixture written to a tmp_path. Avoids touching the live repo state
+except for one smoke test against ``.github/workflows/`` which exercises the
+parser end-to-end.
+"""
+
+from __future__ import annotations
+
+import textwrap
+from pathlib import Path
+
+import pytest
+
+from hogli_commands.workflow_lint.check import CheckResult, WorkflowCheck
+from hogli_commands.workflow_lint.checks import CHECKS, _build_lookup, get_check
+from hogli_commands.workflow_lint.checks.dorny_negation import DornyNegationCheck
+from hogli_commands.workflow_lint.checks.job_timeouts import JobTimeoutsCheck
+from hogli_commands.workflow_lint.checks.pr_concurrency import PrConcurrencyCheck
+from hogli_commands.workflow_lint.checks.semgrep_services_coverage import SemgrepServicesCoverageCheck
+from hogli_commands.workflow_lint.model import PR_TRIGGERS, Workflow, WorkflowParseError, read_workflows
+
+
+def _write(dir_: Path, name: str, content: str) -> Path:
+ path = dir_ / name
+ path.write_text(textwrap.dedent(content).lstrip())
+ return path
+
+
+def _read_all(dir_: Path) -> list[Workflow]:
+ return list(read_workflows(dir_))
+
+
+# ---------------------------------------------------------------------------
+# WorkflowReader / model
+# ---------------------------------------------------------------------------
+
+
+class TestReadWorkflows:
+ def test_normalizes_on_true_key(self, tmp_path: Path) -> None:
+ # PyYAML parses `on:` as the boolean True. The reader must surface it
+ # as the original triggers regardless.
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: My
+ on:
+ pull_request:
+ branches: [master]
+ jobs: {}
+ """,
+ )
+ wf = next(read_workflows(tmp_path))
+ assert wf.is_pr_triggered, f"expected PR-trigger detection, got on={wf.on!r}"
+
+ def test_quoted_on_string_also_works(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: My
+ "on": pull_request
+ jobs: {}
+ """,
+ )
+ wf = next(read_workflows(tmp_path))
+ assert wf.is_pr_triggered
+
+ def test_non_pr_trigger(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: My
+ on: [push]
+ jobs: {}
+ """,
+ )
+ wf = next(read_workflows(tmp_path))
+ assert not wf.is_pr_triggered
+ assert "push" not in PR_TRIGGERS # sanity
+
+ def test_reusable_call_job_marked(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: My
+ on: [pull_request]
+ jobs:
+ call:
+ uses: ./.github/workflows/other.yml
+ """,
+ )
+ wf = next(read_workflows(tmp_path))
+ [job] = wf.jobs
+ assert job.is_reusable_call
+ assert job.uses == "./.github/workflows/other.yml"
+
+ def test_parse_error_raises_typed(self, tmp_path: Path) -> None:
+ bad = tmp_path / "wf.yml"
+ bad.write_text("name: x\non: [\njobs: {}\n")
+ with pytest.raises(WorkflowParseError) as exc:
+ list(read_workflows(tmp_path))
+ assert exc.value.path == bad
+
+
+# ---------------------------------------------------------------------------
+# JobTimeoutsCheck
+# ---------------------------------------------------------------------------
+
+
+class TestJobTimeoutsCheck:
+ def test_passes_when_all_jobs_have_timeout(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: My
+ on: [pull_request]
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - run: echo ok
+ """,
+ )
+ result = JobTimeoutsCheck().run(_read_all(tmp_path))
+ assert result.issues == []
+
+ def test_fails_when_timeout_missing(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: My
+ on: [pull_request]
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - run: echo ok
+ """,
+ )
+ result = JobTimeoutsCheck().run(_read_all(tmp_path))
+ [issue] = result.issues
+ assert issue.workflow == "wf.yml"
+ assert issue.job == "build"
+ assert "timeout-minutes" in issue.message
+
+ def test_skips_reusable_call_jobs(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: My
+ on: [pull_request]
+ jobs:
+ call:
+ uses: ./.github/workflows/other.yml
+ """,
+ )
+ result = JobTimeoutsCheck().run(_read_all(tmp_path))
+ assert result.issues == []
+
+
+# ---------------------------------------------------------------------------
+# PrConcurrencyCheck
+# ---------------------------------------------------------------------------
+
+
+class TestPrConcurrencyCheck:
+ def test_passes_with_concurrency(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "ci-foo.yml",
+ """
+ name: CI Foo
+ on: [pull_request]
+ concurrency:
+ group: x
+ cancel-in-progress: true
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert PrConcurrencyCheck().run(_read_all(tmp_path)).issues == []
+
+ def test_string_concurrency_counts_as_present(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "ci-foo.yml",
+ """
+ name: CI Foo
+ on: [pull_request]
+ concurrency: "${{ github.workflow }}-${{ github.head_ref || github.ref }}"
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert PrConcurrencyCheck().run(_read_all(tmp_path)).issues == []
+
+ def test_fails_without_concurrency(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "ci-foo.yml",
+ """
+ name: CI Foo
+ on: [pull_request]
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ [issue] = PrConcurrencyCheck().run(_read_all(tmp_path)).issues
+ assert issue.workflow == "ci-foo.yml"
+ assert "concurrency" in issue.message
+
+ def test_fails_with_run_id_fallback(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "ci-foo.yml",
+ """
+ name: CI Foo
+ on: [pull_request]
+ concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+ cancel-in-progress: true
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ [issue] = PrConcurrencyCheck().run(_read_all(tmp_path)).issues
+ assert issue.workflow == "ci-foo.yml"
+ assert "github.run_id" in issue.message
+ assert "github.ref" in issue.message
+
+ def test_skips_non_ci_prefix(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "shellcheck.yml",
+ """
+ name: Shell
+ on: [pull_request]
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert PrConcurrencyCheck().run(_read_all(tmp_path)).issues == []
+
+ def test_skips_non_pr_trigger(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "ci-foo.yml",
+ """
+ name: CI Foo
+ on: [push]
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert PrConcurrencyCheck().run(_read_all(tmp_path)).issues == []
+
+ def test_skips_listed_filenames(self, tmp_path: Path) -> None:
+ skip_name = next(iter(PrConcurrencyCheck.SKIP))
+ _write(
+ tmp_path,
+ skip_name,
+ """
+ name: Skipped
+ on: [pull_request]
+ jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert PrConcurrencyCheck().run(_read_all(tmp_path)).issues == []
+
+
+# ---------------------------------------------------------------------------
+# DornyNegationCheck
+# ---------------------------------------------------------------------------
+
+
+_DORNY_USES = "dorny/paths-filter@v3"
+
+
+class TestDornyNegationCheck:
+ def test_passes_without_dorny(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: x
+ on: [pull_request]
+ jobs:
+ j:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert DornyNegationCheck().run(_read_all(tmp_path)).issues == []
+
+ def test_passes_with_positive_filters_only(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ f"""
+ name: x
+ on: [pull_request]
+ jobs:
+ j:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: {_DORNY_USES}
+ with:
+ filters: |
+ backend:
+ - posthog/**
+ """,
+ )
+ assert DornyNegationCheck().run(_read_all(tmp_path)).issues == []
+
+ def test_fails_on_negation_without_quantifier(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ f"""
+ name: x
+ on: [pull_request]
+ jobs:
+ j:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: {_DORNY_USES}
+ with:
+ filters: |
+ backend:
+ - posthog/**
+ - "!docs/**"
+ """,
+ )
+ [issue] = DornyNegationCheck().run(_read_all(tmp_path)).issues
+ assert "negation" in issue.message
+ assert "predicate-quantifier" in issue.message
+
+ def test_passes_with_every_quantifier(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "wf.yml",
+ f"""
+ name: x
+ on: [pull_request]
+ jobs:
+ j:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: {_DORNY_USES}
+ with:
+ predicate-quantifier: 'every'
+ filters: |
+ backend:
+ - posthog/**
+ - "!docs/**"
+ """,
+ )
+ assert DornyNegationCheck().run(_read_all(tmp_path)).issues == []
+
+
+# ---------------------------------------------------------------------------
+# SemgrepServicesCoverageCheck
+# ---------------------------------------------------------------------------
+
+
+class TestSemgrepServicesCoverageCheck:
+ def test_passes_when_all_services_are_covered(self, tmp_path: Path) -> None:
+ repo_root = tmp_path
+ (repo_root / "services" / "api").mkdir(parents=True)
+ (repo_root / "services" / "worker").mkdir()
+ workflows_dir = repo_root / ".github" / "workflows"
+ workflows_dir.mkdir(parents=True)
+ _write(
+ workflows_dir,
+ "ci-security.yaml",
+ """
+ name: Security
+ on: [pull_request]
+ jobs:
+ semgrep-python:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: |
+ semgrep scan services/api/
+ semgrep scan services/worker/
+ semgrep-js:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ assert SemgrepServicesCoverageCheck(repo_root=repo_root).run(_read_all(workflows_dir)).issues == []
+
+ def test_fails_when_a_service_is_missing(self, tmp_path: Path) -> None:
+ repo_root = tmp_path
+ (repo_root / "services" / "api").mkdir(parents=True)
+ (repo_root / "services" / "worker").mkdir()
+ workflows_dir = repo_root / ".github" / "workflows"
+ workflows_dir.mkdir(parents=True)
+ _write(
+ workflows_dir,
+ "ci-security.yaml",
+ """
+ name: Security
+ on: [pull_request]
+ jobs:
+ semgrep-python:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: semgrep scan services/api/
+ semgrep-js:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - run: echo ok
+ """,
+ )
+ [issue] = SemgrepServicesCoverageCheck(repo_root=repo_root).run(_read_all(workflows_dir)).issues
+ assert issue.workflow == "ci-security.yaml"
+ assert "services/worker/" in issue.message
+
+
+# ---------------------------------------------------------------------------
+# Registry / smoke
+# ---------------------------------------------------------------------------
+
+
+class TestRegistry:
+ def test_check_ids_are_unique(self) -> None:
+ ids = [c.id for c in CHECKS]
+ assert len(ids) == len(set(ids)), f"duplicate check ids: {ids}"
+
+ def test_get_check_finds_each(self) -> None:
+ for c in CHECKS:
+ assert get_check(c.id) is c
+
+ def test_get_check_accepts_prefix(self) -> None:
+ for c in CHECKS:
+ prefix = c.id.split("-", 1)[0]
+ assert get_check(prefix) is c
+ assert get_check(prefix.lower()) is c
+
+ def test_get_check_unknown_returns_none(self) -> None:
+ assert get_check("not-a-real-id") is None
+ assert get_check("WF999") is None
+
+ def test_build_lookup_rejects_duplicate_prefix(self) -> None:
+ class _A(WorkflowCheck):
+ id = "WF001-alpha"
+ label = "a"
+ description = "a"
+
+ def run(self, workflows: list[Workflow]) -> CheckResult:
+ return CheckResult()
+
+ class _B(WorkflowCheck):
+ id = "WF001-beta"
+ label = "b"
+ description = "b"
+
+ def run(self, workflows: list[Workflow]) -> CheckResult:
+ return CheckResult()
+
+ with pytest.raises(ValueError, match="WF001"):
+ _build_lookup([_A(), _B()])
+
+ def test_run_returns_check_result(self, tmp_path: Path) -> None:
+ # A near-empty workflow set should not crash any check.
+ _write(
+ tmp_path,
+ "wf.yml",
+ """
+ name: x
+ on: [push]
+ jobs: {}
+ """,
+ )
+ wfs = _read_all(tmp_path)
+ for check in CHECKS:
+ result = check.run(wfs)
+ assert isinstance(result, CheckResult)
+
+
+class TestLiveTreeSmoke:
+ """Smoke test against the live ``.github/workflows/`` tree.
+
+ Asserts that parsing and every check execute without raising — does NOT
+ assert pass/fail of individual rules. This keeps the test stable as
+ workflows evolve while still catching crashes that fixtures miss.
+ """
+
+ def test_live_tree_parses_and_checks_run(self) -> None:
+ from hogli.manifest import REPO_ROOT
+
+ workflows_dir = REPO_ROOT / ".github" / "workflows"
+ if not workflows_dir.exists():
+ pytest.skip("no .github/workflows directory in this checkout")
+ workflows = list(read_workflows(workflows_dir))
+ for check in CHECKS:
+ assert isinstance(check.run(workflows), CheckResult)
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/__init__.py b/tools/hogli-commands/hogli_commands/workflow_lint/__init__.py
new file mode 100644
index 000000000000..36dc2c1abaf6
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/__init__.py
@@ -0,0 +1,10 @@
+"""Workflow lint package: framework + checks for `.github/workflows/**` policies.
+
+The CLI entrypoint is wired via the ``click:`` manifest entry in ``hogli.yaml``;
+the lazy loader resolves ``hogli_commands.workflow_lint.cli:cmd_lint_workflows``
+on demand. To run from the command line:
+
+ bin/hogli lint:workflows
+ bin/hogli lint:workflows --check WF001
+ bin/hogli lint:workflows --list
+"""
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/check.py b/tools/hogli-commands/hogli_commands/workflow_lint/check.py
new file mode 100644
index 000000000000..6d0fbfabaf92
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/check.py
@@ -0,0 +1,62 @@
+"""Check ABC and result type for workflow lint rules.
+
+Mirrors the shape of `hogli_commands.product.checks.ProductCheck` so the two
+frameworks can be unified later (rule of three) without rewriting either.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+
+from .model import Workflow
+
+
+@dataclass(slots=True)
+class Issue:
+ """One actionable problem reported by a check."""
+
+ workflow: str # workflow filename, e.g. "ci-backend.yml"
+ message: str
+ file: str | None = None # path used for GitHub annotations; defaults to the workflow path
+ job: str | None = None
+ step: str | None = None
+
+ def render(self) -> str:
+ parts: list[str] = [self.workflow]
+ if self.job is not None:
+ parts.append(f"job '{self.job}'")
+ if self.step is not None:
+ parts.append(self.step)
+ return f"{': '.join(parts)}: {self.message}"
+
+
+@dataclass(slots=True)
+class CheckResult:
+ issues: list[Issue] = field(default_factory=list)
+
+
+class WorkflowCheck(ABC):
+ """A single workflow lint rule.
+
+ Subclasses set the three class attrs and implement :meth:`run`.
+
+ - ``id``: stable, machine-friendly identifier (used by ``--check`` filter).
+ - ``label``: short human-readable name shown in CLI output and GH annotations.
+ - ``description``: one-line summary; shown by ``--list``.
+ """
+
+ id: str
+ label: str
+ description: str
+
+ @abstractmethod
+ def run(self, workflows: list[Workflow]) -> CheckResult: ...
+
+ @property
+ def fix_hint(self) -> str | None:
+ """Optional remediation message printed once at the end if any issue fires."""
+ return None
+
+
+__all__ = ["CheckResult", "Issue", "WorkflowCheck"]
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py
new file mode 100644
index 000000000000..180e775c462b
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py
@@ -0,0 +1,56 @@
+"""Registry of workflow lint checks.
+
+To add a new rule:
+
+1. Add a new module here that defines a ``WorkflowCheck`` subclass.
+2. Import the class below and append an instance to ``CHECKS``.
+
+Order matters only for output stability — rules with a lower-numbered id show
+up first.
+"""
+
+from __future__ import annotations
+
+from ..check import WorkflowCheck
+from .dorny_negation import DornyNegationCheck
+from .job_timeouts import JobTimeoutsCheck
+from .pr_concurrency import PrConcurrencyCheck
+from .semgrep_services_coverage import SemgrepServicesCoverageCheck
+
+CHECKS: list[WorkflowCheck] = [
+ JobTimeoutsCheck(),
+ PrConcurrencyCheck(),
+ DornyNegationCheck(),
+ SemgrepServicesCoverageCheck(),
+]
+
+
+def _check_aliases(check: WorkflowCheck) -> tuple[str, str]:
+ """Lookup keys for a check: the full id and its ``WF###`` prefix."""
+ return check.id.lower(), check.id.partition("-")[0].lower()
+
+
+def _build_lookup(checks: list[WorkflowCheck]) -> dict[str, WorkflowCheck]:
+ """Build the alias→check map and fail loudly on duplicate ids or prefixes."""
+ lookup: dict[str, WorkflowCheck] = {}
+ for check in checks:
+ for alias in _check_aliases(check):
+ existing = lookup.get(alias)
+ if existing is not None and existing is not check:
+ raise ValueError(
+ f"workflow check alias '{alias}' is registered by both "
+ f"{existing.id!r} and {check.id!r} — pick distinct WF### prefixes"
+ )
+ lookup[alias] = check
+ return lookup
+
+
+_LOOKUP: dict[str, WorkflowCheck] = _build_lookup(CHECKS)
+
+
+def get_check(check_id: str) -> WorkflowCheck | None:
+ """Resolve a check by full id or by its ``WF###`` prefix (case-insensitive)."""
+ return _LOOKUP.get(check_id.strip().lower())
+
+
+__all__ = ["CHECKS", "get_check"]
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/dorny_negation.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/dorny_negation.py
new file mode 100644
index 000000000000..093ca3da9fad
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/dorny_negation.py
@@ -0,0 +1,67 @@
+"""``dorny/paths-filter`` ``!``-patterns must be guarded by ``predicate-quantifier: 'every'``.
+
+With dorny's default predicate-quantifier (``some``), each filter rule is
+OR'd independently. A ``!path`` rule then matches every file NOT at that path
+— silently inverting the intended exclusion. Using ``!`` patterns is only
+safe when the step also sets ``predicate-quantifier: 'every'``.
+
+Docs: https://github.com/dorny/paths-filter#advanced-options
+"""
+
+from __future__ import annotations
+
+from ..check import CheckResult, Issue, WorkflowCheck
+from ..model import Workflow, parse_filters
+
+DORNY_PREFIX = "dorny/paths-filter@"
+DOCS_URL = "https://github.com/dorny/paths-filter#advanced-options"
+
+
+class DornyNegationCheck(WorkflowCheck):
+ id = "WF003-dorny-negation"
+ label = "dorny negation guarded"
+ description = "dorny/paths-filter '!' patterns require predicate-quantifier: 'every'"
+
+ @property
+ def fix_hint(self) -> str | None:
+ return (
+ "Either remove the '!' patterns and use positive filters with count comparison, "
+ "or add `predicate-quantifier: 'every'` to the step's `with:` block. "
+ f"See {DOCS_URL}."
+ )
+
+ def run(self, workflows: list[Workflow]) -> CheckResult:
+ result = CheckResult()
+ for wf in workflows:
+ for job in wf.jobs:
+ for step in job.steps:
+ if step.uses is None or not step.uses.startswith(DORNY_PREFIX):
+ continue
+ if step.with_ is None:
+ continue
+ filters = parse_filters(step.with_.get("filters"))
+ if filters is None:
+ continue
+ quantifier = step.with_.get("predicate-quantifier")
+ if quantifier == "every":
+ continue
+ for filter_name, patterns in filters.items():
+ if not isinstance(patterns, list):
+ continue
+ for pattern in patterns:
+ if isinstance(pattern, str) and pattern.startswith("!"):
+ result.issues.append(
+ Issue(
+ workflow=wf.path.name,
+ job=job.name,
+ step=step.ref,
+ message=(
+ f"filter '{filter_name}' uses negation '{pattern}' without "
+ "`predicate-quantifier: 'every'` — with the default 'some' "
+ "quantifier, '!' rules match every file NOT at the path "
+ f"(including unrelated changes). See {DOCS_URL}."
+ ),
+ file=str(wf.path),
+ )
+ )
+ return result
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/job_timeouts.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/job_timeouts.py
new file mode 100644
index 000000000000..4ddab5fa16cc
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/job_timeouts.py
@@ -0,0 +1,42 @@
+"""Every job must declare ``timeout-minutes``.
+
+Without an explicit ``timeout-minutes``, GitHub Actions jobs default to a
+6-hour execution limit, so a stuck runner silently burns CI credits.
+
+Reusable workflow calls (``jobs.<id>.uses``) don't support ``timeout-minutes``
+at the job level — timeouts are set inside the called workflow — so we skip
+those jobs.
+"""
+
+from __future__ import annotations
+
+from ..check import CheckResult, Issue, WorkflowCheck
+from ..model import Workflow
+
+
+class JobTimeoutsCheck(WorkflowCheck):
+ id = "WF001-job-timeouts"
+ label = "job timeouts"
+ description = "every job declares timeout-minutes (reusable-workflow calls excepted)"
+
+ @property
+ def fix_hint(self) -> str | None:
+ return "Add `timeout-minutes: <n>` at the job level."
+
+ def run(self, workflows: list[Workflow]) -> CheckResult:
+ result = CheckResult()
+ for wf in workflows:
+ for job in wf.jobs:
+ if job.is_reusable_call:
+ continue
+ if job.has_timeout:
+ continue
+ result.issues.append(
+ Issue(
+ workflow=wf.path.name,
+ job=job.name,
+ message="missing timeout-minutes",
+ file=str(wf.path),
+ )
+ )
+ return result
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_concurrency.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_concurrency.py
new file mode 100644
index 000000000000..1382f547344a
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_concurrency.py
@@ -0,0 +1,100 @@
+"""PR-triggered ``ci-*.yml`` workflows must declare a safe top-level ``concurrency:`` block.
+
+Without it, every push to a PR branch starts a fresh run while the in-flight
+one keeps burning minutes. The repo convention (used by 30+ workflows):
+
+ concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+Using ``github.run_id`` as the fallback looks similar but disables dedup for
+push events because every run gets a unique group.
+
+Some workflows are intentionally exempt from cancellation (telemetry / shadow
+measurement, schedule-dominant jobs). Those are listed in ``SKIP`` below with
+a one-line reason each.
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..check import CheckResult, Issue, WorkflowCheck
+from ..model import Workflow
+
+BAD_FALLBACK = re.compile(r"head_ref\s*\|\|\s*github\.run_id")
+
+
+class PrConcurrencyCheck(WorkflowCheck):
+ id = "WF002-pr-concurrency"
+ label = "PR concurrency"
+ description = "PR-triggered ci-*.yml workflows declare safe top-level concurrency"
+
+ # Workflows intentionally exempt from concurrency cancellation. Each entry has
+ # a one-line reason so the next reader knows why.
+ SKIP: frozenset[str] = frozenset(
+ {
+ # Telemetry / shadow measurement — cancelling stale runs may drop data.
+ "ci-test-selection-shadow.yml",
+ # Schedule-dominant; PR trigger filtered to a single script — cosmetic gain.
+ "ci-backend-update-test-timing.yml",
+ # Migration enforcement; arguably wants to complete on every PR state.
+ "ci-migrations-service-separation-check.yml",
+ }
+ )
+
+ @property
+ def fix_hint(self) -> str | None:
+ return (
+ "Add this block after `on:`:\n"
+ "concurrency:\n"
+ " group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}\n"
+ " cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n"
+ "\n"
+ "Do not use `github.run_id` as the fallback; it creates a unique concurrency group per push run.\n"
+ "\n"
+ "Or, if cancelling stale runs would lose data (telemetry, schedule-only PR triggers, etc.),\n"
+ f"add the filename to {type(self).__name__}.SKIP with a one-line reason."
+ )
+
+ def run(self, workflows: list[Workflow]) -> CheckResult:
+ result = CheckResult()
+ for wf in workflows:
+ group_expr = _concurrency_group_expr(wf.concurrency)
+ if BAD_FALLBACK.search(group_expr):
+ result.issues.append(
+ Issue(
+ workflow=wf.path.name,
+ message=(
+ "concurrency group uses `github.head_ref || github.run_id`; use "
+ "`github.head_ref || github.ref` so push runs deduplicate"
+ ),
+ file=str(wf.path),
+ )
+ )
+
+ if not wf.path.name.startswith("ci-"):
+ continue
+ if wf.path.name in self.SKIP:
+ continue
+ if not wf.is_pr_triggered:
+ continue
+ if wf.concurrency is not None:
+ continue
+ result.issues.append(
+ Issue(
+ workflow=wf.path.name,
+ message="missing top-level concurrency block",
+ file=str(wf.path),
+ )
+ )
+ return result
+
+
+def _concurrency_group_expr(concurrency: dict | str | None) -> str:
+ if isinstance(concurrency, str):
+ return concurrency
+ if not isinstance(concurrency, dict):
+ return ""
+ group = concurrency.get("group")
+ return group if isinstance(group, str) else ""
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/semgrep_services_coverage.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/semgrep_services_coverage.py
new file mode 100644
index 000000000000..e199ace6ef44
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/semgrep_services_coverage.py
@@ -0,0 +1,78 @@
+"""Every ``services/<name>/`` is covered by a language-specific Semgrep job.
+
+The repo-wide ``semgrep-general`` job excludes ``services/``, so a new
+service added without updating ``semgrep-python`` or ``semgrep-js`` silently
+drops out of SAST.
+
+Unlike the other checks, this one needs filesystem context (``services/``)
+plus the contents of one specific workflow (``ci-security.yaml``), so it
+walks both via ``REPO_ROOT`` rather than only iterating the parsed
+``Workflow`` list.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from hogli.manifest import REPO_ROOT
+
+from ..check import CheckResult, Issue, WorkflowCheck
+from ..model import Workflow
+
+COVERING_JOBS = ("semgrep-python", "semgrep-js")
+SECURITY_WORKFLOW_NAME = "ci-security.yaml"
+
+
+class SemgrepServicesCoverageCheck(WorkflowCheck):
+ id = "WF004-semgrep-services-coverage"
+ label = "semgrep services coverage"
+ description = f"every services/<name>/ appears in {' or '.join(COVERING_JOBS)} run-text in {SECURITY_WORKFLOW_NAME}"
+
+ def __init__(self, repo_root: Path | None = None) -> None:
+ # Injected so tests can point at a fixture tree without monkeypatching env vars.
+ self._repo_root = repo_root or REPO_ROOT
+
+ @property
+ def fix_hint(self) -> str | None:
+ return f"Add each missing service to the matching job's target list in {SECURITY_WORKFLOW_NAME}."
+
+ def run(self, workflows: list[Workflow]) -> CheckResult:
+ result = CheckResult()
+ services_dir = self._repo_root / "services"
+ if not services_dir.exists():
+ return result
+
+ security_wf = next((wf for wf in workflows if wf.path.name == SECURITY_WORKFLOW_NAME), None)
+ if security_wf is None:
+ result.issues.append(
+ Issue(
+ workflow=SECURITY_WORKFLOW_NAME,
+ message=f"workflow not found in workflows directory; cannot verify coverage of {COVERING_JOBS}",
+ )
+ )
+ return result
+
+ run_text = _covering_run_text(security_wf)
+
+ services = sorted(p.name for p in services_dir.iterdir() if p.is_dir() and not p.name.startswith("."))
+ for name in services:
+ if f"services/{name}/" not in run_text:
+ result.issues.append(
+ Issue(
+ workflow=SECURITY_WORKFLOW_NAME,
+ message=f"services/{name}/ not covered by {' or '.join(COVERING_JOBS)}",
+ file=str(security_wf.path),
+ )
+ )
+ return result
+
+
+def _covering_run_text(wf: Workflow) -> str:
+ parts: list[str] = []
+ for job in wf.jobs:
+ if job.name not in COVERING_JOBS:
+ continue
+ for step in job.steps:
+ if step.run is not None:
+ parts.append(step.run)
+ return "\n".join(parts)
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/cli.py b/tools/hogli-commands/hogli_commands/workflow_lint/cli.py
new file mode 100644
index 000000000000..09a24c747b66
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/cli.py
@@ -0,0 +1,102 @@
+"""Click entrypoint for ``lint:workflows``.
+
+Wired into the hogli CLI via the ``click:`` manifest entry in ``hogli.yaml``;
+the lazy loader resolves this module only when the command actually runs.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import click
+from hogli.manifest import REPO_ROOT
+
+from .check import Issue, WorkflowCheck
+from .checks import CHECKS, get_check
+from .model import Workflow, WorkflowParseError, read_workflows
+
+_IN_GH_ACTIONS = os.environ.get("GITHUB_ACTIONS") == "true"
+
+
+def _gh_annotation(level: str, check_label: str, issue: Issue) -> None:
+ if not _IN_GH_ACTIONS:
+ return
+ file_part = f" file={issue.file}" if issue.file else ""
+ click.echo(f"::{level}{file_part} title=lint:workflows ({check_label})::{issue.render()}")
+
+
+def _run_one(check: WorkflowCheck, workflows: list[Workflow]) -> int:
+ """Run a single check, print results, return the issue count."""
+ click.echo(f" {check.id} ({check.label})...")
+ result = check.run(workflows)
+ for issue in result.issues:
+ click.echo(f" ✗ {issue.render()}")
+ _gh_annotation("error", check.label, issue)
+ if not result.issues:
+ click.echo(" ✓ ok")
+ return len(result.issues)
+
+
+def _default_workflows_dir() -> Path:
+ return REPO_ROOT / ".github" / "workflows"
+
+
+ name="lint:workflows",
+ help="Lint .github/workflows/** for repo conventions (timeouts, concurrency, dorny negation, semgrep coverage)",
+)
+ "--check",
+ "check_id",
+ metavar="ID",
+ help="Run only the check with the given id (full id or WF### prefix, e.g. WF001 or WF001-job-timeouts)",
+)
[email protected]("--list", "list_checks", is_flag=True, help="List registered checks and exit")
+ "--workflows-dir",
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
+ default=None,
+ show_default=False,
+ help="Workflows directory (defaults to <repo>/.github/workflows)",
+)
+def cmd_lint_workflows(check_id: str | None, list_checks: bool, workflows_dir: Path | None) -> None:
+ if list_checks:
+ for check in CHECKS:
+ click.echo(f"{check.id}\t{check.label} — {check.description}")
+ return
+
+ if check_id is not None:
+ target = get_check(check_id)
+ if target is None:
+ raise click.UsageError(f"Unknown check id '{check_id}'. Run with --list to see registered checks.")
+ selected: list[WorkflowCheck] = [target]
+ else:
+ selected = list(CHECKS)
+
+ resolved_dir = workflows_dir or _default_workflows_dir()
+ try:
+ workflows = list(read_workflows(resolved_dir))
+ except WorkflowParseError as exc:
+ click.echo(f"✗ {exc}", err=True)
+ raise SystemExit(1) from exc
+
+ click.echo(f"Linting {len(workflows)} workflow(s) with {len(selected)} check(s):\n")
+
+ total_issues = 0
+ failing_checks: list[WorkflowCheck] = []
+ for check in selected:
+ issues = _run_one(check, workflows)
+ total_issues += issues
+ if issues:
+ failing_checks.append(check)
+
+ click.echo("")
+ if failing_checks:
+ for check in failing_checks:
+ if check.fix_hint:
+ click.echo(f"Fix for {check.id}:\n{check.fix_hint}\n")
+ click.echo(f"✗ {total_issues} issue(s) across {len(failing_checks)} check(s)")
+ raise SystemExit(1)
+
+ click.echo(f"✓ All {len(selected)} check(s) passed across {len(workflows)} workflow(s)")
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/model.py b/tools/hogli-commands/hogli_commands/workflow_lint/model.py
new file mode 100644
index 000000000000..5d4fc8d09cee
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/model.py
@@ -0,0 +1,198 @@
+"""Parsed model of `.github/workflows/*.yml`.
+
+This is the deep module of the workflow_lint package: it hides every PyYAML
+quirk and yields typed Workflow / Job / Step objects so individual checks can
+ignore parsing details and just iterate.
+
+Quirks hidden here:
+- Top-level `on:` parses to a Python `True` key (PyYAML interprets `on` as the
+ boolean literal). We normalize back to the original string/list/dict.
+- `dorny/paths-filter` accepts `with.filters` either as a dict or as a YAML
+ block-string; we parse the block-string form here so checks see one shape.
+- Reusable workflow calls (jobs with `uses:` at the job level) have no steps
+ and no `timeout-minutes` — surfaced as `is_reusable_call` so checks can skip
+ cleanly.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import yaml
+
+PR_TRIGGERS = frozenset({"pull_request", "pull_request_target"})
+
+
+class WorkflowParseError(Exception):
+ """Raised when a workflow file fails to parse as valid YAML."""
+
+ def __init__(self, path: Path, original: Exception) -> None:
+ super().__init__(f"{path.name}: failed to parse YAML: {original}")
+ self.path = path
+ self.original = original
+
+
+@dataclass(frozen=True, slots=True)
+class Step:
+ idx: int
+ uses: str | None
+ run: str | None
+ with_: dict | None
+ id_: str | None
+ raw: dict
+
+ @property
+ def ref(self) -> str:
+ """Human-readable step reference, e.g. ``step id 'install'`` or ``step[3]``."""
+ return f"step id '{self.id_}'" if self.id_ else f"step[{self.idx}]"
+
+
+@dataclass(frozen=True, slots=True)
+class Job:
+ name: str
+ uses: str | None # set when this job is a reusable-workflow call
+ has_timeout: bool # any value at the `timeout-minutes` key (int OR `${{ ... }}` expression)
+ timeout_minutes: int | None # the int value, or None if absent or expression
+ steps: list[Step] = field(default_factory=list)
+ raw: dict = field(default_factory=dict)
+
+ @property
+ def is_reusable_call(self) -> bool:
+ return self.uses is not None
+
+
+@dataclass(frozen=True, slots=True)
+class Workflow:
+ path: Path
+ name: str
+ on: object # str | list | dict — original form, with the True-key quirk normalized away
+ concurrency: dict | str | None
+ jobs: list[Job] = field(default_factory=list)
+ raw: dict = field(default_factory=dict)
+
+ @property
+ def is_pr_triggered(self) -> bool:
+ return _matches_pr_trigger(self.on)
+
+
+def _matches_pr_trigger(triggers: object) -> bool:
+ if isinstance(triggers, str):
+ return triggers in PR_TRIGGERS
+ if isinstance(triggers, (list, dict)):
+ return any(t in PR_TRIGGERS for t in triggers)
+ return False
+
+
+def _normalize_on(data: dict) -> object:
+ # PyYAML parses the bare YAML key `on:` as the boolean literal `True`.
+ # `safe_load` of a quoted "on" gives us the string. Either way, surface
+ # the original triggers regardless of how they were typed.
+ if True in data:
+ return data[True]
+ return data.get("on")
+
+
+def parse_filters(raw: object) -> dict | None:
+ """Parse `dorny/paths-filter` `with.filters`. Returns None for non-dict / external-path strings."""
+ if isinstance(raw, dict):
+ return raw
+ if not isinstance(raw, str):
+ return None
+ # Single-line strings without a colon are external-file path refs (dorny supports those).
+ if "\n" not in raw and ":" not in raw:
+ return None
+ try:
+ parsed = yaml.safe_load(raw)
+ except yaml.YAMLError:
+ return None
+ return parsed if isinstance(parsed, dict) else None
+
+
+def _build_step(idx: int, raw: object) -> Step | None:
+ if not isinstance(raw, dict):
+ return None
+ uses = raw.get("uses")
+ run = raw.get("run")
+ with_block = raw.get("with")
+ step_id = raw.get("id")
+ return Step(
+ idx=idx,
+ uses=uses if isinstance(uses, str) else None,
+ run=run if isinstance(run, str) else None,
+ with_=with_block if isinstance(with_block, dict) else None,
+ id_=step_id if isinstance(step_id, str) else None,
+ raw=raw,
+ )
+
+
+def _build_job(name: str, raw: object) -> Job | None:
+ if not isinstance(raw, dict):
+ return None
+ uses = raw.get("uses")
+ raw_steps = raw.get("steps")
+ steps: list[Step] = []
+ if isinstance(raw_steps, list):
+ for idx, step_raw in enumerate(raw_steps):
+ step = _build_step(idx, step_raw)
+ if step is not None:
+ steps.append(step)
+ has_timeout = "timeout-minutes" in raw
+ timeout = raw.get("timeout-minutes")
+ return Job(
+ name=name,
+ uses=uses if isinstance(uses, str) else None,
+ has_timeout=has_timeout,
+ timeout_minutes=timeout if isinstance(timeout, int) else None,
+ steps=steps,
+ raw=raw,
+ )
+
+
+def _build_workflow(path: Path) -> Workflow | None:
+ """Parse one workflow file. Returns None for non-mapping YAML (rare but legal)."""
+ with open(path, encoding="utf-8") as f:
+ try:
+ data = yaml.safe_load(f)
+ except yaml.YAMLError as exc:
+ raise WorkflowParseError(path, exc) from exc
+ if not isinstance(data, dict):
+ return None
+
+ raw_jobs = data.get("jobs")
+ jobs: list[Job] = []
+ if isinstance(raw_jobs, dict):
+ for job_name, job_raw in raw_jobs.items():
+ job = _build_job(str(job_name), job_raw)
+ if job is not None:
+ jobs.append(job)
+
+ concurrency = data.get("concurrency")
+ return Workflow(
+ path=path,
+ name=str(data.get("name") or path.name),
+ on=_normalize_on(data),
+ concurrency=concurrency if isinstance(concurrency, (dict, str)) else None,
+ jobs=jobs,
+ raw=data,
+ )
+
+
+def read_workflows(workflows_dir: Path, glob: str = "*.y*ml") -> Iterator[Workflow]:
+ """Walk ``workflows_dir`` and yield parsed :class:`Workflow` objects."""
+ for path in sorted(workflows_dir.glob(glob)):
+ wf = _build_workflow(path)
+ if wf is not None:
+ yield wf
+
+
+__all__ = [
+ "Job",
+ "PR_TRIGGERS",
+ "Step",
+ "Workflow",
+ "WorkflowParseError",
+ "parse_filters",
+ "read_workflows",
+]