Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

85.3 KB
Raw Blame
#!/usr/bin/env python3
"""Generate ``.github/CI_HEALTH.md`` — a static configuration-health report.

This is *complementary* to ``docs/ci/workflow-status.md``:

* ``docs/ci/workflow-status.md``  — LIVE run status, generated by
  ``scripts/generate_workflow_status.py`` using the GitHub API.
* ``.github/CI_HEALTH.md`` (this script) — STATIC configuration health:
  GitHub-Actions pinning, permission hygiene, harden-runner coverage,
  pre-commit hook freshness, security-scanner coverage, and a recent-changes
  log for CI/CD config files.

Runs in CI (``.github/workflows/ci-health-report.yml``) and locally:

    python scripts/generate_ci_health.py           # write .github/CI_HEALTH.md
    python scripts/generate_ci_health.py --stdout  # print instead of write
    python scripts/generate_ci_health.py --check   # exit 1 on high/critical findings

Only depends on the standard library + PyYAML (already used elsewhere in CI).
"""

from __future__ import annotations

import argparse
import datetime
import importlib
import importlib.util
import json
import os
import pathlib
import re
import subprocess
import sys
import time
from collections.abc import Iterator
from dataclasses import dataclass, replace
from typing import (
    Final,
    Literal,
    NotRequired,
    Protocol,
    TypeAlias,
    TypedDict,
    runtime_checkable,
)

ROOT: Final = pathlib.Path(__file__).resolve().parents[1]
WORKFLOWS_DIR: Final = ROOT / ".github" / "workflows"
PRECOMMIT_FILE: Final = ROOT / ".pre-commit-config.yaml"
DEPENDABOT_FILE: Final = ROOT / ".github" / "dependabot.yml"
OUT_FILE: Final = ROOT / ".github" / "CI_HEALTH.md"
CI_PATHS: Final = (
    ".github/workflows/",
    ".pre-commit-config.yaml",
    ".github/dependabot.yml",
    "scripts/generate_ci_health.py",
)
SHA_PIN_RE: Final = re.compile(r"[0-9a-f]{40}", re.IGNORECASE)
DOCKER_DIGEST_RE: Final = re.compile(r"sha256:[0-9a-f]{64}")
FLOATING_REVS: Final = frozenset(
    {"main", "master", "latest", "develop", "stable", "head"}
)
PRIVILEGED_PIN_RE: Final = re.compile(r"publish|release|deploy|docker-publish")
PRIVILEGED_PERMS_RE: Final = re.compile(r"publish|release|deploy|gate")

Severity: TypeAlias = Literal["critical", "high", "medium", "low"]
YamlScalar: TypeAlias = (
    None | bool | int | float | str | datetime.date | datetime.datetime
)
YamlValue: TypeAlias = (
    YamlScalar | list["YamlValue"] | dict[YamlScalar, "YamlValue"]
)


@runtime_checkable
class YamlApi(Protocol):
    YAMLError: type[Exception]

    def safe_load(self, stream: str) -> YamlValue: ...

    def safe_load_all(self, stream: str) -> Iterator[YamlValue]: ...


try:
    _yaml_module = importlib.import_module("yaml")
except ImportError:  # pragma: no cover
    sys.exit("PyYAML is required: pip install pyyaml==6.0.3")
if not isinstance(_yaml_module, YamlApi):  # pragma: no cover
    sys.exit("Installed PyYAML does not provide the expected loader API")
YAML: Final[YamlApi] = _yaml_module

REQUIRED_SCANNERS: Final[dict[str, tuple[str, ...]]] = {
    "Dependencies": ("osv-scanner", "dependabot", "npm-audit", "retirejs"),
    "SAST": ("codeql", "semgrep", "bandit", "devskim", "bearer"),
    "Secrets": ("gitleaks", "trufflehog"),
    "Supply-Chain": ("ossf-scorecard", "sbom"),
    "Workflow-Security": ("zizmor",),
}
OPTIONAL_SCANNERS: Final[dict[str, tuple[str, ...]]] = {
    "Containers": (
        "grype",
        "trivy",
        "dockle",
        "hadolint",
        "container-security",
    ),
    "DAST": ("owasp-zap", "nuclei"),
    "IaC": ("checkov",),
}


@dataclass(frozen=True, slots=True)
class Finding:
    severity: Severity
    area: str
    file: str
    message: str
    fixable: bool = True


@dataclass(frozen=True, slots=True)
class WorkflowFile:
    name: str
    uses: int
    pinned: int
    unpinned: tuple[str, ...]


@dataclass(frozen=True, slots=True)
class WorkflowAnalysis:
    files: tuple[WorkflowFile, ...]
    total_uses: int
    pinned_uses: int
    total_checkouts: int
    safe_checkouts: int
    non_exempt_jobs: int
    permissions_jobs: int
    permissions_ok_jobs: int
    harden_ok_jobs: int
    missing_permissions: tuple[str, ...]
    missing_harden: tuple[str, ...]


@dataclass(frozen=True, slots=True)
class PrecommitHook:
    hook_id: str
    repo: str
    rev: str
    revision_kind: Literal["commit", "floating", "tag_or_unknown", "special"]


class PrecommitAnalysis(TypedDict):
    present: bool
    parse_error: NotRequired[str]
    hook_count: int
    hooks: list[PrecommitHook]
    floating_revs: list[PrecommitHook]
    has_secrets_hook: bool
    tag_or_unknown_count: NotRequired[int]


@dataclass(frozen=True, slots=True)
class ScannerCategory:
    name: str
    required: bool
    satisfied: bool
    workflows: tuple[str, ...]
    dependabot_config: bool


@dataclass(frozen=True, slots=True)
class GitChange:
    sha: str
    date: str
    author: str
    subject: str


@dataclass(frozen=True, slots=True)
class GitHistory:
    changes: tuple[GitChange, ...]
    unavailable: str | None


@dataclass(frozen=True, slots=True)
class WorkflowRun:
    database_id: int
    conclusion: str
    event: str
    head_branch: str
    created_at: str
    # True only for the synthetic UNRESOLVED run manufactured when the live
    # time budget ran out before a settled run could be resolved from the
    # fetched gate history: its OWN job list was never queried, so nothing
    # about "not naming this scanner" is known.
    budget_exhausted: bool = False
    # Why this run resolved to `_UNRESOLVED` (``None`` for any other
    # conclusion): "job_list_unreadable" (`gh run view --json jobs` failed,
    # timed out, or returned unparseable JSON -- nothing was learned about
    # this scanner), "job_list_lacked_scanner" (the list WAS read and
    # genuinely didn't name this scanner), "gate_has_no_caller_job" (the
    # gate's workflow file has no job calling this workflow at all -- a
    # per-gate fact, not a per-run one), or "budget_exhausted" (mirrors
    # `budget_exhausted` above: this run's job list was never even
    # queried). Not an exhaustive enum of every failure mode -- a small,
    # short string so a new cause can be added without inventing a type.
    unresolved_reason: str | None = None


@dataclass(frozen=True, slots=True)
class LiveStatus:
    workflow: str
    runs: tuple[WorkflowRun, ...]
    latest_conclusion: str | None
    unavailable: str | None
    # Set when `runs` are the runs of the gate that calls this workflow
    # rather than the workflow's own (reusable scanners have no useful
    # direct history).
    gated_by: str | None = None
    # Computed at collection time against the wall clock so that render()
    # stays a pure function of its inputs.
    stale: bool = False
    # Collection-time remarks that render() cannot derive from the runs alone
    # (a truncated gate history, an unparseable timestamp).
    notes: tuple[str, ...] = ()


@dataclass(frozen=True, slots=True)
class Dimension:
    name: str
    weight: int
    ratio: float | None


def _read(path: pathlib.Path) -> str:
    try:
        return path.read_text(encoding="utf-8")
    except (FileNotFoundError, OSError):
        return ""


def _workflow_files() -> tuple[pathlib.Path, ...]:
    return tuple(
        sorted((*WORKFLOWS_DIR.glob("*.yml"), *WORKFLOWS_DIR.glob("*.yaml")))
    )


def _iter_action_mappings(
    value: YamlValue,
) -> Iterator[tuple[dict[YamlScalar, YamlValue], bool]]:
    if not isinstance(value, dict):
        return
    jobs = value.get("jobs")
    if not isinstance(jobs, dict):
        return
    for job in jobs.values():
        if not isinstance(job, dict):
            continue
        if "uses" in job:
            yield job, False
        steps = job.get("steps")
        if not isinstance(steps, list):
            continue
        for step in steps:
            if isinstance(step, dict) and "uses" in step:
                yield step, True


def _action_head(ref: str) -> str:
    head, separator, _tail = ref.rpartition("@")
    return head if separator else ref


def _pinning_kind(
    ref: str,
) -> Literal["local", "pinned", "unpinned", "expression"]:
    head, separator, tail = ref.rpartition("@")
    if ref.startswith(("./", "$/")):
        return "local"
    if ref.startswith("docker://"):
        return (
            "pinned"
            if separator and DOCKER_DIGEST_RE.fullmatch(tail)
            else "unpinned"
        )
    if "${{" in ref:
        return "expression"
    if separator and head and SHA_PIN_RE.fullmatch(tail):
        return "pinned"
    return "unpinned"


def _is_false(value: YamlValue) -> bool:
    return value is False or (
        isinstance(value, str) and value.casefold() == "false"
    )


