~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
ci(workflows): adopt self-repository $/ refs for local reusable workflows (#6622)
LearningCircuita903a3ae3231
diff --git a/.github/workflows/ci-gate.yml b/.github/workflows/ci-gate.ymlindex f8943dfd66..2f8e7472d0 100644--- a/.github/workflows/ci-gate.yml+++ b/.github/workflows/ci-gate.yml@@ -24,12 +24,12 @@ jobs:# Code Quality# ============================================pre-commit:- uses: ./.github/workflows/pre-commit.yml+ uses: $/.github/workflows/pre-commit.ymlpermissions:contents: readmypy-type-check:- uses: ./.github/workflows/mypy-type-check.yml+ uses: $/.github/workflows/mypy-type-check.ymlpermissions:contents: read@@ -37,7 +37,7 @@ jobs:# Test Suites# ============================================docker-tests:- uses: ./.github/workflows/docker-tests.yml+ uses: $/.github/workflows/docker-tests.ymlwith:strict-mode: truepermissions:@@ -50,24 +50,24 @@ jobs:# Validation# ============================================validate-image-pinning:- uses: ./.github/workflows/validate-image-pinning.yml+ uses: $/.github/workflows/validate-image-pinning.ymlpermissions:contents: readfile-whitelist-check:- uses: ./.github/workflows/file-whitelist-check.yml+ uses: $/.github/workflows/file-whitelist-check.ymlwith:check-all-files: truepermissions:contents: readcheck-env-vars:- uses: ./.github/workflows/check-env-vars.yml+ uses: $/.github/workflows/check-env-vars.ymlpermissions:contents: readsecurity-file-write-check:- uses: ./.github/workflows/security-file-write-check.yml+ uses: $/.github/workflows/security-file-write-check.ymlpermissions:contents: readdiff --git a/.github/workflows/e2e-research-test.yml b/.github/workflows/e2e-research-test.ymlindex 13073519bf..87bfae948f 100644--- a/.github/workflows/e2e-research-test.yml+++ b/.github/workflows/e2e-research-test.yml@@ -110,7 +110,7 @@ jobs:permissions:contents: readactions: write- uses: ./.github/workflows/ldr-research-reusable.yml+ uses: $/.github/workflows/ldr-research-reusable.ymlwith:query: ${{ needs.build-query.outputs.query }}model: ${{ github.event.label.name == 'ldr_research_static' && (vars.LDR_RESEARCH_CHEAP_MODEL || 'google/gemini-2.0-flash-001') || (vars.LDR_RESEARCH_MODEL || 'google/gemini-2.0-flash-001') }}diff --git a/.github/workflows/issue-research.yml b/.github/workflows/issue-research.ymlindex 2852deecc2..82aff0e14e 100644--- a/.github/workflows/issue-research.yml+++ b/.github/workflows/issue-research.yml@@ -87,7 +87,7 @@ jobs:permissions:contents: readactions: write- uses: ./.github/workflows/ldr-research-reusable.yml+ uses: $/.github/workflows/ldr-research-reusable.ymlwith:query: ${{ needs.build-query.outputs.query }}model: ${{ vars.LDR_RESEARCH_MODEL || 'google/gemini-2.0-flash-001' }}diff --git a/.github/workflows/prerelease-docker.yml b/.github/workflows/prerelease-docker.ymlindex 6a45874502..5945402655 100644--- a/.github/workflows/prerelease-docker.yml+++ b/.github/workflows/prerelease-docker.yml@@ -327,10 +327,11 @@ jobs:# is scoped to the CALLER, so `github.workflow_ref` would point# at release.yml (the wrong builder). The `job` context has no# `workflow_ref` property either (only check_run_id, container,- # services, status — actionlint confirms). For a local-path- # reusable workflow (`uses: ./.github/workflows/...`), the- # callee's ref equals the caller's `github.ref`, so composing- # the path manually gives the correct+ # services, status — actionlint confirms). For a self-repository+ # reusable workflow call (`uses: $/.github/workflows/...`), the+ # callee runs from this repository at the exact commit the run+ # is on, addressed by the run's own ref — so composing the path+ # manually gives the correct# `<owner>/<repo>/.github/workflows/prerelease-docker.yml@<ref>`# format that matches the Fulcio cert SAN. Cosign and# slsa-verifier both anchor on the cert anyway, so this fix isdiff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.ymlindex 29f7a7a76e..b43eaf645d 100644--- a/.github/workflows/release-gate.yml+++ b/.github/workflows/release-gate.yml@@ -56,27 +56,27 @@ jobs:# added complexity, and scanners rely on repo config files (.trivyignore,# .grype.yaml) that require a checkout step tied to each scanner's own job.security-tests:- uses: ./.github/workflows/security-tests.yml+ uses: $/.github/workflows/security-tests.ymlpermissions:contents: readsecurity-events: writesemgrep-scan:- uses: ./.github/workflows/semgrep.yml+ uses: $/.github/workflows/semgrep.ymlpermissions:contents: readsecurity-events: writeactions: readcontainer-security:- uses: ./.github/workflows/container-security.yml+ uses: $/.github/workflows/container-security.ymlpermissions:contents: readsecurity-events: writeactions: readowasp-zap-scan:- uses: ./.github/workflows/owasp-zap-scan.yml+ uses: $/.github/workflows/owasp-zap-scan.ymlpermissions:contents: readsecurity-events: write@@ -85,7 +85,7 @@ jobs:# SAST and code analysis# ============================================codeql-scan:- uses: ./.github/workflows/codeql.yml+ uses: $/.github/workflows/codeql.ymlpermissions:contents: readsecurity-events: write@@ -93,14 +93,14 @@ jobs:actions: readdevskim-scan:- uses: ./.github/workflows/devskim.yml+ uses: $/.github/workflows/devskim.ymlpermissions:contents: readsecurity-events: writeactions: readbearer-scan:- uses: ./.github/workflows/bearer.yml+ uses: $/.github/workflows/bearer.ymlpermissions:contents: readsecurity-events: write@@ -121,12 +121,12 @@ jobs:# See: https://docs.github.com/en/actions/using-workflows/reusing-workflows#nesting-reusable-workflowsnpm-audit:- uses: ./.github/workflows/npm-audit.yml+ uses: $/.github/workflows/npm-audit.ymlpermissions:contents: readretirejs-scan:- uses: ./.github/workflows/retirejs.yml+ uses: $/.github/workflows/retirejs.ymlpermissions:contents: readsecurity-events: write@@ -135,25 +135,25 @@ jobs:# Container and IaC security# ============================================dockle-scan:- uses: ./.github/workflows/dockle.yml+ uses: $/.github/workflows/dockle.ymlpermissions:contents: readsecurity-events: writehadolint-scan:- uses: ./.github/workflows/hadolint.yml+ uses: $/.github/workflows/hadolint.ymlpermissions:contents: readsecurity-events: writecheckov-scan:- uses: ./.github/workflows/checkov.yml+ uses: $/.github/workflows/checkov.ymlpermissions:contents: readsecurity-events: writedocker-multiarch-test:- uses: ./.github/workflows/docker-multiarch-test.yml+ uses: $/.github/workflows/docker-multiarch-test.ymlpermissions:contents: read@@ -161,7 +161,7 @@ jobs:# Workflow security# ============================================zizmor-scan:- uses: ./.github/workflows/zizmor-security.yml+ uses: $/.github/workflows/zizmor-security.ymlpermissions:contents: readsecurity-events: write@@ -171,7 +171,7 @@ jobs:# Dependency/container scanning (overlapping coverage)# ============================================grype-scan:- uses: ./.github/workflows/grype.yml+ uses: $/.github/workflows/grype.ymlpermissions:contents: readsecurity-events: write@@ -181,7 +181,7 @@ jobs:# Secret detection - scans only main branch history# ============================================gitleaks-scan:- uses: ./.github/workflows/gitleaks-main.yml+ uses: $/.github/workflows/gitleaks-main.ymlpermissions:contents: readsecurity-events: write@@ -192,7 +192,7 @@ jobs:# ============================================# TEMPORARILY DISABLED: nuclei-scan — causing slowdowns# nuclei-scan:- # uses: ./.github/workflows/nuclei.yml+ # uses: $/.github/workflows/nuclei.yml# permissions:# contents: read# security-events: write@@ -282,14 +282,14 @@ jobs:# Runtime security validation# ============================================security-headers-scan:- uses: ./.github/workflows/security-headers-validation.yml+ uses: $/.github/workflows/security-headers-validation.ymlpermissions:contents: read# Backwards compatibility & migration tests# ============================================backwards-compatibility:- uses: ./.github/workflows/backwards-compatibility.yml+ uses: $/.github/workflows/backwards-compatibility.ymlpermissions:contents: read@@ -298,7 +298,7 @@ jobs:# changes silently breaking the journal-quality build# ============================================journal-data-integration:- uses: ./.github/workflows/journal-data-integration.yml+ uses: $/.github/workflows/journal-data-integration.ymlpermissions:contents: readdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 2a97563b96..18669309da 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -97,7 +97,7 @@ jobs:release-gate:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'- uses: ./.github/workflows/release-gate.yml+ uses: $/.github/workflows/release-gate.ymlpermissions:contents: readsecurity-events: write@@ -113,7 +113,7 @@ jobs:ci-gate:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'- uses: ./.github/workflows/ci-gate.yml+ uses: $/.github/workflows/ci-gate.ymlpermissions:contents: write # Required: docker-tests deploys coverage to gh-pages (force push)pull-requests: write # Required: docker-tests posts coverage PR comments (no-op in release context)@@ -130,7 +130,7 @@ jobs:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'# Runs in parallel with release-gate (no dependency besides version-check)- uses: ./.github/workflows/playwright-webkit-tests.yml+ uses: $/.github/workflows/playwright-webkit-tests.ymlpermissions:contents: read@@ -144,7 +144,7 @@ jobs:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'# Runs in parallel with release-gate (no dependency besides version-check)- uses: ./.github/workflows/puppeteer-e2e-tests.yml+ uses: $/.github/workflows/puppeteer-e2e-tests.ymlpermissions:contents: readpull-requests: write # Required: puppeteer-e2e-tests posts test result comments (no-op in release context)@@ -172,7 +172,7 @@ jobs:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'# Runs in parallel with release-gate (no dependency besides version-check)- uses: ./.github/workflows/playwright-notes-tests.yml+ uses: $/.github/workflows/playwright-notes-tests.ymlpermissions:contents: read@@ -185,7 +185,7 @@ jobs:responsive-test-gate:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'- uses: ./.github/workflows/responsive-ui-tests-enhanced.yml+ uses: $/.github/workflows/responsive-ui-tests-enhanced.ymlpermissions:contents: read@@ -199,7 +199,7 @@ jobs:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'# Runs in parallel with release-gate (no dependency besides version-check)- uses: ./.github/workflows/backwards-compatibility.yml+ uses: $/.github/workflows/backwards-compatibility.ymlpermissions:contents: read@@ -216,7 +216,7 @@ jobs:compose-integration-gate:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'- uses: ./.github/workflows/compose-integration-test.yml+ uses: $/.github/workflows/compose-integration-test.ymlpermissions:contents: read@@ -229,7 +229,7 @@ jobs:vulture-gate:needs: [version-check]if: needs.version-check.outputs.should_release == 'true'- uses: ./.github/workflows/vulture-dead-code.yml+ uses: $/.github/workflows/vulture-dead-code.ymlpermissions:contents: read@@ -546,7 +546,7 @@ jobs:prerelease-docker:needs: [build, provenance]if: ${{ !cancelled() && needs.build.result == 'success' && needs.provenance.result == 'success' && needs.build.outputs.release_exists == 'false' }}- uses: ./.github/workflows/prerelease-docker.yml+ uses: $/.github/workflows/prerelease-docker.ymlwith:version: ${{ needs.build.outputs.version }}short_sha: ${{ needs.build.outputs.short_sha }}@@ -579,7 +579,7 @@ jobs:publish-docker:needs: [build, prerelease-docker]if: ${{ !cancelled() && needs.prerelease-docker.result == 'success' && needs.build.outputs.release_exists == 'false' }}- uses: ./.github/workflows/docker-publish.yml+ uses: $/.github/workflows/docker-publish.ymlwith:tag: ${{ needs.build.outputs.tag }}source_tag: prerelease-v${{ needs.build.outputs.version }}-${{ needs.build.outputs.short_sha }}diff --git a/.github/workflows/ui-full-shards.yml b/.github/workflows/ui-full-shards.ymlindex 15cfeab289..91a96d5f37 100644--- a/.github/workflows/ui-full-shards.yml+++ b/.github/workflows/ui-full-shards.yml@@ -32,7 +32,7 @@ jobs:github.event_name == 'workflow_dispatch' ||(github.event_name == 'pull_request' &&github.event.label.name == 'test:ui-full-shards')- uses: ./.github/workflows/docker-tests.yml+ uses: $/.github/workflows/docker-tests.ymlwith:strict-mode: truepermissions:diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex ccb9ba5cb0..124f700d9a 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -85,6 +85,19 @@ repos:name: Lint GitHub Actions workflowsdescription: "Static checker for GitHub Actions workflow files"files: ^\.github/workflows/.*\.ya?ml$+ # The pinned actionlint predates `$/`. Normalize workflow-call refs+ # in stdin so its input, secret, output and callee checks still run.+ # Keep the original filename for local metadata lookup/diagnostics.+ # Remove the adapter once actionlint supports self-repository refs.+ entry: python3 .pre-commit-hooks/actionlint-self-repository.py+ require_serial: true+ - id: actionlint+ alias: actionlint-self-repository-tests+ name: Check actionlint self-repository validation+ entry: python3 tests/hooks/test_actionlint_self_repository.py+ types: [file]+ files: (^\.pre-commit-config\.yaml$|actionlint[-_]self[-_]repository\.py$)+ pass_filenames: false- repo: localhooks:- id: check-workflow-test-paths@@ -103,7 +116,9 @@ repos:pass_filenames: falsedescription: "Every scan that uploads SARIF to code scanning must be inboth release-gate.yml needs lists (check-code-scanning-alerts and- release-gate-summary); a missing one can silently bypass the gate (#4817)"+ release-gate-summary); a missing one can silently bypass the gate+ (#4817). Also verifies repo-wide that every local reusable-workflow+ reference (uses: $/... or ./...) resolves to an existing file."- id: custom-code-checksname: Custom Code Quality Checksentry: .pre-commit-hooks/custom-checks.pydiff --git a/.pre-commit-hooks/actionlint-self-repository.py b/.pre-commit-hooks/actionlint-self-repository.pynew file mode 100644index 0000000000..c128577645--- /dev/null+++ b/.pre-commit-hooks/actionlint-self-repository.py@@ -0,0 +1,100 @@+#!/usr/bin/env python3+"""Validate self-repository workflow calls with the pinned actionlint.++Until actionlint understands `$/`, normalize job-level call references to+`./` in stdin only. Keeping the original filename lets actionlint load the+callee's inputs, secrets and outputs from the repository. No diagnostics+are suppressed and no workflow files are rewritten.+"""++import argparse+import json+import subprocess+import sys+from pathlib import Path++import yaml+from yaml.nodes import MappingNode, ScalarNode+from yaml.tokens import ScalarToken+++def mapping_values(node, key):+ if isinstance(node, MappingNode):+ for name, value in node.value:+ if isinstance(name, ScalarNode) and name.value == key:+ yield value+++def normalize_workflow_calls(source: str) -> str:+ """Rewrite only job-level uses scalars, retaining diagnostic line numbers."""+ document = yaml.compose(source, Loader=yaml.SafeLoader)+ ends = set()+ for jobs in mapping_values(document, "jobs"):+ if not isinstance(jobs, MappingNode):+ continue+ for _, job in jobs.value:+ for uses in mapping_values(job, "uses"):+ if isinstance(uses, ScalarNode) and uses.value.startswith("$/"):+ ends.add(uses.end_mark.index)++ edits = []+ # Scalar tokens exclude any anchor before the value. Their end marks+ # also identify aliased uses nodes, so a shared scalar is replaced once.+ for token in yaml.scan(source):+ if (+ not isinstance(token, ScalarToken)+ or token.end_mark.index not in ends+ ):+ continue+ start, end = token.start_mark.index, token.end_mark.index+ raw = source[start:end]+ if raw.startswith("$/"):+ edits.append((start, start + 1, "."))+ elif raw.startswith(("'$/", '"$/')):+ edits.append((start + 1, start + 2, "."))+ else:+ # Escaped quotes and block scalars need re-encoding. JSON strings+ # are valid YAML scalars; blank lines preserve following locations.+ value = json.dumps("./" + token.value[2:])+ edits.append((start, end, value + "\n" * raw.count("\n")))+ for start, end, value in reversed(edits):+ source = source[:start] + value + source[end:]+ return source+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--actionlint-arg", action="append", default=[])+ parser.add_argument("files", nargs="+")+ args = parser.parse_args()+ failed = False+ for filename in args.files:+ try:+ source = Path(filename).read_text(encoding="utf-8")+ try:+ source = normalize_workflow_calls(source)+ except yaml.YAMLError:+ # Let actionlint report malformed YAML using its normal+ # diagnostics. A parse failure must never skip validation.+ pass+ result = subprocess.run(+ [+ "actionlint",+ *args.actionlint_arg,+ "-stdin-filename",+ filename,+ "-",+ ],+ input=source,+ text=True,+ check=False,+ )+ failed |= result.returncode != 0+ except (OSError, UnicodeError) as exc:+ print(f"{filename}: {exc}", file=sys.stderr)+ failed = True+ return int(failed)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.pre-commit-hooks/check-release-gate-needs.py b/.pre-commit-hooks/check-release-gate-needs.pyindex dae3b2615d..54a9a804d0 100755--- a/.pre-commit-hooks/check-release-gate-needs.py+++ b/.pre-commit-hooks/check-release-gate-needs.py@@ -16,13 +16,20 @@ needs but was omitted from ``check-code-scanning-alerts`` for ~1.5 yearsalert query could run before Grype's SARIF was even uploaded.This hook recomputes, from source, the set of release-gate jobs that upload a-SARIF to code scanning, and fails if any of them is missing from EITHER needs-list. So the next scanner added to one list but forgotten in the other is+SARIF report to code scanning, and fails if any of them is missing from EITHER+needs list. So the next scanner added to one list but forgotten in the other iscaught at commit time instead of silently not gating a release.+It also verifies repo-wide that every LOCAL reusable-workflow reference+(``uses: $/...`` or legacy ``./...``) in .github/workflows/ resolves to an+existing file. This repository-wide check complements actionlint's checks+of the workflows being linted. The actionlint adapter normalizes ``$/``+calls in stdin to preserve callee, input, secret and output validation.+A job is treated as a SARIF uploader if a ``SARIF_UPLOAD_MARKERS`` substringappears in either its OWN inline steps or the LOCAL reusable workflow it calls-(``uses: ./…``). Limits worth knowing: a uploader pulled in via a REMOTE+(``uses: $/…``; the legacy workspace-relative ``./…`` form is still+recognized). Limits worth knowing: an uploader pulled in via a REMOTEreusable workflow (``uses: org/repo/…@ref``) cannot be inspected here, and anew upload mechanism needs a new entry in ``SARIF_UPLOAD_MARKERS``. None existtoday; revisit this hook if either changes.@@ -56,18 +63,18 @@ def job_uploads_sarif(job: dict, errors: list[str]) -> bool:"""True if a job uploads SARIF via its own inline steps or a localreusable workflow it calls.- A ``uses: ./…`` reference to a file that does not exist is recorded as a- loud error (appended to ``errors``) rather than silently treated as a- non-uploader — a typo'd workflow reference should fail the hook, not slip- a scanner past it.+ A ``uses: $/…`` (or legacy ``./…``) reference to a file that does not+ exist is recorded as a loud error (appended to ``errors``) rather than+ silently treated as a non-uploader — a typo'd workflow reference should+ fail the hook, not slip a scanner past it."""# Inline steps defined directly on the job.if text_uploads_sarif(yaml.safe_dump(job)):return True# Local reusable workflow the job calls.uses = job.get("uses")- if isinstance(uses, str) and uses.startswith("./"):- workflow = REPO_ROOT / uses[2:] # strip leading "./"+ if isinstance(uses, str) and uses.startswith(("./", "$/")):+ workflow = REPO_ROOT / uses[2:] # strip leading "./" or "$/"if not workflow.is_file():errors.append(f"missing reusable workflow referenced by a job: {uses}"@@ -89,18 +96,59 @@ def needs_of(job: object) -> set[str]:return set()+def check_local_workflow_refs(errors: list[str]) -> None:+ """Every local (`$/` or legacy `./`) workflow ref must resolve on disk.++ Unlike the per-file actionlint hook, this pass scans every workflow,+ including callers not present in the changed-file list. Commented-out+ jobs are invisible to the YAML parser and are intentionally skipped.+ release-gate.yml is skipped here: its own pass below already+ existence-checks that file's refs (and words the error with the SARIF+ context this hook exists for), so a duplicate wording would only add+ noise.+ """+ workflows_dir = REPO_ROOT / ".github" / "workflows"+ for path in sorted(+ [*workflows_dir.glob("*.yml"), *workflows_dir.glob("*.yaml")]+ ):+ if path == RELEASE_GATE:+ continue+ try:+ doc = yaml.safe_load(path.read_text(encoding="utf-8"))+ except (OSError, yaml.YAMLError) as exc:+ errors.append(f"{path.name}: cannot parse ({exc})")+ continue+ jobs = doc.get("jobs", {}) if isinstance(doc, dict) else {}+ if not isinstance(jobs, dict):+ continue+ for job_id, job in jobs.items():+ if not isinstance(job, dict):+ continue+ uses = job.get("uses")+ if isinstance(uses, str) and uses.startswith(("./", "$/")):+ if not (REPO_ROOT / uses[2:]).is_file():+ errors.append(+ f"{path.name}: job '{job_id}' references missing "+ f"reusable workflow: {uses}"+ )++def main() -> int:try:gate = yaml.safe_load(RELEASE_GATE.read_text(encoding="utf-8"))except (OSError, yaml.YAMLError) as exc:- print(f"❌ Could not parse {RELEASE_GATE}: {exc}")+ print(f"❌ Could not read or parse {RELEASE_GATE}: {exc}")return 1jobs = gate.get("jobs", {}) if isinstance(gate, dict) else {}+ if not isinstance(jobs, dict):+ print(f"❌ {RELEASE_GATE.name}: 'jobs' is not a mapping")+ return 1# SARIF-uploading jobs = release-gate jobs that upload SARIF (inline or via# the local reusable workflow they call).errors: list[str] = []+ check_local_workflow_refs(errors)sarif_jobs: dict[str, str] = {}for job_id, job in jobs.items():if not isinstance(job, dict):@@ -109,21 +157,29 @@ def main() -> int:uses = job.get("uses")sarif_jobs[job_id] = (uses[2:]- if isinstance(uses, str) and uses.startswith("./")+ if isinstance(uses, str) and uses.startswith(("./", "$/"))else "inline steps")+ # Needs-list violations are only meaningful once every reference+ # resolves: a broken callee cannot be classified as an uploader, so+ # drift computed against an incomplete uploader set would be guesswork.+ # Compute them after the error check, from a clean slate.+ violations: list[tuple[str, str, str]] = [] # (consumer, job, source)+ if not errors:+ for consumer in CONSUMER_JOBS:+ needs = needs_of(jobs.get(consumer, {}))+ for job_id, source in sorted(sarif_jobs.items()):+ if job_id not in needs:+ violations.append((consumer, job_id, source))+if errors:- print(- "❌ release-gate.yml references a workflow file that does not exist"- )+ print("❌ workflow reference errors found")print("=" * 64)for err in errors:print(f" - {err}")print("=" * 64)- print(- "FIX: correct the `uses:` path in .github/workflows/release-gate.yml"- )+ print("FIX: correct the `uses:` path in the workflow listed above")return 1if not sarif_jobs:@@ -131,13 +187,6 @@ def main() -> int:print(" The detector is likely broken — check SARIF_UPLOAD_MARKERS.")return 1- violations: list[tuple[str, str, str]] = [] # (consumer, job, source)- for consumer in CONSUMER_JOBS:- needs = needs_of(jobs.get(consumer, {}))- for job_id, source in sorted(sarif_jobs.items()):- if job_id not in needs:- violations.append((consumer, job_id, source))-if violations:print("❌ SARIF SCANNER MISSING FROM A release-gate.yml needs LIST")print("=" * 64)diff --git a/scripts/generate_workflow_status.py b/scripts/generate_workflow_status.pyindex bd451c66b5..4fa038d1ac 100644--- a/scripts/generate_workflow_status.py+++ b/scripts/generate_workflow_status.py@@ -146,7 +146,7 @@ def preflight(verbose: bool = False) -> tuple[str, str]:USES_LINE_RE = re.compile(r"""^(?P<indent>\s*)(?P<comment>\#\s*)?- uses:\s*(?P<target>\.\/\.github\/workflows\/[A-Za-z0-9_.-]+\.ya?ml)\s*$+ uses:\s*(?P<target>(?:\$|\.)/\.github/workflows/[A-Za-z0-9_.-]+\.ya?ml)\s*$""",re.VERBOSE,)diff --git a/tests/hooks/test_actionlint_self_repository.py b/tests/hooks/test_actionlint_self_repository.pynew file mode 100644index 0000000000..de1bfd1f1a--- /dev/null+++ b/tests/hooks/test_actionlint_self_repository.py@@ -0,0 +1,215 @@+"""Standalone integration checks for self-repository workflow validation.++Run directly with python3 to avoid importing the application. The dedicated+pre-commit hook supplies the same pinned actionlint used for workflow linting.+"""++import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++WRAPPER = (+ Path(__file__).resolve().parents[2]+ / ".pre-commit-hooks"+ / "actionlint-self-repository.py"+)++CALLEE = """\+on:+ workflow_call:+ inputs:+ query:+ type: string+ required: true+ enabled:+ type: boolean+ secrets:+ TOKEN:+ required: true+ outputs:+ result:+ value: ${{ jobs.work.outputs.result }}+jobs:+ work:+ runs-on: ubuntu-latest+ outputs:+ result: ${{ steps.emit.outputs.result }}+ steps:+ - id: emit+ run: echo "result=ok" >> "$GITHUB_OUTPUT"+"""++CALLER = """\+on: workflow_dispatch+jobs:+ call:+ uses: $/.github/workflows/callee.yml+ with:+ query: example+ enabled: true+ secrets:+ TOKEN: ${{ secrets.TOKEN }}+ consume:+ needs: call+ runs-on: ubuntu-latest+ env:+ RESULT: ${{ needs.call.outputs.result }}+ steps:+ - run: echo "$RESULT"+"""++[email protected](shutil.which("actionlint"), "actionlint is not installed")+class TestActionlintSelfRepository(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(+ prefix="actionlint-self-repository-"+ )+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ (self.root / ".git").mkdir()+ self.workflows = self.root / ".github" / "workflows"+ self.workflows.mkdir(parents=True)+ (self.workflows / "callee.yml").write_text(CALLEE, encoding="utf-8")++ def lint(self, source=CALLER, extra_files=()):+ caller = self.workflows / "caller.yml"+ caller.write_text(source, encoding="utf-8")+ result = subprocess.run(+ [+ sys.executable,+ str(WRAPPER),+ "--actionlint-arg=-oneline",+ "--actionlint-arg=-shellcheck=",+ "--actionlint-arg=-pyflakes=",+ ".github/workflows/caller.yml",+ *extra_files,+ ],+ cwd=self.root,+ text=True,+ capture_output=True,+ check=False,+ )+ self.assertEqual(caller.read_text(encoding="utf-8"), source)+ return result++ def assert_rejected(self, source, diagnostic):+ result = self.lint(source)+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)+ self.assertIn(diagnostic, result.stdout + result.stderr)++ def test_valid_self_repository_call(self):+ result = self.lint()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)++ def test_legacy_call_remains_valid(self):+ result = self.lint(CALLER.replace("uses: $/", "uses: ./"))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)++ def test_scalar_spellings_and_line_numbers(self):+ ref = "$/.github/workflows/callee.yml"+ for value in (+ "'" + ref + "'",+ '"' + ref + '"',+ '"\\u0024/.github/workflows/callee.yml"',+ "&callee " + ref,+ ">- # a comment mentioning $/\n " + ref,+ ):+ with self.subTest(value=value):+ result = self.lint(CALLER.replace(ref, value))+ self.assertEqual(+ result.returncode, 0, result.stdout + result.stderr+ )+ source = CALLER.replace(ref, ">-\n " + ref).replace(+ "needs.call.outputs.result", "needs.call.outputs.missing"+ )+ result = self.lint(source)+ line = next(+ i+ for i, text in enumerate(source.splitlines(), 1)+ if "needs.call.outputs.missing" in text+ )+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)+ self.assertIn(f"caller.yml:{line}:", result.stdout)++ def test_unknown_input_is_rejected(self):+ self.assert_rejected(+ CALLER.replace("query: example", "qurey: example"),+ 'input "qurey" is not defined',+ )++ def test_missing_required_input_is_rejected(self):+ self.assert_rejected(+ CALLER.replace(" query: example\n", ""),+ 'input "query" is required',+ )++ def test_wrong_input_type_is_rejected(self):+ self.assert_rejected(+ CALLER.replace("query: example", "query: true"),+ 'input "query" is typed as string',+ )++ def test_missing_required_secret_is_rejected(self):+ self.assert_rejected(+ CALLER.replace(+ " secrets:\n TOKEN: ${{ secrets.TOKEN }}\n", ""+ ),+ 'secret "TOKEN" is required',+ )++ def test_unknown_secret_is_rejected(self):+ self.assert_rejected(+ CALLER.replace(" TOKEN:", " TYPO:"),+ 'secret "TYPO" is not defined',+ )++ def test_unknown_output_is_rejected(self):+ self.assert_rejected(+ CALLER.replace(+ "needs.call.outputs.result", "needs.call.outputs.typo"+ ),+ 'property "typo" is not defined',+ )++ def test_missing_callee_is_rejected(self):+ self.assert_rejected(+ CALLER.replace("callee.yml", "missing.yml"),+ "could not read",+ )++ def test_non_callable_workflow_is_rejected(self):+ (self.workflows / "callee.yml").write_text(+ "on: push\njobs:\n work:\n runs-on: ubuntu-latest\n"+ " steps:\n - run: echo ok\n",+ encoding="utf-8",+ )+ self.assert_rejected(+ CALLER, '"workflow_call" event trigger is not found'+ )++ def test_malformed_remote_reference_is_rejected(self):+ self.assert_rejected(+ CALLER.replace(+ "$/.github/workflows/callee.yml", "owner/repo/w.yml"+ ),+ "is not following the format",+ )++ def test_invalid_yaml_is_rejected(self):+ self.assert_rejected("jobs: [unclosed\n", "could not parse")++ def test_a_later_success_does_not_hide_an_earlier_failure(self):+ result = self.lint(+ CALLER.replace("query: example", "qurey: example"),+ extra_files=(".github/workflows/callee.yml",),+ )+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)+ self.assertIn('input "qurey" is not defined', result.stdout)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/hooks/test_check_release_gate_needs.py b/tests/hooks/test_check_release_gate_needs.pynew file mode 100644index 0000000000..edf5cf3327--- /dev/null+++ b/tests/hooks/test_check_release_gate_needs.py@@ -0,0 +1,321 @@+"""Tests for the check-release-gate-needs pre-commit hook.++Two tripwires live in that hook:++* The original one (#4817): a SARIF-uploading scan missing from either+ release-gate.yml needs list silently bypasses the code-scanning alert+ gate (grype did exactly that for ~1.5 years).+* The repo-wide local-ref existence pass added with the self-repository+ (`uses: $/...`) conversion: every local callee must exist, including+ those referenced by callers outside the changed-file list. This+ complements the actionlint adapter's workflow-interface checks.+"""++import importlib.util+from pathlib import Path++import pytest++HOOKS_DIR = Path(__file__).parent.parent.parent / ".pre-commit-hooks"+++def _load_hook():+ """Import the dash-named hook script as a module."""+ spec = importlib.util.spec_from_file_location(+ "check_release_gate_needs", HOOKS_DIR / "check-release-gate-needs.py"+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def hook():+ return _load_hook()+++def _write_workflow(root: Path, name: str, text: str) -> Path:+ wf_dir = root / ".github" / "workflows"+ wf_dir.mkdir(parents=True, exist_ok=True)+ path = wf_dir / name+ path.write_text(text, encoding="utf-8")+ return path+++# A release-gate skeleton with one inline SARIF uploader and one+# workflow-calling uploader, both present in both consumer needs lists.+CONSUMERS = ("check-code-scanning-alerts", "release-gate-summary")+++def _release_gate(needs_c1: str, needs_c2: str) -> str:+ return (+ "jobs:\n"+ " grype-scan:\n"+ " uses: $/.github/workflows/grype.yml\n"+ " codeql:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: github/codeql-action/analyze@abc\n"+ f" {CONSUMERS[0]}:\n"+ f" needs: {needs_c1}\n"+ " runs-on: ubuntu-latest\n"+ " steps: []\n"+ f" {CONSUMERS[1]}:\n"+ f" needs: {needs_c2}\n"+ " runs-on: ubuntu-latest\n"+ " steps: []\n"+ )+++RELEASE_GATE_OK = _release_gate("[grype-scan, codeql]", "[grype-scan, codeql]")++[email protected](autouse=True)+def _isolate_repo_root(hook, tmp_path):+ """Point the hook's module globals at the per-test tmp tree.++ Without this, the hook module resolves REPO_ROOT from its own file+ location and the tests would silently audit the REAL repository.+ """+ hook.REPO_ROOT = tmp_path+ hook.RELEASE_GATE = tmp_path / ".github" / "workflows" / "release-gate.yml"+++def _make_tree(tmp_path: Path, release_gate: str = RELEASE_GATE_OK) -> Path:+ """A minimal repo tree: a callee for grype plus the release gate.++ The grype stub carries a SARIF upload marker so the hook classifies+ the workflow-calling job as a code-scanning uploader.+ """+ wf_dir = tmp_path / ".github" / "workflows"+ wf_dir.mkdir(parents=True, exist_ok=True)+ (wf_dir / "grype.yml").write_text(+ "jobs: {}\n# github/codeql-action/upload-sarif\n", encoding="utf-8"+ )+ (wf_dir / "release-gate.yml").write_text(release_gate, encoding="utf-8")+ return tmp_path+++def _run_main(hook, capsys) -> tuple[int, str]:+ code = hook.main()+ out = capsys.readouterr().out+ return code, out+++# =========================================================================+# check_local_workflow_refs — the repo-wide existence pass+# =========================================================================+++class TestLocalWorkflowRefs:+ def test_clean_tree_yields_no_errors(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "ci-gate.yml",+ "jobs:\n pre-commit:\n uses: $/.github/workflows/grype.yml\n",+ )+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert errors == []++ def test_missing_self_repo_callee_is_flagged(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "ci-gate.yml",+ "jobs:\n pre-commit:\n"+ " uses: $/.github/workflows/pre-commit-typo.yml\n",+ )+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert len(errors) == 1+ assert "ci-gate.yml" in errors[0]+ assert "pre-commit-typo.yml" in errors[0]++ def test_legacy_dot_slash_callee_is_also_checked(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "old.yml",+ "jobs:\n x:\n uses: ./.github/workflows/nope.yml\n",+ )+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert len(errors) == 1+ assert "nope.yml" in errors[0]++ def test_remote_refs_and_step_uses_are_ignored(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "mixed.yml",+ "jobs:\n"+ " remote:\n"+ " uses: org/repo/.github/workflows/x.yml@0123456789abcdef0123456789abcdef01234567\n"+ " local-job:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: $/./irrelevant-step-action\n"+ " - uses: actions/checkout@v5\n",+ )+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ # The step-level "$/./..." must NOT be treated as a job-level local+ # workflow ref (job.get("uses") only reads the job mapping).+ assert errors == []++ def test_unparseable_yaml_is_reported_not_raised(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(tmp_path, "broken.yml", "jobs: [unclosed\n")+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert any("broken.yml" in e and "parse" in e for e in errors)++ def test_malformed_job_shapes_do_not_crash(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "weird.yml",+ "jobs:\n"+ " null-job:\n"+ " str-job: just-a-string\n"+ " ok-job:\n"+ " uses: $/.github/workflows/grype.yml\n",+ )+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert errors == []++ def test_yaml_extension_workflows_are_globbed(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "dots.yaml",+ "jobs:\n x:\n uses: $/.github/workflows/nope.yaml\n",+ )+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert len(errors) == 1+ assert "dots.yaml" in errors[0]+ assert "nope.yaml" in errors[0]++ def test_empty_uses_value_is_ignored(self, hook, tmp_path):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "empty.yml",+ 'jobs:\n x:\n uses: ""\n',+ )+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert errors == []++ def test_release_gate_is_skipped_no_duplicate_error(self, hook, tmp_path):+ # A missing callee in release-gate.yml is reported exactly once (by+ # the release-gate pass inside main()), not twice.+ _make_tree(+ tmp_path,+ RELEASE_GATE_OK.replace(+ "$/.github/workflows/grype.yml",+ "$/.github/workflows/grype-typo.yml",+ ),+ )+ # grype-typo.yml must not exist+ assert not (+ tmp_path / ".github" / "workflows" / "grype-typo.yml"+ ).exists()+ errors: list[str] = []+ hook.check_local_workflow_refs(errors)+ assert errors == [] # repo-wide pass skips release-gate.yml+++# =========================================================================+# main() — both tripwires together+# =========================================================================+++class TestMain:+ def test_clean_tree_passes(self, hook, tmp_path, capsys):+ _make_tree(tmp_path)+ code, _ = _run_main(hook, capsys)+ assert code == 0++ def test_missing_callee_fails_with_pointer(self, hook, tmp_path, capsys):+ _make_tree(+ tmp_path,+ RELEASE_GATE_OK.replace(+ "$/.github/workflows/grype.yml",+ "$/.github/workflows/grype-typo.yml",+ ),+ )+ code, out = _run_main(hook, capsys)+ assert code == 1+ assert "grype-typo.yml" in out+ # Reported once, by the release-gate pass (repo-wide pass skips+ # release-gate.yml — see TestLocalWorkflowRefs above).+ assert out.count("grype-typo.yml") == 1++ def test_repo_wide_missing_callee_fails(self, hook, tmp_path, capsys):+ _make_tree(tmp_path)+ _write_workflow(+ tmp_path,+ "ci-gate.yml",+ "jobs:\n pre-commit:\n"+ " uses: $/.github/workflows/pre-commit-typo.yml\n",+ )+ code, out = _run_main(hook, capsys)+ assert code == 1+ assert "pre-commit-typo.yml" in out+ assert "FIX" in out++ def test_needs_list_drift_still_detected(self, hook, tmp_path, capsys):+ # The original tripwire: grype-scan removed from ONE needs list+ # (the first consumer) while the second keeps it.+ gate = _release_gate("[codeql]", "[grype-scan, codeql]")+ _make_tree(tmp_path, gate)+ code, out = _run_main(hook, capsys)+ assert code == 1+ assert "grype-scan" in out+ assert CONSUMERS[0] in out++ def test_no_uploader_jobs_at_all_fails_loudly(self, hook, tmp_path, capsys):+ # If the detector stops finding uploaders (e.g. a marker rename),+ # fail closed instead of vacuously passing.+ _make_tree(+ tmp_path,+ "jobs:\n nothing:\n runs-on: ubuntu-latest\n steps: []\n",+ )+ code, out = _run_main(hook, capsys)+ assert code == 1+ assert "No SARIF-uploading jobs" in out++ def test_missing_release_gate_clean_error_not_traceback(+ self, hook, tmp_path, capsys+ ):+ # No release-gate.yml at all: the OSError path prints a clean+ # message and exits 1 (main returns int; no exception escapes).+ wf_dir = tmp_path / ".github" / "workflows"+ wf_dir.mkdir(parents=True, exist_ok=True)+ (wf_dir / "grype.yml").write_text(+ "jobs: {}\n# github/codeql-action/upload-sarif\n", encoding="utf-8"+ )+ code, out = _run_main(hook, capsys)+ assert code == 1+ assert "Could not read or parse" in out++ def test_non_dict_jobs_in_release_gate_clean_error(+ self, hook, tmp_path, capsys+ ):+ # `jobs:` as a list is invalid for this hook's purposes; it must+ # fail with a pointer, not an AttributeError traceback (#round-4+ # review finding).+ _make_tree(tmp_path, "jobs: [not, a, mapping]\n")+ code, out = _run_main(hook, capsys)+ assert code == 1+ assert "'jobs' is not a mapping" in out++ def test_consumer_names_match_hook(self, hook):+ # The fixtures above hardcode the consumer job names; if the hook's+ # CONSUMER_JOBS ever changes, these tests must follow.+ assert CONSUMERS == hook.CONSUMER_JOBS