def _has_explicit_permissions(mapping: dict[YamlScalar, YamlValue]) -> bool:
    if "permissions" not in mapping:
        return False
    value = mapping["permissions"]
    return isinstance(value, dict) or (
        isinstance(value, str) and value.casefold() in ("read-all", "write-all")
    )


def _workflow_is_privileged(
    filename: str, workflow_name: str, pattern: re.Pattern[str]
) -> bool:
    return pattern.search(f"{filename} {workflow_name}".casefold()) is not None


def analyze_workflows(findings: list[Finding]) -> WorkflowAnalysis:
    rows: list[WorkflowFile] = []
    total_uses = pinned_uses = total_checkouts = safe_checkouts = 0
    non_exempt_jobs = permissions_jobs = permissions_ok_jobs = (
        harden_ok_jobs
    ) = 0
    missing_permissions: list[str] = []
    missing_harden: list[str] = []

    for path in _workflow_files():
        try:
            documents = list(YAML.safe_load_all(_read(path)))
        except YAML.YAMLError as error:
            findings.append(
                Finding(
                    "high", "workflow", path.name, f"YAML parse error: {error}"
                )
            )
            continue
        if len(documents) != 1:
            findings.append(
                Finding(
                    "high",
                    "workflow",
                    path.name,
                    "malformed: multi-document YAML",
                )
            )
            continue
        data = documents[0]
        if not isinstance(data, dict):
            findings.append(
                Finding(
                    "high",
                    "workflow",
                    path.name,
                    "malformed: top-level YAML must be a mapping",
                )
            )
            continue

        jobs_value = data.get("jobs")
        if not isinstance(jobs_value, dict) or not jobs_value:
            findings.append(
                Finding(
                    "high",
                    "workflow",
                    path.name,
                    "malformed: jobs must be a non-empty mapping",
                )
            )
            continue

        workflow_name_value = data.get("name", "")
        workflow_name = (
            workflow_name_value if isinstance(workflow_name_value, str) else ""
        )
        pin_privileged = _workflow_is_privileged(
            path.name, workflow_name, PRIVILEGED_PIN_RE
        )
        perms_privileged = _workflow_is_privileged(
            path.name, workflow_name, PRIVILEGED_PERMS_RE
        )
        file_uses = file_pinned = 0
        file_unpinned: list[str] = []

        for mapping, is_step in _iter_action_mappings(data):
            uses_value = mapping.get("uses")
            if uses_value is None:
                continue
            if not isinstance(uses_value, str):
                findings.append(
                    Finding(
                        "medium",
                        "workflow",
                        path.name,
                        "malformed uses value is not a string",
                    )
                )
                continue
            ref = uses_value.strip()
            kind = _pinning_kind(ref)
            if kind != "local":
                total_uses += 1
                file_uses += 1
            if kind == "pinned":
                pinned_uses += 1
                file_pinned += 1
            elif kind == "expression":
                findings.append(
                    Finding(
                        "high",
                        "pinning",
                        path.name,
                        "action ref uses an expression, cannot verify pinning",
                    )
                )
            elif kind == "unpinned":
                severity: Severity = "critical" if pin_privileged else "high"
                findings.append(
                    Finding(
                        severity,
                        "pinning",
                        path.name,
                        f"unpinned action: {ref}",
                    )
                )
                file_unpinned.append(ref)

            if is_step and _action_head(ref).casefold() == "actions/checkout":
                total_checkouts += 1
                with_value = mapping.get("with")
                persist_value: YamlValue = None
                if isinstance(with_value, dict):
                    persist_value = with_value.get("persist-credentials")
                if _is_false(persist_value):
                    safe_checkouts += 1
                else:
                    findings.append(
                        Finding(
                            "high",
                            "checkout",
                            path.name,
                            "checkout without persist-credentials: false",
                        )
                    )

        rows.append(
            WorkflowFile(
                path.name, file_uses, file_pinned, tuple(file_unpinned)
            )
        )

        top_permissions = _has_explicit_permissions(data)
        for job_name_value, job_value in sorted(
            jobs_value.items(), key=lambda item: str(item[0])
        ):
            job_name = str(job_name_value)
            location = f"{path.name} / {job_name}"
            if not isinstance(job_value, dict):
                findings.append(
                    Finding(
                        "high",
                        "workflow",
                        location,
                        "malformed: job must be a mapping",
                    )
                )
                continue
            permissions_jobs += 1
            if top_permissions or _has_explicit_permissions(job_value):
                permissions_ok_jobs += 1
            else:
                severity = "high" if perms_privileged else "medium"
                message = (
                    "no explicit permissions block (uses default token scopes)"
                )
                findings.append(
                    Finding(severity, "permissions", location, message)
                )
                missing_permissions.append(location)

            steps_value = job_value.get("steps")
            if "uses" in job_value and "steps" in job_value:
                findings.append(
                    Finding(
                        "high",
                        "workflow",
                        location,
                        "malformed: a job cannot combine reusable uses with steps",
                    )
                )
            if "steps" in job_value and (
                not isinstance(steps_value, list) or not steps_value
            ):
                findings.append(
                    Finding(
                        "high",
                        "workflow",
                        location,
                        "malformed: steps must be a non-empty list",
                    )
                )
                continue
            if not isinstance(steps_value, list):
                reusable_uses = job_value.get("uses")
                if (
                    not isinstance(reusable_uses, str)
                    or not reusable_uses.strip()
                ):
                    findings.append(
                        Finding(
                            "high",
                            "workflow",
                            location,
                            "job has neither steps nor uses",
                        )
                    )
                continue
            non_exempt_jobs += 1
            for index, step in enumerate(steps_value):
                if not isinstance(step, dict):
                    findings.append(
                        Finding(
                            "high",
                            "workflow",
                            location,
                            f"malformed: step {index} must be a mapping",
                        )
                    )
                    continue
                has_uses = "uses" in step
                has_run = "run" in step
                command = step.get("uses" if has_uses else "run")
                if (
                    has_uses == has_run
                    or not isinstance(command, str)
                    or (has_uses and not command.strip())
                ):
                    findings.append(
                        Finding(
                            "high",
                            "workflow",
                            location,
                            f"malformed: step {index} requires exactly one valid uses or run command",
                        )
                    )

            first_uses = ""
            if steps_value and isinstance(steps_value[0], dict):
                first_uses_value = steps_value[0].get("uses")
                if isinstance(first_uses_value, str):
                    first_uses = first_uses_value
            if (
                _action_head(first_uses).casefold()
                == "step-security/harden-runner"
            ):
                harden_ok_jobs += 1
            else:
                findings.append(
                    Finding(
                        "medium",
                        "harden-runner",
                        location,
                        "first step is not step-security/harden-runner",
                    )
                )
                missing_harden.append(location)

    return WorkflowAnalysis(
        tuple(rows),
        total_uses,
        pinned_uses,
        total_checkouts,
        safe_checkouts,
        non_exempt_jobs,
        permissions_jobs,
        permissions_ok_jobs,
        harden_ok_jobs,
        tuple(missing_permissions),
        tuple(missing_harden),
    )


def analyze_precommit(
    findings: list[Finding] | None = None,
    path: pathlib.Path = PRECOMMIT_FILE,
) -> PrecommitAnalysis:
    finding_list = findings if findings is not None else []
    text = _read(path)
    if not text:
        finding_list.append(
            Finding(
                "medium",
                "pre-commit",
                path.name,
                "configuration file is missing",
            )
        )
        return {
            "present": False,
            "hook_count": 0,
            "hooks": [],
            "floating_revs": [],
            "has_secrets_hook": False,
        }
    try:
        config = YAML.safe_load(text)
    except YAML.YAMLError as error:
        finding_list.append(
            Finding("high", "pre-commit", path.name, "YAML parse error")
        )
        return {
            "present": True,
            "parse_error": str(error),
            "hook_count": 0,
            "hooks": [],
            "floating_revs": [],
            "has_secrets_hook": False,
        }

    hooks: list[PrecommitHook] = []
    has_secrets_hook = False
    if not isinstance(config, dict):
        finding_list.append(
            Finding("medium", "pre-commit", path.name, "repos must be a list")
        )
        return {
            "present": True,
            "hook_count": 0,
            "hooks": [],
            "floating_revs": [],
            "has_secrets_hook": False,
        }

    repos_value = config.get("repos")
    if not isinstance(repos_value, list):
        finding_list.append(
            Finding("medium", "pre-commit", path.name, "repos must be a list")
        )
        return {
            "present": True,
            "hook_count": 0,
            "hooks": [],
            "floating_revs": [],
            "has_secrets_hook": False,
        }
    for index, repo_value in enumerate(repos_value):
        if not isinstance(repo_value, dict):
            finding_list.append(
                Finding(
                    "medium",
                    "pre-commit",
                    path.name,
                    f"malformed repository entry {index}",
                )
            )
            continue
        hooks_value = repo_value.get("hooks")
        if not isinstance(hooks_value, list):
            finding_list.append(
                Finding(
                    "medium",
                    "pre-commit",
                    path.name,
                    f"malformed repository entry {index}",
                )
            )
            continue
        repo_raw = repo_value.get("repo")
        if not isinstance(repo_raw, str) or not repo_raw.strip():
            finding_list.append(
                Finding(
                    "medium",
                    "pre-commit",
                    path.name,
                    f"repository entry {index} has an empty repo",
                )
            )
            continue
        repo = repo_raw.strip()
        rev_raw = repo_value.get("rev", "")
        rev = rev_raw.strip() if isinstance(rev_raw, str) else ""
        if repo in ("local", "meta"):
            revision_kind: Literal[
                "commit", "floating", "tag_or_unknown", "special"
            ] = "special"
        elif not rev or rev.casefold() in FLOATING_REVS:
            revision_kind = "floating"
        elif SHA_PIN_RE.fullmatch(rev):
            revision_kind = "commit"
        else:
            revision_kind = "tag_or_unknown"

        for hook_index, hook_value in enumerate(hooks_value):
            if not isinstance(hook_value, dict):
                finding_list.append(
                    Finding(
                        "medium",
                        "pre-commit",
                        path.name,
                        f"malformed hook {index}.{hook_index}",
                    )
                )
                continue
            hook_id_raw = hook_value.get("id", "")
            hook_id = hook_id_raw if isinstance(hook_id_raw, str) else ""
            if hook_id in (
                "gitleaks",
                "trufflehog",
                "detect-secrets",
                "gitleaks-system",
            ):
                has_secrets_hook = True
            hook = PrecommitHook(hook_id, repo, rev, revision_kind)
            hooks.append(hook)
            if revision_kind == "floating":
                finding_list.append(
                    Finding(
                        "medium",
                        "pre-commit",
                        path.name,
                        f"hook {hook_id or '<unnamed>'} has a floating revision",
                    )
                )

    floating = [hook for hook in hooks if hook.revision_kind == "floating"]
    tag_count = sum(hook.revision_kind == "tag_or_unknown" for hook in hooks)
    if not has_secrets_hook:
        finding_list.append(
            Finding(
                "medium",
                "pre-commit",
                path.name,
                "no secret-scanning hook configured",
            )
        )
    return {
        "present": True,
        "hook_count": len(hooks),
        "hooks": hooks,
        "floating_revs": floating,
        "has_secrets_hook": has_secrets_hook,
        "tag_or_unknown_count": tag_count,
    }


# A workflow whose name only mentions a scanner because it TESTS that
# scanner's configuration (``gitleaks-rule-tests.yml``) is not a scan.
_TEST_WORKFLOW_SUFFIXES: Final = ("-test", "-tests", "_test", "_tests")


def _is_test_workflow(name: str) -> bool:
    stem = name.casefold().rsplit(".", 1)[0]
    return stem.endswith(_TEST_WORKFLOW_SUFFIXES)


def analyze_scanners(findings: list[Finding]) -> tuple[ScannerCategory, ...]:
    workflow_names = tuple(
        path.name.casefold()
        for path in _workflow_files()
        if not _is_test_workflow(path.name)
    )
    categories: list[ScannerCategory] = []
    for required, definitions in (
        (True, REQUIRED_SCANNERS),
        (False, OPTIONAL_SCANNERS),
    ):
        for category, scanners in sorted(definitions.items()):
            matches = tuple(
                name
                for name in workflow_names
                if any(scanner in name for scanner in scanners)
            )
            dependabot_config = (
                category == "Dependencies" and DEPENDABOT_FILE.is_file()
            )
            satisfied = bool(matches) or dependabot_config
            categories.append(
                ScannerCategory(
                    category, required, satisfied, matches, dependabot_config
                )
            )
            if required and not satisfied:
                findings.append(
                    Finding(
                        "medium",
                        "scanners",
                        category,
                        f"required security category {category} has no executing scanner",
                    )
                )
    return tuple(categories)


def _scanner_workflow_files() -> tuple[str, ...]:
    """Return actual filenames of workflows matching any scanner keyword."""
    keywords = [
        keyword
        for group in (REQUIRED_SCANNERS, OPTIONAL_SCANNERS)
        for scanners in group.values()
        for keyword in scanners
    ]
    return tuple(
        sorted(
            path.name
            for path in _workflow_files()
            if any(keyword in path.name.casefold() for keyword in keywords)
            and not _is_test_workflow(path.name)
        )
    )


def discount_idle_scanners(
    scanners: tuple[ScannerCategory, ...],
    live: tuple[LiveStatus, ...],
    findings: list[Finding],
) -> tuple[ScannerCategory, ...]:
    """Drop scanner workflows with NO RUNS from their category's evidence.

    A workflow that exists but never ran on ``main`` in the query window
    (for example one whose only caller is commented out) is not coverage.
    Unavailable live entries are left alone: that is a failed query, not
    evidence of an idle scanner. A required category left with no evidence
    gets the same finding :func:`analyze_scanners` raises statically.
    """
    idle = {
        entry.workflow.casefold()
        for entry in live
        if entry.unavailable is None and not entry.runs
    }
    if not idle:
        return scanners
    adjusted: list[ScannerCategory] = []
    for category in scanners:
        workflows = tuple(
            name for name in category.workflows if name not in idle
        )
        satisfied = bool(workflows) or category.dependabot_config
        if category.required and category.satisfied and not satisfied:
            findings.append(
                Finding(
                    "medium",
                    "scanners",
                    category.name,
                    f"required security category {category.name} has no executing scanner (no runs on {_LIVE_BRANCH} in the query window)",
                )
            )
        adjusted.append(
            replace(category, satisfied=satisfied, workflows=workflows)
        )
    return tuple(adjusted)


def _gh_available() -> str | None:
    """Return ``None`` if gh is usable, or an error reason string."""
    try:
        result = subprocess.run(
            ["gh", "--version"],
            capture_output=True,
            text=True,
            timeout=5,
            check=False,
        )
    except (subprocess.TimeoutExpired, OSError):
        return "gh not found or timed out"
    return None if result.returncode == 0 else f"gh exit {result.returncode}"


# Conclusions that mean the scanner did not produce a clean result. Kept
# separate from "cancelled" and "skipped", which are routinely deliberate (a
# superseded run, a path filter that did not match) and would make the gate
# noisy. "timed_out" is a scanner that never finished and "startup_failure" is
# one that never began (broken workflow YAML, an unresolvable reusable-workflow
# ref); both are the failure mode this whole report exists to surface --
# reporting them as healthy is the same class of lie as reporting a
# never-triggered job as passing. "stale" is deliberately left out: it is rare
# and ambiguous enough that gating on it would cost more than it catches.
_FAILED_CONCLUSIONS = frozenset({"failure", "timed_out", "startup_failure"})

# The report describes the health of the default branch, so live queries are
# scoped to it. Without this, `gh run list` returns runs from every branch and
# the newest one is typically a contributor's pull-request run -- a failure
# there says something about that PR, not about whether the scanner works.
#
# `--branch` is a help, NOT the guard: it matches the run's HEAD REF NAME, and
# a fork whose default branch is also called `main` produces `pull_request`
# runs whose headBranch is literally "main". Those runs execute the
# contributor's tree, so their conclusion says something about that pull
# request, not about whether the scanner works on this repository's main.
# `pull_request_target` is excluded for the same reason: it checks out the
# pull-request head. Hence the event filter below, in addition to --branch.
_LIVE_BRANCH = "main"
_PULL_REQUEST_EVENTS: Final = frozenset({"pull_request", "pull_request_target"})

# Staleness rules are NOT invented here. `scripts/generate_workflow_status.py`
# already defines what "stale" means for this repository (STALE_MULTIPLIER x
# the workflow's own cron cadence) and `docs/ci/workflow-status.md` documents
# that reusable workflows are read through the gate that calls them. Both
# scripts live in `scripts/` and neither is importable as a package, so the
# sibling is loaded by path instead of copied.
_STATUS_RULES_SCRIPT: Final = ROOT / "scripts" / "generate_workflow_status.py"
# The sibling's floor, verbatim: `classify_staleness` computes
# `threshold_days = max(60.0, STALE_MULTIPLIER * min(cadences))`
# (scripts/generate_workflow_status.py:618). Keeping a different floor here
# would make the two dashboards disagree about the same workflow more often
# than the known differences listed in `_stale_threshold_days` already do.
# It doubles as the fallback for a workflow with no cron of its own.
_STALE_FLOOR_DAYS: Final = 60.0
_FALLBACK_GATE_ROOTS: Final = frozenset(
    {"release-gate.yml", "ci-gate.yml", "release.yml"}
)
# A workflow with only these triggers has no DEFAULT-BRANCH run history of
# its own worth reading: its work shows up under whichever gate calls it.
# `pull_request`/`pull_request_target` belong in the set because
# `_is_default_branch_run` already discards runs from those events, so they
# can never become evidence here -- counting them as an own history is how
# `owasp-zap-scan.yml` (path-filtered `pull_request:` + `workflow_call:` +
# `workflow_dispatch:`) fell back to its dead direct-run log and reported
# STALE while release-gate.yml ran it every night.
_GATED_ONLY_TRIGGERS: Final = frozenset(
    {
        "workflow_call",
        "workflow_dispatch",
        "pull_request",
        "pull_request_target",
    }
)
# The line scanner sees `uses:` values verbatim, quotes included; only the
# YAML parser strips them. Both spellings are valid and both appear in the
# wild, so accept either quoting (or none).
_REUSABLE_USES_RE: Final = re.compile(
    r"""^\s*uses:\s*(?P<q>['"]?)[.$]/\.github/workflows/"""
    r"(?P<file>[A-Za-z0-9._-]+\.ya?ml)(?P=q)"
)
# The same reference as PyYAML hands it back (unquoted, whole value).
_REUSABLE_USES_VALUE_RE: Final = re.compile(
    r"^[.$]/\.github/workflows/(?P<file>[A-Za-z0-9._-]+\.ya?ml)$"
)
# Preference order for the gate a reusable scanner is read through.
# `GATE_ROOTS` in the sibling script is an unordered set, and picking its
# first element alphabetically prefers `ci-gate.yml` -- whose `main` history
# is two cancelled dispatches -- over `release-gate.yml`, which runs nightly.
_GATE_PREFERENCE: Final = ("release-gate.yml", "ci-gate.yml", "release.yml")

_status_rules_cache: object | None = None
_status_rules_loaded = False


def _status_rules() -> object | None:
    """Load ``scripts/generate_workflow_status.py`` for its staleness rules."""
    global _status_rules_cache, _status_rules_loaded
    if _status_rules_loaded:
        return _status_rules_cache
    _status_rules_loaded = True
    try:
        spec = importlib.util.spec_from_file_location(
            "_ci_health_status_rules", _STATUS_RULES_SCRIPT
        )
        if spec is None or spec.loader is None:
            return None
        module = importlib.util.module_from_spec(spec)
        # Register BEFORE exec_module: a module absent from sys.modules while
        # its body runs cannot resolve its own name, and
        # `@dataclass(slots=True)` in the sibling would silently degrade.
        sys.modules[spec.name] = module
        try:
            spec.loader.exec_module(module)
        except BaseException:
            sys.modules.pop(spec.name, None)
            raise
    except Exception:  # pragma: no cover - the sibling script is missing/broken
        return None
    _status_rules_cache = module
    return module


def _gate_roots() -> frozenset[str]:
    roots = getattr(_status_rules(), "GATE_ROOTS", None)
    if isinstance(roots, (set, frozenset)):
        return frozenset(str(name) for name in roots)
    return _FALLBACK_GATE_ROOTS


def _utcnow() -> datetime.datetime:
    """Isolated so tests can freeze the clock; ``render()`` stays clock-free."""
    return datetime.datetime.now(datetime.timezone.utc)


def _run_date(created_at: str) -> str:
    """The calendar date of an ISO-8601 run timestamp (stable across runs)."""
    return created_at[:10] if created_at else "—"


def _run_age_days(created_at: str, now: datetime.datetime) -> float | None:
    try:
        created = datetime.datetime.fromisoformat(
            created_at.replace("Z", "+00:00")
        )
    except ValueError:
        return None
    if created.tzinfo is None:
        created = created.replace(tzinfo=datetime.timezone.utc)
    return (now - created).total_seconds() / 86400.0


def _is_default_branch_run(run: WorkflowRun) -> bool:
    """True when the run executed this repository's default-branch tree."""
    return (
        run.event not in _PULL_REQUEST_EVENTS
        and run.head_branch == _LIVE_BRANCH
    )


def _workflow_on_block(path: pathlib.Path) -> dict[str, YamlValue]:
    """Return a workflow's ``on:`` mapping, normalised to a dict."""
    try:
        data = YAML.safe_load(_read(path))
    except YAML.YAMLError:
        return {}
    if not isinstance(data, dict):
        return {}
    # PyYAML follows YAML 1.1 and may coerce the key `on` to boolean True.
    triggers = data.get("on", data.get(True, {}))
    if isinstance(triggers, str):
        return {triggers: None}
    if isinstance(triggers, list):
        return {item: None for item in triggers if isinstance(item, str)}
    if isinstance(triggers, dict):
        return {
            key: value
            for key, value in triggers.items()
            if isinstance(key, str)
        }
    return {}


def _cron_strings(workflow: str) -> tuple[str, ...]:
    schedule = _workflow_on_block(WORKFLOWS_DIR / workflow).get("schedule")
    if not isinstance(schedule, list):
        return ()
    crons: list[str] = []
    for entry in schedule:
        if isinstance(entry, dict):
            cron = entry.get("cron")
            if isinstance(cron, str):
                crons.append(cron)
    return tuple(crons)


def _stale_threshold_days(workflow: str) -> float:
    """Days after which *workflow*'s last SUCCESSFUL run stops being evidence.

    Similar to ``classify_staleness`` in ``scripts/generate_workflow_status.py``
    (:616-618): ``max(60.0, STALE_MULTIPLIER * min(cadences))`` over the
    queried workflow's cron cadences. It is not identical, so the two
    dashboards can disagree: here a workflow with no cron falls back to the
    60-day floor (the sibling never marks it stale), a gated scanner uses its
    gate's cadence, there is no new-file exemption, a window with no runs at
    all is not stale (it is reported as ``NO RUNS`` instead), and ages are
    compared as fractional rather than whole days.
    """
    rules = _status_rules()
    cadence_of = getattr(rules, "cron_cadence_days", None)
    multiplier = getattr(rules, "STALE_MULTIPLIER", 2)
    if cadence_of is None:
        return _STALE_FLOOR_DAYS
    cadences = [
        cadence
        for cadence in (cadence_of(cron) for cron in _cron_strings(workflow))
        if isinstance(cadence, (int, float)) and cadence > 0
    ]
    if not cadences:
        return _STALE_FLOOR_DAYS
    return max(_STALE_FLOOR_DAYS, float(multiplier) * min(cadences))


def _reusable_workflow_callers() -> dict[str, tuple[str, ...]]:
    """Map a reusable workflow's filename to the workflows that call it."""
    callers: dict[str, list[str]] = {}
    for path in _workflow_files():
        for line in _read(path).splitlines():
            match = _REUSABLE_USES_RE.match(line)
            if match is None:
                continue
            called = match.group("file")
            if called == path.name:
                continue
            bucket = callers.setdefault(called, [])
            if path.name not in bucket:
                bucket.append(path.name)
    return {name: tuple(sorted(value)) for name, value in callers.items()}


def _gating_parent(
    workflow: str, callers: dict[str, tuple[str, ...]]
) -> str | None:
    """Return the workflow whose runs carry *workflow*, or ``None``.

    ``docs/ci/workflow-status.md`` states the rule this implements: a
    ``workflow_call:`` workflow whose only OTHER triggers are
    ``workflow_dispatch`` or pull-request events shows its GATED run --
    the most recent run of the parent that included it -- not its own
    empty direct-run history. Reading their own history is how a scanner
    last dispatched eight months ago reports PASS.
    """
    triggers = set(_workflow_on_block(WORKFLOWS_DIR / workflow))
    if not triggers or not triggers <= _GATED_ONLY_TRIGGERS:
        return None
    if "workflow_call" not in triggers:
        return None
    names = callers.get(workflow, ())
    gates = [name for name in names if name in _gate_roots()]
    if gates:
        # NOT `gates[0]`: that is alphabetical order, which prefers
        # `ci-gate.yml` over `release-gate.yml` (see _GATE_PREFERENCE).
        return min(gates, key=_gate_rank)
    return names[0] if names else None


def _gate_rank(gate: str) -> tuple[int, str]:
    """Sort key putting the gate that actually runs on ``main`` first."""
    if gate in _GATE_PREFERENCE:
        return (_GATE_PREFERENCE.index(gate), gate)
    return (len(_GATE_PREFERENCE), gate)


def _gate_job_ids(gate: str) -> dict[str, tuple[str, ...]]:
    """Map each workflow *gate* calls to the job-name PREFIX GitHub renders.

    `release-gate.yml`'s `jobs:` block names them: `semgrep-scan:` has
    `uses: ./.github/workflows/semgrep.yml`, `gitleaks-scan:` has
    `uses: ./.github/workflows/gitleaks-main.yml`, and so on. GitHub renders
    a job's YAML key (the "job id") as its displayed name only when the job
    has no `name:` of its own; when it does, THAT is the prefix every job the
    called workflow contributes is nested under (see
    :data:`_JOB_PATH_SEPARATOR`) -- `job.get("name") or job_id`, not the id
    alone. A matrixed caller job appends its matrix value in parens directly
    to that same prefix (`prefix (ubuntu-latest) / scan`), so callers must
    also prefix-match `f"{prefix} ("`.
    """
    try:
        data = YAML.safe_load(_read(WORKFLOWS_DIR / gate))
    except YAML.YAMLError:
        return {}
    jobs = data.get("jobs") if isinstance(data, dict) else None
    if not isinstance(jobs, dict):
        return {}
    mapping: dict[str, list[str]] = {}
    for job_id, job in jobs.items():
        if not isinstance(job_id, str) or not isinstance(job, dict):
            continue
        uses = job.get("uses")
        if not isinstance(uses, str):
            continue
        match = _REUSABLE_USES_VALUE_RE.match(uses.strip())
        if match is not None:
            name = job.get("name")
            prefix = name if isinstance(name, str) and name else job_id
            mapping.setdefault(match.group("file"), []).append(prefix)
    return {name: tuple(ids) for name, ids in mapping.items()}


# Leave time for setup, rendering and report publication in the five-minute job.
_LIVE_BUDGET_SECONDS = 120.0
# A gate run is only resolved per job while this much of the shared budget is
# left, so the per-job lookups cannot starve the remaining scanners' queries.
_JOBS_QUERY_RESERVE_SECONDS = 15.0
# Jobs a called ("reusable") workflow contributes to the caller's run are
# named "<caller job id> / <called job name>". Verified on release-gate run
# 35810068506: `semgrep-scan / semgrep-scan`, `owasp-zap-scan / ZAP API Scan`,
# `grype-scan / Grype Filesystem Scan`. A nested call adds another segment
# (`osv-scan / scan / osv-scan`), hence a prefix match rather than equality.
_JOB_PATH_SEPARATOR: Final = " / "
# Synthetic conclusion for a gate run whose job list did not name the
# scanner. It is NOT a gh conclusion (so it stays out of
# _KNOWN_CONCLUSIONS) and it is NOT a failure: it means "not measured".
_UNRESOLVED: Final = "unresolved"
# Conclusions that decide nothing: a run still in flight, and one whose jobs
# could not be resolved. Neither may hide the newest run that did conclude.
_INCONCLUSIVE: Final = frozenset({"unknown", _UNRESOLVED})


def _fetch_run_jobs(
    run_id: int, timeout: float
) -> tuple[tuple[str, str], ...] | None:
    """``(job name, conclusion)`` for one run, or ``None`` if unreadable."""
    try:
        result = subprocess.run(
            ["gh", "run", "view", str(run_id), "--json=jobs"],
            cwd=ROOT,
            capture_output=True,
            text=True,
            timeout=timeout,
            check=False,
        )
    except (subprocess.TimeoutExpired, OSError):
        return None
    if result.returncode != 0:
        return None
    try:
        payload = json.loads(result.stdout)
    except json.JSONDecodeError:
        return None
    jobs = payload.get("jobs") if isinstance(payload, dict) else None
    if not isinstance(jobs, list):
        return None
    parsed: list[tuple[str, str]] = []
    for job in jobs:
        if not isinstance(job, dict):
            return None
        name = job.get("name")
        conclusion = job.get("conclusion")
        if not isinstance(name, str) or (
            conclusion is not None and not isinstance(conclusion, str)
        ):
            return None
        parsed.append((name, conclusion or "unknown"))
    return tuple(parsed)


def _scanner_conclusion_from_jobs(
    jobs: tuple[tuple[str, str], ...], job_ids: tuple[str, ...]
) -> str | None:
    """This scanner's own conclusion inside a gate run, or ``None``.

    ``None`` means the run's job list named no job of this scanner: that is
    an unresolved measurement, never a failure.
    """
    own = [
        conclusion
        for name, conclusion in jobs
        if any(
            name == job_id
            or name.startswith(job_id + _JOB_PATH_SEPARATOR)
            # A matrixed caller job's name gets its matrix value appended
            # in parens BEFORE the " / " path separator, e.g.
            # "owasp-zap-scan (staging) / ZAP API Scan".
            or name.startswith(f"{job_id} (")
            for job_id in job_ids
        )
    ]
    if not own:
        return None
    # A scanner may contribute several jobs (ZAP runs a baseline and an API
    # scan). The worst of them is the scanner's result.
    for conclusion in own:
        if conclusion in _FAILED_CONCLUSIONS:
            return conclusion
    if "unknown" in own:
        return "unknown"
    for conclusion in own:
        if conclusion != "success":
            return conclusion
    return "success"


def _resolve_gated_runs(
    workflow: str,
    gate: str,
    runs: tuple[WorkflowRun, ...],
    jobs_cache: dict[int, tuple[tuple[str, str], ...] | None],
    deadline: float,
) -> tuple[tuple[WorkflowRun, ...], list[str]]:
    """Replace each GATE run's conclusion with *workflow*'s own job result.

    The gate's roll-up is not this scanner's result. `release-gate.yml`
    concluded `failure` on 19 of its last 20 `main` runs because of a
    standing `Check Code Scanning Alerts` condition while every scanner job
    in those runs succeeded; printing that `failure` under a scanner's name
    is the same class of lie this report exists to catch, in the opposite
    direction. One `gh run view <id> --json jobs` call per gate run, memoised
    in *jobs_cache*, makes it a measurement: the seven scanners sharing
    `release-gate.yml` cost one call per run between them, not seven.
    """
    job_ids = _gate_job_ids(gate).get(workflow, ())
    if not job_ids:
        return (
            tuple(
                replace(
                    run,
                    conclusion=_UNRESOLVED,
                    unresolved_reason="gate_has_no_caller_job",
                )
                for run in runs
            ),
            [f"`{gate}` has no job calling this workflow"],
        )
    resolved: list[WorkflowRun] = []
    notes: list[str] = []
    for run in runs:
        if run.database_id not in jobs_cache:
            remaining = deadline - time.monotonic()
            if remaining <= _JOBS_QUERY_RESERVE_SECONDS:
                notes.append(
                    f"gate history truncated to {len(resolved)} of "
                    f"{len(runs)} runs by the live time budget"
                )
                break
            jobs_cache[run.database_id] = _fetch_run_jobs(
                run.database_id, min(15.0, remaining)
            )
        jobs = jobs_cache[run.database_id]
        conclusion = (
            None
            if jobs is None
            else _scanner_conclusion_from_jobs(jobs, job_ids)
        )
        if (
            conclusion is None
            and jobs is not None
            and run.conclusion == "unknown"
        ):
            # The gate run itself is still in flight: this scanner's job
            # simply hasn't been created in it yet, which is "in flight",
            # not "a completed run whose job list stayed silent about it"
            # (UNRESOLVED). Keep it "unknown" so the caller reports RUNNING
            # and computes its finding from the previous CONCLUSIVE gate run.
            resolved.append(replace(run, conclusion="unknown"))
            continue
        if conclusion is None:
            resolved.append(
                replace(
                    run,
                    conclusion=_UNRESOLVED,
                    unresolved_reason=(
                        "job_list_unreadable"
                        if jobs is None
                        else "job_list_lacked_scanner"
                    ),
                )
            )
        else:
            resolved.append(replace(run, conclusion=conclusion))
    return tuple(resolved), notes


_KNOWN_CONCLUSIONS = frozenset(
    {
        "success",
        "failure",
        "neutral",
        "cancelled",
        "skipped",
        "timed_out",
        "action_required",
        "startup_failure",
        "stale",
    }
)


def _parse_workflow_runs(
    payload: list[object],
) -> tuple[WorkflowRun, ...] | None:
    """Reject an incomplete response rather than silently choosing an older run."""
    runs: list[WorkflowRun] = []
    for row in payload:
        if not isinstance(row, dict):
            return None
        run_id = row.get("databaseId")
        conclusion = row.get("conclusion")
        event = row.get("event")
        branch = row.get("headBranch")
        created_at = row.get("createdAt")
        if (
            not isinstance(run_id, int)
            or isinstance(run_id, bool)
            or run_id <= 0
            or not isinstance(event, str)
            or not isinstance(branch, str)
            or not isinstance(created_at, str)
            or (conclusion is not None and not isinstance(conclusion, str))
        ):
            return None
        if conclusion and conclusion not in _KNOWN_CONCLUSIONS:
            return None
        runs.append(
            WorkflowRun(
                run_id, conclusion or "unknown", event, branch, created_at
            )
        )
    return tuple(runs)


def analyze_live_status(
    findings: list[Finding],
    scanner_workflows: tuple[str, ...],
    *,
    enabled: bool = True,
    limit: int = 5,
) -> tuple[LiveStatus, ...]:
    """Query recent CI run conclusions for each scanner workflow via ``gh``.

    Only default-branch runs count: ``--branch`` plus an event filter, because
    ``--branch`` matches the run's head ref name and a fork PR from a branch
    called ``main`` passes it (see :data:`_PULL_REQUEST_EVENTS`).

    A scanner with no default-branch history of its own is read through the
    gate that calls it, matching the rule already documented in
    ``docs/ci/workflow-status.md``; its entry records ``gated_by``. The
    gate's own conclusion is never shown under the scanner's name: each gate
    run is resolved to the scanner's OWN job conclusions via
    ``gh run view <id> --json jobs`` (:func:`_resolve_gated_runs`), and a run
    whose job list does not name the scanner renders ``UNRESOLVED``.

    Returns an empty tuple when *enabled* is False.  When ``gh`` is
    unavailable or unauthenticated, every entry carries an *unavailable*
    reason and no findings are emitted.  When the most recent COMPLETED run of
    a scanner workflow ended in a :data:`_FAILED_CONCLUSIONS` conclusion, a
    ``high`` finding is appended so that ``--check`` gates on it -- an
    in-flight run does not hide it. A gated scanner's failing JOB is a
    measurement of that scanner, so it is ``high`` too; only an unresolved
    one is ``medium``. When the last SUCCESSFUL run is older than the
    workflow's staleness threshold a ``medium`` finding is appended and the
    entry renders ``STALE``: an eight-month-old success is not evidence that a
    scanner works, and reporting it as ``PASS`` is the same class of lie as
    reporting a never-triggered job as passing. A workflow with NO successful
    run in the window is stale unconditionally, however young its newest
    (non-passing) run is: the ``medium`` finding names that run's OWN
    conclusion, never a fabricated success, and the row keeps that
    conclusion's label -- ``STALE`` only ever replaces a ``PASS`` label, never
    ``FAIL`` or another one. Staleness stays below the ``--check`` gate
    because it reports absent evidence, not a failed scan. So does a
    workflow with NO qualifying run in the window at all (``NO RUNS``): it
    raises a ``medium`` finding, and :func:`discount_idle_scanners` stops
    counting it as coverage for its category.
    Invalid run entries make that workflow unavailable, and so does a
    non-empty page whose runs are ALL filtered out (pull-request or
    other-branch runs): that is a crowded query window, not an idle scanner.
    Collection shares a
    120-second budget; remaining workflows are marked unavailable when it is
    exhausted.
    """
    if not enabled or not scanner_workflows:
        return ()

    deadline = time.monotonic() + _LIVE_BUDGET_SECONDS
    unavailable = _gh_available()
    if unavailable:
        return tuple(
            LiveStatus(workflow, (), None, unavailable)
            for workflow in scanner_workflows
        )

    callers = _reusable_workflow_callers()
    now = _utcnow()
    # run id -> job list, shared across every scanner behind the same gate.
    jobs_cache: dict[int, tuple[tuple[str, str], ...] | None] = {}
    statuses: list[LiveStatus] = []
    for workflow in scanner_workflows:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            statuses.append(
                LiveStatus(
                    workflow, (), None, "live query time budget exhausted"
                )
            )
            continue
        parent = _gating_parent(workflow, callers)
        queried = parent or workflow
        threshold_days = _stale_threshold_days(queried)
        command = [
            "gh",
            "run",
            "list",
            f"--workflow={queried}",
            f"--branch={_LIVE_BRANCH}",
            f"--limit={limit}",
            "--json=databaseId,conclusion,event,headBranch,createdAt",
        ]
        try:
            result = subprocess.run(
                command,
                cwd=ROOT,
                capture_output=True,
                text=True,
                timeout=min(15.0, remaining),
                check=False,
            )
        except (subprocess.TimeoutExpired, OSError):
            statuses.append(LiveStatus(workflow, (), None, "gh timed out"))
            continue

        if result.returncode != 0:
            stderr = result.stderr.strip()
            reason = (
                stderr.splitlines()[0][:200]
                if stderr
                else f"exit {result.returncode}"
            )
            statuses.append(LiveStatus(workflow, (), None, reason))
            continue

        try:
            payload = json.loads(result.stdout)
        except json.JSONDecodeError:
            statuses.append(
                LiveStatus(workflow, (), None, "gh returned invalid JSON")
            )
            continue

        if not isinstance(payload, list):
            statuses.append(
                LiveStatus(workflow, (), None, "gh returned non-list payload")
            )
            continue

        runs = _parse_workflow_runs(payload)
        if runs is None:
            statuses.append(
                LiveStatus(
                    workflow, (), None, "gh returned malformed run entries"
                )
            )
            continue

        fetched_count = len(runs)
        runs = tuple(run for run in runs if _is_default_branch_run(run))
        if fetched_count and not runs:
            # Every fetched row was a pull-request (e.g. a fork's `main`) or
            # other-branch run: the page was crowded out, which says nothing
            # about whether the scanner ran on the default branch. Treat it
            # as an unavailable query, not as an idle scanner (`NO RUNS`),
            # so discount_idle_scanners() keeps counting it as coverage.
            statuses.append(
                LiveStatus(
                    workflow,
                    (),
                    None,
                    f"all {fetched_count} fetched runs were pull-request or "
                    f"non-{_LIVE_BRANCH} runs; default-branch status unknown",
                )
            )
            continue
        notes: list[str] = []
        if parent is not None:
            # The rows carry this scanner's own job conclusions inside the
            # gate runs, never the gate's roll-up.
            fetched = runs
            runs, notes = _resolve_gated_runs(
                workflow, parent, runs, jobs_cache, deadline
            )
            truncated = any("time budget" in note for note in notes)
            no_settled_run = not any(
                run.conclusion != "unknown" for run in runs
            )
            if truncated and no_settled_run and fetched:
                # The live time budget ran out before a settled run could be
                # resolved from the fetched gate history: absence of
                # evidence from the budget, not absence of a qualifying run
                # (which is what `NO RUNS` would claim -- false, some were
                # found). This also covers the newest run being in flight
                # ("unknown", kept as-is below to render RUNNING) while
                # every OLDER run got truncated away before its job list
                # could even be queried: without this finding, an older
                # scanner failure sitting behind the cut would be silently
                # invisible.
                findings.append(
                    Finding(
                        "medium",
                        "scanner-runtime",
                        workflow,
                        "gate history could not be resolved within the live time budget",
                    )
                )
                if not runs:
                    runs = (
                        replace(
                            fetched[0],
                            conclusion=_UNRESOLVED,
                            budget_exhausted=True,
                            unresolved_reason="budget_exhausted",
                        ),
                    )
        latest = runs[0] if runs else None
        # A run still in flight has no conclusion yet ("unknown"), and an
        # unresolved gate run measured nothing. Neither may hide the last
        # run that did conclude, or a push racing the report turns a red
        # scanner green.
        completed = next(
            (run for run in runs if run.conclusion not in _INCONCLUSIVE), None
        )
        latest_conclusion = latest.conclusion if latest else None
        gated = f" (gated by {parent})" if parent else ""
        if not runs:
            # A scanner that never ran in the window is not coverage: an
            # absent run is absent evidence (e.g. a caller commented out).
            findings.append(
                Finding(
                    "medium",
                    "scanner-runtime",
                    workflow,
                    f"no qualifying run on {_LIVE_BRANCH} in the query window{gated}; an idle scanner is not coverage",
                )
            )

        if (
            completed is not None
            and completed.conclusion in _FAILED_CONCLUSIONS
        ):
            where = f"(branch={completed.head_branch}, event={completed.event}, run #{completed.database_id})"
            if parent is None:
                findings.append(
                    Finding(
                        "high",
                        "scanner-runtime",
                        workflow,
                        f"latest completed run {completed.conclusion} on {_run_date(completed.created_at)} {where}",
                    )
                )
            else:
                # This is the scanner's OWN job conclusion inside the gate
                # run, not the gate's roll-up, so it gates exactly like a
                # direct failure would.
                findings.append(
                    Finding(
                        "high",
                        "scanner-runtime",
                        workflow,
                        f"this scanner's job in {parent} concluded {completed.conclusion} on {_run_date(completed.created_at)} {where}",
                    )
                )
        # The newest run that resolved to ANYTHING -- not `latest`, which is
        # "unknown" while the newest gate run is still in flight. Mirrors
        # `completed`'s treatment: an in-flight newest run must not hide an
        # unresolved run underneath it, exactly as it must not hide a failed
        # one (the `completed` finding above).
        newest_settled = next(
            (run for run in runs if run.conclusion != "unknown"), None
        )
        if (
            newest_settled is not None
            and newest_settled.conclusion == _UNRESOLVED
            and not newest_settled.budget_exhausted
        ):
            # Unresolved is absent evidence, not a failed scan: reported,
            # but below the --check gate. A run only UNRESOLVED because the
            # live time budget ran out before it could even be queried
            # (`budget_exhausted`) already got its own "could not be
            # resolved within the live time budget" finding above and was
            # never actually checked, so it does not get a second finding
            # naming a run number that was never queried.
            findings.append(
                Finding(
                    "medium",
                    "scanner-runtime",
                    workflow,
                    f"could not resolve this scanner's jobs in {parent} run #{newest_settled.database_id}; its result is unknown, not passing",
                )
            )

        # Measured from the last SUCCESSFUL run, as `classify_staleness`
        # does (generate_workflow_status.py:616-619): a scanner whose runs
        # in the window include NO success is stale unconditionally -- a
        # rule similar to the sibling's "no success ⇒ stale" (see
        # _stale_threshold_days for the differences) -- never "fresh" just
        # because its most recent (failing) run happens to be young.
        success = next(
            (run for run in runs if run.conclusion == "success"), None
        )
        stale = False
        if success is None:
            # `completed`, not `latest`: an in-flight or unresolved newest
            # run is not evidence one way or the other (R5) -- report the
            # last run that actually concluded something, exactly like the
            # FAILED_CONCLUSIONS finding above does.
            if completed is not None:
                stale = True
                findings.append(
                    Finding(
                        "medium",
                        "scanner-runtime",
                        workflow,
                        f"no successful run in the query window (newest run "
                        f"{_run_date(completed.created_at)}, {completed.conclusion}){gated}",
                    )
                )
        else:
            age_days = _run_age_days(success.created_at, now)
            if age_days is None:
                # Fail closed: a timestamp we cannot parse is not evidence of
                # a recent run.
                stale = True
                notes.append(
                    f"unparseable run timestamp {success.created_at!r} — treated as stale"
                )
                findings.append(
                    Finding(
                        "medium",
                        "scanner-runtime",
                        workflow,
                        f"run #{success.database_id} has an unparseable createdAt ({success.created_at!r}); treated as stale{gated}",
                    )
                )
            elif age_days > threshold_days:
                stale = True
                findings.append(
                    Finding(
                        "medium",
                        "scanner-runtime",
                        workflow,
                        f"newest successful run is {int(age_days)} days old ({_run_date(success.created_at)}), past the {int(threshold_days)}-day staleness threshold{gated}",
                    )
                )

        statuses.append(
            LiveStatus(
                workflow,
                runs,
                latest_conclusion,
                None,
                parent,
                stale,
                tuple(notes),
            )
        )

    return tuple(statuses)


def recent_cicd_changes(limit: int = 10) -> GitHistory:
    command = [
        "git",
        "log",
        f"-{limit}",
        "--pretty=format:%h%x1f%ad%x1f%an%x1f%s%x1e",
        "--date=short",
        "--",
        *CI_PATHS,
    ]
    try:
        result = subprocess.run(
            command,
            cwd=ROOT,
            capture_output=True,
            text=True,
            timeout=15,
            check=False,
        )
    except subprocess.TimeoutExpired:
        return GitHistory((), "returncode 124")
    except OSError:
        return GitHistory((), "returncode unavailable")
    if result.returncode != 0:
        return GitHistory((), f"returncode {result.returncode}")

    changes: list[GitChange] = []
    for record in result.stdout.split("\x1e"):
        fields = record.strip().split("\x1f")
        if len(fields) == 4:
            changes.append(GitChange(*fields))
    return GitHistory(tuple(changes), None)


def report_baseline() -> str:
    command = ["git", "log", "-1", "--format=%h", "--", *CI_PATHS]
    try:
        result = subprocess.run(
            command,
            cwd=ROOT,
            capture_output=True,
            text=True,
            timeout=15,
            check=False,
        )
    except (subprocess.TimeoutExpired, OSError):
        return "unknown"
    return (
        result.stdout.strip()
        if result.returncode == 0 and result.stdout.strip()
        else "unknown"
    )


def _precommit_ratio(precommit: PrecommitAnalysis) -> float:
    if not precommit["present"] or precommit.get("parse_error"):
        return 0.0
    return (
        0.4
        + (0.3 if precommit["has_secrets_hook"] else 0.0)
        + (0.3 if not precommit["floating_revs"] else 0.0)
    )


def score_dimensions(
    workflows: WorkflowAnalysis,
    precommit: PrecommitAnalysis,
    scanners: tuple[ScannerCategory, ...],
) -> tuple[Dimension, ...]:
    required = tuple(category for category in scanners if category.required)
    return (
        Dimension(
            "Actions pinned by SHA",
            35,
            workflows.pinned_uses / workflows.total_uses
            if workflows.total_uses
            else None,
        ),
        Dimension(
            "Explicit permissions",
            15,
            workflows.permissions_ok_jobs / workflows.permissions_jobs
            if workflows.permissions_jobs
            else None,
        ),
        Dimension(
            "Harden-runner first",
            15,
            workflows.harden_ok_jobs / workflows.non_exempt_jobs
            if workflows.non_exempt_jobs
            else None,
        ),
        Dimension(
            "Safe checkouts",
            10,
            workflows.safe_checkouts / workflows.total_checkouts
            if workflows.total_checkouts
            else None,
        ),
        Dimension("Pre-commit", 10, _precommit_ratio(precommit)),
        Dimension(
            "Required scanners",
            15,
            sum(category.satisfied for category in required) / len(required)
            if required
            else None,
        ),
    )


def compute_score(dimensions: tuple[Dimension, ...]) -> int:
    active = tuple(
        dimension for dimension in dimensions if dimension.ratio is not None
    )
    denominator = sum(dimension.weight for dimension in active)
    raw = sum(
        dimension.weight * dimension.ratio
        for dimension in active
        if dimension.ratio is not None
    )
    return (
        max(0, min(100, round(100 * raw / denominator))) if denominator else 0
    )


def grade(score: int) -> str:
    if score >= 90:
        return "A"
    if score >= 80:
        return "B"
    if score >= 70:
        return "C"
    if score >= 60:
        return "D"
    return "F"


def _icon(ok: bool) -> str:
    return "PASS" if ok else "FAIL"


def _ratio_detail(dimension: Dimension) -> str:
    if dimension.ratio is None:
        suffix = (
            "no checkouts"
            if dimension.name == "Safe checkouts"
            else "no applicable occurrences"
        )
        return f"N/A — {suffix}"
    return f"{round(100 * dimension.ratio)}% (weight {dimension.weight})"


def _markdown_cell(value: str) -> str:
    escaped = (
        value.replace("\\", "\\\\")
        .replace("|", "\\|")
        .replace("\r", " ")
        .replace("\n", " ")
    )
    return "".join(
        character
        for character in escaped
        if ord(character) >= 32 and ord(character) != 127
    )


_STATUS_LABELS: Final[dict[str, str]] = {
    "success": "PASS",
    "failure": "FAIL",
    "cancelled": "CANCELLED",
    "skipped": "SKIPPED",
    "timed_out": "TIMED_OUT",
    "startup_failure": "STARTUP_FAILURE",
    "action_required": "ACTION_REQUIRED",
    # `gh` also reports these two. "stale" is a gh conclusion meaning the run
    # outlived its log retention; it is NOT this report's staleness verdict,
    # so it is labelled distinctly rather than colliding with STALE.
    "neutral": "NEUTRAL",
    "stale": "STALE (gh)",
    # A run with no conclusion yet is in flight, not an unknowable state.
    "unknown": "RUNNING",
    # A gate run whose job list did not name this scanner: not measured.
    _UNRESOLVED: "UNRESOLVED",
}


def _status_label(conclusion: str | None) -> str:
    if conclusion is None:
        return "—"
    return _STATUS_LABELS.get(conclusion, conclusion)


def render(
    workflows: WorkflowAnalysis,
    precommit: PrecommitAnalysis,
    scanners: tuple[ScannerCategory, ...],
    history: GitHistory,
    findings: list[Finding],
    live: tuple[LiveStatus, ...] = (),
) -> tuple[str, int]:
    dimensions = score_dimensions(workflows, precommit, scanners)
    score = compute_score(dimensions)
    ordered_findings = sorted(
        findings,
        key=lambda item: (
            {"critical": 0, "high": 1, "medium": 2, "low": 3}[item.severity],
            item.area,
            item.file,
            item.message,
        ),
    )
    if live:
        intro = [
            "> Auto-generated by `scripts/generate_ci_health.py` (run by",
            "> `.github/workflows/ci-health-report.yml`). This reports",
            "> **static configuration health** plus a **live scanner status**",
            "> section; only the static half is scored. For live run status",
            "> across every workflow see",
            "> [`docs/ci/workflow-status.md`](../docs/ci/workflow-status.md).",
        ]
    else:
        intro = [
            "> Auto-generated by `scripts/generate_ci_health.py` (run by",
            "> `.github/workflows/ci-health-report.yml`). This reports",
            "> **static configuration health**, not live run status — for",
            "> that see [`docs/ci/workflow-status.md`](../docs/ci/workflow-status.md).",
        ]
    # NOTE: no line below may end in whitespace. Markdown hard breaks (two
    # trailing spaces) are stripped by the repo's `trailing-whitespace`
    # pre-commit hook (.pre-commit-config.yaml:9), which would make the
    # generated file impossible to commit unchanged.
    lines = [
        "# CI/CD Configuration Health",
        "",
        *intro,
        "",
        f"- **Report baseline:** `{report_baseline()}`",
        f"- **Workflows analyzed:** {len(workflows.files)}",
        f"- **Overall score:** **{score}/100** (grade **{grade(score)}**)",
        f"- **Findings:** {len(ordered_findings)}",
        "",
        "---",
        "",
        "## Summary",
        "",
        "| Check | Result | Detail |",
        "|---|---|---|",
    ]
    for dimension in dimensions:
        result = (
            "N/A" if dimension.ratio is None else _icon(dimension.ratio == 1.0)
        )
        lines.append(
            f"| {dimension.name} | {result} | {_ratio_detail(dimension)} |"
        )
    lines.extend(
        [
            "",
            "## Headline counts",
            "",
            f"- Non-local action references: **{workflows.pinned_uses}/{workflows.total_uses} pinned**",
            f"- Checkout occurrences: **{workflows.safe_checkouts}/{workflows.total_checkouts} safe**",
            f"- Non-exempt jobs: **{workflows.non_exempt_jobs}**",
            f"- Jobs missing harden-runner as step 0: **{len(workflows.missing_harden)}**",
            f"- Jobs without explicit permissions: **{len(workflows.missing_permissions)}**",
            "",
        ]
    )

    if ordered_findings:
        lines.extend(
            [
                "## Findings",
                "",
                "| Severity | Area | File/job | Finding |",
                "|---|---|---|---|",
            ]
        )
        for finding in ordered_findings:
            finding_row = (
                f"| {finding.severity.upper()} | {_markdown_cell(finding.area)} | "
                + f"{_markdown_cell(finding.file)} | {_markdown_cell(finding.message)} |"
            )
            lines.append(finding_row)
        lines.append("")

    unpinned = [
        (row.name, ref) for row in workflows.files for ref in row.unpinned
    ]
    if unpinned:
        lines.extend(["## Unpinned actions (not pinned by commit SHA)", ""])
        for filename, ref in sorted(unpinned):
            lines.append(f"- `{filename}`: `{ref}`")
        lines.append("")

    lines.extend(
        [
            "## Security-scanner coverage",
            "",
            "| Category | Requirement | Status | Evidence |",
            "|---|---|---|---|",
        ]
    )
    for category in scanners:
        evidence = ", ".join(category.workflows)
        if category.dependabot_config:
            evidence = (
                f"{evidence}, .github/dependabot.yml"
                if evidence
                else ".github/dependabot.yml"
            )
        scanner_row = (
            f"| {category.name} | {'required' if category.required else 'optional'} | "
            + f"{'SATISFIED' if category.satisfied else 'MISSING'} | {evidence or '—'} |"
        )
        lines.append(scanner_row)
    lines.append("")

    if live:
        lines.extend(
            [
                "",
                "## Live scanner status",
                "",
                "_Queried via `gh run list` (up to 5 most recent `main` runs per",
                "scanner workflow; pull-request events excluded because a fork",
                "PR branch may itself be named `main`). A scanner with no",
                "default-branch history of its own is read through the gate that",
                "calls it, and each gate run is resolved to that scanner's OWN",
                "job conclusions (`gh run view --json jobs`) — the gate's roll-up",
                "is never shown under a scanner's name; `UNRESOLVED` covers",
                "causes such as a job list that could not be read or didn't",
                "name this scanner, or the live time budget running out",
                "before it could be checked. Runtime status, not static",
                "configuration — a failed run here may be transient, and it",
                "does not affect the score; a `NO RUNS` scanner does not",
                "count as coverage for its category._",
                "",
                "| Workflow | Latest | Last run | Recent runs (newest first) | Note |",
                "|---|---|---|---|---|",
            ]
        )
        any_unavailable = False
        any_no_runs = False
        any_unresolved = False
        for entry in live:
            if entry.unavailable:
                any_unavailable = True
                lines.append(
                    f"| `{_markdown_cell(entry.workflow)}` | — | — | — "
                    f"| _unavailable: {_markdown_cell(entry.unavailable)}_ |"
                )
                continue
            latest = entry.runs[0] if entry.runs else None
            completed = next(
                (
                    run
                    for run in entry.runs
                    if run.conclusion not in _INCONCLUSIVE
                ),
                None,
            )
            any_unresolved = any_unresolved or any(
                run.conclusion == _UNRESOLVED for run in entry.runs
            )
            notes: list[str] = []
            if entry.gated_by:
                # The runs are the gate's, but every conclusion in this row is
                # this scanner's own job result inside them.
                notes.append(
                    f"gated by `{entry.gated_by}` (this scanner's own jobs)"
                )
            notes.extend(entry.notes)
            if latest is None:
                # R8: an empty history is absence of evidence. Rendering it as
                # an em dash next to PASS rows reads as "nothing to report".
                any_no_runs = True
                latest_label = "NO RUNS"
                last_run = "—"
                notes.append("no qualifying run on `main` in the query window")
            else:
                last_run = _run_date(latest.created_at)
                if latest.conclusion == "unknown":
                    # R7: in flight. Show it as such and carry the previous
                    # conclusion, so a racing push cannot mask a red scanner.
                    latest_label = "RUNNING"
                    previous = (
                        _status_label(completed.conclusion)
                        if completed is not None
                        else "none"
                    )
                    notes.append(f"in flight — previous run {previous}")
                elif latest.conclusion == _UNRESOLVED:
                    latest_label = "UNRESOLVED"
                    if latest.unresolved_reason == "job_list_unreadable":
                        # `gh run view --json jobs` failed/timed out/returned
                        # unparseable JSON: nothing was learned about this
                        # scanner, so say so rather than guessing it was
                        # simply absent from a list that was never read.
                        notes.append(
                            "the gate run's job list could not be read"
                        )
                    elif latest.unresolved_reason not in (
                        "budget_exhausted",
                        "gate_has_no_caller_job",
                    ):
                        # `latest` here is genuinely fetched and resolved --
                        # its job list was checked and did not name this
                        # scanner. Skipped for two reasons that already have
                        # their own explanation and would otherwise duplicate
                        # it: the run synthesized because the live time
                        # budget ran out before it could even be queried
                        # (`budget_exhausted` -- its job list was never
                        # checked, so claiming its name was absent would be a
                        # guess, and the truncation note already explains
                        # it), and a gate with no job calling this workflow
                        # at all (`gate_has_no_caller_job` -- the entry-level
                        # note above already says so; repeating it here would
                        # be the same cause twice). A genuinely unresolved
                        # run keeps this note even when OTHER runs in the
                        # same row were truncated by the budget.
                        notes.append(
                            "the gate run's job list did not name this scanner"
                        )
                else:
                    latest_label = _status_label(latest.conclusion)
                if entry.stale:
                    # Staleness is measured on the last SUCCESSFUL run, so the
                    # date named here is that run's, not necessarily the newest.
                    success = next(
                        (
                            run
                            for run in entry.runs
                            if run.conclusion == "success"
                        ),
                        None,
                    )
                    if success is None:
                        # `completed`, not `latest`: an in-flight/unresolved
                        # newest run is not evidence either way (R5).
                        named = completed if completed is not None else latest
                        notes.append(
                            "no successful run in the query window (newest "
                            f"run {_run_date(named.created_at)}, "
                            f"{named.conclusion})"
                        )
                    else:
                        notes.append(
                            f"last successful run {_run_date(success.created_at)}"
                            " is past the staleness threshold"
                        )
                    if latest_label == _status_label("success"):
                        # A stale PASS is the lie this label exists to stop.
                        latest_label = "STALE"
            recent = (
                " ".join(_status_label(run.conclusion) for run in entry.runs)
                or "—"
            )
            if (
                completed is not None
                and completed.conclusion in _FAILED_CONCLUSIONS
            ):
                notes.append("latest run did not pass — see Actions tab")
            lines.append(
                f"| `{_markdown_cell(entry.workflow)}` | {latest_label} "
                f"| {last_run} | {recent} "
                f"| {_markdown_cell('; '.join(notes) or '—')} |"
            )
        lines.append("")
        if any_no_runs:
            lines.extend(
                [
                    "_`NO RUNS` means no qualifying default-branch run was found — absence of evidence, not a healthy scanner._",
                    "",
                ]
            )
        if any_unresolved:
            lines.extend(
                [
                    "_`UNRESOLVED` covers causes such as a job list that could not be read or didn't name that scanner, or gate history that could not be resolved within the live time budget — absence of evidence, not a passing or failing scan._",
                    "",
                ]
            )
        if any_unavailable:
            lines.extend(
                [
                    "_Some entries unavailable — `gh` may not be installed or authenticated, or every fetched run was a pull-request run._",
                    "",
                ]
            )

    lines.extend(["## Pre-commit hooks", ""])
    parse_error = precommit.get("parse_error")
    if parse_error:
        lines.extend(
            [
                f"`.pre-commit-config.yaml` YAML parse error: `{_markdown_cell(parse_error)}`",
                "",
            ]
        )
    elif not precommit["present"]:
        lines.extend(["`.pre-commit-config.yaml` is not present.", ""])
    else:
        lines.append(
            f"{precommit['hook_count']} hooks configured in `.pre-commit-config.yaml`."
        )
        lines.append(
            f"{precommit.get('tag_or_unknown_count', 0)} hooks use a tag or otherwise non-SHA static revision."
        )
        if precommit["floating_revs"]:
            lines.extend(["", "### Hooks not pinned to a commit SHA", ""])
            for hook in precommit["floating_revs"]:
                lines.append(
                    f"- `{hook.hook_id}` — `{hook.repo}` @ `{hook.rev or '<absent>'}`"
                )
        lines.append("")

    lines.extend(["## Recent CI/CD config changes", ""])
    if history.unavailable:
        lines.append(f"_Git history unavailable ({history.unavailable})._")
    elif history.changes:
        lines.extend(
            ["| Commit | Date | Author | Subject |", "|---|---|---|---|"]
        )
        for change in history.changes:
            change_row = (
                f"| `{_markdown_cell(change.sha)}` | {_markdown_cell(change.date)} | "
                + f"{_markdown_cell(change.author)} | {_markdown_cell(change.subject)} |"
            )
            lines.append(change_row)
    else:
        lines.append("_No recent CI/CD config changes found._")
    lines.extend(
        [
            "",
            "---",
            "",
            "Regenerate locally: `python scripts/generate_ci_health.py`",
            "",
        ]
    )
    return "\n".join(lines), score


def _write_github_output(score: int, findings: list[Finding]) -> bool:
    output_path = os.environ.get("GITHUB_OUTPUT")
    if not output_path:
        print(
            "--github-output requires GITHUB_OUTPUT to be set", file=sys.stderr
        )
        return False
    critical = sum(finding.severity == "critical" for finding in findings)
    high = sum(finding.severity == "high" for finding in findings)
    with pathlib.Path(output_path).open("a", encoding="utf-8") as output:
        github_values = (
            f"score={score}\ngrade={grade(score)}\nfindings={len(findings)}\n"
            + f"findings_critical={critical}\nfindings_high={high}\n"
        )
        _ = output.write(github_values)
    return True


class CliArgs(argparse.Namespace):
    stdout: bool = False
    check: bool = False
    out: str = str(OUT_FILE)
    github_output: bool = False
    live: bool = False


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    _ = parser.add_argument(
        "--stdout",
        action="store_true",
        help="print report instead of writing file",
    )
    _ = parser.add_argument(
        "--check",
        action="store_true",
        help="exit 1 on critical or high findings",
    )
    _ = parser.add_argument("--out", default=str(OUT_FILE), help="output path")
    _ = parser.add_argument(
        "--github-output",
        action="store_true",
        help="append summary values to $GITHUB_OUTPUT",
    )
    _ = parser.add_argument(
        "--live",
        action="store_true",
        help="query recent scanner runs; combine with --check to fail on latest failures",
    )
    args = parser.parse_args(namespace=CliArgs())

    findings: list[Finding] = []
    workflows = analyze_workflows(findings)
    precommit = analyze_precommit(findings)
    scanners = analyze_scanners(findings)
    live = analyze_live_status(
        findings,
        _scanner_workflow_files(),
        enabled=args.live,
    )
    scanners = discount_idle_scanners(scanners, live, findings)
    report, score = render(
        workflows,
        precommit,
        scanners,
        recent_cicd_changes(),
        findings,
        live,
    )

    if args.stdout:
        print(report)
    else:
        requested = pathlib.Path(args.out)
        output_path = requested if requested.is_absolute() else ROOT / requested
        output_path.parent.mkdir(parents=True, exist_ok=True)
        _ = output_path.write_text(report, encoding="utf-8")
        try:
            display_path = output_path.relative_to(ROOT)
        except ValueError:
            display_path = output_path
        print(f"Wrote {display_path} (score {score}/100, grade {grade(score)})")

    if args.github_output and not _write_github_output(score, findings):
        return 2
    gate_findings = [
        finding
        for finding in findings
        if finding.severity in ("critical", "high")
    ]
    if args.check and gate_findings:
        print(
            f"CI health has {len(gate_findings)} critical/high finding(s) — failing gate.",
            file=sys.stderr,
        )
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())