From 71ba4ae796292423fa330a9baeaf6352c0b3fb81 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Thu, 13 Aug 2026 11:46:26 -0400 Subject: [PATCH 01/44] docs(standards): add organization health defaults Adds organization-wide community health defaults, validation, ownership, contribution guidance, security policy, and hardened workflow checks. --- .github/CODEOWNERS | 1 + .github/ISSUE_TEMPLATE/bug_report.yml | 77 ++++++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature_request.yml | 42 ++++ .github/ISSUE_TEMPLATE/question.yml | 36 +++ .github/PULL_REQUEST_TEMPLATE.md | 35 +++ .github/markdownlint-profile.yaml | 3 + .../tests/community_health_contract_test.py | 223 ++++++++++++++++++ .github/workflows/standards-validation.yml | 97 ++++++++ .github/workflows/update-stats.yml | 9 +- CONTRIBUTING.md | 56 +++++ SECURITY.md | 49 ++++ 12 files changed, 631 insertions(+), 2 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/ISSUE_TEMPLATE/question.yml create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/markdownlint-profile.yaml create mode 100644 .github/tests/community_health_contract_test.py create mode 100644 .github/workflows/standards-validation.yml create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..787cb14 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @scttbnsn @ALARGECOMPANY @biggest-littlest diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..0782aa8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,77 @@ +name: Bug report +description: Report a reproducible problem +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thanks for reporting a bug. Do not include secrets or private data, and redact logs and configuration. Email security@codeswhat.com instead of filing a public issue for a suspected vulnerability. + + - type: input + id: version + attributes: + label: Version or commit + description: Provide the release version, image digest, or commit SHA. + placeholder: "e.g. 1.2.3 or abc1234" + validations: + required: true + + - type: textarea + id: description + attributes: + label: What happened? + description: Describe the observed behavior and its impact. + validations: + required: true + + - type: textarea + id: expected + attributes: + label: What did you expect? + description: Describe what should have happened instead. + validations: + required: true + + - type: textarea + id: reproduce + attributes: + label: Steps to reproduce + description: Provide the smallest complete reproduction you can. + placeholder: | + 1. Configure ... + 2. Run ... + 3. Observe ... + validations: + required: true + + - type: textarea + id: environment + attributes: + label: Environment + description: Include relevant OS, architecture, runtime, and install method. + placeholder: | + - OS and architecture: + - Runtime or toolchain: + - Install method: + validations: + required: true + + - type: textarea + id: configuration + attributes: + label: Redacted configuration + description: Include only configuration needed to reproduce the problem. + render: yaml + + - type: textarea + id: logs + attributes: + label: Redacted logs + description: Remove credentials, private paths, hostnames, and user data. + render: text + + - type: textarea + id: additional + attributes: + label: Additional context + description: Add screenshots, links, or other useful context. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..632633e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: mailto:security@codeswhat.com + about: Report suspected vulnerabilities privately, not in a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..ff53175 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,42 @@ +name: Feature request +description: Propose a focused improvement +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + Search existing issues and pull requests before proposing a feature. Describe the need before the implementation. + + - type: textarea + id: problem + attributes: + label: Problem + description: What use case or limitation should this change address? + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: Proposed change + description: Describe the behavior you want and who benefits from it. + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: Alternatives considered + description: Describe current workarounds or other approaches you considered. + + - type: textarea + id: compatibility + attributes: + label: Compatibility and security + description: Note migration, breaking-change, privacy, or security effects. + + - type: textarea + id: additional + attributes: + label: Additional context + description: Add examples, screenshots, or links that clarify the request. diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml new file mode 100644 index 0000000..2d697bf --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -0,0 +1,36 @@ +name: Question or help +description: Ask about setup, usage, or project behavior +labels: ["question"] +body: + - type: markdown + attributes: + value: | + Check the README, documentation, and existing issues first. Email security@codeswhat.com instead of asking publicly about a suspected vulnerability. + + - type: textarea + id: question + attributes: + label: Question + description: What are you trying to understand or accomplish? + validations: + required: true + + - type: textarea + id: attempted + attributes: + label: What have you tried? + description: Include the relevant documentation and commands you used. + validations: + required: true + + - type: input + id: version + attributes: + label: Version or commit + description: Provide the release version or commit SHA when relevant. + + - type: textarea + id: context + attributes: + label: Additional context + description: Add redacted configuration, logs, screenshots, or links. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..96f9712 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,35 @@ +# Pull request + +## Summary + + + +Related issue: + +## Changes + + + +## Verification + + + +## Security and compatibility + + + +## Checklist + +- [ ] This pull request targets the repository's documented target branch. +- [ ] The change is focused and follows the repository's contributor + instructions. +- [ ] Tests cover non-trivial behavior, or the verification section explains + why they do not apply. +- [ ] Relevant documentation and changelog entries are updated, or they do not + apply. +- [ ] Required local checks pass. +- [ ] The change contains no secrets, credentials, or private data. +- [ ] All required checks and reviews are complete before merge. diff --git a/.github/markdownlint-profile.yaml b/.github/markdownlint-profile.yaml new file mode 100644 index 0000000..b6a8dcf --- /dev/null +++ b/.github/markdownlint-profile.yaml @@ -0,0 +1,3 @@ +config: + MD033: false + MD041: false diff --git a/.github/tests/community_health_contract_test.py b/.github/tests/community_health_contract_test.py new file mode 100644 index 0000000..9439282 --- /dev/null +++ b/.github/tests/community_health_contract_test.py @@ -0,0 +1,223 @@ +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[2] + + +class CommunityHealthContractTest(unittest.TestCase): + def test_required_default_files_exist(self): + required = ( + "SECURITY.md", + "CONTRIBUTING.md", + ".github/CODEOWNERS", + ".github/markdownlint-profile.yaml", + ".github/ISSUE_TEMPLATE/bug_report.yml", + ".github/ISSUE_TEMPLATE/feature_request.yml", + ".github/ISSUE_TEMPLATE/question.yml", + ".github/ISSUE_TEMPLATE/config.yml", + ".github/PULL_REQUEST_TEMPLATE.md", + ".github/workflows/standards-validation.yml", + ) + + missing = [path for path in required if not (ROOT / path).is_file()] + + self.assertEqual([], missing, f"missing community health files: {missing}") + + def test_codeowners_has_org_catch_all(self): + codeowners = self.read_text(".github/CODEOWNERS") + + self.assertEqual( + "* @scttbnsn @ALARGECOMPANY @biggest-littlest\n", + codeowners, + ) + + def test_security_policy_has_org_baseline(self): + policy = self.read_text("SECURITY.md") + + for expected in ( + "## Supported versions", + "## Reporting a vulnerability", + "## Security scope", + "Do not open a public GitHub issue", + "security@codeswhat.com", + "private vulnerability reporting", + "48 hours", + "7 days", + ): + self.assertIn(expected, policy) + + def test_contributor_guide_matches_org_workflow(self): + guide = self.read_text("CONTRIBUTING.md") + + for expected in ( + "AGENTS.md", + "active development or integration branch", + "Conventional Commits", + "feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert", + "without emoji", + "tests", + "documentation", + "required checks and reviews", + "SECURITY.md", + ): + self.assertIn(expected, guide) + + def test_issue_forms_have_unique_ids_and_required_reproduction_fields(self): + bug_report = self.read_text(".github/ISSUE_TEMPLATE/bug_report.yml") + feature_request = self.read_text( + ".github/ISSUE_TEMPLATE/feature_request.yml" + ) + question = self.read_text(".github/ISSUE_TEMPLATE/question.yml") + + self.assertIn('labels: ["bug"]', bug_report) + self.assertIn('labels: ["enhancement"]', feature_request) + self.assertIn('labels: ["question"]', question) + self.assert_form_ids_are_unique(bug_report) + self.assert_form_ids_are_unique(feature_request) + self.assert_form_ids_are_unique(question) + + required_bug_fields = {"version", "description", "expected", "reproduce"} + actual_required = self.required_form_ids(bug_report) + self.assertTrue(required_bug_fields <= actual_required) + + self.assertIn("security@codeswhat.com", bug_report) + self.assertIn("redact", bug_report.lower()) + + def test_issue_template_config_routes_security_reports_privately(self): + config = self.read_text(".github/ISSUE_TEMPLATE/config.yml") + + self.assertIn("blank_issues_enabled: false", config) + self.assertIn("url: mailto:security@codeswhat.com", config) + self.assertIn("privately", config.lower()) + + def test_pull_request_template_requires_verification_and_safe_content(self): + template = self.read_text(".github/PULL_REQUEST_TEMPLATE.md") + + for expected in ( + "## Summary", + "## Changes", + "## Verification", + "## Security and compatibility", + "## Checklist", + "target branch", + "tests", + "documentation", + "required checks and reviews", + "secrets, credentials, or private data", + ): + self.assertIn(expected, template) + + def test_standards_workflow_has_unconditional_stable_jobs(self): + workflow = self.read_text(".github/workflows/standards-validation.yml") + + self.assertEqual(2, workflow.count("name: Standards Validation")) + self.assertIn(" name: CodeQL\n", workflow) + self.assertIn(" pull_request:\n", workflow) + self.assertIn(" - main\n", workflow) + self.assertIn(" - dev/repository-standards\n", workflow) + self.assertNotIn("\n push:", workflow) + self.assertIn("permissions: {}", workflow) + self.assertIn("runs-on: ubuntu-24.04", workflow) + self.assertNotIn("matrix:", workflow) + self.assertNotIn("continue-on-error:", workflow) + self.assertNotIn("\n if:", workflow) + + validation_job = workflow.split(" validation:\n", 1)[1].split( + "\n codeql:\n", 1 + )[0] + self.assertIn(" actions: read", validation_job) + self.assertIn(" contents: read", validation_job) + self.assertNotIn("write", validation_job) + + codeql_job = workflow.split("\n codeql:\n", 1)[1] + self.assertIn(" actions: read", codeql_job) + self.assertIn(" contents: read", codeql_job) + self.assertIn(" security-events: write", codeql_job) + + jobs = re.findall( + r"^ ([a-z][a-z0-9-]+):$", + workflow.split("\njobs:\n", 1)[1], + re.MULTILINE, + ) + self.assertEqual(["validation", "codeql"], jobs) + + def test_standards_workflow_pins_actions_and_runs_every_contract(self): + workflow = self.read_text(".github/workflows/standards-validation.yml") + actions = re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE) + + self.assertTrue(actions) + for action in actions: + self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") + + for expected in ( + "persist-credentials: false", + "community_health_contract_test.py", + "python3 -m compileall -q .", + "YAML.parse_file", + "json.load", + "markdownlint-cli2@0.23.2", + "markdownlint-profile.yaml", + "actionlint", + "zizmorcore/zizmor-action@", + "github/codeql-action/init@", + "languages: python", + "github/codeql-action/analyze@", + ): + self.assertIn(expected, workflow) + + def test_zizmor_action_owns_its_supported_cli_version(self): + workflow = self.read_text(".github/workflows/standards-validation.yml") + zizmor_step = workflow.split( + " - name: Validate workflows with zizmor\n", 1 + )[1].split("\n codeql:\n", 1)[0] + + self.assertNotIn("\n version:", zizmor_step) + + def test_linter_configs_do_not_suppress_workflow_findings(self): + markdown_config = self.read_text(".github/markdownlint-profile.yaml") + + self.assertIn("MD033: false", markdown_config) + self.assertIn("MD041: false", markdown_config) + self.assertNotIn("ignores:", markdown_config) + self.assertEqual(2, markdown_config.count(": false")) + self.assertFalse((ROOT / ".github/zizmor.yml").exists()) + + def test_profile_workflow_pins_actions_and_pushes_without_persisted_credentials(self): + workflow = self.read_text(".github/workflows/update-stats.yml") + actions = re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE) + + self.assertEqual(2, len(actions)) + for action in actions: + self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") + + checkout_step = workflow.split(" - name: Checkout\n", 1)[1].split( + "\n - name:", 1 + )[0] + push_step = workflow.split(" - name: Commit and push\n", 1)[1] + + self.assertIn("persist-credentials: false", checkout_step) + self.assertIn("GH_TOKEN: ${{ github.token }}", push_step) + self.assertIn("gh auth setup-git", push_step) + + def read_text(self, relative_path): + path = ROOT / relative_path + self.assertTrue(path.is_file(), f"missing community health file: {relative_path}") + return path.read_text() + + def assert_form_ids_are_unique(self, form): + ids = re.findall(r"^ id: ([a-z][a-z0-9_-]*)$", form, re.MULTILINE) + self.assertEqual(len(ids), len(set(ids))) + + def required_form_ids(self, form): + required = set() + for field in form.split("\n - type:"): + field_id = re.search(r"^ id: ([a-z][a-z0-9_-]*)$", field, re.MULTILINE) + if field_id and " required: true" in field: + required.add(field_id.group(1)) + return required + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml new file mode 100644 index 0000000..edfbdfd --- /dev/null +++ b/.github/workflows/standards-validation.yml @@ -0,0 +1,97 @@ +name: Standards Validation + +on: + pull_request: + branches: + - main + - dev/repository-standards + +permissions: {} + +jobs: + validation: + name: Standards Validation + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Validate community health contract + run: python3 .github/tests/community_health_contract_test.py + + - name: Compile Python + run: python3 -m compileall -q . + + - name: Parse YAML and JSON + run: | + set -euo pipefail + ruby -e 'require "yaml"; Dir.glob("**/*.{yml,yaml}", File::FNM_DOTMATCH).sort.each { |path| YAML.parse_file(path) }' + python3 -c 'import json; from pathlib import Path; [json.load(path.open()) for path in Path(".").rglob("*.json")]' + + - name: Lint Markdown + run: | + set -euo pipefail + npx --yes markdownlint-cli2@0.23.2 "**/*.md" "#profile/README.md" + npx --yes markdownlint-cli2@0.23.2 "profile/README.md" --config .github/markdownlint-profile.yaml + + - name: Validate workflows with actionlint + run: | + set -euo pipefail + bash <(curl -fsSL https://raw.githubusercontent.com/rhysd/actionlint/914e7df21a07ef503a81201c76d2b11c789d3fca/scripts/download-actionlint.bash) 1.7.12 "$RUNNER_TEMP" + "$RUNNER_TEMP/actionlint" -color + + - name: Validate workflows with zizmor + uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 + with: + advanced-security: false + annotations: true + collect: workflows + inputs: .github/workflows/ + online-audits: false + + codeql: + name: CodeQL + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: read + security-events: write + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + with: + languages: python + + - name: Analyze + uses: github/codeql-action/analyze@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + with: + category: /language:python diff --git a/.github/workflows/update-stats.yml b/.github/workflows/update-stats.yml index ba295c7..cb79f7c 100644 --- a/.github/workflows/update-stats.yml +++ b/.github/workflows/update-stats.yml @@ -17,10 +17,12 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: '3.11' @@ -31,7 +33,10 @@ jobs: python generate_svg.py - name: Commit and push + env: + GH_TOKEN: ${{ github.token }} run: | + gh auth setup-git git config --global user.email "github-actions[bot]@users.noreply.github.com" git config --global user.name "github-actions[bot]" git add profile/dark_mode.svg profile/light_mode.svg cache/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..1d31cae --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,56 @@ +# Contributing to CodesWhat projects + +Bug fixes, focused features, tests, and documentation improvements are welcome. +Repository-specific instructions take precedence over this organization +default. + +## Before starting + +1. Read the repository's `README.md`, `AGENTS.md`, and development or release + documentation. +2. Search existing issues and pull requests for the same problem. +3. Open an issue before starting a large feature, breaking change, architecture + change, or release-process change. +4. From the documented active development or integration branch, create a + focused branch in your fork. + +Do not commit credentials, private data, local planning files, editor state, or +generated artifacts that the repository does not track. + +## Making a change + +- Keep the change focused on one concern. +- Follow the repository's existing language, formatting, and architecture + conventions. +- Add regression tests for bug fixes and coverage for non-trivial behavior. +- Update documentation and changelog entries when public behavior changes. +- Run the exact formatter, lint, test, build, and local hook commands documented + by the repository. + +## Commits + +Use plain Conventional Commits without emoji: + +```text +(): +``` + +Allowed types are +`feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert`. Keep the subject +concise and describe the change in the imperative mood. + +## Pull requests + +- Select the repository's documented target branch. Do not assume the GitHub + default branch is the correct target. +- Explain the problem, the change, and the verification performed. +- Call out security, compatibility, migration, or release effects. +- Include tests and documentation, or explain why they do not apply. +- Wait for all required checks and reviews before merge. + +Maintainers may ask for changes or decline work that does not fit the project's +scope. Contributions are licensed under the license of the repository receiving +them. + +Report suspected vulnerabilities privately as described in +[`SECURITY.md`](SECURITY.md), never in a public issue or pull request. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..5cf164d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,49 @@ +# Security policy + +## Supported versions + +CodesWhat ships security fixes for the latest maintained release or branch of +each project. A repository-specific policy, release notes, or README may define +a narrower support window and takes precedence over this organization default. + +| Release or branch | Supported | +| --- | --- | +| Latest maintained release or branch | Yes | +| Older or unmaintained releases and branches | No | + +For a project that does not publish versioned releases, support applies to the +latest commit on its documented maintained branch. + +## Reporting a vulnerability + +Do not open a public GitHub issue for a suspected security vulnerability. + +Open this repository's **Security** tab and select **Report a vulnerability** +to use GitHub private vulnerability reporting when it is enabled. Otherwise, +email ****. Include the affected version or commit, +minimal reproduction steps, observed and expected behavior, and your assessment +of the impact. Redact credentials, private data, and identifying environment +details. + +You can expect: + +- acknowledgement within 48 hours; +- a status update within 7 days; and +- a fix or mitigation as soon as feasible, depending on severity and release + safety. + +CodesWhat coordinates disclosure with the reporter and credits reporters in +release notes unless they prefer to remain anonymous. + +## Security scope + +Unless a repository-specific policy says otherwise, the following are in +scope: + +- source code and configuration maintained in the repository; +- artifacts published by CodesWhat from that repository; and +- repository-owned build, test, and release automation. + +Third-party services, dependencies, and deployments are out of scope unless the +repository introduces or amplifies the reported impact. If the boundary is +unclear, report the issue privately and let the maintainers triage it. From 22feaaa1cd49740a453e9cd611745edbb13c6e8d Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 01:15:14 -0400 Subject: [PATCH 02/44] ci(greptile): require manual review requests (#11) --- .github/tests/greptile_config_contract_test.py | 18 ++++++++++++++++++ .github/workflows/standards-validation.yml | 1 + greptile.json | 3 +++ 3 files changed, 22 insertions(+) create mode 100644 .github/tests/greptile_config_contract_test.py create mode 100644 greptile.json diff --git a/.github/tests/greptile_config_contract_test.py b/.github/tests/greptile_config_contract_test.py new file mode 100644 index 0000000..33f7fb8 --- /dev/null +++ b/.github/tests/greptile_config_contract_test.py @@ -0,0 +1,18 @@ +import json +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[2] + + +class GreptileConfigContractTest(unittest.TestCase): + def test_reviews_are_manual_only(self): + with (ROOT / "greptile.json").open() as config_file: + config = json.load(config_file) + + self.assertEqual({"skipReview": "AUTOMATIC"}, config) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index edfbdfd..d9079a1 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -44,6 +44,7 @@ jobs: set -euo pipefail ruby -e 'require "yaml"; Dir.glob("**/*.{yml,yaml}", File::FNM_DOTMATCH).sort.each { |path| YAML.parse_file(path) }' python3 -c 'import json; from pathlib import Path; [json.load(path.open()) for path in Path(".").rglob("*.json")]' + python3 .github/tests/greptile_config_contract_test.py - name: Lint Markdown run: | diff --git a/greptile.json b/greptile.json new file mode 100644 index 0000000..34c493d --- /dev/null +++ b/greptile.json @@ -0,0 +1,3 @@ +{ + "skipReview": "AUTOMATIC" +} From bc5ab596a2c715cd8eb7b87230abb5e568c33021 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 10:54:26 -0400 Subject: [PATCH 03/44] ci(workflows): add reusable CI foundation (#13) * ci(workflows): add reusable CI foundation * fix(workflows): harden reusable release contracts --- .github/tests/reusable_ci_contract_test.py | 527 +++++++++++++++++++++ .github/workflows/go-ci.yml | 460 ++++++++++++++++++ .github/workflows/node-ci.yml | 186 ++++++++ .github/workflows/release-gate.yml | 172 +++++++ .github/workflows/standards-validation.yml | 1 + 5 files changed, 1346 insertions(+) create mode 100644 .github/tests/reusable_ci_contract_test.py create mode 100644 .github/workflows/go-ci.yml create mode 100644 .github/workflows/node-ci.yml create mode 100644 .github/workflows/release-gate.yml diff --git a/.github/tests/reusable_ci_contract_test.py b/.github/tests/reusable_ci_contract_test.py new file mode 100644 index 0000000..a6ec3f5 --- /dev/null +++ b/.github/tests/reusable_ci_contract_test.py @@ -0,0 +1,527 @@ +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOWS = { + "go": ROOT / ".github/workflows/go-ci.yml", + "node": ROOT / ".github/workflows/node-ci.yml", + "release": ROOT / ".github/workflows/release-gate.yml", +} +TARGET_SHA = "a" * 40 + + +class ReusableCIContractTest(unittest.TestCase): + def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self): + go_inputs = [ + "module-directory", + "go-version-file", + "go-cache-dependency-path", + "lint-check-name", + "test-check-name", + "fuzzers-json", + "run-govulncheck", + "run-qlty", + "run-goreleaser", + "run-workflow-security", + "run-commit-message", + "run-codeql", + ] + self.egress_inputs( + ( + "test", + "lint", + "govulncheck", + "workflow-security", + "commit-message", + "goreleaser", + "codeql", + "qlty", + "fuzz", + ) + ) + node_inputs = [ + "node-version", + "lockfile-path", + "lint-check-name", + "test-check-name", + "build-check-name", + "run-lint", + "run-test", + "run-build", + ] + self.egress_inputs(("lint", "test", "build")) + release_inputs = [ + "target-sha", + "workflow-files-json", + "max-attempts", + "sleep-seconds", + ] + + expected_inputs = { + "go": go_inputs, + "node": node_inputs, + "release": release_inputs, + } + expected_jobs = { + "go": { + "test", + "lint", + "govulncheck", + "workflow-security", + "commit-message", + "goreleaser", + "codeql", + "qlty", + "fuzz", + }, + "node": {"lint", "test", "build"}, + "release": {"gate"}, + } + + for name, path in WORKFLOWS.items(): + workflow = self.read_workflow(path) + header = workflow.split("\npermissions:", 1)[0] + inputs = re.findall(r"^ ([a-z][a-z0-9-]+):$", header, re.MULTILINE) + self.assertEqual(expected_inputs[name], inputs) + self.assertRegex(workflow, r"(?m)^on:\n workflow_call:\s+inputs:") + self.assertNotRegex( + workflow, + r"(?m)^ (push|pull_request|schedule|workflow_dispatch):", + ) + self.assertNotIn("concurrency:", workflow) + self.assertNotIn("outputs:", header) + self.assertNotIn("secrets:", header) + self.assertNotIn("secrets: inherit", workflow) + self.assertIn("permissions: {}", workflow) + + jobs = set( + re.findall( + r"^ ([a-z][a-z0-9-]+):$", + workflow.split("\njobs:\n", 1)[1], + re.MULTILINE, + ) + ) + self.assertEqual(expected_jobs[name], jobs) + + self.assert_input("go", "module-directory", "string", default=".") + self.assert_input("go", "go-version-file", "string", default="go.mod") + self.assert_input("go", "go-cache-dependency-path", "string", default="go.sum") + self.assert_input("go", "lint-check-name", "string", default="Go Lint") + self.assert_input("go", "test-check-name", "string", default="Go Test") + self.assert_input("go", "fuzzers-json", "string", default="[]") + for input_name in ( + "run-govulncheck", + "run-qlty", + "run-goreleaser", + "run-workflow-security", + "run-commit-message", + "run-codeql", + ): + self.assert_input("go", input_name, "boolean", default="false") + + self.assert_input("node", "node-version", "string", default="24") + self.assert_input("node", "lockfile-path", "string", default="package-lock.json") + self.assert_input("node", "lint-check-name", "string", default="Node Lint") + self.assert_input("node", "test-check-name", "string", default="Node Test") + self.assert_input("node", "build-check-name", "string", default="Node Build") + for input_name in ("run-lint", "run-test", "run-build"): + self.assert_input("node", input_name, "boolean", default="false") + + for workflow_name, job_names in ( + ("go", ("test", "lint", "govulncheck", "workflow-security", "commit-message", "goreleaser", "codeql", "qlty", "fuzz")), + ("node", ("lint", "test", "build")), + ): + for job_name in job_names: + self.assert_input(workflow_name, f"{job_name}-egress-policy", "string", default="audit") + self.assert_input(workflow_name, f"{job_name}-allowed-endpoints", "string", default="") + + self.assert_input("release", "target-sha", "string", required=True) + self.assert_input("release", "workflow-files-json", "string", required=True) + self.assert_input("release", "max-attempts", "number", default="12") + self.assert_input("release", "sleep-seconds", "number", default="300") + + def test_central_jobs_have_exact_names_fixed_commands_and_per_job_egress(self): + go = self.read_workflow(WORKFLOWS["go"]) + expected_go_names = { + "test": "${{ inputs.test-check-name }}", + "lint": "${{ inputs.lint-check-name }}", + "govulncheck": "Govulncheck", + "workflow-security": "Workflow Security", + "commit-message": "Commit Message", + "goreleaser": "GoReleaser Config", + "codeql": "CodeQL Analysis", + "qlty": "Qlty Check", + "fuzz": 'Go Fuzz (${{ matrix.fuzzer.name }})', + } + for job, display_name in expected_go_names.items(): + self.assertEqual(display_name, self.job_name(go, job)) + self.assert_job_egress(go, job) + + expected_go_scripts = [ + "./scripts/ci/go-test.sh", + "./scripts/ci/go-lint.sh", + "./scripts/ci/go-govulncheck.sh", + "./scripts/ci/commit-message.sh", + "./scripts/ci/go-release-check.sh", + "./scripts/ci/go-codeql-build.sh", + "./scripts/ci/go-qlty.sh", + "./scripts/ci/go-fuzz.sh", + ] + self.assertEqual(expected_go_scripts, self.fixed_scripts(go)) + self.assertIn("fuzzer: ${{ fromJSON(inputs.fuzzers-json) }}", go) + self.assertIn( + "if: inputs.fuzzers-json != '' && fromJSON(inputs.fuzzers-json)[0] != null", + go, + ) + self.assertIn("go-version-file: ${{ inputs.go-version-file }}", go) + self.assertIn("cache-dependency-path: ${{ inputs.go-cache-dependency-path }}", go) + self.assertIn("MODULE_DIRECTORY: ${{ inputs.module-directory }}", go) + + node = self.read_workflow(WORKFLOWS["node"]) + expected_node_names = { + "lint": "${{ inputs.lint-check-name }}", + "test": "${{ inputs.test-check-name }}", + "build": "${{ inputs.build-check-name }}", + } + for job, display_name in expected_node_names.items(): + self.assertEqual(display_name, self.job_name(node, job)) + self.assert_job_egress(node, job) + self.assertEqual( + [ + "./scripts/ci/node-lint.sh", + "./scripts/ci/node-test.sh", + "./scripts/ci/node-build.sh", + ], + self.fixed_scripts(node), + ) + self.assertIn("node-version: ${{ inputs.node-version }}", node) + self.assertIn("cache-dependency-path: ${{ inputs.lockfile-path }}", node) + + for workflow in (go, node, self.read_workflow(WORKFLOWS["release"])): + self.assertIn("runs-on: ubuntu-24.04", workflow) + for action in re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE): + self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") + for run_block in re.findall(r"run: \|\n((?: {10}.*\n|\n)+)", workflow): + self.assertNotIn("${{ inputs.", run_block) + + def test_artifact_uploads_are_central_and_fixed(self): + go = self.read_workflow(WORKFLOWS["go"]) + node = self.read_workflow(WORKFLOWS["node"]) + + self.assertEqual( + ["artifacts/go-test/", "artifacts/go-fuzz/"], + re.findall(r"^\s+path: (artifacts/[^\s]+)$", go, re.MULTILINE), + ) + self.assertEqual( + ["artifacts/node-test/", "artifacts/node-build/"], + re.findall(r"^\s+path: (artifacts/[^\s]+)$", node, re.MULTILINE), + ) + for workflow in (go, node): + upload_count = workflow.count("actions/upload-artifact@") + self.assertEqual(upload_count, workflow.count("if-no-files-found: ignore")) + self.assertEqual(upload_count, workflow.count("retention-days: 14")) + self.assertEqual(upload_count, workflow.count("if: always()")) + + def test_release_gate_checks_every_workflow_by_exact_sha_push_and_nonempty_branch(self): + exact_success = { + "head_sha": TARGET_SHA, + "event": "push", + "head_branch": "dev/v1.7", + "status": "completed", + "conclusion": "success", + } + wrong_runs = [ + {**exact_success, "event": "pull_request"}, + {**exact_success, "head_branch": ""}, + {**exact_success, "head_sha": "b" * 40}, + ] + result = self.run_release_gate( + { + "ci-verify.yml": wrong_runs + [exact_success], + "e2e-playwright.yml": [ + {**exact_success, "head_branch": "main"}, + ], + } + ) + + self.assertEqual(0, result.returncode, result.stderr) + self.assertIn(f"Found successful CI Verify push run for {TARGET_SHA}.", result.stdout) + self.assertIn(f"Found successful E2E Playwright push run for {TARGET_SHA}.", result.stdout) + + def test_release_gate_keeps_authoritative_client_side_run_filtering(self): + release = self.read_workflow(WORKFLOWS["release"]) + + self.assertIn("/runs?per_page=100\"", release) + self.assertNotRegex(release, r"runs\?[^\"\n]*(?:event|head_sha)=") + self.assertIn("spuriously returning 0 results since 2026-04-27", release) + + def test_release_gate_uses_one_shared_poll_budget_for_every_workflow(self): + in_progress = { + "head_sha": TARGET_SHA, + "event": "push", + "head_branch": "dev/v1.7", + "status": "in_progress", + "conclusion": None, + } + success = {**in_progress, "status": "completed", "conclusion": "success"} + result = self.run_release_gate( + {}, + runs_sequences_by_workflow={ + "ci-verify.yml": [[in_progress], [success]], + "e2e-playwright.yml": [[in_progress], [success]], + }, + max_attempts="2", + ) + + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual(1, result.stdout.count("FAKE_SLEEP"), result.stdout) + + def test_release_gate_waits_when_an_exact_run_is_still_in_progress(self): + exact_run = { + "head_sha": TARGET_SHA, + "event": "push", + "head_branch": "main", + } + result = self.run_release_gate( + { + "ci-verify.yml": [ + {**exact_run, "status": "completed", "conclusion": "failure"}, + {**exact_run, "status": "in_progress", "conclusion": None}, + ], + } + ) + + self.assertNotEqual(0, result.returncode) + self.assertIn("Attempt 1/1: waiting for CI Verify", result.stdout) + self.assertIn( + f"Timed out waiting for successful CI Verify push run for {TARGET_SHA}.", + result.stdout, + ) + + def test_release_gate_fails_closed_when_any_workflow_lacks_exact_success(self): + result = self.run_release_gate( + { + "ci-verify.yml": [ + { + "head_sha": TARGET_SHA, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + ], + "e2e-playwright.yml": [ + { + "head_sha": "b" * 40, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + ], + } + ) + + self.assertNotEqual(0, result.returncode) + self.assertIn( + f"Timed out waiting for successful E2E Playwright push run for {TARGET_SHA}.", + result.stdout, + ) + + def test_release_gate_rejects_unsafe_inputs_before_api_calls(self): + bad_sha = self.run_release_gate({"ci-verify.yml": []}, target_sha="main") + bad_files = self.run_release_gate( + {"ci-verify.yml": []}, + workflow_files_json='["../../release.yml"]', + ) + bad_attempts = self.run_release_gate( + {"ci-verify.yml": []}, + max_attempts="0", + ) + + self.assertNotEqual(0, bad_sha.returncode) + self.assertIn("target-sha must be a full lowercase commit SHA", bad_sha.stdout) + self.assertNotEqual(0, bad_files.returncode) + self.assertIn("workflow-files-json must be a nonempty JSON array", bad_files.stdout) + self.assertNotEqual(0, bad_attempts.returncode) + self.assertIn("max-attempts must be a positive integer", bad_attempts.stdout) + + def test_release_gate_rejects_non_github_api_hosts_before_api_calls(self): + result = self.run_release_gate( + { + "ci-verify.yml": [ + { + "head_sha": TARGET_SHA, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + ] + }, + api_url="https://github.example/api/v3", + ) + + self.assertNotEqual(0, result.returncode) + self.assertIn("release-gate supports api.github.com only", result.stdout) + + def test_standards_validation_runs_this_contract(self): + workflow = self.read_workflow(ROOT / ".github/workflows/standards-validation.yml") + self.assertEqual(1, workflow.count("python3 .github/tests/reusable_ci_contract_test.py")) + + def egress_inputs(self, job_names): + return [item for job in job_names for item in (f"{job}-egress-policy", f"{job}-allowed-endpoints")] + + def read_workflow(self, path): + self.assertTrue(path.is_file(), f"missing reusable workflow: {path.name}") + return path.read_text() + + def input_header(self, workflow_name): + workflow = self.read_workflow(WORKFLOWS[workflow_name]) + return workflow.split("\npermissions:", 1)[0] + + def assert_input(self, workflow_name, input_name, input_type, default=None, required=False): + header = self.input_header(workflow_name) + block = header.split(f" {input_name}:\n", 1)[1] + next_input = re.search(r"^ [a-z][a-z0-9-]+:$", block, re.MULTILINE) + if next_input: + block = block[: next_input.start()] + self.assertIn(f" type: {input_type}\n", block) + if default is not None: + expected = ( + f' default: "{default}"\n' + if default in {"", "[]"} + else f" default: {default}\n" + ) + self.assertIn(expected, block) + if required: + self.assertIn(" required: true\n", block) + + def job_section(self, workflow, job_name): + jobs = workflow.split("\njobs:\n", 1)[1] + section = jobs.split(f" {job_name}:\n", 1)[1] + next_job = re.search(r"^ [a-z][a-z0-9-]+:$", section, re.MULTILINE) + return section[: next_job.start()] if next_job else section + + def job_name(self, workflow, job_name): + section = self.job_section(workflow, job_name) + return re.search(r"^ name: (.+)$", section, re.MULTILINE).group(1).strip('"') + + def assert_job_egress(self, workflow, job_name): + section = self.job_section(workflow, job_name) + self.assertIn(f"egress-policy: ${{{{ inputs.{job_name}-egress-policy }}}}", section) + self.assertIn(f"allowed-endpoints: ${{{{ inputs.{job_name}-allowed-endpoints }}}}", section) + + def fixed_scripts(self, workflow): + return re.findall(r"^\s+run: (\./scripts/ci/[^\s]+)$", workflow, re.MULTILINE) + + def release_gate_script(self): + workflow = self.read_workflow(WORKFLOWS["release"]) + marker = " - name: Verify required CI workflows\n" + self.assertIn(marker, workflow) + step = workflow.split(marker, 1)[1] + block = step.split(" run: |\n", 1)[1] + lines = [] + for line in block.splitlines(): + if line.startswith(" "): + lines.append(line[10:]) + elif not line: + lines.append("") + else: + break + self.assertTrue(lines, "release gate shell step is empty") + return "\n".join(lines) + + def run_release_gate( + self, + runs_by_workflow, + target_sha=TARGET_SHA, + workflow_files_json=None, + max_attempts="1", + api_url="https://api.github.com", + runs_sequences_by_workflow=None, + ): + with tempfile.TemporaryDirectory() as temp_dir: + temp = Path(temp_dir) + fake_bin = temp / "bin" + fake_bin.mkdir() + fixtures = temp / "fixtures" + fixtures.mkdir() + + metadata = { + "ci-verify.yml": (123, "CI Verify"), + "e2e-playwright.yml": (456, "E2E Playwright"), + } + sequences = { + workflow_file: [runs] + for workflow_file, runs in runs_by_workflow.items() + } + sequences.update(runs_sequences_by_workflow or {}) + for workflow_file, runs_sequence in sequences.items(): + workflow_id = metadata[workflow_file][0] + for index, runs in enumerate(runs_sequence, start=1): + (fixtures / f"{workflow_id}.{index}.json").write_text( + json.dumps({"workflow_runs": runs}) + ) + (fixtures / f"{workflow_id}.last").write_text(str(len(runs_sequence))) + + curl = fake_bin / "curl" + curl.write_text( + "#!/usr/bin/env bash\n" + "for argument in \"$@\"; do url=\"$argument\"; done\n" + "case \"$url\" in\n" + " */actions/workflows/ci-verify.yml) printf '%s' '{\"id\":123,\"name\":\"CI Verify\",\"path\":\".github/workflows/ci-verify.yml\"}' ;;\n" + " */actions/workflows/e2e-playwright.yml) printf '%s' '{\"id\":456,\"name\":\"E2E Playwright\",\"path\":\".github/workflows/e2e-playwright.yml\"}' ;;\n" + " */actions/workflows/123/runs?per_page=100) workflow_id=123 ;;\n" + " */actions/workflows/456/runs?per_page=100) workflow_id=456 ;;\n" + " *) printf 'unexpected URL: %s\\n' \"$url\" >&2; exit 22 ;;\n" + "esac\n" + "if [ -n \"${workflow_id:-}\" ]; then\n" + " count_file=\"$RUNS_FIXTURES/$workflow_id.count\"\n" + " count=0\n" + " [ ! -f \"$count_file\" ] || count=$(cat \"$count_file\")\n" + " count=$((count + 1))\n" + " printf '%s' \"$count\" > \"$count_file\"\n" + " last=$(cat \"$RUNS_FIXTURES/$workflow_id.last\")\n" + " [ \"$count\" -le \"$last\" ] || count=\"$last\"\n" + " cat \"$RUNS_FIXTURES/$workflow_id.$count.json\"\n" + "fi\n" + ) + curl.chmod(0o755) + + sleep = fake_bin / "sleep" + sleep.write_text("#!/usr/bin/env bash\nprintf 'FAKE_SLEEP %s\\n' \"$1\"\n") + sleep.chmod(0o755) + + if workflow_files_json is None: + workflow_files_json = json.dumps(list(sequences)) + env = os.environ.copy() + env.update( + { + "GH_TOKEN": "test-token", + "GITHUB_API_URL": api_url, + "GITHUB_REPOSITORY": "CodesWhat/example", + "MAX_ATTEMPTS": max_attempts, + "PATH": f"{fake_bin}:{env['PATH']}", + "RUNS_FIXTURES": str(fixtures), + "SLEEP_SECONDS": "0", + "TARGET_SHA": target_sha, + "WORKFLOW_FILES_JSON": workflow_files_json, + } + ) + return subprocess.run( + ["bash", "-c", self.release_gate_script()], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + check=False, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml new file mode 100644 index 0000000..46601d4 --- /dev/null +++ b/.github/workflows/go-ci.yml @@ -0,0 +1,460 @@ +name: Reusable Go CI + +on: + workflow_call: + inputs: + module-directory: + description: Repository-relative Go module directory + required: false + type: string + default: . + go-version-file: + description: Repository-relative Go version file + required: false + type: string + default: go.mod + go-cache-dependency-path: + description: Repository-relative Go cache dependency path + required: false + type: string + default: go.sum + lint-check-name: + description: Exact display name for the Go lint job + required: false + type: string + default: Go Lint + test-check-name: + description: Exact display name for the Go test job + required: false + type: string + default: Go Test + fuzzers-json: + description: JSON array of caller-owned fuzzer name and pkg objects + required: false + type: string + default: "[]" + run-govulncheck: + description: Run the fixed repository govulncheck gate + required: false + type: boolean + default: false + run-qlty: + description: Run the fixed repository Qlty gate + required: false + type: boolean + default: false + run-goreleaser: + description: Run the fixed repository GoReleaser gate + required: false + type: boolean + default: false + run-workflow-security: + description: Run the central workflow security gate + required: false + type: boolean + default: false + run-commit-message: + description: Run the fixed repository commit-message gate on pull requests + required: false + type: boolean + default: false + run-codeql: + description: Run CodeQL for Actions and Go + required: false + type: boolean + default: false + test-egress-policy: + description: Harden Runner egress policy for Go test + required: false + type: string + default: audit + test-allowed-endpoints: + description: Harden Runner allowlist for Go test + required: false + type: string + default: "" + lint-egress-policy: + description: Harden Runner egress policy for Go lint + required: false + type: string + default: audit + lint-allowed-endpoints: + description: Harden Runner allowlist for Go lint + required: false + type: string + default: "" + govulncheck-egress-policy: + description: Harden Runner egress policy for govulncheck + required: false + type: string + default: audit + govulncheck-allowed-endpoints: + description: Harden Runner allowlist for govulncheck + required: false + type: string + default: "" + workflow-security-egress-policy: + description: Harden Runner egress policy for workflow security + required: false + type: string + default: audit + workflow-security-allowed-endpoints: + description: Harden Runner allowlist for workflow security + required: false + type: string + default: "" + commit-message-egress-policy: + description: Harden Runner egress policy for commit-message validation + required: false + type: string + default: audit + commit-message-allowed-endpoints: + description: Harden Runner allowlist for commit-message validation + required: false + type: string + default: "" + goreleaser-egress-policy: + description: Harden Runner egress policy for GoReleaser + required: false + type: string + default: audit + goreleaser-allowed-endpoints: + description: Harden Runner allowlist for GoReleaser + required: false + type: string + default: "" + codeql-egress-policy: + description: Harden Runner egress policy for CodeQL + required: false + type: string + default: audit + codeql-allowed-endpoints: + description: Harden Runner allowlist for CodeQL + required: false + type: string + default: "" + qlty-egress-policy: + description: Harden Runner egress policy for Qlty + required: false + type: string + default: audit + qlty-allowed-endpoints: + description: Harden Runner allowlist for Qlty + required: false + type: string + default: "" + fuzz-egress-policy: + description: Harden Runner egress policy for Go fuzzing + required: false + type: string + default: audit + fuzz-allowed-endpoints: + description: Harden Runner allowlist for Go fuzzing + required: false + type: string + default: "" + +permissions: {} + +jobs: + test: + name: ${{ inputs.test-check-name }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.test-egress-policy }} + allowed-endpoints: ${{ inputs.test-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: ${{ inputs.go-version-file }} + cache-dependency-path: ${{ inputs.go-cache-dependency-path }} + + - name: Run repository Go test gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} + run: ./scripts/ci/go-test.sh + + - name: Upload Go test artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: go-test-${{ github.run_id }}-${{ github.run_attempt }} + path: artifacts/go-test/ + if-no-files-found: ignore + retention-days: 14 + + lint: + name: ${{ inputs.lint-check-name }} + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.lint-egress-policy }} + allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: ${{ inputs.go-version-file }} + cache-dependency-path: ${{ inputs.go-cache-dependency-path }} + + - name: Run repository Go lint gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} + run: ./scripts/ci/go-lint.sh + + govulncheck: + name: Govulncheck + if: inputs.run-govulncheck + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.govulncheck-egress-policy }} + allowed-endpoints: ${{ inputs.govulncheck-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: ${{ inputs.go-version-file }} + cache-dependency-path: ${{ inputs.go-cache-dependency-path }} + + - name: Run repository govulncheck gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} + run: ./scripts/ci/go-govulncheck.sh + + workflow-security: + name: Workflow Security + if: inputs.run-workflow-security + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.workflow-security-egress-policy }} + allowed-endpoints: ${{ inputs.workflow-security-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run zizmor + uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 + with: + token: ${{ github.token }} + advanced-security: false + online-audits: false + + commit-message: + name: Commit Message + if: inputs.run-commit-message && github.event_name == 'pull_request' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.commit-message-egress-policy }} + allowed-endpoints: ${{ inputs.commit-message-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Run repository commit-message gate + env: + BASE_REF: ${{ github.base_ref }} + HEAD_REF: ${{ github.head_ref }} + run: ./scripts/ci/commit-message.sh + + goreleaser: + name: GoReleaser Config + if: inputs.run-goreleaser + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.goreleaser-egress-policy }} + allowed-endpoints: ${{ inputs.goreleaser-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: ${{ inputs.go-version-file }} + cache-dependency-path: ${{ inputs.go-cache-dependency-path }} + + - name: Run repository GoReleaser gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} + run: ./scripts/ci/go-release-check.sh + + codeql: + name: CodeQL Analysis + if: inputs.run-codeql + runs-on: ubuntu-24.04 + timeout-minutes: 60 + permissions: + actions: read + contents: read + security-events: write + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.codeql-egress-policy }} + allowed-endpoints: ${{ inputs.codeql-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + with: + languages: actions, go + queries: security-and-quality + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: ${{ inputs.go-version-file }} + cache-dependency-path: ${{ inputs.go-cache-dependency-path }} + + - name: Build for CodeQL + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} + run: ./scripts/ci/go-codeql-build.sh + + - name: Analyze with CodeQL + uses: github/codeql-action/analyze@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + + qlty: + name: Qlty Check + if: inputs.run-qlty + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.qlty-egress-policy }} + allowed-endpoints: ${{ inputs.qlty-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Qlty + uses: qltysh/qlty-action/install@08a0a862c159eae9b9003081da6663d96efef637 # v2.3.0 + + - name: Run repository Qlty gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} + run: ./scripts/ci/go-qlty.sh + + fuzz: + name: "Go Fuzz (${{ matrix.fuzzer.name }})" + if: inputs.fuzzers-json != '' && fromJSON(inputs.fuzzers-json)[0] != null + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + fuzzer: ${{ fromJSON(inputs.fuzzers-json) }} + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.fuzz-egress-policy }} + allowed-endpoints: ${{ inputs.fuzz-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: ${{ inputs.go-version-file }} + cache-dependency-path: ${{ inputs.go-cache-dependency-path }} + + - name: Run repository Go fuzzer + env: + FUZZER: ${{ matrix.fuzzer.name }} + MODULE_DIRECTORY: ${{ inputs.module-directory }} + PKG: ${{ matrix.fuzzer.pkg }} + run: ./scripts/ci/go-fuzz.sh + + - name: Upload Go fuzz artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: go-fuzz-${{ matrix.fuzzer.name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: artifacts/go-fuzz/ + if-no-files-found: ignore + retention-days: 14 diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml new file mode 100644 index 0000000..e699a9b --- /dev/null +++ b/.github/workflows/node-ci.yml @@ -0,0 +1,186 @@ +name: Reusable Node CI + +on: + workflow_call: + inputs: + node-version: + description: Node.js version used by enabled jobs + required: false + type: string + default: 24 + lockfile-path: + description: Repository-relative npm lockfile path or multiline paths + required: false + type: string + default: package-lock.json + lint-check-name: + description: Exact display name for the Node lint job + required: false + type: string + default: Node Lint + test-check-name: + description: Exact display name for the Node test job + required: false + type: string + default: Node Test + build-check-name: + description: Exact display name for the Node build job + required: false + type: string + default: Node Build + run-lint: + description: Run the fixed repository Node lint gate + required: false + type: boolean + default: false + run-test: + description: Run the fixed repository Node test gate + required: false + type: boolean + default: false + run-build: + description: Run the fixed repository Node build gate + required: false + type: boolean + default: false + lint-egress-policy: + description: Harden Runner egress policy for Node lint + required: false + type: string + default: audit + lint-allowed-endpoints: + description: Harden Runner allowlist for Node lint + required: false + type: string + default: "" + test-egress-policy: + description: Harden Runner egress policy for Node test + required: false + type: string + default: audit + test-allowed-endpoints: + description: Harden Runner allowlist for Node test + required: false + type: string + default: "" + build-egress-policy: + description: Harden Runner egress policy for Node build + required: false + type: string + default: audit + build-allowed-endpoints: + description: Harden Runner allowlist for Node build + required: false + type: string + default: "" + +permissions: {} + +jobs: + lint: + name: ${{ inputs.lint-check-name }} + if: inputs.run-lint + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.lint-egress-policy }} + allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ inputs.node-version }} + cache: npm + cache-dependency-path: ${{ inputs.lockfile-path }} + + - name: Run repository Node lint gate + run: ./scripts/ci/node-lint.sh + + test: + name: ${{ inputs.test-check-name }} + if: inputs.run-test + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.test-egress-policy }} + allowed-endpoints: ${{ inputs.test-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ inputs.node-version }} + cache: npm + cache-dependency-path: ${{ inputs.lockfile-path }} + + - name: Run repository Node test gate + run: ./scripts/ci/node-test.sh + + - name: Upload Node test artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: node-test-${{ github.run_id }}-${{ github.run_attempt }} + path: artifacts/node-test/ + if-no-files-found: ignore + retention-days: 14 + + build: + name: ${{ inputs.build-check-name }} + if: inputs.run-build + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: ${{ inputs.build-egress-policy }} + allowed-endpoints: ${{ inputs.build-allowed-endpoints }} + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: ${{ inputs.node-version }} + cache: npm + cache-dependency-path: ${{ inputs.lockfile-path }} + + - name: Run repository Node build gate + run: ./scripts/ci/node-build.sh + + - name: Upload Node build artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: node-build-${{ github.run_id }}-${{ github.run_attempt }} + path: artifacts/node-build/ + if-no-files-found: ignore + retention-days: 14 diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml new file mode 100644 index 0000000..f86ff64 --- /dev/null +++ b/.github/workflows/release-gate.yml @@ -0,0 +1,172 @@ +name: Reusable Release Gate + +on: + workflow_call: + inputs: + target-sha: + description: Full commit SHA whose branch push runs must have succeeded + required: true + type: string + workflow-files-json: + description: Nonempty JSON array of workflow filenames to verify + required: true + type: string + max-attempts: + description: Maximum polls for each required workflow + required: false + type: number + default: 12 + sleep-seconds: + description: Seconds between polls + required: false + type: number + default: 300 + +permissions: {} + +jobs: + gate: + name: Release Gate + runs-on: ubuntu-24.04 + timeout-minutes: 360 + permissions: + actions: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: block + allowed-endpoints: api.github.com:443 + + - name: Verify required CI workflows + env: + GH_TOKEN: ${{ github.token }} + MAX_ATTEMPTS: ${{ inputs.max-attempts }} + SLEEP_SECONDS: ${{ inputs.sleep-seconds }} + TARGET_SHA: ${{ inputs.target-sha }} + WORKFLOW_FILES_JSON: ${{ inputs.workflow-files-json }} + run: | + set -euo pipefail + + if [ "${GITHUB_API_URL}" != "https://api.github.com" ]; then + echo "::error::release-gate supports api.github.com only so its blocked egress allowlist matches the API host." + exit 1 + fi + if ! [[ "${TARGET_SHA}" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::target-sha must be a full lowercase commit SHA." + exit 1 + fi + if ! [[ "${MAX_ATTEMPTS}" =~ ^[1-9][0-9]*$ ]]; then + echo "::error::max-attempts must be a positive integer." + exit 1 + fi + if ! [[ "${SLEEP_SECONDS}" =~ ^[0-9]+$ ]]; then + echo "::error::sleep-seconds must be a nonnegative integer." + exit 1 + fi + if ! jq -e ' + type == "array" + and length > 0 + and all(.[]; + type == "string" + and test("^[A-Za-z0-9][A-Za-z0-9._-]*[.]ya?ml$") + ) + ' <<< "${WORKFLOW_FILES_JSON}" >/dev/null; then + echo "::error::workflow-files-json must be a nonempty JSON array of workflow filenames." + exit 1 + fi + + workflow_files=() + while IFS= read -r workflow_file; do + workflow_files+=("${workflow_file}") + done < <(jq -r '.[]' <<< "${WORKFLOW_FILES_JSON}") + + workflow_ids=() + workflow_names=() + for workflow_file in "${workflow_files[@]}"; do + workflow_url="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_file}" + workflow_json="$(curl --proto '=https' --tlsv1.2 --retry 3 --fail --silent --show-error \ + -H "Authorization: Bearer ${GH_TOKEN}" \ + -H "Accept: application/vnd.github+json" \ + "${workflow_url}")" + workflow_id="$(echo "${workflow_json}" | jq -r '.id // empty')" + workflow_name="$(echo "${workflow_json}" | jq -r '.name // empty')" + workflow_path="$(echo "${workflow_json}" | jq -r '.path // empty')" + expected_path=".github/workflows/${workflow_file}" + if [ -z "${workflow_id}" ] || [ -z "${workflow_name}" ] || [ "${workflow_path}" != "${expected_path}" ]; then + echo "::error::Failed to resolve workflow metadata for ${workflow_file}." + exit 1 + fi + workflow_ids+=("${workflow_id}") + workflow_names+=("${workflow_name}") + done + + workflow_succeeded=() + for index in "${!workflow_ids[@]}"; do + workflow_succeeded["${index}"]=false + done + + for attempt in $(seq 1 "${MAX_ATTEMPTS}"); do + waiting=false + for index in "${!workflow_ids[@]}"; do + if [ "${workflow_succeeded[${index}]}" = "true" ]; then + continue + fi + + workflow_id="${workflow_ids[${index}]}" + workflow_name="${workflow_names[${index}]}" + # GitHub's `?head_sha=` and `?event=` query filters have been spuriously returning 0 results since 2026-04-27. + # Filter the latest 100 runs client-side instead. + runs_url="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_id}/runs?per_page=100" + runs_json="$(curl --proto '=https' --tlsv1.2 --retry 3 --fail --silent --show-error \ + -H "Authorization: Bearer ${GH_TOKEN}" \ + -H "Accept: application/vnd.github+json" \ + "${runs_url}")" + filtered="$(echo "${runs_json}" | jq --arg sha "${TARGET_SHA}" '{ + workflow_runs: [.workflow_runs[] + | select( + .head_sha == $sha + and .event == "push" + and ((.head_branch // "") | length > 0) + )] + }')" + + success_count="$(echo "${filtered}" | jq '[.workflow_runs[] | select(.conclusion == "success")] | length')" + in_progress_count="$(echo "${filtered}" | jq '[.workflow_runs[] | select(.status != "completed")] | length')" + completed_count="$(echo "${filtered}" | jq '[.workflow_runs[] | select(.status == "completed")] | length')" + + if [ "${success_count}" -gt 0 ]; then + echo "Found successful ${workflow_name} push run for ${TARGET_SHA}." + workflow_succeeded["${index}"]=true + continue + fi + + if [ "${completed_count}" -gt 0 ] && [ "${in_progress_count}" -eq 0 ]; then + echo "::error::${workflow_name} push runs for ${TARGET_SHA} completed without success." + echo "${filtered}" | jq '.workflow_runs[] | {id, status, conclusion, head_branch, html_url}' + exit 1 + fi + + echo "Attempt ${attempt}/${MAX_ATTEMPTS}: waiting for ${workflow_name} push run for ${TARGET_SHA}." + waiting=true + done + + if [ "${waiting}" != "true" ]; then + break + fi + if [ "${attempt}" -lt "${MAX_ATTEMPTS}" ]; then + sleep "${SLEEP_SECONDS}" + fi + done + + timed_out=false + for index in "${!workflow_ids[@]}"; do + if [ "${workflow_succeeded[${index}]}" != "true" ]; then + echo "::error::Timed out waiting for successful ${workflow_names[${index}]} push run for ${TARGET_SHA}." + timed_out=true + fi + done + if [ "${timed_out}" = "true" ]; then + exit 1 + fi diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index d9079a1..192e5bd 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -45,6 +45,7 @@ jobs: ruby -e 'require "yaml"; Dir.glob("**/*.{yml,yaml}", File::FNM_DOTMATCH).sort.each { |path| YAML.parse_file(path) }' python3 -c 'import json; from pathlib import Path; [json.load(path.open()) for path in Path(".").rglob("*.json")]' python3 .github/tests/greptile_config_contract_test.py + python3 .github/tests/reusable_ci_contract_test.py - name: Lint Markdown run: | From 16a6680ee0bdeb32f5a768557413503adc4c36c8 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 13:35:36 -0400 Subject: [PATCH 04/44] feat(quality): standardize long-run reporting (#15) * feat(quality): add normalized reporting foundation * test(quality): run reporting contracts in standards validation * fix(quality): align report validator with schema * test(quality): verify GitHub integration outputs --- .../quality-result-config/target-result.json | 22 + .../quality-result-filter/target-result.json | 22 + .../quality-result-stats/target-result.json | 16 + .../quality-result-verify/target-result.json | 16 + .../quality-result-stats/target-result.json | 15 + .../quality-result-verify/target-result.json | 16 + .../quality-result-ops-1/target-result.json | 22 + .../quality-result-ops-1/target-result.json | 22 + .../quality-result-ops-2/target-result.json | 22 + .../quality-result-config/target-result.json | 22 + .../target-result.invalid | 21 + .github/tests/quality_report_contract_test.py | 447 ++++++++++ .../workflows/quality-report-aggregate.yml | 157 ++++ .github/workflows/standards-validation.yml | 1 + decisions/quality-reporting.md | 162 ++++ quality-report/v1/quality_report.py | 765 ++++++++++++++++++ quality-report/v1/schema.json | 496 ++++++++++++ 17 files changed, 2244 insertions(+) create mode 100644 .github/tests/fixtures/quality-report/v1/canonical-score/quality-result-config/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/canonical-score/quality-result-filter/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/crash/quality-result-verify/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/incomplete/quality-result-ops-1/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-1/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-2/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/parse-error/quality-result-config/target-result.json create mode 100644 .github/tests/fixtures/quality-report/v1/parse-error/quality-result-filter/target-result.invalid create mode 100644 .github/tests/quality_report_contract_test.py create mode 100644 .github/workflows/quality-report-aggregate.yml create mode 100644 decisions/quality-reporting.md create mode 100644 quality-report/v1/quality_report.py create mode 100644 quality-report/v1/schema.json diff --git a/.github/tests/fixtures/quality-report/v1/canonical-score/quality-result-config/target-result.json b/.github/tests/fixtures/quality-report/v1/canonical-score/quality-result-config/target-result.json new file mode 100644 index 0000000..d4f7466 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/canonical-score/quality-result-config/target-result.json @@ -0,0 +1,22 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "mutation", + "tool": "gremlins", + "target": { + "name": "./internal/config", + "outcome": "passed", + "metrics": { + "killed": 40, + "timeout": 10, + "survived": 5, + "no_coverage": 5, + "invalid": 2, + "ignored": 3, + "tool_score_numerator": 40, + "tool_score_denominator": 45, + "tool_score_pct": 88.89, + "tool_score_definition": "killed / (killed + survived)" + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/canonical-score/quality-result-filter/target-result.json b/.github/tests/fixtures/quality-report/v1/canonical-score/quality-result-filter/target-result.json new file mode 100644 index 0000000..a4b3164 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/canonical-score/quality-result-filter/target-result.json @@ -0,0 +1,22 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "mutation", + "tool": "gremlins", + "target": { + "name": "./internal/filter", + "outcome": "passed", + "metrics": { + "killed": 30, + "timeout": 0, + "survived": 0, + "no_coverage": 10, + "invalid": 1, + "ignored": 2, + "tool_score_numerator": 30, + "tool_score_denominator": 30, + "tool_score_pct": 100.0, + "tool_score_definition": "killed / (killed + survived)" + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json b/.github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json new file mode 100644 index 0000000..627a14e --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json @@ -0,0 +1,16 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "fuzz", + "tool": "go-fuzz", + "target": { + "name": "internal/docker/FuzzDecodeStats", + "outcome": "passed", + "metrics": { + "budget_seconds": 120, + "elapsed_seconds": 111.25, + "executions": 650000, + "new_interesting_inputs": 2 + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json b/.github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json new file mode 100644 index 0000000..472e276 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json @@ -0,0 +1,16 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "fuzz", + "tool": "go-fuzz", + "target": { + "name": "internal/auth/FuzzVerifyRequest", + "outcome": "passed", + "metrics": { + "budget_seconds": 300, + "elapsed_seconds": 288.25, + "executions": 1250000, + "new_interesting_inputs": 3 + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json b/.github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json new file mode 100644 index 0000000..0db4a95 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json @@ -0,0 +1,15 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "fuzz", + "tool": "go-fuzz", + "target": { + "name": "internal/docker/FuzzDecodeStats", + "outcome": "crashed", + "metrics": null, + "diagnostic": "tool process exited 2", + "reproduction": { + "seed": "-test.fuzzcachedir=/tmp/fuzz-cache" + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/crash/quality-result-verify/target-result.json b/.github/tests/fixtures/quality-report/v1/crash/quality-result-verify/target-result.json new file mode 100644 index 0000000..c2f7e89 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/crash/quality-result-verify/target-result.json @@ -0,0 +1,16 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "fuzz", + "tool": "go-fuzz", + "target": { + "name": "internal/auth/FuzzVerifyRequest", + "outcome": "passed", + "metrics": { + "budget_seconds": 300, + "elapsed_seconds": 300.0, + "executions": 990000, + "new_interesting_inputs": 0 + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/incomplete/quality-result-ops-1/target-result.json b/.github/tests/fixtures/quality-report/v1/incomplete/quality-result-ops-1/target-result.json new file mode 100644 index 0000000..4a5d472 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/incomplete/quality-result-ops-1/target-result.json @@ -0,0 +1,22 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "mutation", + "tool": "stryker", + "target": { + "name": "apps-api-ops-1", + "outcome": "passed", + "metrics": { + "killed": 20, + "timeout": 2, + "survived": 3, + "no_coverage": 5, + "invalid": 1, + "ignored": 2, + "tool_score_numerator": 22, + "tool_score_denominator": 25, + "tool_score_pct": 88.0, + "tool_score_definition": "detected / mutants with test coverage" + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-1/target-result.json b/.github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-1/target-result.json new file mode 100644 index 0000000..f79465e --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-1/target-result.json @@ -0,0 +1,22 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "mutation", + "tool": "stryker", + "target": { + "name": "apps-api-ops-1", + "outcome": "passed", + "metrics": { + "killed": 3, + "timeout": 1, + "survived": 1, + "no_coverage": 1, + "invalid": 0, + "ignored": 0, + "tool_score_numerator": 4, + "tool_score_denominator": 5, + "tool_score_pct": 80.0, + "tool_score_definition": "detected / mutants with test coverage" + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-2/target-result.json b/.github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-2/target-result.json new file mode 100644 index 0000000..403a77f --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/native-score/quality-result-ops-2/target-result.json @@ -0,0 +1,22 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "mutation", + "tool": "stryker", + "target": { + "name": "apps-api-ops-2", + "outcome": "passed", + "metrics": { + "killed": 2, + "timeout": 0, + "survived": 2, + "no_coverage": 0, + "invalid": 1, + "ignored": 1, + "tool_score_numerator": 2, + "tool_score_denominator": 4, + "tool_score_pct": 50.0, + "tool_score_definition": "detected / mutants with test coverage" + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/parse-error/quality-result-config/target-result.json b/.github/tests/fixtures/quality-report/v1/parse-error/quality-result-config/target-result.json new file mode 100644 index 0000000..d1f3655 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/parse-error/quality-result-config/target-result.json @@ -0,0 +1,22 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "mutation", + "tool": "gremlins", + "target": { + "name": "./internal/config", + "outcome": "passed", + "metrics": { + "killed": 12, + "timeout": 1, + "survived": 2, + "no_coverage": 1, + "invalid": 0, + "ignored": 1, + "tool_score_numerator": 12, + "tool_score_denominator": 14, + "tool_score_pct": 85.71, + "tool_score_definition": "killed / (killed + survived)" + } + } +} diff --git a/.github/tests/fixtures/quality-report/v1/parse-error/quality-result-filter/target-result.invalid b/.github/tests/fixtures/quality-report/v1/parse-error/quality-result-filter/target-result.invalid new file mode 100644 index 0000000..783dac7 --- /dev/null +++ b/.github/tests/fixtures/quality-report/v1/parse-error/quality-result-filter/target-result.invalid @@ -0,0 +1,21 @@ +{ + "schema_version": "quality-report/v1", + "kind": "target-result", + "track": "mutation", + "tool": "gremlins", + "target": { + "name": "./internal/filter", + "outcome": "passed", + "metrics": { + "killed": 31, + "timeout": 4, + "survived": 2, + "no_coverage": 3, + "invalid": 1, + "ignored": 0, + "tool_score_numerator": 31, + "tool_score_denominator": 33, + "tool_score_pct": 93.94, + "tool_score_definition": "killed / (killed + survived)" + } + } diff --git a/.github/tests/quality_report_contract_test.py b/.github/tests/quality_report_contract_test.py new file mode 100644 index 0000000..b456ce7 --- /dev/null +++ b/.github/tests/quality_report_contract_test.py @@ -0,0 +1,447 @@ +import json +from pathlib import Path +import runpy +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +CONTRACT_ROOT = ROOT / "quality-report" / "v1" +FIXTURES = ROOT / ".github" / "tests" / "fixtures" / "quality-report" / "v1" +SCRIPT = CONTRACT_ROOT / "quality_report.py" +SCHEMA = CONTRACT_ROOT / "schema.json" +WORKFLOW = ROOT / ".github" / "workflows" / "quality-report-aggregate.yml" +DECISION = ROOT / "decisions" / "quality-reporting.md" +SHA = "0123456789abcdef0123456789abcdef01234567" +QUALITY_REPORT = runpy.run_path(str(SCRIPT)) + + +class QualityReportContractTest(unittest.TestCase): + def test_fixture_inventory_covers_failure_and_score_boundaries(self): + self.assertEqual( + { + "canonical-score", + "complete", + "crash", + "incomplete", + "native-score", + "parse-error", + }, + {path.name for path in FIXTURES.iterdir() if path.is_dir()}, + ) + + def test_complete_fuzz_fixture_emits_a_valid_report_and_summary(self): + result, report, summary = self.aggregate( + "complete", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + ) + + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual("quality-report/v1", report["schema_version"]) + self.assertEqual("report", report["kind"]) + self.assertEqual( + {"expected": 2, "reported": 2, "complete": True}, + report["completeness"], + ) + self.assertEqual("passed", report["outcome"]) + self.assertEqual(420, report["metrics"]["declared_budget_seconds"]) + self.assertEqual(399.5, report["metrics"]["elapsed_seconds"]) + self.assertEqual(1900000, report["metrics"]["executions"]) + self.assertEqual(5, report["metrics"]["new_interesting_inputs"]) + self.assertNotIn("canonical_score_pct", report["metrics"]) + self.assertIn("complete 2/2", summary) + self.assertEqual(0, self.validate_report(report).returncode) + + def test_incomplete_fixture_fails_closed_without_a_subset_score(self): + result, report, summary = self.aggregate( + "incomplete", + track="mutation", + tool="stryker", + expected=["apps-api-ops-1", "apps-api-ops-2"], + ) + + self.assertNotEqual(0, result.returncode) + self.assertEqual( + {"expected": 2, "reported": 1, "complete": False}, + report["completeness"], + ) + self.assertEqual("error", report["outcome"]) + self.assertIsNone(report["metrics"]) + self.assertIn("missing target: apps-api-ops-2", report["errors"]) + self.assertIn("partial 1/2", summary) + self.assertNotIn("Canonical score", summary) + self.assertEqual(0, self.validate_report(report).returncode) + + def test_crash_fixture_fails_even_when_every_target_reports(self): + result, report, summary = self.aggregate( + "crash", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + ) + + self.assertNotEqual(0, result.returncode) + self.assertTrue(report["completeness"]["complete"]) + self.assertEqual("crashed", report["outcome"]) + self.assertIsNone(report["metrics"]) + self.assertIn("tool process exited 2", summary) + self.assertEqual(0, self.validate_report(report).returncode) + + def test_parse_error_fixture_still_emits_an_error_report(self): + result, report, summary = self.aggregate( + "parse-error", + track="mutation", + tool="gremlins", + expected=["./internal/config", "./internal/filter"], + ) + + self.assertNotEqual(0, result.returncode) + self.assertEqual("error", report["outcome"]) + self.assertFalse(report["completeness"]["complete"]) + self.assertIsNone(report["metrics"]) + self.assertTrue( + any("invalid JSON" in error for error in report["errors"]), + report["errors"], + ) + self.assertIn("partial 1/2", summary) + self.assertEqual(0, self.validate_report(report).returncode) + + def test_canonical_score_counts_timeout_and_no_coverage(self): + result, report, summary = self.aggregate( + "canonical-score", + track="mutation", + tool="gremlins", + expected=["./internal/config", "./internal/filter"], + ) + + self.assertEqual(0, result.returncode, result.stderr) + metrics = report["metrics"] + self.assertEqual(70, metrics["killed"]) + self.assertEqual(10, metrics["timeout"]) + self.assertEqual(5, metrics["survived"]) + self.assertEqual(15, metrics["no_coverage"]) + self.assertEqual(80, metrics["detected"]) + self.assertEqual(20, metrics["missed"]) + self.assertEqual(80.0, metrics["canonical_score_pct"]) + self.assertEqual(93.33, metrics["tool_score_pct"]) + self.assertIn("Canonical score: **80.00%**", summary) + + def test_decision_defines_canonical_score_as_a_percentage(self): + decision = DECISION.read_text() + + self.assertIn( + "canonical_score_pct = 100 * detected / (detected + missed)", + decision, + ) + + def test_decision_documents_track_and_tool_pairings(self): + decision = " ".join(DECISION.read_text().split()) + + self.assertIn("`mutation` permits `gremlins` and `stryker`", decision) + self.assertIn("`fuzz` permits `fast-check` and `go-fuzz`", decision) + + def test_native_score_is_weighted_and_keeps_its_definition(self): + result, report, summary = self.aggregate( + "native-score", + track="mutation", + tool="stryker", + expected=["apps-api-ops-1", "apps-api-ops-2"], + ) + + self.assertEqual(0, result.returncode, result.stderr) + metrics = report["metrics"] + self.assertEqual(60.0, metrics["canonical_score_pct"]) + self.assertEqual(66.67, metrics["tool_score_pct"]) + self.assertEqual(6, metrics["tool_score_numerator"]) + self.assertEqual(9, metrics["tool_score_denominator"]) + self.assertEqual( + "detected / mutants with test coverage", + metrics["tool_score_definition"], + ) + self.assertIn("Native score: **66.67%**", summary) + + def test_validator_rejects_unknown_report_fields(self): + result, report, _ = self.aggregate( + "complete", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + ) + self.assertEqual(0, result.returncode, result.stderr) + report["unreviewed"] = True + + validation = self.validate_report(report) + + self.assertNotEqual(0, validation.returncode) + self.assertIn("unknown field", validation.stderr) + + def test_validator_rejects_missing_start_time_from_a_success_report(self): + result, report, _ = self.aggregate( + "complete", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + ) + self.assertEqual(0, result.returncode, result.stderr) + report["run"]["started_at"] = None + + validation = self.validate_report(report) + + self.assertNotEqual(0, validation.returncode) + self.assertIn("started_at", validation.stderr) + + def test_validator_rejects_target_names_beyond_the_schema_limit(self): + target = json.loads( + ( + FIXTURES + / "complete" + / "quality-result-stats" + / "target-result.json" + ).read_text() + ) + target["target"]["name"] = "x" * 257 + + with self.assertRaisesRegex(QUALITY_REPORT["ContractError"], "256"): + QUALITY_REPORT["validate_target_document"](target) + with self.assertRaisesRegex(QUALITY_REPORT["ContractError"], "256"): + QUALITY_REPORT["parse_expected_targets"]( + json.dumps([target["target"]["name"]]) + ) + + def test_validator_requires_a_positive_declared_fuzz_budget(self): + metrics = { + "declared_budget_seconds": 0, + "elapsed_seconds": 0, + "executions": 0, + "new_interesting_inputs": 0, + } + + with self.assertRaisesRegex(QUALITY_REPORT["ContractError"], ">= 1"): + QUALITY_REPORT["validate_fuzz_report_metrics"](metrics, [], "$.metrics") + + def test_validator_requires_time_and_offset_in_timestamps(self): + for timestamp in ("2026-08-14", "2026-08-14T15:00:00"): + with self.subTest(timestamp=timestamp): + with self.assertRaisesRegex( + QUALITY_REPORT["ContractError"], "RFC 3339" + ): + QUALITY_REPORT["require_timestamp"](timestamp, "$.run.started_at") + + def test_schema_is_versioned_and_fail_closed(self): + with SCHEMA.open() as schema_file: + schema = json.load(schema_file) + + self.assertEqual( + "https://json-schema.org/draft/2020-12/schema", + schema["$schema"], + ) + self.assertEqual( + "https://codeswhat.com/schemas/quality-report/v1/schema.json", + schema["$id"], + ) + self.assertEqual("quality-report/v1", schema["$defs"]["version"]["const"]) + self.assertNotIn("additionalProperties", schema) + self.assertTrue(self.all_objects_are_closed(schema)) + + def test_reusable_workflow_matches_the_public_contract(self): + workflow = WORKFLOW.read_text() + + self.assertIn(" workflow_call:", workflow) + for input_name in ( + "track", + "tool", + "policy", + "expected_targets", + "result_artifact_pattern", + "report_name", + "retention_days", + "fail_on_incomplete", + ): + self.assertIn(f" {input_name}:\n", workflow) + for output_name in ( + "report_artifact_name", + "completeness", + "expected_targets", + "reported_targets", + "outcome", + "canonical_score_pct", + ): + self.assertIn(f" {output_name}:\n", workflow) + + self.assertIn(" default: quality-result-*", workflow) + self.assertIn(" default: 90", workflow) + self.assertIn(" default: true", workflow) + self.assertIn(" if: always()", workflow) + self.assertIn( + "repository: ${{ fromJSON(toJSON(job)).workflow_repository }}", workflow + ) + self.assertIn("ref: ${{ fromJSON(toJSON(job)).workflow_sha }}", workflow) + self.assertIn( + "name: quality-report-${{ inputs.track }}-${{ github.run_id }}-${{ github.run_attempt }}", + workflow, + ) + self.assertIn("retention-days: ${{ inputs.retention_days }}", workflow) + self.assertIn("if: always()", workflow) + + actions = [ + line.split("uses: ", 1)[1].split()[0] + for line in workflow.splitlines() + if "uses: " in line + ] + self.assertTrue(actions) + for action in actions: + self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") + for forbidden in ("git add", "git commit", "git push", "badges/"): + self.assertNotIn(forbidden, workflow) + + def test_public_decision_records_fail_closed_and_no_source_badges(self): + decision = DECISION.read_text() + + for expected in ( + "quality-report/v1", + "target-result.json", + "if: always()", + "quality-report---", + "90 days", + "partial N/M", + "Do not commit badge JSON to `main`", + "Native percentages are not comparable", + ): + self.assertIn(expected, decision) + + def test_standards_validation_runs_this_contract(self): + workflow = (ROOT / ".github/workflows/standards-validation.yml").read_text() + self.assertEqual( + 1, + workflow.count("python3 .github/tests/quality_report_contract_test.py"), + ) + + def aggregate(self, fixture, *, track, tool, expected): + self.assertTrue(SCRIPT.is_file(), f"missing aggregator: {SCRIPT}") + with tempfile.TemporaryDirectory() as temp_dir: + input_dir = Path(temp_dir) / "input" + shutil.copytree(FIXTURES / fixture, input_dir) + for invalid_fixture in input_dir.rglob("target-result.invalid"): + invalid_fixture.rename(invalid_fixture.with_name("target-result.json")) + output_dir = Path(temp_dir) / "output" + github_output = Path(temp_dir) / "github-output" + summary_path = Path(temp_dir) / "step-summary" + command = [ + "python3", + str(SCRIPT), + "aggregate", + "--input-dir", + str(input_dir), + "--output-dir", + str(output_dir), + "--repository", + "CodesWhat/example", + "--ref", + "refs/heads/dev/example", + "--sha", + SHA, + "--run-id", + "1234567890", + "--run-attempt", + "2", + "--event", + "workflow_dispatch", + "--run-url", + "https://github.com/CodesWhat/example/actions/runs/1234567890", + "--started-at", + "2026-08-13T12:34:56Z", + "--track", + track, + "--tool", + tool, + "--policy", + "advisory", + "--expected-targets", + json.dumps(expected), + "--report-name", + "Fixture quality report", + "--fail-on-incomplete", + "true", + "--github-output", + str(github_output), + "--github-step-summary", + str(summary_path), + ] + result = subprocess.run(command, capture_output=True, text=True) + report_path = output_dir / "report.json" + summary_file = output_dir / "summary.md" + self.assertTrue(report_path.is_file(), result.stderr) + self.assertTrue(summary_file.is_file(), result.stderr) + report = json.loads(report_path.read_text()) + summary = summary_file.read_text() + self.assertTrue(github_output.is_file(), result.stderr) + self.assertTrue(summary_path.is_file(), result.stderr) + github_outputs = dict( + line.split("=", 1) for line in github_output.read_text().splitlines() + ) + canonical_score = "" + if ( + report["track"] == "mutation" + and report["metrics"] is not None + and report["metrics"]["canonical_score_pct"] is not None + ): + canonical_score = "{0:.2f}".format( + report["metrics"]["canonical_score_pct"] + ) + self.assertEqual( + { + "report_artifact_name": "quality-report-{0}-1234567890-2".format( + track + ), + "completeness": str(report["completeness"]["complete"]).lower(), + "expected_targets": str(report["completeness"]["expected"]), + "reported_targets": str(report["completeness"]["reported"]), + "outcome": report["outcome"], + "canonical_score_pct": canonical_score, + }, + github_outputs, + ) + self.assertEqual(summary, summary_path.read_text()) + return result, report, summary + + def validate_report(self, report): + with tempfile.TemporaryDirectory() as temp_dir: + report_path = Path(temp_dir) / "report.json" + report_path.write_text(json.dumps(report)) + return subprocess.run( + ["python3", str(SCRIPT), "validate", str(report_path)], + capture_output=True, + text=True, + ) + + def all_objects_are_closed(self, value): + if isinstance(value, dict): + if ( + value.get("type") == "object" + and value.get("additionalProperties") is not False + ): + return False + return all(self.all_objects_are_closed(item) for item in value.values()) + if isinstance(value, list): + return all(self.all_objects_are_closed(item) for item in value) + return True + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/quality-report-aggregate.yml b/.github/workflows/quality-report-aggregate.yml new file mode 100644 index 0000000..86ef420 --- /dev/null +++ b/.github/workflows/quality-report-aggregate.yml @@ -0,0 +1,157 @@ +name: Quality Report Aggregate + +on: + workflow_call: + inputs: + track: + description: Quality track, mutation or fuzz + required: true + type: string + tool: + description: Native tool that produced the normalized target results + required: true + type: string + policy: + description: Reporting policy, advisory or signal + required: true + type: string + expected_targets: + description: Non-empty JSON array of unique target names + required: true + type: string + result_artifact_pattern: + description: Artifact-name pattern containing target-result.json files + required: false + type: string + default: quality-result-* + report_name: + description: Human-readable report name + required: true + type: string + retention_days: + description: Aggregate artifact retention in days + required: false + type: number + default: 90 + fail_on_incomplete: + description: Must remain true for CodesWhat telemetry + required: false + type: boolean + default: true + outputs: + report_artifact_name: + description: Fixed aggregate artifact name + value: ${{ jobs.aggregate.outputs.report_artifact_name }} + completeness: + description: Whether every expected target reported valid JSON + value: ${{ jobs.aggregate.outputs.completeness }} + expected_targets: + description: Number of expected targets + value: ${{ jobs.aggregate.outputs.expected_targets }} + reported_targets: + description: Number of valid expected target results + value: ${{ jobs.aggregate.outputs.reported_targets }} + outcome: + description: Aggregate outcome + value: ${{ jobs.aggregate.outputs.outcome }} + canonical_score_pct: + description: Canonical mutation score, empty for fuzz or partial reports + value: ${{ jobs.aggregate.outputs.canonical_score_pct }} + +permissions: {} + +jobs: + aggregate: + name: Quality Report Aggregate + if: always() + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: read + outputs: + report_artifact_name: ${{ steps.aggregate.outputs.report_artifact_name }} + completeness: ${{ steps.aggregate.outputs.completeness }} + expected_targets: ${{ steps.aggregate.outputs.expected_targets }} + reported_targets: ${{ steps.aggregate.outputs.reported_targets }} + outcome: ${{ steps.aggregate.outputs.outcome }} + canonical_score_pct: ${{ steps.aggregate.outputs.canonical_score_pct }} + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out the called workflow contract + if: always() + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # actionlint 1.7.12 does not model these current reusable-workflow fields. + repository: ${{ fromJSON(toJSON(job)).workflow_repository }} + ref: ${{ fromJSON(toJSON(job)).workflow_sha }} + path: quality-report-contract + persist-credentials: false + + - name: Read workflow run metadata + id: metadata + if: always() + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + started_at="$(gh api "/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" --jq .run_started_at)" + test -n "$started_at" + echo "started_at=${started_at}" >> "$GITHUB_OUTPUT" + + - name: Download normalized target results + id: download + if: always() + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: ${{ inputs.result_artifact_pattern }} + path: quality-result-artifacts + + - name: Validate and aggregate target results + id: aggregate + if: always() + env: + EXPECTED_TARGETS: ${{ inputs.expected_targets }} + FAIL_ON_INCOMPLETE: ${{ inputs.fail_on_incomplete }} + POLICY: ${{ inputs.policy }} + REPORT_NAME: ${{ inputs.report_name }} + RUN_STARTED_AT: ${{ steps.metadata.outputs.started_at }} + TOOL: ${{ inputs.tool }} + TRACK: ${{ inputs.track }} + run: | + set -euo pipefail + python3 quality-report-contract/quality-report/v1/quality_report.py aggregate \ + --input-dir quality-result-artifacts \ + --output-dir quality-report-output \ + --repository "$GITHUB_REPOSITORY" \ + --ref "$GITHUB_REF" \ + --sha "$GITHUB_SHA" \ + --run-id "$GITHUB_RUN_ID" \ + --run-attempt "$GITHUB_RUN_ATTEMPT" \ + --event "$GITHUB_EVENT_NAME" \ + --run-url "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" \ + --started-at "$RUN_STARTED_AT" \ + --track "$TRACK" \ + --tool "$TOOL" \ + --policy "$POLICY" \ + --expected-targets "$EXPECTED_TARGETS" \ + --report-name "$REPORT_NAME" \ + --fail-on-incomplete "$FAIL_ON_INCOMPLETE" \ + --github-output "$GITHUB_OUTPUT" \ + --github-step-summary "$GITHUB_STEP_SUMMARY" + + - name: Upload normalized quality report + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: quality-report-${{ inputs.track }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + quality-report-output/report.json + quality-report-output/summary.md + if-no-files-found: error + retention-days: ${{ inputs.retention_days }} diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 192e5bd..ceb4606 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -45,6 +45,7 @@ jobs: ruby -e 'require "yaml"; Dir.glob("**/*.{yml,yaml}", File::FNM_DOTMATCH).sort.each { |path| YAML.parse_file(path) }' python3 -c 'import json; from pathlib import Path; [json.load(path.open()) for path in Path(".").rglob("*.json")]' python3 .github/tests/greptile_config_contract_test.py + python3 .github/tests/quality_report_contract_test.py python3 .github/tests/reusable_ci_contract_test.py - name: Lint Markdown diff --git a/decisions/quality-reporting.md b/decisions/quality-reporting.md new file mode 100644 index 0000000..6182c97 --- /dev/null +++ b/decisions/quality-reporting.md @@ -0,0 +1,162 @@ +# Quality Reporting + +Last updated: 2026-08-13 + +## Decision + +Keep each repository's native test tool. Normalize the result envelope, not the +runner: + +- Drydock keeps Stryker and fast-check. +- Sockguard keeps Gremlins and Go fuzzing. +- Portwing keeps Gremlins and Go fuzzing. + +Mutation stays advisory and absent from required PR checks. A scheduled or +manual mutation workflow must still fail when its telemetry is incomplete or a +tool crashes. Non-blocking means it does not gate a PR. It does not mean the +workflow may report success after losing results. + +Long fuzzing succeeds only when every declared target completes its budget. A +crash, repeated boundary flake, setup failure, or missing target result makes +the workflow red. + +## Evidence behind the decision + +The 2026-08-01 Drydock mutation run completed at the workflow level while 13 of +27 Stryker shards failed. Its aggregate used `--allow-missing` and published an +81.79% score from the remaining 14 shards. The workflow status and numeric +badge therefore described a partial result as success. + +Sockguard's existing 97.8% badge uses `killed / (killed + lived)`. Counting +timeout as detected and no-coverage as missed gives 93.91% for the same run. +Portwing has no aggregate badge; applying the same canonical definition to its +latest complete Gremlins run gives 77.31%, versus 81.98% under Gremlins' +efficacy definition. Native percentages are not comparable until their +denominators are explicit. + +Sockguard inventories all 48 in-tree fuzzers and covers every target in at +least one tier. Portwing's `FuzzVerifyRequest` runs in primary CI and scheduled +long tiers. Drydock's five fast-check fuzz tests run as ordinary Vitest tests +with default run counts and have no scheduled long-fuzz workflow. + +## Normalized envelope + +Every matrix leg writes one `target-result.json`. An always-running aggregate +job validates the set and publishes `quality-report/v1` with: + +- `repository`, `ref`, `sha` +- `run`: `id`, `attempt`, `event`, `url`, `started_at` +- `track`: `mutation` or `fuzz` +- `tool`: `mutation` permits `gremlins` and `stryker`; `fuzz` permits + `fast-check` and `go-fuzz` +- `policy`: `advisory` or `signal` +- `completeness`: `expected`, `reported`, `complete` +- `outcome`: `passed`, `failed`, `crashed`, `flaked`, `cancelled`, `error` +- `targets`: the declared target names and their individual results +- track-specific `metrics` + +The schema and dependency-free validator live under [`quality-report/v1`](../quality-report/v1). +Both target-result fragments and aggregate reports carry the exact +`quality-report/v1` version. Objects reject unknown fields, JSON parsing rejects +duplicate fields and non-finite numbers, and semantic validation recomputes +completeness, outcomes, and scores. Callers pass `expected_targets` as a +non-empty JSON array of unique target names. + +Mutation metrics are: + +- `killed`, `timeout`, `survived`, `no_coverage`, `invalid`, `ignored` +- `detected = killed + timeout` +- `missed = survived + no_coverage` +- `canonical_score_pct = 100 * detected / (detected + missed)`, rounded + half-up to two decimals, or `null` when the denominator is zero +- `tool_score_pct` and `tool_score_definition` + +Each target also supplies the native numerator and denominator. The aggregate +weights those counts instead of averaging percentages, and rejects mixed native +score definitions. The native score remains available with its definition. +Only the canonical score is comparable across mutation tools. + +Fuzz metrics include the declared budget, elapsed time, and executions or new +interesting inputs when the runner exposes them. Do not compare execution +counts between runners or tools. A failed, crashed, or flaked fuzz result must +retain a seed, path, or corpus reference for reproduction. + +## Reusable workflow contract + +Inputs: + +- `track` +- `tool` +- `policy` +- `expected_targets` +- `result_artifact_pattern`, default `quality-result-*` +- `report_name` +- `retention_days`, default `90` +- `fail_on_incomplete`, always `true` for CodesWhat telemetry + +Outputs: + +- `report_artifact_name` +- `completeness` +- `expected_targets` +- `reported_targets` +- `outcome` +- `canonical_score_pct` for mutation reports + +The aggregate artifact is named +`quality-report---` and contains `report.json` plus +`summary.md`. Native reports and crash corpora remain separate artifacts. +Target result JSON is always uploaded; crash forensics remain failure-only. +Normalized aggregate artifacts use at least 90 days of retention. + +The reusable workflow checks out its own contract at the exact called-workflow +commit via `job.workflow_repository` and `job.workflow_sha`. Product workflows +remain responsible for native tool adapters and uploading their target-result +artifacts. + +## Status and badge semantics + +- The aggregate job runs under `if: always()` and fails on an incomplete set, + tool crash, parse error, invalid contract, or policy failure. +- Numeric mutation badges publish only a complete canonical score. An + incomplete run displays `partial N/M`, never a subset score or stale score. +- Do not commit badge JSON to `main`. Bot commits bypass the dev-to-main flow + and make telemetry part of source history. +- Use the native workflow-status badge as the stable shared badge. Put numeric + scores and native dashboard links in the run summary and retained artifact + until there is a non-source telemetry endpoint. +- Long-fuzz failures must retain the runner seed, path, or corpus needed to + reproduce the failure. + +## Migration order + +1. Add and test the schema, validator, and reusable aggregate in + `CodesWhat/.github`. +2. Canary Portwing. It has the smallest Gremlins and fuzz matrices. Keep + `FuzzVerifyRequest` in a long tier and preserve its source-to-tier inventory + contract. +3. Migrate Sockguard's Gremlins aggregation, retire its direct badge commit, + and preserve its existing fuzz inventory contract. +4. Migrate Drydock's Stryker aggregate, remove partial score publication, then + add a scheduled fast-check workflow with explicit run count and seed/path + reproduction. +5. Manually dispatch each workflow on the exact active dev head before syncing + it to `main`. Scheduled workflows exercise `main`, not the active dev branch. + +Native runner adapters and product callers are intentionally outside this +foundation change. Each migration supplies and tests its own mapping from +native output into the target-result contract. + +## Risks and controls + +- The three first-of-month mutation runs compete for organization runner + capacity. Stagger their schedules. +- Gremlins text parsing is version-sensitive. Pin the tool and test fixtures + from real output. +- Stryker reports compile/runtime-invalid mutants and may lose shards. Preserve + native categories and fail closed on a missing shard. +- Fast-check failures are not reproducible without seed and path. Make both + mandatory failure fields. +- Artifacts expire. Ninety days is the minimum retention for normalized + reports; durable trend storage is a separate decision. +- `continue-on-error` on a matrix leg must not make the final aggregate green. diff --git a/quality-report/v1/quality_report.py b/quality-report/v1/quality_report.py new file mode 100644 index 0000000..8b8c93a --- /dev/null +++ b/quality-report/v1/quality_report.py @@ -0,0 +1,765 @@ +#!/usr/bin/env python3 +"""Validate and aggregate CodesWhat quality-report/v1 result envelopes.""" + +import argparse +from datetime import datetime +from decimal import Decimal, ROUND_HALF_UP +import json +import math +from pathlib import Path +import re +import sys +from urllib.parse import urlparse + + +VERSION = "quality-report/v1" +KINDS = {"target-result", "report"} +TRACK_TOOLS = { + "mutation": {"gremlins", "stryker"}, + "fuzz": {"fast-check", "go-fuzz"}, +} +POLICIES = {"advisory", "signal"} +OUTCOMES = {"passed", "failed", "crashed", "flaked", "cancelled", "error"} +OUTCOME_PRIORITY = ("error", "crashed", "cancelled", "flaked", "failed") +MUTATION_COUNT_FIELDS = ( + "killed", + "timeout", + "survived", + "no_coverage", + "invalid", + "ignored", +) +TARGET_MUTATION_FIELDS = set(MUTATION_COUNT_FIELDS) | { + "tool_score_numerator", + "tool_score_denominator", + "tool_score_pct", + "tool_score_definition", +} +REPORT_MUTATION_FIELDS = TARGET_MUTATION_FIELDS | { + "detected", + "missed", + "canonical_score_pct", +} +TARGET_FUZZ_REQUIRED = {"budget_seconds", "elapsed_seconds"} +TARGET_FUZZ_OPTIONAL = {"executions", "new_interesting_inputs"} +REPORT_FUZZ_FIELDS = { + "declared_budget_seconds", + "elapsed_seconds", + "executions", + "new_interesting_inputs", +} +SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$") +RFC3339_PATTERN = re.compile( + r"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$" +) + + +class ContractError(ValueError): + pass + + +def reject_constant(value): + raise ContractError("non-finite JSON number: {0}".format(value)) + + +def reject_duplicate_keys(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ContractError("duplicate JSON field: {0}".format(key)) + result[key] = value + return result + + +def load_json_text(text, source): + try: + return json.loads( + text, + object_pairs_hook=reject_duplicate_keys, + parse_constant=reject_constant, + ) + except (json.JSONDecodeError, ContractError) as error: + raise ContractError("{0}: invalid JSON: {1}".format(source, error)) + + +def load_json_file(path): + try: + return load_json_text(path.read_text(), str(path)) + except OSError as error: + raise ContractError("{0}: cannot read JSON: {1}".format(path, error)) + + +def require_object(value, path, required, optional=()): + if not isinstance(value, dict): + raise ContractError("{0}: expected object".format(path)) + required = set(required) + allowed = required | set(optional) + missing = sorted(required - set(value)) + unknown = sorted(set(value) - allowed) + if missing: + raise ContractError( + "{0}: missing field(s): {1}".format(path, ", ".join(missing)) + ) + if unknown: + raise ContractError( + "{0}: unknown field(s): {1}".format(path, ", ".join(unknown)) + ) + return value + + +def require_string(value, path, *, pattern=None, max_length=None): + if not isinstance(value, str) or not value or "\n" in value or "\r" in value: + raise ContractError("{0}: expected non-empty single-line string".format(path)) + if max_length is not None and len(value) > max_length: + raise ContractError( + "{0}: expected at most {1} characters".format(path, max_length) + ) + if pattern is not None and pattern.fullmatch(value) is None: + raise ContractError("{0}: invalid value".format(path)) + return value + + +def require_enum(value, path, choices): + require_string(value, path) + if value not in choices: + raise ContractError( + "{0}: expected one of {1}".format(path, ", ".join(sorted(choices))) + ) + return value + + +def require_integer(value, path, *, minimum=0): + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise ContractError("{0}: expected integer >= {1}".format(path, minimum)) + return value + + +def require_number(value, path, *, minimum=0): + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ContractError("{0}: expected number >= {1}".format(path, minimum)) + if not math.isfinite(value) or value < minimum: + raise ContractError("{0}: expected finite number >= {1}".format(path, minimum)) + return value + + +def require_nullable_integer(value, path): + if value is not None: + require_integer(value, path) + + +def require_percentage(value, path, *, nullable=False): + if value is None and nullable: + return + require_number(value, path) + if value > 100: + raise ContractError("{0}: expected percentage <= 100".format(path)) + + +def require_url(value, path): + require_string(value, path) + parsed = urlparse(value) + if parsed.scheme != "https" or not parsed.netloc: + raise ContractError("{0}: expected HTTPS URL".format(path)) + + +def require_timestamp(value, path): + require_string(value, path) + try: + if RFC3339_PATTERN.fullmatch(value) is None: + raise ValueError + datetime.fromisoformat(value.replace("Z", "+00:00").replace("z", "+00:00")) + except ValueError: + raise ContractError("{0}: expected RFC 3339 timestamp".format(path)) + + +def percentage(numerator, denominator): + if denominator == 0: + return None + value = Decimal(numerator) * Decimal(100) / Decimal(denominator) + return float(value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) + + +def validate_mutation_target_metrics(metrics, path): + require_object(metrics, path, TARGET_MUTATION_FIELDS) + for field in MUTATION_COUNT_FIELDS: + require_integer(metrics[field], "{0}.{1}".format(path, field)) + numerator = require_integer( + metrics["tool_score_numerator"], path + ".tool_score_numerator" + ) + denominator = require_integer( + metrics["tool_score_denominator"], path + ".tool_score_denominator" + ) + require_percentage( + metrics["tool_score_pct"], path + ".tool_score_pct", nullable=True + ) + require_string(metrics["tool_score_definition"], path + ".tool_score_definition") + expected = percentage(numerator, denominator) + if metrics["tool_score_pct"] != expected: + raise ContractError( + "{0}.tool_score_pct: expected {1} from numerator/denominator".format( + path, expected + ) + ) + + +def validate_fuzz_target_metrics(metrics, path): + require_object(metrics, path, TARGET_FUZZ_REQUIRED, TARGET_FUZZ_OPTIONAL) + require_integer(metrics["budget_seconds"], path + ".budget_seconds", minimum=1) + require_number(metrics["elapsed_seconds"], path + ".elapsed_seconds") + for field in TARGET_FUZZ_OPTIONAL: + if field in metrics: + require_integer(metrics[field], "{0}.{1}".format(path, field)) + + +def validate_reproduction(value, path): + require_object(value, path, (), {"seed", "path", "corpus"}) + if not value: + raise ContractError("{0}: expected seed, path, or corpus".format(path)) + for field, item in value.items(): + require_string(item, "{0}.{1}".format(path, field)) + + +def validate_target(target, track, path): + require_object( + target, + path, + {"name", "outcome", "metrics"}, + {"diagnostic", "reproduction"}, + ) + require_string(target["name"], path + ".name", max_length=256) + outcome = require_enum(target["outcome"], path + ".outcome", OUTCOMES) + metrics = target["metrics"] + if metrics is None: + if outcome == "passed": + raise ContractError( + "{0}.metrics: passed target requires metrics".format(path) + ) + elif track == "mutation": + validate_mutation_target_metrics(metrics, path + ".metrics") + else: + validate_fuzz_target_metrics(metrics, path + ".metrics") + + if outcome == "passed": + if "diagnostic" in target or "reproduction" in target: + raise ContractError( + "{0}: passed target cannot contain diagnostic or reproduction".format( + path + ) + ) + else: + if "diagnostic" not in target: + raise ContractError( + "{0}: non-passed target requires diagnostic".format(path) + ) + require_string(target["diagnostic"], path + ".diagnostic") + if track == "fuzz" and outcome in {"failed", "crashed", "flaked"}: + if "reproduction" not in target: + raise ContractError( + "{0}: failed fuzz target requires reproduction".format(path) + ) + if "reproduction" in target: + validate_reproduction(target["reproduction"], path + ".reproduction") + + +def validate_target_document(document, path="$"): + require_object( + document, + path, + {"schema_version", "kind", "track", "tool", "target"}, + ) + if document["schema_version"] != VERSION: + raise ContractError("{0}.schema_version: expected {1}".format(path, VERSION)) + if document["kind"] != "target-result": + raise ContractError("{0}.kind: expected target-result".format(path)) + track = require_enum(document["track"], path + ".track", set(TRACK_TOOLS)) + tool = require_enum( + document["tool"], path + ".tool", set().union(*TRACK_TOOLS.values()) + ) + if tool not in TRACK_TOOLS[track]: + raise ContractError("{0}.tool: {1} is not a {2} tool".format(path, tool, track)) + validate_target(document["target"], track, path + ".target") + return document + + +def aggregate_mutation_metrics(targets): + metrics = {field: 0 for field in MUTATION_COUNT_FIELDS} + definitions = set() + for target in targets: + target_metrics = target["metrics"] + for field in MUTATION_COUNT_FIELDS: + metrics[field] += target_metrics[field] + metrics.setdefault("tool_score_numerator", 0) + metrics.setdefault("tool_score_denominator", 0) + metrics["tool_score_numerator"] += target_metrics["tool_score_numerator"] + metrics["tool_score_denominator"] += target_metrics["tool_score_denominator"] + definitions.add(target_metrics["tool_score_definition"]) + if len(definitions) != 1: + raise ContractError("target results use inconsistent native score definitions") + metrics["detected"] = metrics["killed"] + metrics["timeout"] + metrics["missed"] = metrics["survived"] + metrics["no_coverage"] + metrics["canonical_score_pct"] = percentage( + metrics["detected"], metrics["detected"] + metrics["missed"] + ) + metrics["tool_score_pct"] = percentage( + metrics["tool_score_numerator"], metrics["tool_score_denominator"] + ) + metrics["tool_score_definition"] = definitions.pop() + return metrics + + +def aggregate_fuzz_metrics(targets): + metrics = { + "declared_budget_seconds": sum( + target["metrics"]["budget_seconds"] for target in targets + ), + "elapsed_seconds": sum( + target["metrics"]["elapsed_seconds"] for target in targets + ), + } + for field in ("executions", "new_interesting_inputs"): + if all(field in target["metrics"] for target in targets): + metrics[field] = sum(target["metrics"][field] for target in targets) + else: + metrics[field] = None + return metrics + + +def derive_outcome(targets, errors): + if errors: + return "error" + outcomes = {target["outcome"] for target in targets} + for outcome in OUTCOME_PRIORITY: + if outcome in outcomes: + return outcome + return "passed" + + +def validate_mutation_report_metrics(metrics, targets, path): + require_object(metrics, path, REPORT_MUTATION_FIELDS) + for field in MUTATION_COUNT_FIELDS + ( + "detected", + "missed", + "tool_score_numerator", + "tool_score_denominator", + ): + require_integer(metrics[field], "{0}.{1}".format(path, field)) + require_percentage( + metrics["canonical_score_pct"], path + ".canonical_score_pct", nullable=True + ) + require_percentage( + metrics["tool_score_pct"], path + ".tool_score_pct", nullable=True + ) + require_string(metrics["tool_score_definition"], path + ".tool_score_definition") + expected = aggregate_mutation_metrics(targets) + if metrics != expected: + raise ContractError( + "{0}: aggregate mutation metrics do not match targets".format(path) + ) + + +def validate_fuzz_report_metrics(metrics, targets, path): + require_object(metrics, path, REPORT_FUZZ_FIELDS) + require_integer( + metrics["declared_budget_seconds"], + path + ".declared_budget_seconds", + minimum=1, + ) + require_number(metrics["elapsed_seconds"], path + ".elapsed_seconds") + require_nullable_integer(metrics["executions"], path + ".executions") + require_nullable_integer( + metrics["new_interesting_inputs"], path + ".new_interesting_inputs" + ) + expected = aggregate_fuzz_metrics(targets) + if metrics != expected: + raise ContractError( + "{0}: aggregate fuzz metrics do not match targets".format(path) + ) + + +def validate_report(document, path="$"): + require_object( + document, + path, + { + "schema_version", + "kind", + "repository", + "ref", + "sha", + "run", + "report_name", + "track", + "tool", + "policy", + "completeness", + "outcome", + "targets", + "metrics", + "errors", + }, + ) + if document["schema_version"] != VERSION: + raise ContractError("{0}.schema_version: expected {1}".format(path, VERSION)) + if document["kind"] != "report": + raise ContractError("{0}.kind: expected report".format(path)) + require_string(document["repository"], path + ".repository") + require_string(document["ref"], path + ".ref") + require_string(document["sha"], path + ".sha", pattern=SHA_PATTERN) + require_string(document["report_name"], path + ".report_name") + track = require_enum(document["track"], path + ".track", set(TRACK_TOOLS)) + tool = require_enum( + document["tool"], path + ".tool", set().union(*TRACK_TOOLS.values()) + ) + if tool not in TRACK_TOOLS[track]: + raise ContractError("{0}.tool: {1} is not a {2} tool".format(path, tool, track)) + require_enum(document["policy"], path + ".policy", POLICIES) + + run = require_object( + document["run"], + path + ".run", + {"id", "attempt", "event", "url", "started_at"}, + ) + require_string(run["id"], path + ".run.id") + require_integer(run["attempt"], path + ".run.attempt", minimum=1) + require_string(run["event"], path + ".run.event") + require_url(run["url"], path + ".run.url") + if run["started_at"] is not None: + require_timestamp(run["started_at"], path + ".run.started_at") + + completeness = require_object( + document["completeness"], + path + ".completeness", + {"expected", "reported", "complete"}, + ) + require_integer( + completeness["expected"], path + ".completeness.expected", minimum=1 + ) + require_integer(completeness["reported"], path + ".completeness.reported") + if not isinstance(completeness["complete"], bool): + raise ContractError(path + ".completeness.complete: expected boolean") + + targets = document["targets"] + if not isinstance(targets, list): + raise ContractError(path + ".targets: expected array") + names = [] + for index, target in enumerate(targets): + validate_target(target, track, "{0}.targets[{1}]".format(path, index)) + names.append(target["name"]) + if len(names) != len(set(names)): + raise ContractError(path + ".targets: duplicate target name") + if names != sorted(names): + raise ContractError(path + ".targets: targets must be sorted by name") + if completeness["reported"] != len(targets): + raise ContractError(path + ".completeness.reported: does not match targets") + + errors = document["errors"] + if not isinstance(errors, list) or any( + not isinstance(error, str) or not error for error in errors + ): + raise ContractError(path + ".errors: expected non-empty strings") + if errors != sorted(set(errors)): + raise ContractError(path + ".errors: errors must be sorted and unique") + if run["started_at"] is None and not errors: + raise ContractError(path + ".run.started_at: required for an error-free report") + expected_complete = ( + completeness["expected"] == completeness["reported"] and not errors + ) + if completeness["complete"] != expected_complete: + raise ContractError(path + ".completeness.complete: inconsistent value") + + outcome = require_enum(document["outcome"], path + ".outcome", OUTCOMES) + if outcome != derive_outcome(targets, errors): + raise ContractError(path + ".outcome: does not match target results") + + metrics = document["metrics"] + metrics_available = ( + completeness["complete"] + and bool(targets) + and all(target["metrics"] is not None for target in targets) + ) + if not metrics_available: + if metrics is not None: + raise ContractError(path + ".metrics: must be null for partial results") + elif track == "mutation": + validate_mutation_report_metrics(metrics, targets, path + ".metrics") + else: + validate_fuzz_report_metrics(metrics, targets, path + ".metrics") + return document + + +def validate_document(document): + if not isinstance(document, dict): + raise ContractError("$: expected object") + kind = document.get("kind") + if kind not in KINDS: + raise ContractError("$.kind: expected one of report, target-result") + if kind == "target-result": + return validate_target_document(document) + return validate_report(document) + + +def parse_expected_targets(raw): + value = load_json_text(raw, "expected_targets") + if not isinstance(value, list) or not value: + raise ContractError("expected_targets: expected a non-empty JSON array") + targets = [] + for index, target in enumerate(value): + targets.append( + require_string( + target, + "expected_targets[{0}]".format(index), + max_length=256, + ) + ) + if len(targets) != len(set(targets)): + raise ContractError("expected_targets: duplicate target") + return targets + + +def relative_label(path, root): + try: + return str(path.relative_to(root)) + except ValueError: + return path.name + + +def collect_targets(input_dir, expected_targets, track, tool): + errors = [] + reported = {} + paths = sorted(input_dir.rglob("target-result.json")) if input_dir.is_dir() else [] + if not paths: + errors.append("no target-result.json files found") + for path in paths: + label = relative_label(path, input_dir) + try: + document = load_json_file(path) + validate_target_document(document, label) + if document["track"] != track: + raise ContractError( + "{0}.track: expected {1}, got {2}".format( + label, track, document["track"] + ) + ) + if document["tool"] != tool: + raise ContractError( + "{0}.tool: expected {1}, got {2}".format( + label, tool, document["tool"] + ) + ) + target = document["target"] + name = target["name"] + if name not in expected_targets: + raise ContractError("{0}: unexpected target: {1}".format(label, name)) + if name in reported: + raise ContractError("{0}: duplicate target: {1}".format(label, name)) + reported[name] = target + except ContractError as error: + errors.append(str(error)) + for target in expected_targets: + if target not in reported: + errors.append("missing target: {0}".format(target)) + return [reported[name] for name in sorted(reported)], sorted(set(errors)) + + +def build_summary(report): + completeness = report["completeness"] + if completeness["complete"]: + completeness_text = "complete {0}/{1}".format( + completeness["reported"], completeness["expected"] + ) + else: + completeness_text = "partial {0}/{1}".format( + completeness["reported"], completeness["expected"] + ) + lines = [ + "# {0}".format(report["report_name"]), + "", + "- Track: `{0}` via `{1}`".format(report["track"], report["tool"]), + "- Policy: `{0}`".format(report["policy"]), + "- Completeness: **{0}**".format(completeness_text), + "- Outcome: **{0}**".format(report["outcome"]), + ] + metrics = report["metrics"] + if report["track"] == "mutation" and metrics is not None: + canonical = metrics["canonical_score_pct"] + native = metrics["tool_score_pct"] + if canonical is not None: + lines.append("- Canonical score: **{0:.2f}%**".format(canonical)) + if native is not None: + lines.append( + "- Native score: **{0:.2f}%** ({1})".format( + native, metrics["tool_score_definition"] + ) + ) + lines.extend(("", "## Targets", "")) + for target in report["targets"]: + detail = "" + if "diagnostic" in target: + detail = ": {0}".format(target["diagnostic"]) + lines.append( + "- `{0}`: {1}{2}".format(target["name"], target["outcome"], detail) + ) + if report["errors"]: + lines.extend(("", "## Contract errors", "")) + lines.extend("- {0}".format(error) for error in report["errors"]) + return "\n".join(lines) + "\n" + + +def append_lines(path, values): + if path is None: + return + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a") as output: + for key, value in values.items(): + output.write("{0}={1}\n".format(key, value)) + + +def command_aggregate(args): + errors = [] + try: + expected_targets = parse_expected_targets(args.expected_targets) + except ContractError as error: + expected_targets = ["invalid-expected-targets"] + errors.append(str(error)) + if args.fail_on_incomplete != "true": + errors.append("fail_on_incomplete must be true for CodesWhat telemetry") + try: + require_timestamp(args.started_at, "started_at") + started_at = args.started_at + except ContractError as error: + started_at = None + errors.append(str(error)) + + targets, collection_errors = collect_targets( + args.input_dir, expected_targets, args.track, args.tool + ) + errors.extend(collection_errors) + errors = sorted(set(errors)) + completeness = { + "expected": len(expected_targets), + "reported": len(targets), + "complete": len(targets) == len(expected_targets) and not errors, + } + metrics = None + if completeness["complete"] and all( + target["metrics"] is not None for target in targets + ): + try: + if args.track == "mutation": + metrics = aggregate_mutation_metrics(targets) + else: + metrics = aggregate_fuzz_metrics(targets) + except ContractError as error: + errors.append(str(error)) + errors = sorted(set(errors)) + completeness["complete"] = False + + report = { + "schema_version": VERSION, + "kind": "report", + "repository": args.repository, + "ref": args.ref, + "sha": args.sha, + "run": { + "id": args.run_id, + "attempt": args.run_attempt, + "event": args.event, + "url": args.run_url, + "started_at": started_at, + }, + "report_name": args.report_name, + "track": args.track, + "tool": args.tool, + "policy": args.policy, + "completeness": completeness, + "outcome": derive_outcome(targets, errors), + "targets": targets, + "metrics": metrics, + "errors": errors, + } + validate_report(report) + + args.output_dir.mkdir(parents=True, exist_ok=True) + summary = build_summary(report) + (args.output_dir / "report.json").write_text( + json.dumps(report, indent=2, allow_nan=False) + "\n" + ) + (args.output_dir / "summary.md").write_text(summary) + append_lines( + args.github_output, + { + "report_artifact_name": "quality-report-{0}-{1}-{2}".format( + args.track, args.run_id, args.run_attempt + ), + "completeness": str(completeness["complete"]).lower(), + "expected_targets": completeness["expected"], + "reported_targets": completeness["reported"], + "outcome": report["outcome"], + "canonical_score_pct": ( + "" + if metrics is None + or args.track != "mutation" + or metrics["canonical_score_pct"] is None + else "{0:.2f}".format(metrics["canonical_score_pct"]) + ), + }, + ) + if args.github_step_summary is not None: + args.github_step_summary.parent.mkdir(parents=True, exist_ok=True) + with args.github_step_summary.open("a") as step_summary: + step_summary.write(summary) + return 0 if completeness["complete"] and report["outcome"] == "passed" else 1 + + +def command_validate(args): + document = load_json_file(args.document) + validate_document(document) + return 0 + + +def build_parser(): + parser = argparse.ArgumentParser(description=__doc__) + subparsers = parser.add_subparsers(dest="command", required=True) + + validate_parser = subparsers.add_parser("validate") + validate_parser.add_argument("document", type=Path) + validate_parser.set_defaults(handler=command_validate) + + aggregate_parser = subparsers.add_parser("aggregate") + aggregate_parser.add_argument("--input-dir", type=Path, required=True) + aggregate_parser.add_argument("--output-dir", type=Path, required=True) + aggregate_parser.add_argument("--repository", required=True) + aggregate_parser.add_argument("--ref", required=True) + aggregate_parser.add_argument("--sha", required=True) + aggregate_parser.add_argument("--run-id", required=True) + aggregate_parser.add_argument("--run-attempt", type=int, required=True) + aggregate_parser.add_argument("--event", required=True) + aggregate_parser.add_argument("--run-url", required=True) + aggregate_parser.add_argument("--started-at", required=True) + aggregate_parser.add_argument("--track", choices=sorted(TRACK_TOOLS), required=True) + aggregate_parser.add_argument( + "--tool", choices=sorted(set().union(*TRACK_TOOLS.values())), required=True + ) + aggregate_parser.add_argument("--policy", choices=sorted(POLICIES), required=True) + aggregate_parser.add_argument("--expected-targets", required=True) + aggregate_parser.add_argument("--report-name", required=True) + aggregate_parser.add_argument( + "--fail-on-incomplete", choices=("true", "false"), required=True + ) + aggregate_parser.add_argument("--github-output", type=Path) + aggregate_parser.add_argument("--github-step-summary", type=Path) + aggregate_parser.set_defaults(handler=command_aggregate) + return parser + + +def main(): + args = build_parser().parse_args() + try: + return args.handler(args) + except ContractError as error: + print("quality-report: {0}".format(error), file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/quality-report/v1/schema.json b/quality-report/v1/schema.json new file mode 100644 index 0000000..46c38f1 --- /dev/null +++ b/quality-report/v1/schema.json @@ -0,0 +1,496 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://codeswhat.com/schemas/quality-report/v1/schema.json", + "title": "CodesWhat quality-report/v1", + "description": "Normalized target results and aggregate quality reports.", + "oneOf": [ + { + "$ref": "#/$defs/targetResult" + }, + { + "$ref": "#/$defs/report" + } + ], + "$defs": { + "version": { + "type": "string", + "const": "quality-report/v1" + }, + "outcome": { + "type": "string", + "enum": [ + "passed", + "failed", + "crashed", + "flaked", + "cancelled", + "error" + ] + }, + "reproduction": { + "type": "object", + "additionalProperties": false, + "minProperties": 1, + "properties": { + "seed": { + "type": "string", + "minLength": 1 + }, + "path": { + "type": "string", + "minLength": 1 + }, + "corpus": { + "type": "string", + "minLength": 1 + } + } + }, + "mutationTargetMetrics": { + "type": "object", + "additionalProperties": false, + "required": [ + "killed", + "timeout", + "survived", + "no_coverage", + "invalid", + "ignored", + "tool_score_numerator", + "tool_score_denominator", + "tool_score_pct", + "tool_score_definition" + ], + "properties": { + "killed": { + "type": "integer", + "minimum": 0 + }, + "timeout": { + "type": "integer", + "minimum": 0 + }, + "survived": { + "type": "integer", + "minimum": 0 + }, + "no_coverage": { + "type": "integer", + "minimum": 0 + }, + "invalid": { + "type": "integer", + "minimum": 0 + }, + "ignored": { + "type": "integer", + "minimum": 0 + }, + "tool_score_numerator": { + "type": "integer", + "minimum": 0 + }, + "tool_score_denominator": { + "type": "integer", + "minimum": 0 + }, + "tool_score_pct": { + "type": [ + "number", + "null" + ], + "minimum": 0, + "maximum": 100 + }, + "tool_score_definition": { + "type": "string", + "minLength": 1 + } + } + }, + "fuzzTargetMetrics": { + "type": "object", + "additionalProperties": false, + "required": [ + "budget_seconds", + "elapsed_seconds" + ], + "properties": { + "budget_seconds": { + "type": "integer", + "minimum": 1 + }, + "elapsed_seconds": { + "type": "number", + "minimum": 0 + }, + "executions": { + "type": "integer", + "minimum": 0 + }, + "new_interesting_inputs": { + "type": "integer", + "minimum": 0 + } + } + }, + "target": { + "type": "object", + "additionalProperties": false, + "required": [ + "name", + "outcome", + "metrics" + ], + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\r\\n]+$" + }, + "outcome": { + "$ref": "#/$defs/outcome" + }, + "metrics": { + "oneOf": [ + { + "$ref": "#/$defs/mutationTargetMetrics" + }, + { + "$ref": "#/$defs/fuzzTargetMetrics" + }, + { + "type": "null" + } + ] + }, + "diagnostic": { + "type": "string", + "minLength": 1 + }, + "reproduction": { + "$ref": "#/$defs/reproduction" + } + } + }, + "targetResult": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "kind", + "track", + "tool", + "target" + ], + "properties": { + "schema_version": { + "$ref": "#/$defs/version" + }, + "kind": { + "type": "string", + "const": "target-result" + }, + "track": { + "type": "string", + "enum": [ + "mutation", + "fuzz" + ] + }, + "tool": { + "type": "string", + "enum": [ + "stryker", + "gremlins", + "go-fuzz", + "fast-check" + ] + }, + "target": { + "$ref": "#/$defs/target" + } + } + }, + "mutationReportMetrics": { + "type": "object", + "additionalProperties": false, + "required": [ + "killed", + "timeout", + "survived", + "no_coverage", + "invalid", + "ignored", + "detected", + "missed", + "canonical_score_pct", + "tool_score_numerator", + "tool_score_denominator", + "tool_score_pct", + "tool_score_definition" + ], + "properties": { + "killed": { + "type": "integer", + "minimum": 0 + }, + "timeout": { + "type": "integer", + "minimum": 0 + }, + "survived": { + "type": "integer", + "minimum": 0 + }, + "no_coverage": { + "type": "integer", + "minimum": 0 + }, + "invalid": { + "type": "integer", + "minimum": 0 + }, + "ignored": { + "type": "integer", + "minimum": 0 + }, + "detected": { + "type": "integer", + "minimum": 0 + }, + "missed": { + "type": "integer", + "minimum": 0 + }, + "canonical_score_pct": { + "type": [ + "number", + "null" + ], + "minimum": 0, + "maximum": 100 + }, + "tool_score_numerator": { + "type": "integer", + "minimum": 0 + }, + "tool_score_denominator": { + "type": "integer", + "minimum": 0 + }, + "tool_score_pct": { + "type": [ + "number", + "null" + ], + "minimum": 0, + "maximum": 100 + }, + "tool_score_definition": { + "type": "string", + "minLength": 1 + } + } + }, + "fuzzReportMetrics": { + "type": "object", + "additionalProperties": false, + "required": [ + "declared_budget_seconds", + "elapsed_seconds", + "executions", + "new_interesting_inputs" + ], + "properties": { + "declared_budget_seconds": { + "type": "integer", + "minimum": 1 + }, + "elapsed_seconds": { + "type": "number", + "minimum": 0 + }, + "executions": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + }, + "new_interesting_inputs": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + } + } + }, + "run": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "attempt", + "event", + "url", + "started_at" + ], + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "attempt": { + "type": "integer", + "minimum": 1 + }, + "event": { + "type": "string", + "minLength": 1 + }, + "url": { + "type": "string", + "format": "uri", + "pattern": "^https://" + }, + "started_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + } + }, + "completeness": { + "type": "object", + "additionalProperties": false, + "required": [ + "expected", + "reported", + "complete" + ], + "properties": { + "expected": { + "type": "integer", + "minimum": 1 + }, + "reported": { + "type": "integer", + "minimum": 0 + }, + "complete": { + "type": "boolean" + } + } + }, + "report": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "kind", + "repository", + "ref", + "sha", + "run", + "report_name", + "track", + "tool", + "policy", + "completeness", + "outcome", + "targets", + "metrics", + "errors" + ], + "properties": { + "schema_version": { + "$ref": "#/$defs/version" + }, + "kind": { + "type": "string", + "const": "report" + }, + "repository": { + "type": "string", + "minLength": 1 + }, + "ref": { + "type": "string", + "minLength": 1 + }, + "sha": { + "type": "string", + "pattern": "^[0-9a-f]{40}$" + }, + "run": { + "$ref": "#/$defs/run" + }, + "report_name": { + "type": "string", + "minLength": 1 + }, + "track": { + "type": "string", + "enum": [ + "mutation", + "fuzz" + ] + }, + "tool": { + "type": "string", + "enum": [ + "stryker", + "gremlins", + "go-fuzz", + "fast-check" + ] + }, + "policy": { + "type": "string", + "enum": [ + "advisory", + "signal" + ] + }, + "completeness": { + "$ref": "#/$defs/completeness" + }, + "outcome": { + "$ref": "#/$defs/outcome" + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/target" + } + }, + "metrics": { + "oneOf": [ + { + "$ref": "#/$defs/mutationReportMetrics" + }, + { + "$ref": "#/$defs/fuzzReportMetrics" + }, + { + "type": "null" + } + ] + }, + "errors": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1 + } + } + } + } + } +} From 99a7a997425bec33f51328d10a784f4612a4d3d3 Mon Sep 17 00:00:00 2001 From: scttbnsn <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 15:50:56 -0400 Subject: [PATCH 05/44] fix(quality): enforce report contract boundaries --- .../quality-result-stats/target-result.json | 2 +- .../quality-result-verify/target-result.json | 2 +- .../quality-result-stats/target-result.json | 2 +- .github/tests/quality_report_contract_test.py | 259 +++++++++++++++++- decisions/quality-reporting.md | 7 + quality-report/v1/quality_report.py | 23 +- quality-report/v1/schema.json | 216 ++++++++++++++- 7 files changed, 495 insertions(+), 16 deletions(-) diff --git a/.github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json b/.github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json index 627a14e..1f79ab0 100644 --- a/.github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json +++ b/.github/tests/fixtures/quality-report/v1/complete/quality-result-stats/target-result.json @@ -8,7 +8,7 @@ "outcome": "passed", "metrics": { "budget_seconds": 120, - "elapsed_seconds": 111.25, + "elapsed_seconds": 120.0, "executions": 650000, "new_interesting_inputs": 2 } diff --git a/.github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json b/.github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json index 472e276..3e0c633 100644 --- a/.github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json +++ b/.github/tests/fixtures/quality-report/v1/complete/quality-result-verify/target-result.json @@ -8,7 +8,7 @@ "outcome": "passed", "metrics": { "budget_seconds": 300, - "elapsed_seconds": 288.25, + "elapsed_seconds": 300.0, "executions": 1250000, "new_interesting_inputs": 3 } diff --git a/.github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json b/.github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json index 0db4a95..4530c33 100644 --- a/.github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json +++ b/.github/tests/fixtures/quality-report/v1/crash/quality-result-stats/target-result.json @@ -9,7 +9,7 @@ "metrics": null, "diagnostic": "tool process exited 2", "reproduction": { - "seed": "-test.fuzzcachedir=/tmp/fuzz-cache" + "path": "internal/docker/testdata/fuzz/FuzzDecodeStats/6f2c1b8d9a4e5c37" } } } diff --git a/.github/tests/quality_report_contract_test.py b/.github/tests/quality_report_contract_test.py index b456ce7..6c65a24 100644 --- a/.github/tests/quality_report_contract_test.py +++ b/.github/tests/quality_report_contract_test.py @@ -3,6 +3,7 @@ import runpy import shutil import subprocess +import sys import tempfile import unittest @@ -52,7 +53,7 @@ def test_complete_fuzz_fixture_emits_a_valid_report_and_summary(self): ) self.assertEqual("passed", report["outcome"]) self.assertEqual(420, report["metrics"]["declared_budget_seconds"]) - self.assertEqual(399.5, report["metrics"]["elapsed_seconds"]) + self.assertEqual(420.0, report["metrics"]["elapsed_seconds"]) self.assertEqual(1900000, report["metrics"]["executions"]) self.assertEqual(5, report["metrics"]["new_interesting_inputs"]) self.assertNotIn("canonical_score_pct", report["metrics"]) @@ -97,6 +98,23 @@ def test_crash_fixture_fails_even_when_every_target_reports(self): self.assertIn("tool process exited 2", summary) self.assertEqual(0, self.validate_report(report).returncode) + def test_crash_fixture_uses_a_native_go_crasher_path(self): + result = json.loads( + ( + FIXTURES + / "crash" + / "quality-result-stats" + / "target-result.json" + ).read_text() + ) + + self.assertEqual( + { + "path": "internal/docker/testdata/fuzz/FuzzDecodeStats/6f2c1b8d9a4e5c37" + }, + result["target"]["reproduction"], + ) + def test_parse_error_fixture_still_emits_an_error_report(self): result, report, summary = self.aggregate( "parse-error", @@ -116,6 +134,33 @@ def test_parse_error_fixture_still_emits_an_error_report(self): self.assertIn("partial 1/2", summary) self.assertEqual(0, self.validate_report(report).returncode) + def test_non_utf8_target_still_emits_an_error_report(self): + def corrupt_target(input_dir): + target = next(input_dir.rglob("target-result.json")) + target.write_bytes(b"\xff") + + result, report, summary = self.aggregate( + "complete", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + input_mutator=corrupt_target, + ) + + self.assertNotEqual(0, result.returncode) + self.assertEqual("error", report["outcome"]) + self.assertFalse(report["completeness"]["complete"]) + self.assertIsNone(report["metrics"]) + self.assertTrue( + any("cannot read JSON" in error for error in report["errors"]), + report["errors"], + ) + self.assertIn("partial 1/2", summary) + self.assertEqual(0, self.validate_report(report).returncode) + def test_canonical_score_counts_timeout_and_no_coverage(self): result, report, summary = self.aggregate( "canonical-score", @@ -150,6 +195,14 @@ def test_decision_documents_track_and_tool_pairings(self): self.assertIn("`mutation` permits `gremlins` and `stryker`", decision) self.assertIn("`fuzz` permits `fast-check` and `go-fuzz`", decision) + def test_decision_defines_go_fuzz_as_the_native_go_engine(self): + decision = " ".join(DECISION.read_text().split()) + + self.assertIn( + "`go-fuzz` identifies Go's native `go test -fuzz` engine, not the legacy third-party go-fuzz tool.", + decision, + ) + def test_native_score_is_weighted_and_keeps_its_definition(self): result, report, summary = self.aggregate( "native-score", @@ -235,6 +288,21 @@ def test_validator_requires_a_positive_declared_fuzz_budget(self): with self.assertRaisesRegex(QUALITY_REPORT["ContractError"], ">= 1"): QUALITY_REPORT["validate_fuzz_report_metrics"](metrics, [], "$.metrics") + def test_passed_fuzz_target_requires_its_full_declared_budget(self): + target = { + "name": "internal/auth/FuzzVerifyRequest", + "outcome": "passed", + "metrics": { + "budget_seconds": 300, + "elapsed_seconds": 299.99, + }, + } + + with self.assertRaisesRegex( + QUALITY_REPORT["ContractError"], "completed fuzz budget" + ): + QUALITY_REPORT["validate_target"](target, "fuzz", "$.target") + def test_validator_requires_time_and_offset_in_timestamps(self): for timestamp in ("2026-08-14", "2026-08-14T15:00:00"): with self.subTest(timestamp=timestamp): @@ -243,6 +311,91 @@ def test_validator_requires_time_and_offset_in_timestamps(self): ): QUALITY_REPORT["require_timestamp"](timestamp, "$.run.started_at") + def test_invalid_json_contract_error_retains_its_cause(self): + with self.assertRaises(QUALITY_REPORT["ContractError"]) as raised: + QUALITY_REPORT["load_json_text"]("{", "target-result.json") + + self.assertIsInstance(raised.exception.__cause__, json.JSONDecodeError) + + def test_invalid_timestamp_contract_error_retains_its_cause(self): + with self.assertRaises(QUALITY_REPORT["ContractError"]) as raised: + QUALITY_REPORT["require_timestamp"]("2026-08-14", "$.run.started_at") + + self.assertIsInstance(raised.exception.__cause__, ValueError) + + def test_json_parser_rejects_duplicate_fields_and_non_finite_numbers(self): + cases = ( + ('{"value": 1, "value": 2}', "duplicate JSON field"), + ('{"value": NaN}', "non-finite JSON number"), + ('{"value": Infinity}', "non-finite JSON number"), + ) + + for document, message in cases: + with self.subTest(document=document): + with self.assertRaisesRegex(QUALITY_REPORT["ContractError"], message): + QUALITY_REPORT["load_json_text"](document, "target-result.json") + + def test_mutation_aggregate_rejects_mixed_native_score_definitions(self): + targets = [] + for definition in ("detected / covered", "killed / lived"): + targets.append( + { + "metrics": { + "killed": 1, + "timeout": 0, + "survived": 0, + "no_coverage": 0, + "invalid": 0, + "ignored": 0, + "tool_score_numerator": 1, + "tool_score_denominator": 1, + "tool_score_pct": 100.0, + "tool_score_definition": definition, + } + } + ) + + with self.assertRaisesRegex( + QUALITY_REPORT["ContractError"], + "inconsistent native score definitions", + ): + QUALITY_REPORT["aggregate_mutation_metrics"](targets) + + def test_target_collection_rejects_unexpected_and_duplicate_names(self): + document = json.loads( + ( + FIXTURES + / "complete" + / "quality-result-stats" + / "target-result.json" + ).read_text() + ) + target_name = document["target"]["name"] + + with tempfile.TemporaryDirectory() as temp_dir: + input_dir = Path(temp_dir) + (input_dir / "unexpected").mkdir() + (input_dir / "unexpected" / "target-result.json").write_text( + json.dumps(document) + ) + targets, errors = QUALITY_REPORT["collect_targets"]( + input_dir, ["expected-target"], "fuzz", "go-fuzz" + ) + self.assertEqual([], targets) + self.assertTrue(any("unexpected target" in error for error in errors)) + + with tempfile.TemporaryDirectory() as temp_dir: + input_dir = Path(temp_dir) + for directory in ("first", "second"): + path = input_dir / directory + path.mkdir() + (path / "target-result.json").write_text(json.dumps(document)) + targets, errors = QUALITY_REPORT["collect_targets"]( + input_dir, [target_name], "fuzz", "go-fuzz" + ) + self.assertEqual([target_name], [target["name"] for target in targets]) + self.assertTrue(any("duplicate target" in error for error in errors)) + def test_schema_is_versioned_and_fail_closed(self): with SCHEMA.open() as schema_file: schema = json.load(schema_file) @@ -259,6 +412,97 @@ def test_schema_is_versioned_and_fail_closed(self): self.assertNotIn("additionalProperties", schema) self.assertTrue(self.all_objects_are_closed(schema)) + def test_schema_encodes_python_target_and_track_guards(self): + schema = json.loads(SCHEMA.read_text()) + definitions = schema["$defs"] + + self.assertEqual( + [ + { + "if": { + "properties": {"outcome": {"const": "passed"}}, + "required": ["outcome"], + }, + "then": { + "properties": {"metrics": {"not": {"type": "null"}}}, + "not": { + "anyOf": [ + {"required": ["diagnostic"]}, + {"required": ["reproduction"]}, + ] + }, + }, + "else": {"required": ["diagnostic"]}, + } + ], + definitions["target"]["allOf"], + ) + self.assertEqual( + {"gremlins", "stryker"}, + set( + definitions["targetResult"]["allOf"][0]["then"]["properties"][ + "tool" + ]["enum"] + ), + ) + self.assertEqual( + {"fast-check", "go-fuzz"}, + set( + definitions["targetResult"]["allOf"][0]["else"]["properties"][ + "tool" + ]["enum"] + ), + ) + self.assertEqual( + "#/$defs/mutationTargetMetrics", + definitions["mutationTarget"]["allOf"][1]["properties"]["metrics"][ + "oneOf" + ][0]["$ref"], + ) + self.assertEqual( + "#/$defs/fuzzTargetMetrics", + definitions["fuzzTarget"]["allOf"][1]["properties"]["metrics"][ + "oneOf" + ][0]["$ref"], + ) + self.assertEqual( + ["reproduction"], + definitions["fuzzTarget"]["allOf"][2]["then"]["required"], + ) + self.assertEqual( + "#/$defs/mutationTarget", + definitions["report"]["allOf"][0]["then"]["properties"]["targets"][ + "items" + ]["$ref"], + ) + self.assertEqual( + "#/$defs/fuzzTarget", + definitions["report"]["allOf"][0]["else"]["properties"]["targets"][ + "items" + ]["$ref"], + ) + self.assertEqual( + "#/$defs/mutationReportMetrics", + definitions["report"]["allOf"][0]["then"]["properties"]["metrics"][ + "oneOf" + ][0]["$ref"], + ) + self.assertEqual( + "#/$defs/fuzzReportMetrics", + definitions["report"]["allOf"][0]["else"]["properties"]["metrics"][ + "oneOf" + ][0]["$ref"], + ) + self.assertTrue(definitions["report"]["properties"]["targets"]["uniqueItems"]) + + def test_decision_names_python_as_the_cross_field_semantic_authority(self): + decision = " ".join(DECISION.read_text().split()) + + self.assertIn( + "The Python validator is authoritative for cross-field semantics that JSON Schema cannot express, including unique and sorted target names, recomputed completeness, outcomes, and aggregate metrics.", + decision, + ) + def test_reusable_workflow_matches_the_public_contract(self): workflow = WORKFLOW.read_text() @@ -332,18 +576,20 @@ def test_standards_validation_runs_this_contract(self): workflow.count("python3 .github/tests/quality_report_contract_test.py"), ) - def aggregate(self, fixture, *, track, tool, expected): + def aggregate(self, fixture, *, track, tool, expected, input_mutator=None): self.assertTrue(SCRIPT.is_file(), f"missing aggregator: {SCRIPT}") with tempfile.TemporaryDirectory() as temp_dir: input_dir = Path(temp_dir) / "input" shutil.copytree(FIXTURES / fixture, input_dir) + if input_mutator is not None: + input_mutator(input_dir) for invalid_fixture in input_dir.rglob("target-result.invalid"): invalid_fixture.rename(invalid_fixture.with_name("target-result.json")) output_dir = Path(temp_dir) / "output" github_output = Path(temp_dir) / "github-output" summary_path = Path(temp_dir) / "step-summary" command = [ - "python3", + sys.executable, str(SCRIPT), "aggregate", "--input-dir", @@ -383,7 +629,9 @@ def aggregate(self, fixture, *, track, tool, expected): "--github-step-summary", str(summary_path), ] - result = subprocess.run(command, capture_output=True, text=True) + result = subprocess.run( + command, capture_output=True, text=True, timeout=30 + ) report_path = output_dir / "report.json" summary_file = output_dir / "summary.md" self.assertTrue(report_path.is_file(), result.stderr) @@ -425,9 +673,10 @@ def validate_report(self, report): report_path = Path(temp_dir) / "report.json" report_path.write_text(json.dumps(report)) return subprocess.run( - ["python3", str(SCRIPT), "validate", str(report_path)], + [sys.executable, str(SCRIPT), "validate", str(report_path)], capture_output=True, text=True, + timeout=30, ) def all_objects_are_closed(self, value): diff --git a/decisions/quality-reporting.md b/decisions/quality-reporting.md index 6182c97..b826c22 100644 --- a/decisions/quality-reporting.md +++ b/decisions/quality-reporting.md @@ -55,6 +55,9 @@ job validates the set and publishes `quality-report/v1` with: - `targets`: the declared target names and their individual results - track-specific `metrics` +`go-fuzz` identifies Go's native `go test -fuzz` engine, not the legacy +third-party go-fuzz tool. + The schema and dependency-free validator live under [`quality-report/v1`](../quality-report/v1). Both target-result fragments and aggregate reports carry the exact `quality-report/v1` version. Objects reject unknown fields, JSON parsing rejects @@ -62,6 +65,10 @@ duplicate fields and non-finite numbers, and semantic validation recomputes completeness, outcomes, and scores. Callers pass `expected_targets` as a non-empty JSON array of unique target names. +The Python validator is authoritative for cross-field semantics that JSON +Schema cannot express, including unique and sorted target names, recomputed +completeness, outcomes, and aggregate metrics. + Mutation metrics are: - `killed`, `timeout`, `survived`, `no_coverage`, `invalid`, `ignored` diff --git a/quality-report/v1/quality_report.py b/quality-report/v1/quality_report.py index 8b8c93a..274308f 100644 --- a/quality-report/v1/quality_report.py +++ b/quality-report/v1/quality_report.py @@ -79,14 +79,16 @@ def load_json_text(text, source): parse_constant=reject_constant, ) except (json.JSONDecodeError, ContractError) as error: - raise ContractError("{0}: invalid JSON: {1}".format(source, error)) + raise ContractError("{0}: invalid JSON: {1}".format(source, error)) from error def load_json_file(path): try: return load_json_text(path.read_text(), str(path)) - except OSError as error: - raise ContractError("{0}: cannot read JSON: {1}".format(path, error)) + except (OSError, UnicodeDecodeError) as error: + raise ContractError( + "{0}: cannot read JSON: {1}".format(path, error) + ) from error def require_object(value, path, required, optional=()): @@ -168,8 +170,10 @@ def require_timestamp(value, path): if RFC3339_PATTERN.fullmatch(value) is None: raise ValueError datetime.fromisoformat(value.replace("Z", "+00:00").replace("z", "+00:00")) - except ValueError: - raise ContractError("{0}: expected RFC 3339 timestamp".format(path)) + except ValueError as error: + raise ContractError( + "{0}: expected RFC 3339 timestamp".format(path) + ) from error def percentage(numerator, denominator): @@ -238,6 +242,15 @@ def validate_target(target, track, path): validate_mutation_target_metrics(metrics, path + ".metrics") else: validate_fuzz_target_metrics(metrics, path + ".metrics") + if ( + outcome == "passed" + and metrics["elapsed_seconds"] < metrics["budget_seconds"] + ): + raise ContractError( + "{0}.metrics.elapsed_seconds: passed target has not completed fuzz budget".format( + path + ) + ) if outcome == "passed": if "diagnostic" in target or "reproduction" in target: diff --git a/quality-report/v1/schema.json b/quality-report/v1/schema.json index 46c38f1..2ce2acc 100644 --- a/quality-report/v1/schema.json +++ b/quality-report/v1/schema.json @@ -172,7 +172,112 @@ "reproduction": { "$ref": "#/$defs/reproduction" } - } + }, + "allOf": [ + { + "if": { + "properties": { + "outcome": { + "const": "passed" + } + }, + "required": [ + "outcome" + ] + }, + "then": { + "properties": { + "metrics": { + "not": { + "type": "null" + } + } + }, + "not": { + "anyOf": [ + { + "required": [ + "diagnostic" + ] + }, + { + "required": [ + "reproduction" + ] + } + ] + } + }, + "else": { + "required": [ + "diagnostic" + ] + } + } + ] + }, + "mutationTarget": { + "allOf": [ + { + "$ref": "#/$defs/target" + }, + { + "properties": { + "metrics": { + "oneOf": [ + { + "$ref": "#/$defs/mutationTargetMetrics" + }, + { + "type": "null" + } + ] + } + } + } + ] + }, + "fuzzTarget": { + "allOf": [ + { + "$ref": "#/$defs/target" + }, + { + "properties": { + "metrics": { + "oneOf": [ + { + "$ref": "#/$defs/fuzzTargetMetrics" + }, + { + "type": "null" + } + ] + } + } + }, + { + "if": { + "properties": { + "outcome": { + "enum": [ + "failed", + "crashed", + "flaked" + ] + } + }, + "required": [ + "outcome" + ] + }, + "then": { + "required": [ + "reproduction" + ] + } + } + ] }, "targetResult": { "type": "object", @@ -211,7 +316,47 @@ "target": { "$ref": "#/$defs/target" } - } + }, + "allOf": [ + { + "if": { + "properties": { + "track": { + "const": "mutation" + } + }, + "required": [ + "track" + ] + }, + "then": { + "properties": { + "tool": { + "enum": [ + "gremlins", + "stryker" + ] + }, + "target": { + "$ref": "#/$defs/mutationTarget" + } + } + }, + "else": { + "properties": { + "tool": { + "enum": [ + "fast-check", + "go-fuzz" + ] + }, + "target": { + "$ref": "#/$defs/fuzzTarget" + } + } + } + } + ] }, "mutationReportMetrics": { "type": "object", @@ -465,6 +610,7 @@ }, "targets": { "type": "array", + "uniqueItems": true, "items": { "$ref": "#/$defs/target" } @@ -490,7 +636,71 @@ "minLength": 1 } } - } + }, + "allOf": [ + { + "if": { + "properties": { + "track": { + "const": "mutation" + } + }, + "required": [ + "track" + ] + }, + "then": { + "properties": { + "tool": { + "enum": [ + "gremlins", + "stryker" + ] + }, + "targets": { + "items": { + "$ref": "#/$defs/mutationTarget" + } + }, + "metrics": { + "oneOf": [ + { + "$ref": "#/$defs/mutationReportMetrics" + }, + { + "type": "null" + } + ] + } + } + }, + "else": { + "properties": { + "tool": { + "enum": [ + "fast-check", + "go-fuzz" + ] + }, + "targets": { + "items": { + "$ref": "#/$defs/fuzzTarget" + } + }, + "metrics": { + "oneOf": [ + { + "$ref": "#/$defs/fuzzReportMetrics" + }, + { + "type": "null" + } + ] + } + } + } + } + ] } } } From 9a5362a6666d6ee42a3c5e47bf78b88eb21021f6 Mon Sep 17 00:00:00 2001 From: scttbnsn <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 16:08:46 -0400 Subject: [PATCH 06/44] fix(quality): decode reports as utf-8 --- .github/tests/quality_report_contract_test.py | 30 +++++++++++++++++++ quality-report/v1/quality_report.py | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/.github/tests/quality_report_contract_test.py b/.github/tests/quality_report_contract_test.py index 6c65a24..858507c 100644 --- a/.github/tests/quality_report_contract_test.py +++ b/.github/tests/quality_report_contract_test.py @@ -6,6 +6,7 @@ import sys import tempfile import unittest +from unittest import mock ROOT = Path(__file__).resolve().parents[2] @@ -161,6 +162,35 @@ def corrupt_target(input_dir): self.assertIn("partial 1/2", summary) self.assertEqual(0, self.validate_report(report).returncode) + def test_utf8_target_load_does_not_depend_on_the_locale_encoding(self): + document = json.loads( + ( + FIXTURES + / "complete" + / "quality-result-stats" + / "target-result.json" + ).read_text() + ) + document["target"]["name"] = "internal/docker/FuzzDécodage" + + with tempfile.TemporaryDirectory() as temp_dir: + path = Path(temp_dir) / "target-result.json" + path.write_bytes(json.dumps(document, ensure_ascii=False).encode("utf-8")) + + def read_with_ascii_default(*, encoding=None, errors=None): + return path.read_bytes().decode( + encoding or "ascii", errors or "strict" + ) + + with mock.patch.object( + Path, "read_text", side_effect=read_with_ascii_default + ): + loaded = QUALITY_REPORT["load_json_file"](path) + + self.assertEqual( + "internal/docker/FuzzDécodage", loaded["target"]["name"] + ) + def test_canonical_score_counts_timeout_and_no_coverage(self): result, report, summary = self.aggregate( "canonical-score", diff --git a/quality-report/v1/quality_report.py b/quality-report/v1/quality_report.py index 274308f..1c4a4c2 100644 --- a/quality-report/v1/quality_report.py +++ b/quality-report/v1/quality_report.py @@ -84,7 +84,7 @@ def load_json_text(text, source): def load_json_file(path): try: - return load_json_text(path.read_text(), str(path)) + return load_json_text(path.read_text(encoding="utf-8"), str(path)) except (OSError, UnicodeDecodeError) as error: raise ContractError( "{0}: cannot read JSON: {1}".format(path, error) From a39c5bd4697a7e513694c4a227dc8b15099f12a8 Mon Sep 17 00:00:00 2001 From: scttbnsn <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 16:38:16 -0400 Subject: [PATCH 07/44] test(quality): pin fixture encoding --- .github/tests/quality_report_contract_test.py | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/.github/tests/quality_report_contract_test.py b/.github/tests/quality_report_contract_test.py index 858507c..6fabc70 100644 --- a/.github/tests/quality_report_contract_test.py +++ b/.github/tests/quality_report_contract_test.py @@ -163,13 +163,19 @@ def corrupt_target(input_dir): self.assertEqual(0, self.validate_report(report).returncode) def test_utf8_target_load_does_not_depend_on_the_locale_encoding(self): - document = json.loads( - ( - FIXTURES - / "complete" - / "quality-result-stats" - / "target-result.json" - ).read_text() + fixture = ( + FIXTURES + / "complete" + / "quality-result-stats" + / "target-result.json" + ) + original_read_text = Path.read_text + with mock.patch.object( + Path, "read_text", autospec=True, side_effect=original_read_text + ) as fixture_read: + document = json.loads(fixture.read_text(encoding="utf-8")) + self.assertEqual( + mock.call(fixture, encoding="utf-8"), fixture_read.call_args ) document["target"]["name"] = "internal/docker/FuzzDécodage" From 7be30f375a4303edd1f135e919d02b9ac3cfe875 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:23:49 -0400 Subject: [PATCH 08/44] ci(profile): make asset generation read-only (#10) * ci(profile): make asset generation read-only * fix(profile): restrict asset validation egress --- .../tests/community_health_contract_test.py | 78 ++++++++++++++++--- .github/workflows/profile-assets.yml | 60 ++++++++++++++ .github/workflows/standards-validation.yml | 14 ++-- .github/workflows/update-stats.yml | 44 ----------- .gitignore | 1 + cache/.gitignore | 2 - cache/stats.json | 22 ------ .../generate_profile_svg.py | 6 +- 8 files changed, 140 insertions(+), 87 deletions(-) create mode 100644 .github/workflows/profile-assets.yml delete mode 100644 .github/workflows/update-stats.yml delete mode 100644 cache/.gitignore delete mode 100644 cache/stats.json rename generate_svg.py => scripts/generate_profile_svg.py (98%) diff --git a/.github/tests/community_health_contract_test.py b/.github/tests/community_health_contract_test.py index 9439282..7d36a25 100644 --- a/.github/tests/community_health_contract_test.py +++ b/.github/tests/community_health_contract_test.py @@ -1,5 +1,7 @@ from pathlib import Path import re +import subprocess +import sys import unittest @@ -119,6 +121,9 @@ def test_standards_workflow_has_unconditional_stable_jobs(self): self.assertIn(" - dev/repository-standards\n", workflow) self.assertNotIn("\n push:", workflow) self.assertIn("permissions: {}", workflow) + self.assertIn("concurrency:", workflow) + self.assertIn("group: standards-validation-", workflow) + self.assertIn("cancel-in-progress: true", workflow) self.assertIn("runs-on: ubuntu-24.04", workflow) self.assertNotIn("matrix:", workflow) self.assertNotIn("continue-on-error:", workflow) @@ -127,14 +132,14 @@ def test_standards_workflow_has_unconditional_stable_jobs(self): validation_job = workflow.split(" validation:\n", 1)[1].split( "\n codeql:\n", 1 )[0] - self.assertIn(" actions: read", validation_job) - self.assertIn(" contents: read", validation_job) + self.assertIn(" actions: read # Read workflow metadata", validation_job) + self.assertIn(" contents: read # Check out and validate repository files", validation_job) self.assertNotIn("write", validation_job) codeql_job = workflow.split("\n codeql:\n", 1)[1] - self.assertIn(" actions: read", codeql_job) - self.assertIn(" contents: read", codeql_job) - self.assertIn(" security-events: write", codeql_job) + self.assertIn(" actions: read # Read workflow metadata", codeql_job) + self.assertIn(" contents: read # Check out Python sources", codeql_job) + self.assertIn(" security-events: write # Upload CodeQL analysis", codeql_job) jobs = re.findall( r"^ ([a-z][a-z0-9-]+):$", @@ -184,22 +189,73 @@ def test_linter_configs_do_not_suppress_workflow_findings(self): self.assertEqual(2, markdown_config.count(": false")) self.assertFalse((ROOT / ".github/zizmor.yml").exists()) - def test_profile_workflow_pins_actions_and_pushes_without_persisted_credentials(self): - workflow = self.read_text(".github/workflows/update-stats.yml") + def test_profile_generator_has_one_canonical_location(self): + self.assertFalse((ROOT / "generate_svg.py").exists()) + self.assertTrue((ROOT / "scripts/generate_profile_svg.py").is_file()) + + def test_dead_profile_cache_is_removed(self): + self.assertFalse((ROOT / "cache").exists()) + + def test_font_reference_is_local_only(self): + gitignore = self.read_text(".gitignore") + self.assertIn("profile/font_reference.svg", gitignore.splitlines()) + + def test_profile_generator_reproduces_committed_assets(self): + generator = ROOT / "scripts/generate_profile_svg.py" + self.assertTrue(generator.is_file(), f"missing generator: {generator}") + outputs = ( + ROOT / "profile/dark_mode.svg", + ROOT / "profile/light_mode.svg", + ) + before = {path: path.read_bytes() for path in outputs} + + subprocess.run( + [sys.executable, generator], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + ) + + after = {path: path.read_bytes() for path in outputs} + self.assertEqual(before, after) + + def test_profile_workflow_is_read_only_bounded_and_pinned(self): + workflow = self.read_text(".github/workflows/profile-assets.yml") actions = re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE) self.assertEqual(2, len(actions)) for action in actions: self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") - checkout_step = workflow.split(" - name: Checkout\n", 1)[1].split( + harden_marker = " - name: Harden runner\n" + self.assertIn(harden_marker, workflow) + harden_step = workflow.split(harden_marker, 1)[1].split("\n - name:", 1)[0] + + self.assertIn("egress-policy: block", harden_step) + self.assertIn("allowed-endpoints: github.com:443", harden_step) + + checkout_marker = " - name: Check out repository\n" + self.assertIn(checkout_marker, workflow) + checkout_step = workflow.split(checkout_marker, 1)[1].split( "\n - name:", 1 )[0] - push_step = workflow.split(" - name: Commit and push\n", 1)[1] self.assertIn("persist-credentials: false", checkout_step) - self.assertIn("GH_TOKEN: ${{ github.token }}", push_step) - self.assertIn("gh auth setup-git", push_step) + self.assertIn("permissions: {}", workflow) + self.assertIn("name: Profile Assets", workflow) + self.assertIn("contents: read", workflow) + self.assertIn("timeout-minutes:", workflow) + self.assertIn("concurrency:", workflow) + self.assertIn("step-security/harden-runner@", workflow) + self.assertIn("python3 scripts/generate_profile_svg.py", workflow) + self.assertIn("git diff --exit-code -- profile/", workflow) + self.assertIn("git status --porcelain --untracked-files=all -- profile/", workflow) + self.assertNotIn("contents: write", workflow) + self.assertNotIn("git push", workflow) + self.assertNotIn("GH_TOKEN", workflow) + self.assertNotIn("schedule:", workflow) + self.assertFalse((ROOT / ".github/workflows/update-stats.yml").exists()) def read_text(self, relative_path): path = ROOT / relative_path diff --git a/.github/workflows/profile-assets.yml b/.github/workflows/profile-assets.yml new file mode 100644 index 0000000..0fd6154 --- /dev/null +++ b/.github/workflows/profile-assets.yml @@ -0,0 +1,60 @@ +name: Profile Assets + +on: + pull_request: + branches: + - main + - dev/repository-standards + paths: + - .github/tests/community_health_contract_test.py + - .github/workflows/profile-assets.yml + - .gitignore + - profile/*.svg + - scripts/generate_profile_svg.py + push: + branches: + - main + paths: + - .github/tests/community_health_contract_test.py + - .github/workflows/profile-assets.yml + - .gitignore + - profile/*.svg + - scripts/generate_profile_svg.py + workflow_dispatch: + +permissions: {} + +concurrency: + group: profile-assets-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + validate: + name: Profile Assets + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: block + allowed-endpoints: github.com:443 + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Verify generated profile assets + run: | + set -euo pipefail + python3 scripts/generate_profile_svg.py + git diff --exit-code -- profile/ + changes="$(git status --porcelain --untracked-files=all -- profile/)" + if [[ -n "$changes" ]]; then + printf '%s\n' "$changes" + exit 1 + fi diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index ceb4606..30ea7f4 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -8,14 +8,18 @@ on: permissions: {} +concurrency: + group: standards-validation-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: validation: name: Standards Validation runs-on: ubuntu-24.04 timeout-minutes: 10 permissions: - actions: read - contents: read + actions: read # Read workflow metadata + contents: read # Check out and validate repository files steps: - name: Harden runner @@ -74,9 +78,9 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 10 permissions: - actions: read - contents: read - security-events: write + actions: read # Read workflow metadata + contents: read # Check out Python sources + security-events: write # Upload CodeQL analysis steps: - name: Harden runner diff --git a/.github/workflows/update-stats.yml b/.github/workflows/update-stats.yml deleted file mode 100644 index cb79f7c..0000000 --- a/.github/workflows/update-stats.yml +++ /dev/null @@ -1,44 +0,0 @@ -name: Update Org Profile Stats - -on: - push: - branches: - - main - schedule: - - cron: '0 0 * * *' - workflow_dispatch: - -permissions: - contents: write - -jobs: - update: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - with: - persist-credentials: false - - - name: Set up Python - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 - with: - python-version: '3.11' - - - name: Generate SVGs - env: - GH_TOKEN: ${{ secrets.ACCESS_TOKEN }} - run: | - python generate_svg.py - - - name: Commit and push - env: - GH_TOKEN: ${{ github.token }} - run: | - gh auth setup-git - git config --global user.email "github-actions[bot]@users.noreply.github.com" - git config --global user.name "github-actions[bot]" - git add profile/dark_mode.svg profile/light_mode.svg cache/ - git diff --staged --quiet || git commit -m "Update stats" - git push diff --git a/.gitignore b/.gitignore index c54ade8..d66d040 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ __pycache__/ # Local planning/scratch workspace — not for commit .planning/ +profile/font_reference.svg diff --git a/cache/.gitignore b/cache/.gitignore deleted file mode 100644 index 688f1fa..0000000 --- a/cache/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Track cache files (needed for CI) -!*.json diff --git a/cache/stats.json b/cache/stats.json deleted file mode 100644 index 42f10e4..0000000 --- a/cache/stats.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "timestamp": "2026-02-09T23:00:00.795596", - "org": { - "public_repos": 2, - "private_repos": 3, - "total_repos": 5, - "total_stars": 0, - "total_forks": 0, - "total_commits": 398, - "total_prs": 11, - "total_issues": 1, - "members": 0, - "loc_added": 354732, - "loc_deleted": 283673, - "loc_total": 71059, - "languages": [ - "Python", - "Swift", - "TypeScript" - ] - } -} \ No newline at end of file diff --git a/generate_svg.py b/scripts/generate_profile_svg.py similarity index 98% rename from generate_svg.py rename to scripts/generate_profile_svg.py index 02f2b1b..436b7c6 100644 --- a/generate_svg.py +++ b/scripts/generate_profile_svg.py @@ -211,16 +211,16 @@ def art_color(ch): def main(): """Generate both dark and light mode SVGs.""" - script_dir = Path(__file__).parent + repo_root = Path(__file__).resolve().parents[1] dark_svg = generate_svg("dark") - dark_path = script_dir / "profile" / "dark_mode.svg" + dark_path = repo_root / "profile" / "dark_mode.svg" with open(dark_path, 'w', encoding='utf-8') as f: f.write(dark_svg) print(f"Generated: {dark_path}") light_svg = generate_svg("light") - light_path = script_dir / "profile" / "light_mode.svg" + light_path = repo_root / "profile" / "light_mode.svg" with open(light_path, 'w', encoding='utf-8') as f: f.write(light_svg) print(f"Generated: {light_path}") From 55c58e856c5f2a680b8e616158b76328831fad76 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:31:52 -0400 Subject: [PATCH 09/44] ci(review): add deduplicated Greptile summon (#9) * ci(review): add deduplicated Greptile summon * fix(review): serialize exact-head Greptile summons * test(review): lock Greptile security controls --- .../tests/greptile_summon_contract_test.py | 92 ++++++++++++++ .github/workflows/greptile-summon.yml | 120 ++++++++++++++++++ .github/workflows/standards-validation.yml | 4 +- 3 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 .github/tests/greptile_summon_contract_test.py create mode 100644 .github/workflows/greptile-summon.yml diff --git a/.github/tests/greptile_summon_contract_test.py b/.github/tests/greptile_summon_contract_test.py new file mode 100644 index 0000000..7584077 --- /dev/null +++ b/.github/tests/greptile_summon_contract_test.py @@ -0,0 +1,92 @@ +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = ROOT / ".github/workflows/greptile-summon.yml" + + +class GreptileSummonContractTest(unittest.TestCase): + def test_reusable_workflow_has_exact_head_inputs_and_narrow_permissions(self): + workflow = self.read_workflow() + + for expected in ( + " workflow_call:\n", + " pr_number:\n", + " type: number\n", + " head_sha:\n", + " type: string\n", + " focus:\n", + "permissions: {}", + " runs-on: ubuntu-24.04", + " timeout-minutes: 5", + " pull-requests: write", + "uses: step-security/harden-runner@", + "egress-policy: block", + "api.github.com:443", + "github-token: ${{ github.token }}", + ): + self.assertIn(expected, workflow) + + self.assertNotIn("actions/checkout", workflow) + + def test_workflow_verifies_head_and_deduplicates_before_commenting(self): + workflow = self.read_workflow() + + for expected in ( + "github.rest.pulls.get", + 'pull.state !== "open"', + "pull.head.sha !== headSha", + "github.paginate", + "github.rest.issues.listComments", + "greptile-summon:${headSha}", + 'comment.user?.login === "github-actions[bot]"', + "github.rest.issues.createComment", + "@greptileai", + ): + self.assertIn(expected, workflow) + + self.assertIn( + "greptile-summon-${{ github.repository }}-${{ inputs.pr_number }}-${{ inputs.head_sha }}", + workflow, + ) + self.assertIn(" cancel-in-progress: false", workflow) + self.assertGreaterEqual(workflow.count("github.rest.pulls.get"), 2) + self.assertIn("currentPull.head.sha !== headSha", workflow) + self.assertIn("HEAD_SHA: ${{ inputs.head_sha }}", workflow) + self.assertIn("REVIEW_FOCUS: ${{ inputs.focus }}", workflow) + self.assertNotIn("const headSha = '${{ inputs.head_sha }}'", workflow) + self.assertNotIn("const focus = '${{ inputs.focus }}'", workflow) + + def test_workflow_rejects_partial_pull_request_numbers(self): + workflow = self.read_workflow() + + self.assertIn("const prNumberText = process.env.PR_NUMBER", workflow) + self.assertIn("const prNumber = Number(prNumberText)", workflow) + self.assertIn("!/^[1-9]\\d*$/.test(prNumberText)", workflow) + self.assertIn("PR_NUMBER: ${{ inputs.pr_number }}", workflow) + self.assertIn("if (!/^[0-9a-f]{40}$/.test(headSha))", workflow) + self.assertIn("if (focus.length === 0 || focus.length > 500)", workflow) + self.assertNotIn("Number.parseInt(process.env.PR_NUMBER", workflow) + + def test_workflow_pins_actions_and_is_run_by_standards_validation(self): + workflow = self.read_workflow() + actions = re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE) + + self.assertTrue(actions) + for action in actions: + self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") + + validation = ( + ROOT / ".github/workflows/standards-validation.yml" + ).read_text() + self.assertIn("greptile_summon_contract_test.py", validation) + + def read_workflow(self): + self.assertTrue(WORKFLOW.is_file(), f"missing workflow: {WORKFLOW}") + return WORKFLOW.read_text() + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/greptile-summon.yml b/.github/workflows/greptile-summon.yml new file mode 100644 index 0000000..3484f9b --- /dev/null +++ b/.github/workflows/greptile-summon.yml @@ -0,0 +1,120 @@ +name: Summon Greptile + +on: + workflow_call: + inputs: + pr_number: + description: Pull request number in the caller repository + required: true + type: number + head_sha: + description: Exact pull request head to review + required: true + type: string + focus: + description: Short review focus based on the risk in the diff + required: false + default: Review for correctness, security issues, and cross-file regressions. + type: string + +permissions: {} + +jobs: + summon: + name: Summon Greptile + runs-on: ubuntu-24.04 + timeout-minutes: 5 + concurrency: + group: greptile-summon-${{ github.repository }}-${{ inputs.pr_number }}-${{ inputs.head_sha }} + cancel-in-progress: false + permissions: + pull-requests: write # Create the intentional Greptile summon comment. + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: block + allowed-endpoints: > + api.github.com:443 + + - name: Comment once on the exact pull request head + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + PR_NUMBER: ${{ inputs.pr_number }} + HEAD_SHA: ${{ inputs.head_sha }} + REVIEW_FOCUS: ${{ inputs.focus }} + with: + github-token: ${{ github.token }} + script: | + const prNumberText = process.env.PR_NUMBER; + const prNumber = Number(prNumberText); + const headSha = process.env.HEAD_SHA; + const focus = process.env.REVIEW_FOCUS.trim(); + const { owner, repo } = context.repo; + + if (!/^[1-9]\d*$/.test(prNumberText) || !Number.isSafeInteger(prNumber)) { + core.setFailed(`Invalid pull request number: ${prNumberText}`); + return; + } + if (!/^[0-9a-f]{40}$/.test(headSha)) { + core.setFailed(`Invalid full head SHA: ${headSha}`); + return; + } + if (focus.length === 0 || focus.length > 500) { + core.setFailed("Review focus must contain 1 to 500 characters"); + return; + } + + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: prNumber, + }); + if (pull.state !== "open") { + core.setFailed(`Pull request #${prNumber} is ${pull.state}`); + return; + } + if (pull.head.sha !== headSha) { + core.setFailed( + `Pull request head changed: expected ${headSha}, got ${pull.head.sha}`, + ); + return; + } + + const marker = ``; + const comments = await github.paginate( + github.rest.issues.listComments, + { owner, repo, issue_number: prNumber, per_page: 100 }, + ); + const alreadySummoned = comments.some( + (comment) => comment.user?.login === "github-actions[bot]" + && comment.body?.includes(marker), + ); + if (alreadySummoned) { + core.notice(`Greptile already summoned for ${headSha}`); + return; + } + + const { data: currentPull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: prNumber, + }); + if (currentPull.state !== "open") { + core.setFailed(`Pull request #${prNumber} is ${currentPull.state}`); + return; + } + if (currentPull.head.sha !== headSha) { + core.setFailed( + `Pull request head changed: expected ${headSha}, got ${currentPull.head.sha}`, + ); + return; + } + + await github.rest.issues.createComment({ + owner, + repo, + issue_number: prNumber, + body: `@greptileai Review exact head \`${headSha}\`. ${focus}\n\n${marker}`, + }); diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 30ea7f4..0ea5ad0 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -38,7 +38,9 @@ jobs: node-version: 24 - name: Validate community health contract - run: python3 .github/tests/community_health_contract_test.py + run: | + python3 .github/tests/community_health_contract_test.py + python3 .github/tests/greptile_summon_contract_test.py - name: Compile Python run: python3 -m compileall -q . From 6e7a78dc13d099cb27669c0a0f8a75836de97f03 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 16 Aug 2026 08:24:16 -0400 Subject: [PATCH 10/44] ci(workflows): add run-test and run-lint toggles to go-ci (#19) go-ci.yml's test and lint jobs ran unconditionally, so a Go-less repo that only wants the language-agnostic workflow-security (zizmor) job couldn't call it. Add run-test/run-lint boolean inputs, mirroring the existing run-govulncheck/run-workflow-security/etc. toggle pattern, defaulting to true so existing callers see no behavior change. Fixes: #18 --- .github/tests/reusable_ci_contract_test.py | 4 ++++ .github/workflows/go-ci.yml | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/.github/tests/reusable_ci_contract_test.py b/.github/tests/reusable_ci_contract_test.py index a6ec3f5..b958eb6 100644 --- a/.github/tests/reusable_ci_contract_test.py +++ b/.github/tests/reusable_ci_contract_test.py @@ -25,6 +25,8 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) "lint-check-name", "test-check-name", "fuzzers-json", + "run-test", + "run-lint", "run-govulncheck", "run-qlty", "run-goreleaser", @@ -113,6 +115,8 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) self.assert_input("go", "lint-check-name", "string", default="Go Lint") self.assert_input("go", "test-check-name", "string", default="Go Test") self.assert_input("go", "fuzzers-json", "string", default="[]") + for input_name in ("run-test", "run-lint"): + self.assert_input("go", input_name, "boolean", default="true") for input_name in ( "run-govulncheck", "run-qlty", diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 46601d4..8e14b1c 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -33,6 +33,16 @@ on: required: false type: string default: "[]" + run-test: + description: Run the fixed repository Go test gate + required: false + type: boolean + default: true + run-lint: + description: Run the fixed repository Go lint gate + required: false + type: boolean + default: true run-govulncheck: description: Run the fixed repository govulncheck gate required: false @@ -159,6 +169,7 @@ permissions: {} jobs: test: name: ${{ inputs.test-check-name }} + if: inputs.run-test runs-on: ubuntu-24.04 timeout-minutes: 30 permissions: @@ -198,6 +209,7 @@ jobs: lint: name: ${{ inputs.lint-check-name }} + if: inputs.run-lint runs-on: ubuntu-24.04 timeout-minutes: 20 permissions: From 04ad251abff43346cd46b836f323421a0f99bd00 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 16 Aug 2026 13:05:50 -0400 Subject: [PATCH 11/44] ci(workflows): add module-directory input to node-ci (#22) * ci(workflows): add module-directory input to node-ci Mirrors go-ci's module-directory idiom: a string input defaulting to "." threaded into each fixed script's env as MODULE_DIRECTORY, so a repo with several independently-gated Node projects can call node-ci once per project. The default preserves current behavior for existing callers. Extends the reusable CI contract test to assert the new input and its threading, matching how run-test/run-lint were added for go-ci in #19. * test(workflows): assert module-directory threads into all three node jobs --- .github/tests/reusable_ci_contract_test.py | 5 +++++ .github/workflows/node-ci.yml | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/.github/tests/reusable_ci_contract_test.py b/.github/tests/reusable_ci_contract_test.py index b958eb6..b4fc0fa 100644 --- a/.github/tests/reusable_ci_contract_test.py +++ b/.github/tests/reusable_ci_contract_test.py @@ -47,6 +47,7 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) ) ) node_inputs = [ + "module-directory", "node-version", "lockfile-path", "lint-check-name", @@ -127,6 +128,7 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) ): self.assert_input("go", input_name, "boolean", default="false") + self.assert_input("node", "module-directory", "string", default=".") self.assert_input("node", "node-version", "string", default="24") self.assert_input("node", "lockfile-path", "string", default="package-lock.json") self.assert_input("node", "lint-check-name", "string", default="Node Lint") @@ -204,6 +206,9 @@ def test_central_jobs_have_exact_names_fixed_commands_and_per_job_egress(self): ) self.assertIn("node-version: ${{ inputs.node-version }}", node) self.assertIn("cache-dependency-path: ${{ inputs.lockfile-path }}", node) + self.assertEqual( + 3, node.count("MODULE_DIRECTORY: ${{ inputs.module-directory }}") + ) for workflow in (go, node, self.read_workflow(WORKFLOWS["release"])): self.assertIn("runs-on: ubuntu-24.04", workflow) diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index e699a9b..c953151 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -3,6 +3,11 @@ name: Reusable Node CI on: workflow_call: inputs: + module-directory: + description: Repository-relative Node module directory + required: false + type: string + default: . node-version: description: Node.js version used by enabled jobs required: false @@ -105,6 +110,8 @@ jobs: cache-dependency-path: ${{ inputs.lockfile-path }} - name: Run repository Node lint gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} run: ./scripts/ci/node-lint.sh test: @@ -135,6 +142,8 @@ jobs: cache-dependency-path: ${{ inputs.lockfile-path }} - name: Run repository Node test gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} run: ./scripts/ci/node-test.sh - name: Upload Node test artifacts @@ -174,6 +183,8 @@ jobs: cache-dependency-path: ${{ inputs.lockfile-path }} - name: Run repository Node build gate + env: + MODULE_DIRECTORY: ${{ inputs.module-directory }} run: ./scripts/ci/node-build.sh - name: Upload Node build artifacts From 7f9be8b854dd345814537fd0d7f24b2509760f96 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 16 Aug 2026 16:30:27 -0400 Subject: [PATCH 12/44] docs(onboarding): record the qlty alignment baseline (#24) --- REPOSITORY_ONBOARDING.md | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index a06bb7a..7510744 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -115,10 +115,8 @@ repositories. Language-specific tests do not. - [ ] Add language formatters to `pre-commit` only when they can safely operate on staged files. Verify the hook does not rewrite unrelated work. -Qlty Cloud enrollment and usage data are not an organization-wide prerequisite. -Do not make a Qlty upload or check required until the repository is enrolled and -the check has proved stable. Local Qlty checks may still be stricter than this -baseline. +Qlty spans local and CI gates; the full baseline, including why Qlty Cloud +checks stay non-required, is in the Qlty subsection of section 4. ## 3. Protect `main` @@ -194,6 +192,37 @@ Add these only when the behavior exists: - [ ] Translation synchronization only for a repository with a translation source of truth and configured provider credentials. +### Qlty + +Qlty appears in three places. The committed configuration and the repository-run +gates are the alignment surface; the Qlty Cloud GitHub App is not. + +- [ ] Commit `.qlty/qlty.toml` (`config_version = "0"`) with the organization + exclude baseline for generated, minified, and vendored paths. Drydock's file + is the reference posture and Portwing's is its Go-repo mirror; start from the + closer of the two. The same file drives the local CLI and Qlty Cloud, so + changes to it are quality-gate changes, not formatting. +- [ ] Add the repository's Qlty gate script (`scripts/qlty-check-gate.sh all`) + to `pre-push`, fail-fast like every other local gate. An advisory smells + gate may run alongside it (Drydock pattern) but must not mask the gating + script's failure. +- [ ] Gate Qlty in CI with the repository-run check, which needs no Qlty Cloud + account. Go repositories call `go-ci.yml` with `run-qlty` enabled, + `qlty-egress-policy: block`, and the proven endpoint allowlist — copy the + allowlist from Portwing's `ci-verify.yml` rather than re-deriving it, and do + not widen it. Node repositories run the SHA-pinned + `qltysh/qlty-action/install` plus the same gate script inside their own + workflow (Drydock pattern). + +The Qlty Cloud GitHub App's statuses (`qlty check`, `qlty coverage`, +`qlty coverage diff`) currently error organization-wide with out-of-minutes +billing failures. Treat them as non-gating: never add them to required status +checks, and do not chase these failures on PRs — the repository-run gate above +is the enforced check. Qlty Cloud enrollment and usage data are not an +organization-wide prerequisite; do not make a Cloud upload or check required +until the repository is enrolled and the check has proved stable. Local Qlty +checks may still be stricter than this baseline. + ## 5. Add delivery controls only for shipped artifacts - [ ] Keep release construction separate from ordinary CI. A release-cut From f4c1d509fe98551d6e6d6c819d2bb618711e460f Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 16 Aug 2026 18:34:58 -0400 Subject: [PATCH 13/44] docs(onboarding): align with the codified standards registry (#26) * docs(onboarding): align with the codified standards registry - docs(onboarding): name Codecov as the coverage cloud; Qlty Cloud App and maintainability badge stay, checks stay non-required - docs(onboarding): trivy deprecated in favor of Grype, including the qlty plugin blocks in the two reference configs (drydock#753, portwing#135) - docs(onboarding): CodeRabbit free Pro is public-only; private repos use cross-account human review - docs(onboarding): add the greptile.json contract and the label-gated second-opinion caller * docs(onboarding): reword the CodeRabbit private-repo claim as org policy - docs(onboarding): free-plan private-repo reviews exist but are rate-limited and never fired here; the skip is policy, not a plan fact - docs(onboarding): pair the Greptile caller with auto-applied CodeRabbit labeling so the second-opinion label is criteria-driven --- REPOSITORY_ONBOARDING.md | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index 7510744..8929480 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -100,6 +100,20 @@ repositories. Language-specific tests do not. request an explicit CodeRabbit review on the first PR to prove it works. - [ ] Confirm CodeRabbit can access the repository and posts an actual review comment. A green check without review output is not enough for this test. + Automated Pro-level reviews are free on public repositories only; on + private repositories the free plan rate-limits automated reviews, and they + have not fired for this organization in practice. Organization policy: on a + private repository skip both CodeRabbit items, use cross-account human + review, and add the config when the repository goes public. +- [ ] Keep `greptile.json` at exactly `{"skipReview": "AUTOMATIC"}` + (contract-tested in this repository) so Greptile never reviews unbidden. A + repository that wants opt-in second opinions adds a label-gated caller + workflow (`.github/workflows/greptile.yml`, firing on the `second-opinion` + label) that calls this repository's `greptile-summon.yml` at a pinned full + commit SHA. Pair the caller with a CodeRabbit `labeling_instructions` entry + for `second-opinion` and `auto_apply_labels` enabled, so applying the label + is criteria-driven rather than left to memory. The label is Greptile's only + trigger; never wire it to review every PR directly. ### Local gates @@ -156,7 +170,8 @@ must push, and use `step-security/harden-runner` with the smallest practical egress allowlist. Every repository with executable code needs the applicable format or lint and -test gates. Require coverage when the language and test tooling measure it, a +test gates. Require coverage when the language and test tooling measure it +(uploaded to Codecov, not Qlty Cloud), a production build when the repository ships a buildable artifact, dependency review when it has dependencies, workflow validation when it has GitHub Actions, and CodeQL when its language is supported. Add the matching language or artifact @@ -174,8 +189,9 @@ checks below: - **GitHub Actions:** actionlint and zizmor on every PR, plus tests for non-trivial embedded shell and workflow contracts. - **Container image:** build the real Dockerfile, smoke-test the image, and scan - the built image and locked dependencies with Grype or the current organization - scanner. + the built image and locked dependencies with Grype. Trivy is deprecated + organization-wide in favor of Grype; do not adopt it, including as a Qlty + plugin. - **Public repository:** OpenSSF Scorecard on its supported triggers and dependency review on PRs. @@ -200,8 +216,11 @@ gates are the alignment surface; the Qlty Cloud GitHub App is not. - [ ] Commit `.qlty/qlty.toml` (`config_version = "0"`) with the organization exclude baseline for generated, minified, and vendored paths. Drydock's file is the reference posture and Portwing's is its Go-repo mirror; start from the - closer of the two. The same file drives the local CLI and Qlty Cloud, so - changes to it are quality-gate changes, not formatting. + closer of the two. Do not copy the trivy plugin block from either reference: + trivy is deprecated in favor of Grype and its removal from both files is + tracked (drydock#753, portwing#135). The trufflehog plugin stays. The same + file drives the local CLI and Qlty Cloud, so changes to it are quality-gate + changes, not formatting. - [ ] Add the repository's Qlty gate script (`scripts/qlty-check-gate.sh all`) to `pre-push`, fail-fast like every other local gate. An advisory smells gate may run alongside it (Drydock pattern) but must not mask the gating @@ -218,8 +237,12 @@ The Qlty Cloud GitHub App's statuses (`qlty check`, `qlty coverage`, `qlty coverage diff`) currently error organization-wide with out-of-minutes billing failures. Treat them as non-gating: never add them to required status checks, and do not chase these failures on PRs — the repository-run gate above -is the enforced check. Qlty Cloud enrollment and usage data are not an -organization-wide prerequisite; do not make a Cloud upload or check required +is the enforced check. Coverage reporting is Codecov's job (decided +2026-08-16): upload coverage to Codecov and carry its badge in the README. +The Qlty Cloud App and its maintainability badge stay installed, but its +coverage upload is not the coverage system and its checks stay non-required. +Qlty Cloud enrollment and usage data are not an organization-wide +prerequisite; do not make a Cloud upload or check required until the repository is enrolled and the check has proved stable. Local Qlty checks may still be stricter than this baseline. From 5ac2e3fa208ef8724e163230adf8ed18ff607424 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 16 Aug 2026 19:41:50 -0400 Subject: [PATCH 14/44] chore(repo): meet our own onboarding checklist (#28) * chore(repo): meet our own onboarding checklist - chore(repo): MIT LICENSE (infrastructure repos are MIT; products AGPL) - docs(repo): root AGENTS.md with repo-specific rules and validation - build(hooks): lefthook with commit-msg + pre-push mirroring CI via scripts/validate.sh * fix(hooks): tighten the commit-msg exemptions and mirror zizmor's CI flags - fix(hooks): merge/revert exemptions match git's generated subjects only, so a hand-typed 'Merge ...' subject no longer bypasses the check - fix(hooks): require a non-whitespace character after the colon - fix(hooks): zizmor runs --no-online-audits locally, matching CI's online-audits: false for local/CI parity * fix(hooks): exempt only git-generated merge and revert subjects --- AGENTS.md | 50 +++++++++++++++++++++++++++++++++++++ LICENSE | 21 ++++++++++++++++ lefthook.yml | 12 +++++++++ scripts/check-commit-msg.sh | 25 +++++++++++++++++++ scripts/validate.sh | 45 +++++++++++++++++++++++++++++++++ 5 files changed, 153 insertions(+) create mode 100644 AGENTS.md create mode 100644 LICENSE create mode 100644 lefthook.yml create mode 100755 scripts/check-commit-msg.sh create mode 100755 scripts/validate.sh diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0d27337 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,50 @@ +# Agent instructions for CodesWhat/.github + +This repository is the organization's meta layer: community health defaults, +the repository onboarding checklist (`REPOSITORY_ONBOARDING.md`), reusable CI +workflows, the organization profile README and its generator, and the +contract tests that pin the shapes other repositories depend on. + +## What lives here + +- `.github/workflows/go-ci.yml`, `node-ci.yml`, `release-gate.yml`, + `greptile-summon.yml`, `quality-report-aggregate.yml` — reusable workflows + consumed by other CodesWhat repositories. +- `.github/tests/` — contract tests. These are the public API of the org's + shared configs (the `greptile.json` shape, the quality-report v1 contract, + the reusable CI inputs). Change a contract test and its consumers together, + never one side alone. +- `profile/` — the organization profile README plus generated SVG assets + from `scripts/generate_profile_svg.py`. The untracked + `profile/font_reference.svg` is user-owned; leave it alone. + +## Rules that are specific to this repository + +- Consumers pin the reusable workflows to frozen full commit SHAs. Treat + every workflow change as breaking for pinned consumers: add new inputs + with safe defaults, never repurpose an existing input, and let consumers + adopt by rolling their pin deliberately. +- PRs target `dev/repository-standards`. `main` advances only through + promotion PRs. Reconcile before promoting: + `git merge -s ours origin/main -m "chore(sync): reconcile main before promotion"`. + Verify promotions with tree equality + (`git diff --quiet origin/main origin/dev/repository-standards`), never + commit ancestry. +- CodeRabbit auto-reviews PRs against `dev/*` branches only (scoped in + `.coderabbit.yaml`); summon it explicitly anywhere else and read its + inline comments before merging. +- Commits are plain Conventional Commits, `(scope): `, + no emoji, no AI attribution trailers. +- Never weaken branch protection or rulesets to land a change. + +## Validation + +Run before pushing (the lefthook pre-push hook runs the same set): + +```bash +bash scripts/validate.sh +``` + +That script mirrors the Standards Validation CI job: contract tests, Python +compile, YAML/JSON parse, markdownlint (with the separate profile config for +`profile/README.md`), and actionlint/zizmor when installed locally. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..af599c9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 CodesWhat + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lefthook.yml b/lefthook.yml new file mode 100644 index 0000000..3872369 --- /dev/null +++ b/lefthook.yml @@ -0,0 +1,12 @@ +# Local git hooks. Install once with: npx --yes lefthook install +# pre-push mirrors the Standards Validation CI job via scripts/validate.sh. + +commit-msg: + commands: + conventional-commits: + run: bash scripts/check-commit-msg.sh {1} + +pre-push: + commands: + validate: + run: bash scripts/validate.sh diff --git a/scripts/check-commit-msg.sh b/scripts/check-commit-msg.sh new file mode 100755 index 0000000..3b3320e --- /dev/null +++ b/scripts/check-commit-msg.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# commit-msg hook: enforce plain Conventional Commits on the subject line. +set -euo pipefail + +msg_file="$1" +subject="$(head -n 1 "$msg_file")" + +case "$subject" in + "Merge branch '"*|"Merge pull request #"*|"Merge remote-tracking branch '"*|fixup!\ *|squash!\ *) exit 0 ;; +esac + +if [[ "$subject" =~ ^Revert\ \".+\"$ ]]; then + exit 0 +fi + +pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9./-]+\))?!?: [^[:space:]]' +if ! [[ "$subject" =~ $pattern ]]; then + { + echo "commit subject must be plain Conventional Commits:" + echo " (scope): " + echo "allowed types: feat fix docs style refactor perf test build ci chore revert" + echo "got: $subject" + } >&2 + exit 1 +fi diff --git a/scripts/validate.sh b/scripts/validate.sh new file mode 100755 index 0000000..5d02c10 --- /dev/null +++ b/scripts/validate.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Local mirror of the Standards Validation CI job. Run before pushing; +# lefthook pre-push runs this same script. +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" + +echo "==> clean tree" +if ! git diff --quiet || ! git diff --cached --quiet; then + echo "commit or stash local changes before pushing" >&2 + exit 1 +fi + +echo "==> contract tests" +python3 .github/tests/community_health_contract_test.py +python3 .github/tests/greptile_summon_contract_test.py +python3 .github/tests/greptile_config_contract_test.py +python3 .github/tests/quality_report_contract_test.py +python3 .github/tests/reusable_ci_contract_test.py + +echo "==> compile python" +python3 -m compileall -q . + +echo "==> parse yaml and json" +ruby -e 'require "yaml"; Dir.glob("**/*.{yml,yaml}", File::FNM_DOTMATCH).sort.each { |path| YAML.parse_file(path) }' +python3 -c 'import json; from pathlib import Path; [json.load(path.open()) for path in Path(".").rglob("*.json")]' + +echo "==> markdownlint" +npx --yes markdownlint-cli2@0.23.2 "**/*.md" "#profile/README.md" +npx --yes markdownlint-cli2@0.23.2 "profile/README.md" --config .github/markdownlint-profile.yaml + +echo "==> actionlint" +if command -v actionlint >/dev/null 2>&1; then + actionlint -color +else + echo "actionlint not installed locally; CI will run it" +fi + +echo "==> zizmor" +if command -v zizmor >/dev/null 2>&1; then + zizmor --no-online-audits .github/workflows/ +else + echo "zizmor not installed locally; CI will run it" +fi + +echo "==> ok" From 30d6b13d3340a67297ca9c2a0370715fc317bfde Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 16 Aug 2026 21:48:43 -0400 Subject: [PATCH 15/44] docs(community): org-default code of conduct + community checklist (#30) * docs(community): add org-default code of conduct and community checklist items CODE_OF_CONDUCT.md is Contributor Covenant 2.0 (drydock's tuned copy) with the org contact security@codeswhat.com, cascading to every repo without a local one. Onboarding checklist gains the cascade-first rule and the Discussions on/off split for product vs meta repos. * test(community): assert the code of conduct in the community-health contract --- .../tests/community_health_contract_test.py | 12 ++ CODE_OF_CONDUCT.md | 128 ++++++++++++++++++ REPOSITORY_ONBOARDING.md | 8 ++ 3 files changed, 148 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/.github/tests/community_health_contract_test.py b/.github/tests/community_health_contract_test.py index 7d36a25..69c2020 100644 --- a/.github/tests/community_health_contract_test.py +++ b/.github/tests/community_health_contract_test.py @@ -13,6 +13,7 @@ def test_required_default_files_exist(self): required = ( "SECURITY.md", "CONTRIBUTING.md", + "CODE_OF_CONDUCT.md", ".github/CODEOWNERS", ".github/markdownlint-profile.yaml", ".github/ISSUE_TEMPLATE/bug_report.yml", @@ -66,6 +67,17 @@ def test_contributor_guide_matches_org_workflow(self): ): self.assertIn(expected, guide) + def test_code_of_conduct_has_org_contact_and_attribution(self): + conduct = self.read_text("CODE_OF_CONDUCT.md") + + for expected in ( + "Contributor Covenant", + "security@codeswhat.com", + "monitored for both security and conduct reports", + "## Enforcement", + ): + self.assertIn(expected, conduct) + def test_issue_forms_have_unique_ids_and_required_reproduction_fields(self): bug_report = self.read_text(".github/ISSUE_TEMPLATE/bug_report.yml") feature_request = self.read_text( diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..8d99e9f --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +**** (monitored for both security and conduct reports). +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +. Translations are available at +. diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index 8929480..f0bfd3b 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -48,6 +48,14 @@ repositories. Language-specific tests do not. planning details in it. - [ ] Add `CONTRIBUTING.md` when the repository accepts contributions. It must agree with `AGENTS.md` about commands, branches, reviews, tests, and commits. +- [ ] Rely on this repository's org-default community-health files + (CONTRIBUTING baseline, `SECURITY.md`, issue forms, PR template, + `CODE_OF_CONDUCT.md`). Add a local override only when the repository needs + repo-specific content, never as a reflex copy. +- [ ] Public product repositories: enable GitHub Discussions and state the + routing in the README's Community section (durable bugs and feature + requests go to Issues, open-ended Q&A and ideas to Discussions, chat to + Discord). Meta and infrastructure repositories keep Discussions off. - [ ] Add tool-specific contributor instructions only when the tool is used. For example, `CLAUDE.md` can supplement `AGENTS.md`, but it does not replace the required `AGENTS.md`. From dd74a99506bd364b882b8e064744f1f1e1a3d93d Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Thu, 20 Aug 2026 18:58:45 -0400 Subject: [PATCH 16/44] feat(workflows): add the shared star-chart refresh reusable workflow (#32) * feat(workflows): add the shared star-chart refresh reusable workflow Replaces both retired star-chart engines org-wide. The chart becomes a first-party SVG generated from GitHub's own stargazer timestamps and committed into the consuming repository, so it needs no secret and makes no request at render time. That property is the point. A live route that loses its credential serves a plausible placeholder at HTTP 200 forever with nothing reporting red, which is exactly how drydock's chart sat broken. A committed artifact fails visibly or not at all. The generator is embedded in the workflow rather than checked out from a second repository, so a caller's SHA pin covers every line of behaviour with nothing resolved at run time. Verified against live data before committing: byte-identical output to the reference implementation for drydock at 238 stars and 3 API calls, and a clean no-op exit on a repo with a single star. - feat(workflows): starchart-refresh.yml, egress-blocked to api.github.com and github.com, contents: write as its only elevated scope - test(workflows): contract test covering the embedded generator, env-var input handling, the self-contained SVG, and the conditional commit-back - ci(validation): run the new contract test in standards validation - docs(onboarding): document the caller shape and why the artifact is committed rather than served * test(workflows): syntax-check the embedded star-chart generator This workflow never runs in this repository, so a syntax error inside the heredoc would first surface in a consumer's scheduled job, days later and in someone else's lane. The test recovers the generator the way the shell will actually see it, stripping the run block's base indentation rather than reading the file as written, since a heredoc body that looks correct in YAML can still reach node malformed. Then node --check parses it. Verified with a negative control rather than assumed: injecting a syntax error into the generator fails the test, and reverting passes it. * fix(workflows): reject the inputs that would publish a wrong star chart All three from CodeRabbit on #32, and the max-pages one was a real bug of exactly the kind this workflow exists to prevent. max-pages: 0 made pages 0, which fetched nothing, which hit the "too few stars" clean exit. A repository with 238 stars would have reported a green no-op. A cap below the needed page count was worse than that: it drew a chart from the first N pages and published a partial history as a whole one behind a ::warning:: nobody reads. Both now fail loudly, and the cap must be a positive integer. branch had no runtime guard. Omitting a default only prevents omission, so a caller could still pass main and, on a repository whose ruleset let the push through, commit straight to the default branch. Rejected before checkout rather than at the push, where the error would be confusing. output-path was read through the environment, which stops script injection but not traversal. An absolute or ../ path reached writeFileSync outside the checkout, and the commit step then found nothing staged and reported success. Writes now use the resolved and validated path rather than the raw input, since a check that doesn't govern the write is decoration. Verified behaviourally, not by reading: each rejected input throws, the one-star exit still no-ops, nothing lands outside the workspace, and the happy path is still byte-identical to the reference output for drydock. --- .../tests/starchart_refresh_contract_test.py | 203 +++++++++++++++ .github/workflows/standards-validation.yml | 1 + .github/workflows/starchart-refresh.yml | 232 ++++++++++++++++++ REPOSITORY_ONBOARDING.md | 13 + 4 files changed, 449 insertions(+) create mode 100644 .github/tests/starchart_refresh_contract_test.py create mode 100644 .github/workflows/starchart-refresh.yml diff --git a/.github/tests/starchart_refresh_contract_test.py b/.github/tests/starchart_refresh_contract_test.py new file mode 100644 index 0000000..1454c19 --- /dev/null +++ b/.github/tests/starchart_refresh_contract_test.py @@ -0,0 +1,203 @@ +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = ROOT / ".github/workflows/starchart-refresh.yml" + + +class StarchartRefreshContractTest(unittest.TestCase): + def test_reusable_workflow_shape_and_narrow_permissions(self): + workflow = self.read_workflow() + + for expected in ( + " workflow_call:\n", + " branch:\n", + " required: true\n", + " output-path:\n", + " default: docs/assets/star-history.svg\n", + " max-pages:\n", + " type: number\n", + "permissions: {}", + " runs-on: ubuntu-24.04", + " timeout-minutes: 10", + "uses: step-security/harden-runner@", + "egress-policy: block", + "api.github.com:443", + "github.com:443", + ): + self.assertIn(expected, workflow) + + # contents: write is the whole point of this workflow, but it must be + # the ONLY elevated scope. A second write scope here would be a + # commit-back job that can also move issues, releases, or packages. + job_scopes = re.findall(r"^ (\w[\w-]*): write", workflow, re.MULTILINE) + self.assertEqual(job_scopes, ["contents"]) + + def test_generator_is_embedded_rather_than_fetched_at_run_time(self): + """The caller pins this file by SHA. Anything resolved at run time + escapes that pin, so the generator lives inline and the only network + reads are GitHub's own API.""" + workflow = self.read_workflow() + + self.assertIn("node --input-type=module - <<'GENERATOR'", workflow) + self.assertIn("application/vnd.github.star+json", workflow) + self.assertIn("https://api.github.com/", workflow) + + # No second repository checkout, and no curl/wget/npm pulling code in. + self.assertEqual(workflow.count("actions/checkout@"), 1) + self.assertNotIn("repository: CodesWhat/.github", workflow) + for forbidden in ("curl ", "wget ", "npx ", "npm install", "pip install"): + self.assertNotIn(forbidden, workflow) + + def test_untrusted_input_is_read_from_the_environment(self): + """Caller-controlled values reach the script as env vars, never as + ${{ }} interpolated into a shell or JavaScript body.""" + workflow = self.read_workflow() + + for expected in ( + "TARGET_REPO: ${{ github.repository }}", + "OUTPUT_PATH: ${{ inputs.output-path }}", + "MAX_PAGES: ${{ inputs.max-pages }}", + "TARGET_BRANCH: ${{ inputs.branch }}", + "const repo = process.env.TARGET_REPO", + "const out = process.env.OUTPUT_PATH", + ): + self.assertIn(expected, workflow) + + generator = workflow.split("<<'GENERATOR'", 1)[1].split("GENERATOR", 1)[0] + self.assertNotIn("${{", generator) + + def test_chart_is_self_contained_with_no_external_references(self): + """A committed artifact that reaches out at render time would + reintroduce exactly the silent failure this replaced.""" + workflow = self.read_workflow() + + self.assertIn(" maxPages)", workflow) + self.assertNotIn("Math.min(Math.ceil(total / 100), maxPages)", workflow) + self.assertNotIn("::warning::capping", workflow) + + def test_too_few_stars_is_a_clean_exit_not_a_failure(self): + """A young repo having one star is a real state, not a broken build. + Reporting red there trains people to ignore the signal.""" + workflow = self.read_workflow() + + self.assertIn("if (stars.length < 2)", workflow) + self.assertIn("process.exit(0)", workflow) + self.assertNotIn("process.exit(1)", workflow) + self.assertNotIn("process.exit(2)", workflow) + + def test_embedded_generator_is_valid_javascript(self): + """This workflow never runs in this repository, so a syntax error in + the heredoc would first surface in a consumer's scheduled job. Parse + it here instead.""" + node = shutil.which("node") + if node is None: + self.skipTest("node is not available") + + source = self.read_generator() + with tempfile.TemporaryDirectory() as tmp: + script = Path(tmp) / "generator.mjs" + script.write_text(source) + result = subprocess.run( + [node, "--check", str(script)], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_workflow_pins_actions_and_is_run_by_standards_validation(self): + workflow = self.read_workflow() + actions = re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE) + + self.assertTrue(actions) + for action in actions: + self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") + + validation = (ROOT / ".github/workflows/standards-validation.yml").read_text() + self.assertIn("starchart_refresh_contract_test.py", validation) + + def read_workflow(self): + self.assertTrue(WORKFLOW.is_file(), f"missing workflow: {WORKFLOW}") + return WORKFLOW.read_text() + + def read_generator(self): + """Recover the generator exactly as the shell will see it: YAML strips + the run block's base indentation, so a heredoc body that only looks + right in the file can still reach node malformed.""" + workflow = self.read_workflow() + opener = "node --input-type=module - <<'GENERATOR'\n" + self.assertIn(opener, workflow) + + indent = " " * (len(workflow.split(opener)[0].rsplit("\n", 1)[-1])) + self.assertTrue(indent, "expected the run block to be indented") + + body = workflow.split(opener, 1)[1].split(f"\n{indent}GENERATOR", 1)[0] + return "\n".join( + line[len(indent):] if line.startswith(indent) else line + for line in body.split("\n") + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 0ea5ad0..3966ebe 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -53,6 +53,7 @@ jobs: python3 .github/tests/greptile_config_contract_test.py python3 .github/tests/quality_report_contract_test.py python3 .github/tests/reusable_ci_contract_test.py + python3 .github/tests/starchart_refresh_contract_test.py - name: Lint Markdown run: | diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml new file mode 100644 index 0000000..8517969 --- /dev/null +++ b/.github/workflows/starchart-refresh.yml @@ -0,0 +1,232 @@ +name: Star Chart Refresh + +# Regenerates a repository's star-history chart as a first-party SVG and +# commits it back. The chart is a committed artifact on purpose: it needs no +# secret and no request at render time, so it cannot fail silently the way a +# live route or a third-party embed can (standards/readme-shape.md). +# +# Callers declare their own triggers and pin this file by full commit SHA: +# +# on: +# schedule: [{cron: "17 6 * * 1"}] +# workflow_dispatch: +# permissions: {} +# jobs: +# starchart: +# permissions: +# contents: write +# uses: CodesWhat/.github/.github/workflows/starchart-refresh.yml@ +# with: +# branch: dev/v1.7 +# +# The generator is embedded rather than checked out from a second repository +# so that the caller's SHA pin covers every line of behaviour, with nothing +# resolved at run time. + +on: + workflow_call: + inputs: + branch: + description: Branch to read and commit the refreshed chart to. Never main under the strict release flow. + required: true + type: string + output-path: + description: Path the SVG is written to, relative to the repository root. + required: false + default: docs/assets/star-history.svg + type: string + max-pages: + description: Safety cap on stargazer pages fetched (100 stars per page). + required: false + default: 100 + type: number + +permissions: {} + +jobs: + refresh: + name: Star Chart Refresh + runs-on: ubuntu-24.04 + timeout-minutes: 10 + concurrency: + group: starchart-refresh-${{ github.repository }}-${{ inputs.branch }} + cancel-in-progress: false + permissions: + contents: write # Commit the regenerated SVG back to the caller's branch. + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: block + allowed-endpoints: > + api.github.com:443 + github.com:443 + + - name: Reject a protected branch as the commit-back target + env: + TARGET_BRANCH: ${{ inputs.branch }} + run: | + set -euo pipefail + # Omitting a default only prevents omission. Under the strict + # release flow nothing commits back to a default branch, and a + # named rejection here beats a confusing push rejection at the end + # of the job, or none at all on a repo that forgot its ruleset. + case "${TARGET_BRANCH#refs/heads/}" in + main | master | HEAD | "") + echo "::error::refusing to commit the chart to '$TARGET_BRANCH'; pass an integration branch such as dev/v1.7" >&2 + exit 1 + ;; + esac + + - name: Check out the caller at the target branch + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.branch }} + # Kept, unlike everywhere else in this org: the whole job is a + # commit-back, so the pushing credential has to survive checkout. + persist-credentials: true # zizmor: ignore[artipacked] + + - name: Generate the star-history SVG + env: + # Read via the environment, never interpolated into the script body. + TARGET_REPO: ${{ github.repository }} + OUTPUT_PATH: ${{ inputs.output-path }} + MAX_PAGES: ${{ inputs.max-pages }} + GITHUB_API_TOKEN: ${{ github.token }} + run: | + node --input-type=module - <<'GENERATOR' + import { mkdirSync, writeFileSync } from 'node:fs' + import { dirname, isAbsolute, relative, resolve } from 'node:path' + + const repo = process.env.TARGET_REPO + const out = process.env.OUTPUT_PATH + const maxPages = Number(process.env.MAX_PAGES) + const auth = process.env.GITHUB_API_TOKEN + const workspace = process.env.GITHUB_WORKSPACE + + // Reading through the environment stops script injection but not + // path traversal. A write outside the checkout is worse than an + // error: the commit step finds nothing staged and reports success. + const target = resolve(workspace, out) + if (isAbsolute(out) || relative(workspace, target).startsWith('..')) { + throw new Error(`output-path must stay inside the repository: ${out}`) + } + if (!Number.isInteger(maxPages) || maxPages < 1) { + throw new Error(`max-pages must be a positive integer, got: ${process.env.MAX_PAGES}`) + } + + const api = async (path, accept) => { + const res = await fetch(`https://api.github.com/${path}`, { + headers: { + accept, + authorization: `Bearer ${auth}`, + 'user-agent': 'codeswhat-starchart', + 'x-github-api-version': '2022-11-28', + }, + }) + if (!res.ok) throw new Error(`GET ${path} -> ${res.status} ${res.statusText}`) + return res.json() + } + + const total = (await api(`repos/${repo}`, 'application/vnd.github+json')).stargazers_count + const pages = Math.ceil(total / 100) + // Truncating is a hard failure, not a warning. A chart drawn from + // the first N pages is a partial history rendered as a whole one, + // and a log line nobody reads is how that ships unnoticed. + if (pages > maxPages) { + throw new Error( + `${repo} has ${total} stars needing ${pages} pages but max-pages is ${maxPages}; ` + + 'raise the cap rather than publishing a truncated history', + ) + } + + const stars = [] + for (let p = 1; p <= pages; p++) { + const page = await api( + `repos/${repo}/stargazers?per_page=100&page=${p}`, + 'application/vnd.github.star+json', + ) + for (const s of page) if (s.starred_at) stars.push(new Date(s.starred_at).getTime()) + } + stars.sort((a, b) => a - b) + + // Too few points to plot is a real state for a young repo, not a + // failure. Leaving the previous SVG in place beats committing an + // empty chart or reporting red on nothing being wrong. + if (stars.length < 2) { + console.log(`::notice::${repo} has ${stars.length} star(s); leaving the chart untouched`) + process.exit(0) + } + + const W = 800, H = 400, P = { t: 30, r: 30, b: 45, l: 60 } + const [t0, t1] = [stars[0], stars.at(-1)] + const x = (t) => P.l + ((t - t0) / (t1 - t0 || 1)) * (W - P.l - P.r) + const y = (n) => H - P.b - (n / stars.length) * (H - P.t - P.b) + + const pts = stars.map((t, i) => `${x(t).toFixed(1)},${y(i + 1).toFixed(1)}`) + const line = `M ${x(t0).toFixed(1)},${y(0).toFixed(1)} L ${pts.join(' L ')}` + const area = `${line} L ${x(t1).toFixed(1)},${(H - P.b).toFixed(1)} L ${x(t0).toFixed(1)},${(H - P.b).toFixed(1)} Z` + + const fmt = (ms) => new Date(ms).toISOString().slice(0, 7) + const ticks = 4 + const xLabels = Array.from({ length: ticks + 1 }, (_, i) => { + const t = t0 + ((t1 - t0) * i) / ticks + // Anchor the end labels inward so they can't clip the viewBox edges. + const anchor = i === 0 ? 'start' : i === ticks ? 'end' : 'middle' + return `${fmt(t)}` + }).join('\n ') + const yLabels = Array.from({ length: ticks + 1 }, (_, i) => { + const n = Math.round((stars.length * i) / ticks) + return ` + ${n}` + }).join('\n ') + + // Write the path that was validated, not the raw input. In Actions + // the working directory is the workspace so they agree, but a + // check that doesn't govern the write is decoration. + mkdirSync(dirname(target), { recursive: true }) + writeFileSync(target, ` + Star history for ${repo} + + + ${repo} · ${stars.length} stars + + ${yLabels} + + + + + ${xLabels} + + + `) + console.log(`${repo}: ${stars.length} stars, ${pages} API call(s) -> ${out}`) + GENERATOR + + - name: Commit the chart only when it actually changed + env: + OUTPUT_PATH: ${{ inputs.output-path }} + TARGET_BRANCH: ${{ inputs.branch }} + run: | + set -euo pipefail + # --porcelain rather than `git diff`, which reports clean for a + # path that is new and therefore still untracked on first run. + if [ -z "$(git status --porcelain -- "$OUTPUT_PATH")" ]; then + echo "::notice::chart unchanged; nothing to commit" + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add -- "$OUTPUT_PATH" + git commit -m "chore(docs): refresh the star-history chart" + git push origin "HEAD:$TARGET_BRANCH" diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index f0bfd3b..896dda6 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -215,6 +215,19 @@ Add these only when the behavior exists: with a clear enforced or advisory threshold. - [ ] Translation synchronization only for a repository with a translation source of truth and configured provider credentials. +- [ ] Star-history chart refresh for a public repository whose README carries a + Star History section. Call this repository's `starchart-refresh.yml` at a + pinned full commit SHA from a thin caller on `schedule` plus + `workflow_dispatch`, granting the job `contents: write` and passing the + active integration branch as `branch`. It regenerates a first-party SVG from + GitHub's stargazer timestamps and commits it only when the chart actually + changed. The chart is a committed artifact rather than a live route or a + third-party embed on purpose: it needs no secret and makes no request at + render time, so a stale one is visible and a missing one is a visibly broken + image, where a route that loses its credential serves a plausible placeholder + at HTTP 200 indefinitely. Do not embed `star-history.com` or `warpchart.dev`; + both are retired organization-wide, and adopting the chart means removing + what it replaced in the same change. ### Qlty From 79801afde32380fa5797d6daedbffc65dfca2a92 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 21 Aug 2026 10:28:55 -0400 Subject: [PATCH 17/44] Main-is-released check, and the codified star-chart shape (#34) * ci(standards): assert main points at a release tag Reusable workflow for the invariant behind "main is the released version, not the newest work": every commit on main is a tagged release, so an untagged main head is itself the alarm. Callers pin it by SHA and run it on a schedule plus push to main. It separates three states that all look like "not tagged" from the outside. A repository with zero tags cannot be evaluated at all and says so rather than reporting drift. A drifted main reports the newest reachable tag and how many commits it is behind. A prerelease on main is its own failure by default, since a release candidate on the default branch is the exact drift this exists to catch. Read-only: contents: read, egress blocked to github.com, and no credentials persisted through checkout. fetch-depth: 0 because tags only travel with full history and a shallow clone would fail for the wrong reason and read as real drift. * ci(starchart): render the codified chart shape in both themes Scott drew the target and it is now the renderer. The chart reads as native GitHub UI rather than as a third-party embed: a 900x460 card on GitHub's own border colour, sans for the words and mono for every number, a 2px accent line over a faint gradient, interior gridlines and a solid baseline. The accent is the repository's logo colour, passed as a new required input, and an accent that is not a colour now fails instead of drawing a chart with no line. Three behaviours the renderer decides rather than hard-codes, each because the naive version produced something wrong on a real repository. The y-axis searches step-and-tick-count pairs, since rounding the step alone put drydock's 239 stars on a 0-400 axis with the curve in the bottom 60% of the plot. The curve is a monotone cubic, since a cardinal spline overshoots on a curve this flat and an overshoot on a cumulative count draws a dip that never happened. X labels drop to day precision when month names collide, which is the actual condition rather than a guessed span threshold. Two files ship now, not one. GitHub's theme toggle does not reach a media query inside an -embedded SVG, so a self-theming file shows a white card to anyone reading GitHub dark with a light OS. It does drive a element in the README, so the pair is generated from one fetch and the markup chooses. They commit together or not at all: a with a fresh light chart and a stale dark one shows two different histories depending on who is looking, and nothing reports it. The documented trigger moves from a cron to the release cut. A committed artifact refreshed on a schedule mutates underneath a tag, which is what the main-is-released rule forbids. The renderer block is generated from ops render-chart.mjs by splice-into-workflow.mjs rather than hand-copied, and byte parity with that module was verified against live drydock data before this landed. Also fixes an assertion in the main-is-released test that sliced the whole if-block as the decisive expression and so could never pass. * docs(onboarding): add the main-is-released caller to the section 4 checklist --- .../tests/main_is_released_contract_test.py | 93 +++++ .../tests/starchart_refresh_contract_test.py | 64 ++- .github/workflows/main-is-released.yml | 92 +++++ .github/workflows/standards-validation.yml | 1 + .github/workflows/starchart-refresh.yml | 376 +++++++++++++++--- REPOSITORY_ONBOARDING.md | 77 +++- 6 files changed, 639 insertions(+), 64 deletions(-) create mode 100644 .github/tests/main_is_released_contract_test.py create mode 100644 .github/workflows/main-is-released.yml diff --git a/.github/tests/main_is_released_contract_test.py b/.github/tests/main_is_released_contract_test.py new file mode 100644 index 0000000..c9368b2 --- /dev/null +++ b/.github/tests/main_is_released_contract_test.py @@ -0,0 +1,93 @@ +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = ROOT / ".github/workflows/main-is-released.yml" + + +class MainIsReleasedContractTest(unittest.TestCase): + def test_reusable_workflow_shape_and_read_only_permissions(self): + workflow = self.read_workflow() + + for expected in ( + " workflow_call:\n", + "permissions: {}", + " runs-on: ubuntu-24.04", + "uses: step-security/harden-runner@", + "egress-policy: block", + "github.com:443", + " contents: read", + ): + self.assertIn(expected, workflow) + + # This check only ever reads. Any write scope here would be a + # scheduled job with credentials to change the thing it audits. + self.assertNotIn(": write", workflow) + self.assertNotIn("persist-credentials: true", workflow) + + def test_the_invariant_is_an_exact_tag_match(self): + workflow = self.read_workflow() + + self.assertIn("git describe --exact-match --tags HEAD", workflow) + # --abbrev=0 alone answers "what tag is nearest", which is true of a + # drifted main too. It may only be used to report inside the failure + # branch, never in the condition that decides pass or fail — so the + # decisive slice is the condition line, not the whole if-block. + decisive = workflow.split("if ! tag=", 1)[1].split("\n", 1)[0] + self.assertIn("--exact-match", decisive) + self.assertNotIn("--abbrev=0", decisive) + + def test_no_tags_is_reported_as_unevaluable_not_as_drift(self): + """A repo with zero tags produces the same 'not tagged' as one that + drifted. Those need different answers, so the measurement proves it + could have worked before its result is trusted.""" + workflow = self.read_workflow() + + self.assertIn('if [ -z "$(git tag)" ]; then', workflow) + self.assertLess( + workflow.index('if [ -z "$(git tag)" ]'), + workflow.index("git describe --exact-match"), + ) + + def test_shallow_checkout_would_break_the_measurement(self): + """describe needs tags and history; a shallow clone fails for the + wrong reason and reads as real drift.""" + workflow = self.read_workflow() + self.assertIn("fetch-depth: 0", workflow) + + def test_a_prerelease_on_main_fails_by_default(self): + """A release candidate on the default branch is the exact drift this + exists to catch: drydock's main sat on v1.7.0-rc.2.""" + workflow = self.read_workflow() + + self.assertIn(" default: false\n", workflow) + self.assertIn('if [ "$ALLOW_PRERELEASE" != "true" ]', workflow) + self.assertIn("ALLOW_PRERELEASE: ${{ inputs.allow-prerelease }}", workflow) + + def test_failures_say_what_to_do_next(self): + workflow = self.read_workflow() + + for expected in ("::error::", "cut a release", "dev branch"): + self.assertIn(expected, workflow) + self.assertIn("set -euo pipefail", workflow) + + def test_workflow_pins_actions_and_is_run_by_standards_validation(self): + workflow = self.read_workflow() + actions = re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE) + + self.assertTrue(actions) + for action in actions: + self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") + + validation = (ROOT / ".github/workflows/standards-validation.yml").read_text() + self.assertIn("main_is_released_contract_test.py", validation) + + def read_workflow(self): + self.assertTrue(WORKFLOW.is_file(), f"missing workflow: {WORKFLOW}") + return WORKFLOW.read_text() + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/tests/starchart_refresh_contract_test.py b/.github/tests/starchart_refresh_contract_test.py index 1454c19..8fb137f 100644 --- a/.github/tests/starchart_refresh_contract_test.py +++ b/.github/tests/starchart_refresh_contract_test.py @@ -20,6 +20,7 @@ def test_reusable_workflow_shape_and_narrow_permissions(self): " required: true\n", " output-path:\n", " default: docs/assets/star-history.svg\n", + " accent:\n", " max-pages:\n", " type: number\n", "permissions: {}", @@ -62,10 +63,12 @@ def test_untrusted_input_is_read_from_the_environment(self): for expected in ( "TARGET_REPO: ${{ github.repository }}", "OUTPUT_PATH: ${{ inputs.output-path }}", + "ACCENT: ${{ inputs.accent }}", "MAX_PAGES: ${{ inputs.max-pages }}", "TARGET_BRANCH: ${{ inputs.branch }}", "const repo = process.env.TARGET_REPO", "const out = process.env.OUTPUT_PATH", + "const accent = process.env.ACCENT", ): self.assertIn(expected, workflow) @@ -78,8 +81,13 @@ def test_chart_is_self_contained_with_no_external_references(self): workflow = self.read_workflow() self.assertIn("-embedded SVG, so a self-theming file shows a + # white card to anyone reading GitHub dark with a light OS. Two files + # and a README is the mechanism that does follow the toggle. + self.assertNotIn("prefers-color-scheme", workflow) for forbidden in (" that gained a fresh light chart and kept a stale dark + one shows two different histories depending on who is looking, and + nothing reports it as wrong.""" + workflow = self.read_workflow() + + self.assertIn("writeFileSync(target, light)", workflow) + self.assertIn("writeFileSync(darkTarget, dark)", workflow) + self.assertIn('DARK_PATH="${OUTPUT_PATH%.svg}-dark.svg"', workflow) + self.assertIn('git add -- "$OUTPUT_PATH" "$DARK_PATH"', workflow) + self.assertIn('git status --porcelain -- "$OUTPUT_PATH" "$DARK_PATH"', workflow) + + # Both derivations strip a .svg suffix, so the input has to have one. + self.assertIn("!out.endsWith('.svg')", workflow) + + def test_the_documented_trigger_is_the_release_cut_not_a_cron(self): + """A committed artifact refreshed on a schedule mutates underneath a + tag, which is what 'main is the released version' forbids.""" + workflow = self.read_workflow() + + example = workflow.split("# on:\n", 1)[1].split("# permissions:", 1)[0] + self.assertIn("release:", example) + self.assertIn("types: [published]", example) + self.assertIn('# accent: "#49bcfb"', workflow) + self.assertNotIn("cron", example) + self.assertNotIn("schedule:", example) + + def test_the_embedded_renderer_names_its_source(self): + """The same renderer exists here and in ops. Hand-copying is how they + drift, so the block is generated and says so.""" + workflow = self.read_workflow() + + self.assertIn("// BEGIN GENERATED FROM ops scripts/starchart/render-chart.mjs", workflow) + self.assertIn("// END GENERATED", workflow) + self.assertIn("splice-into-workflow.mjs", workflow) + self.assertLess( + workflow.index("// BEGIN GENERATED"), + workflow.index("// END GENERATED"), + ) + def test_too_few_stars_is_a_clean_exit_not_a_failure(self): """A young repo having one star is a real state, not a broken build. Reporting red there trains people to ignore the signal.""" diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml new file mode 100644 index 0000000..c4bb47e --- /dev/null +++ b/.github/workflows/main-is-released.yml @@ -0,0 +1,92 @@ +name: Main Is Released + +# Asserts the one invariant behind "main is the released version, not the +# newest work": every commit on main is a tagged release, so an untagged main +# head is itself the alarm (REPOSITORY_ONBOARDING.md section 3). +# +# Callers declare their own triggers and pin this file by full commit SHA: +# +# on: +# schedule: [{cron: "23 7 * * *"}] +# push: +# branches: [main] +# workflow_dispatch: +# permissions: {} +# jobs: +# released: +# uses: CodesWhat/.github/.github/workflows/main-is-released.yml@ +# +# Continuously deployed repositories that never tag (a website, a meta repo) +# should not call this at all rather than calling it with a carve-out input. +# For them "main equals production" is enforced by the deploy, not by a tag. + +on: + workflow_call: + inputs: + allow-prerelease: + description: > + Accept a prerelease tag (-rc.N, -beta.N) as satisfying the invariant. + Defaults false: a release candidate on main is the exact drift this + check exists to catch. + required: false + default: false + type: boolean + +permissions: {} + +jobs: + released: + name: Main Is Released + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read # Read main and its tags. + + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: block + allowed-endpoints: > + github.com:443 + + - name: Check out main with tags + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + # Tags only travel with full history; a shallow clone would make + # describe fail for the wrong reason and read as real drift. + fetch-depth: 0 + persist-credentials: false + + - name: Assert main points at a release tag + env: + ALLOW_PRERELEASE: ${{ inputs.allow-prerelease }} + run: | + set -euo pipefail + + # Prove the measurement can work before trusting its result. A repo + # with no tags at all reports the same "not tagged" as one that + # drifted, and those need different answers. + if [ -z "$(git tag)" ]; then + echo "::error::no tags in this repository, so the invariant cannot be evaluated; a repository that never releases should not call this workflow" >&2 + exit 1 + fi + + if ! tag="$(git describe --exact-match --tags HEAD 2>/dev/null)"; then + latest="$(git describe --tags --abbrev=0 HEAD 2>/dev/null || echo '')" + ahead="$(git rev-list --count "${latest}..HEAD" 2>/dev/null || echo '?')" + echo "::error::main is not a tagged release. Newest reachable tag is ${latest}, and main is ${ahead} commit(s) past it. Either cut a release or move the unshipped work to a dev branch." >&2 + exit 1 + fi + + case "$tag" in + *-*) + if [ "$ALLOW_PRERELEASE" != "true" ]; then + echo "::error::main points at prerelease ${tag}. Prereleases belong on the dev branch; main carries what users actually run." >&2 + exit 1 + fi + echo "::warning::main points at prerelease ${tag}, accepted because allow-prerelease is set" ;; + esac + + echo "main is released at ${tag}" diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 3966ebe..425ef4e 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -54,6 +54,7 @@ jobs: python3 .github/tests/quality_report_contract_test.py python3 .github/tests/reusable_ci_contract_test.py python3 .github/tests/starchart_refresh_contract_test.py + python3 .github/tests/main_is_released_contract_test.py - name: Lint Markdown run: | diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index 8517969..3caaf04 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -8,7 +8,8 @@ name: Star Chart Refresh # Callers declare their own triggers and pin this file by full commit SHA: # # on: -# schedule: [{cron: "17 6 * * 1"}] +# release: +# types: [published] # workflow_dispatch: # permissions: {} # jobs: @@ -18,10 +19,19 @@ name: Star Chart Refresh # uses: CodesWhat/.github/.github/workflows/starchart-refresh.yml@ # with: # branch: dev/v1.7 +# accent: "#49bcfb" +# +# The trigger is the release cut, not a cron. A committed artifact refreshed +# on a schedule mutates underneath a tag, which is exactly what "main is the +# released version" forbids. Regenerating at the cut means the chart in a +# released README is as of that release. # # The generator is embedded rather than checked out from a second repository # so that the caller's SHA pin covers every line of behaviour, with nothing -# resolved at run time. +# resolved at run time. It is written by ops +# scripts/starchart/splice-into-workflow.mjs from that repo's +# render-chart.mjs; edit there and re-splice rather than editing the block +# below by hand. on: workflow_call: @@ -31,10 +41,20 @@ on: required: true type: string output-path: - description: Path the SVG is written to, relative to the repository root. + description: > + Path the light SVG is written to, relative to the repository root. + Must end in .svg; the dark sibling is written alongside it with a + -dark suffix. required: false default: docs/assets/star-history.svg type: string + accent: + description: > + The repository's logo colour as #rrggbb. The dark-theme variant is + derived from it, so there is only one value to keep in sync. The + registry is in ops standards/readme-shape.md. + required: true + type: string max-pages: description: Safety cap on stargazer pages fetched (100 stars per page). required: false @@ -87,11 +107,12 @@ jobs: # commit-back, so the pushing credential has to survive checkout. persist-credentials: true # zizmor: ignore[artipacked] - - name: Generate the star-history SVG + - name: Generate the star-history SVGs env: # Read via the environment, never interpolated into the script body. TARGET_REPO: ${{ github.repository }} OUTPUT_PATH: ${{ inputs.output-path }} + ACCENT: ${{ inputs.accent }} MAX_PAGES: ${{ inputs.max-pages }} GITHUB_API_TOKEN: ${{ github.token }} run: | @@ -101,6 +122,7 @@ jobs: const repo = process.env.TARGET_REPO const out = process.env.OUTPUT_PATH + const accent = process.env.ACCENT const maxPages = Number(process.env.MAX_PAGES) const auth = process.env.GITHUB_API_TOKEN const workspace = process.env.GITHUB_WORKSPACE @@ -112,6 +134,17 @@ jobs: if (isAbsolute(out) || relative(workspace, target).startsWith('..')) { throw new Error(`output-path must stay inside the repository: ${out}`) } + // The dark sibling is derived from this path and the commit step + // derives it again in shell. Both derivations assume the suffix. + if (!out.endsWith('.svg')) { + throw new Error(`output-path must end in .svg: ${out}`) + } + // An accent that isn't a colour renders a chart with no line rather + // than failing, which is the silent-success shape this file exists + // to avoid. Reject it here instead. + if (!/^#[0-9a-fA-F]{6}$/.test(accent ?? '')) { + throw new Error(`accent must be a #rrggbb colour, got: ${accent}`) + } if (!Number.isInteger(maxPages) || maxPages < 1) { throw new Error(`max-pages must be a positive integer, got: ${process.env.MAX_PAGES}`) } @@ -159,58 +192,285 @@ jobs: process.exit(0) } - const W = 800, H = 400, P = { t: 30, r: 30, b: 45, l: 60 } - const [t0, t1] = [stars[0], stars.at(-1)] - const x = (t) => P.l + ((t - t0) / (t1 - t0 || 1)) * (W - P.l - P.r) - const y = (n) => H - P.b - (n / stars.length) * (H - P.t - P.b) - - const pts = stars.map((t, i) => `${x(t).toFixed(1)},${y(i + 1).toFixed(1)}`) - const line = `M ${x(t0).toFixed(1)},${y(0).toFixed(1)} L ${pts.join(' L ')}` - const area = `${line} L ${x(t1).toFixed(1)},${(H - P.b).toFixed(1)} L ${x(t0).toFixed(1)},${(H - P.b).toFixed(1)} Z` - - const fmt = (ms) => new Date(ms).toISOString().slice(0, 7) - const ticks = 4 - const xLabels = Array.from({ length: ticks + 1 }, (_, i) => { - const t = t0 + ((t1 - t0) * i) / ticks - // Anchor the end labels inward so they can't clip the viewBox edges. - const anchor = i === 0 ? 'start' : i === ticks ? 'end' : 'middle' - return `${fmt(t)}` - }).join('\n ') - const yLabels = Array.from({ length: ticks + 1 }, (_, i) => { - const n = Math.round((stars.length * i) / ticks) - return ` - ${n}` - }).join('\n ') + // BEGIN GENERATED FROM ops scripts/starchart/render-chart.mjs + // Shared renderer: star timestamps -> self-contained SVG. + // Split out from the fetch layer so the identical code can be exercised + // against fixture data without hitting the API. + // + // The visual shape is fixed (standards/readme-shape.md). The only thing a + // repository varies is `accent`, its logo's main colour. + + const W = 900 + const H = 460 + const PLOT = { l: 62, r: 860, top: 76, base: 408 } + const SAMPLE = 10 // px between resampled points along the curve + + const LIGHT = { + card: '#ffffff', + edge: '#d0d7de', + ink: '#1f2328', + muted: '#656d76', + grid: '#eaeef2', + axis: '#d0d7de', + ylabel: '#8c959f', + } + const DARK = { + card: '#0d1117', + edge: '#30363d', + ink: '#e6edf3', + muted: '#8b949e', + grid: '#21262d', + axis: '#30363d', + ylabel: '#6e7681', + } + + const SANS = "-apple-system,'Segoe UI',Helvetica,Arial,sans-serif" + const MONO = 'ui-monospace,SFMono-Regular,Menlo,monospace' + + const NICE = [1, 2, 2.5, 4, 5, 10] + // Pick a y-axis that reads like a human wrote it (50/100/150/200) AND wastes + // as little of the plot as possible. Rounding the step alone isn't enough: + // 239 stars over 4 ticks rounds to 100, which puts the curve in the bottom + // 60% of a chart whose whole job is showing the curve. So search step-and- + // tick-count pairs and keep the smallest ceiling that clears the total. + const niceAxis = (total) => { + const need = Math.max(total * 1.02, 1) + let best = null + for (let ticks = 3; ticks <= 6; ticks += 1) { + for (let mag = 1; mag <= 10 ** 7; mag *= 10) { + for (const n of NICE) { + const step = n * mag + if (!Number.isInteger(step)) continue + const max = step * ticks + if (max < need) continue + if (!best || max < best.max) best = { step, ticks, max } + break + } + } + } + return best + } + + const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>') + const num = (n) => Number(n.toFixed(1)) + + // "Feb 10 - Aug 21, 2026" when the whole history sits in one year, and both + // years spelled out when it doesn't. The axis below carries month names only, + // so this line is the sole place the year appears in the common case. + const range = (a, b) => { + const [d0, d1] = [new Date(a), new Date(b)] + const [y0, y1] = [d0.getUTCFullYear(), d1.getUTCFullYear()] + const day = (d) => `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}` + return y0 === y1 + ? `${day(d0)} – ${day(d1)}, ${y1}` + : `${day(d0)}, ${y0} – ${day(d1)}, ${y1}` + } + + const srgb = (c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4) + const luminance = (hex) => { + const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255) + return 0.2126 * srgb(r) + 0.7152 * srgb(g) + 0.0722 * srgb(b) + } + const contrast = (a, b) => { + const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) + return (x + 0.05) / (y + 0.05) + } + + const toHsl = (hex) => { + const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255) + const mx = Math.max(r, g, b) + const mn = Math.min(r, g, b) + const l = (mx + mn) / 2 + if (mx === mn) return [0, 0, l] + const d = mx - mn + const s = l > 0.5 ? d / (2 - mx - mn) : d / (mx + mn) + const h = + mx === r ? (g - b) / d + (g < b ? 6 : 0) : mx === g ? (b - r) / d + 2 : (r - g) / d + 4 + return [h / 6, s, l] + } + const channel = (p, q, t0) => { + const t = (t0 + 1) % 1 + if (t < 1 / 6) return p + (q - p) * 6 * t + if (t < 1 / 2) return q + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6 + return p + } + const toHex = (h, s, l) => { + let rgb = [l, l, l] + if (s) { + const q = l < 0.5 ? l * (1 + s) : l + s - l * s + const p = 2 * l - q + rgb = [channel(p, q, h + 1 / 3), channel(p, q, h), channel(p, q, h - 1 / 3)] + } + return `#${rgb.map((v) => Math.round(v * 255).toString(16).padStart(2, '0')).join('')}` + } + + // A logo colour picked against white can vanish on GitHub's dark surface: + // portwing's #7230d2 scores 2.8:1 there. Rather than make every repository + // record two colours and keep them in sync, derive the dark one by raising + // lightness at a fixed hue and saturation until it clears 6:1 — the band + // drydock's untouched #49bcfb already sits in. Lifting lightness rather than + // blending toward white is what keeps sockguard's orange an orange instead of + // fading it to salmon. + const DARK_TARGET = 6 + const forDark = (accent, surface) => { + const [h, s] = toHsl(accent) + let [, , l] = toHsl(accent) + let out = accent + while (contrast(out, surface) < DARK_TARGET && l < 0.92) { + l += 0.02 + out = toHex(h, s, l) + } + return out + } + + // Resample the step function onto an even x grid, then run a monotone cubic + // (Fritsch-Carlson) through it. A plain cardinal spline overshoots on a curve + // this flat, and an overshoot on a cumulative star count draws a dip that + // never happened. + const smoothPath = (points) => { + const n = points.length + const slope = [] + for (let i = 0; i < n - 1; i += 1) { + slope.push((points[i + 1][1] - points[i][1]) / (points[i + 1][0] - points[i][0])) + } + const tan = [slope[0]] + for (let i = 1; i < n - 1; i += 1) { + tan.push(slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2) + } + tan.push(slope[n - 2]) + for (let i = 0; i < n - 1; i += 1) { + if (slope[i] === 0) { + tan[i] = 0 + tan[i + 1] = 0 + continue + } + const a = tan[i] / slope[i] + const b = tan[i + 1] / slope[i] + const s = a * a + b * b + if (s > 9) { + const t = 3 / Math.sqrt(s) + tan[i] = t * a * slope[i] + tan[i + 1] = t * b * slope[i] + } + } + + let d = `M ${num(points[0][0])},${num(points[0][1])}` + for (let i = 0; i < n - 1; i += 1) { + const [x0, y0] = points[i] + const [x1, y1] = points[i + 1] + const h = (x1 - x0) / 3 + d += ` C ${num(x0 + h)},${num(y0 + tan[i] * h)} ${num(x1 - h)},${num(y1 - tan[i + 1] * h)} ${num(x1)},${num(y1)}` + } + return d + } + + const draw = (repo, stars, accent, theme, id) => { + const c = theme === 'dark' ? DARK : LIGHT + const ink = theme === 'dark' ? forDark(accent, c.card) : accent + const total = stars.length + const [t0, t1] = [stars[0], stars.at(-1)] + const { step, ticks, max: yMax } = niceAxis(total) + + const plotW = PLOT.r - PLOT.l + const plotH = PLOT.base - PLOT.top + const x = (t) => PLOT.l + ((t - t0) / (t1 - t0 || 1)) * plotW + const y = (n) => PLOT.base - (n / yMax) * plotH + + // Star i lands at x(stars[i]); between stars the count is flat. Sample that + // step function on an even grid so the spline has uniform spans to work with. + const grid = [] + for (let px = PLOT.l; px < PLOT.r; px += SAMPLE) grid.push(px) + grid.push(PLOT.r) + let seen = 0 + const points = grid.map((px) => { + while (seen < total && x(stars[seen]) <= px) seen += 1 + return [px, y(seen)] + }) + + const linePath = smoothPath(points) + const areaPath = `${linePath} L ${PLOT.r},${PLOT.base} L ${PLOT.l},${PLOT.base} Z` + + const gridLines = Array.from({ length: ticks - 1 }, (_, i) => { + const gy = num(y(step * (i + 1))) + return `` + }).join('') + + const yLabels = Array.from({ length: ticks - 1 }, (_, i) => { + const n = step * (i + 1) + return `${n}` + }).join('') + + const xCount = 5 + const stops = Array.from({ length: xCount }, (_, i) => new Date(t0 + ((t1 - t0) * i) / (xCount - 1))) + // "Feb 26" reads as the 26th of February, and the subtitle already carries + // the years, so month names alone are the default. A history shorter than + // five months puts two stops in one month and prints "Jun Jun Jul Jul Aug", + // so fall back to day precision when the labels collide rather than guess a + // span threshold. Either way a year appears only where one changes. + const name = (d) => MONTHS[d.getUTCMonth()] + const byMonth = stops.map(name) + const withDay = new Set(byMonth).size < byMonth.length + let lastYear = null + const xLabels = stops + .map((d, i) => { + const year = d.getUTCFullYear() + const base = withDay ? `${name(d)} ${d.getUTCDate()}` : name(d) + const label = lastYear !== null && year !== lastYear ? `${base}, ${year}` : base + lastYear = year + const anchor = + i === 0 ? '' : i === xCount - 1 ? ' text-anchor="end"' : ' text-anchor="middle"' + return `${label}` + }) + .join('') + + const [endX, endY] = points.at(-1) + + return ` + Star history for ${esc(repo)} — ${total} stars + + + + + + + + ${esc(repo)} + ${range(t0, t1)} + ${total} + STARS + ${gridLines} + + + + + ${xLabels} + ${yLabels} + + ` + } + + // GitHub's theme toggle does not reach a media query inside an -embedded + // SVG, but it does drive a element in the README. So ship the pair + // and let the markup choose, rather than one file that guesses. + const renderChart = (repo, stars, accent) => ({ + light: draw(repo, stars, accent, 'light', 'sc-light'), + dark: draw(repo, stars, accent, 'dark', 'sc-dark'), + }) + + const darkAccent = (accent) => forDark(accent, DARK.card) + // END GENERATED // Write the path that was validated, not the raw input. In Actions // the working directory is the workspace so they agree, but a // check that doesn't govern the write is decoration. + const darkTarget = target.replace(/\.svg$/, '-dark.svg') + const { light, dark } = renderChart(repo, stars, accent) mkdirSync(dirname(target), { recursive: true }) - writeFileSync(target, ` - Star history for ${repo} - - - ${repo} · ${stars.length} stars - - ${yLabels} - - - - - ${xLabels} - - - `) - console.log(`${repo}: ${stars.length} stars, ${pages} API call(s) -> ${out}`) + writeFileSync(target, light) + writeFileSync(darkTarget, dark) + console.log(`${repo}: ${stars.length} stars, ${pages} API call(s) -> ${out} + dark`) GENERATOR - name: Commit the chart only when it actually changed @@ -219,14 +479,24 @@ jobs: TARGET_BRANCH: ${{ inputs.branch }} run: | set -euo pipefail + DARK_PATH="${OUTPUT_PATH%.svg}-dark.svg" # --porcelain rather than `git diff`, which reports clean for a # path that is new and therefore still untracked on first run. - if [ -z "$(git status --porcelain -- "$OUTPUT_PATH")" ]; then + if [ -z "$(git status --porcelain -- "$OUTPUT_PATH" "$DARK_PATH")" ]; then echo "::notice::chart unchanged; nothing to commit" exit 0 fi + # Both or neither. A README that gained a light chart and + # kept a stale dark one shows two different histories depending on + # who is looking, and neither is flagged as wrong. + for path in "$OUTPUT_PATH" "$DARK_PATH"; do + if [ ! -f "$path" ]; then + echo "::error::expected $path to exist after generation" >&2 + exit 1 + fi + done git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add -- "$OUTPUT_PATH" + git add -- "$OUTPUT_PATH" "$DARK_PATH" git commit -m "chore(docs): refresh the star-history chart" git push origin "HEAD:$TARGET_BRANCH" diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index 896dda6..40809ad 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -142,6 +142,44 @@ checks stay non-required, is in the Qlty subsection of section 4. ## 3. Protect `main` +`main` is the released version, not the newest work. It always equals what +users currently have: the GA tag on a versioned product, production on a +continuously deployed site. It is never the GA tag plus merged work that has +not shipped. The next version lives on its own branch, `dev/vX.Y`, which is +the integration target for every feature pull request, and prereleases are +tagged there rather than on `main`. + +The reason is measurement accuracy rather than tidiness. OpenSSF Scorecard, +CodeQL default-branch analysis, Dependabot alerts, README badges, and every +published vulnerability report describe the default branch and nothing else. +Unshipped work on `main` makes all of them describe software no user runs. + +One invariant covers it, and it is mechanical rather than a judgement call: + +```sh +git describe --exact-match origin/main +``` + +Every commit on `main` is a tagged release, so an untagged `main` head is +itself the alarm. Check the tag rather than auditing what a promotion diff +contains. Call this repository's `main-is-released.yml` on a schedule to +enforce it; see section 4. + +`main` advances only through a promotion pull request from `dev/*` or +`maintenance/*` that is tagged on merge. There is no documentation, README, or +generated-asset exception: a second path into `main` is a second thing that +drifts, and an incorrect README is a defect in the released version like any +other. Fix it on a hotfix branch and cut a patch release. For that to stay +honest, a documentation-only release must skip artifact publication — +GoReleaser, signing, deb/rpm, Homebrew, npm — or maintainers will route around +the rule. Generated assets committed to the repository, such as a star-history +chart, regenerate at the release cut rather than on a schedule that commits to +a branch, so they cannot change underneath a tag. + +Adopting this on a repository whose `main` is already ahead of its newest tag +means either cutting a release or resetting `main` to the last released tag. +That is the maintainer's decision, because it changes what every user sees. + Create an active branch ruleset named `Main branch protection`, targeting only the default branch. Its baseline is: @@ -215,19 +253,38 @@ Add these only when the behavior exists: with a clear enforced or advisory threshold. - [ ] Translation synchronization only for a repository with a translation source of truth and configured provider credentials. +- [ ] Release-invariant enforcement for a repository that tags releases. Call + this repository's `main-is-released.yml` at a pinned full commit SHA from a + thin caller on `schedule` plus `push` to `main` plus `workflow_dispatch`. The + called workflow declares `contents: read` itself, and a reusable workflow can + only narrow what the caller grants, so the caller needs no `permissions` + block beyond the top-level `permissions: {}` — a job-level grant would only + widen the ceiling it runs under. It asserts the section 3 invariant: an + untagged `main` head fails, and so does a prerelease tag unless the caller + passes `allow-prerelease: true`. A repository that never tags, such as a + continuously deployed site or a meta repository, should not call this at all + rather than call it with a carve-out; for those, "`main` equals production" + is enforced by the deploy. - [ ] Star-history chart refresh for a public repository whose README carries a Star History section. Call this repository's `starchart-refresh.yml` at a - pinned full commit SHA from a thin caller on `schedule` plus + pinned full commit SHA from a thin caller on `release: [published]` plus `workflow_dispatch`, granting the job `contents: write` and passing the - active integration branch as `branch`. It regenerates a first-party SVG from - GitHub's stargazer timestamps and commits it only when the chart actually - changed. The chart is a committed artifact rather than a live route or a - third-party embed on purpose: it needs no secret and makes no request at - render time, so a stale one is visible and a missing one is a visibly broken - image, where a route that loses its credential serves a plausible placeholder - at HTTP 200 indefinitely. Do not embed `star-history.com` or `warpchart.dev`; - both are retired organization-wide, and adopting the chart means removing - what it replaced in the same change. + active integration branch as `branch` and the repository's logo colour as + `accent`. It regenerates a first-party SVG pair from GitHub's stargazer + timestamps and commits only when the chart actually changed. The trigger is + the release cut rather than a schedule because a committed artifact + refreshed on a cron mutates underneath a tag, which section 3 forbids. The + chart is a committed artifact rather than a live route or a third-party + embed on purpose: it needs no secret and makes no request at render time, so + a stale one is visible and a missing one is a visibly broken image, where a + route that loses its credential serves a plausible placeholder at HTTP 200 + indefinitely. Two files ship, `star-history.svg` and `star-history-dark.svg`, + because GitHub's theme toggle does not reach a media query inside an + ``-embedded SVG but does drive a `` element in the README, so + the markup chooses and the `` stays the fallback for anything that does + not understand ``. Do not embed `star-history.com` or + `warpchart.dev`; both are retired organization-wide, and adopting the chart + means removing what it replaced in the same change. ### Qlty From 58c1fd46ba9122abe426f0b0cfdd261c1653c55e Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Fri, 21 Aug 2026 13:53:31 -0400 Subject: [PATCH 18/44] fix(workflows): close three shared-workflow defects (#36) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(workflows): close three shared-workflow defects starchart-refresh: the documented `release: [published]` trigger never fires. GitHub suppresses workflow runs for events caused by GITHUB_TOKEN, and every consuming repo publishes its release with exactly that — portwing via GoReleaser, drydock via `gh release create`. A caller wired from this file's own example lints clean, reads as correctly configured, and refreshes nothing forever. That's the silent-success shape the committed-SVG rework existed to remove, reintroduced by the instructions for it. Example is now a workflow_dispatch the release cut fires, with the suppression and its two documented exceptions written down so the next person doesn't rederive the broken version. Found by the sockguard lane after three repos had been told to adopt it. main-is-released: an exact tag match alone was never the invariant. Any tag satisfied it, so one named `snapshot` or `latest` parked on a drifted main read as a pass. Now requires a release-shaped version. Prerelease detection moved off `case *-*`, which called `my-tag` a prerelease and would have accepted it under allow-prerelease. main-is-released: a promotion merges before its tag is pushed, so a run in that window reported drift that resolved itself seconds later. Three attempts with a tag refetch between them. It can't mask real drift — an untagged main is still untagged on the last attempt — and a failed refetch warns rather than passing. Verified by extracting the decision block and running it against real repositories: v1.7.4 and 1.7.4 pass, snapshot/latest/my-tag fail as malformed, v1.7.0-rc.2 fails as prerelease and passes under allow-prerelease, and allow-prerelease does not reopen the any-tag hole. 87 contract tests green. * fix(workflows): correct two overstated claims CodeRabbit caught The refetch warning said the verdict uses the refs from checkout. It might not: attempt 1 can succeed and attempt 2 fail, and a failed fetch can leave some refs updated. Now says the refs currently available on the runner, which is what's actually true. 'The two documented exceptions to the suppression' was an overclaim. pull_request with opened/synchronize/reopened is a third — it creates a run in an approval-required state rather than being suppressed. workflow_dispatch and repository_dispatch are the two that fire UNATTENDED, which is the property a release cut actually needs, so the comment now says that instead. --- .../tests/main_is_released_contract_test.py | 34 ++++++++++++- .../tests/starchart_refresh_contract_test.py | 39 ++++++++++++--- .github/workflows/main-is-released.yml | 48 +++++++++++++++---- .github/workflows/starchart-refresh.yml | 43 ++++++++++++++--- 4 files changed, 140 insertions(+), 24 deletions(-) diff --git a/.github/tests/main_is_released_contract_test.py b/.github/tests/main_is_released_contract_test.py index c9368b2..3a6fbc5 100644 --- a/.github/tests/main_is_released_contract_test.py +++ b/.github/tests/main_is_released_contract_test.py @@ -35,7 +35,7 @@ def test_the_invariant_is_an_exact_tag_match(self): # drifted main too. It may only be used to report inside the failure # branch, never in the condition that decides pass or fail — so the # decisive slice is the condition line, not the whole if-block. - decisive = workflow.split("if ! tag=", 1)[1].split("\n", 1)[0] + decisive = workflow.split('if tag="$(', 1)[1].split("\n", 1)[0] self.assertIn("--exact-match", decisive) self.assertNotIn("--abbrev=0", decisive) @@ -57,6 +57,38 @@ def test_shallow_checkout_would_break_the_measurement(self): workflow = self.read_workflow() self.assertIn("fetch-depth: 0", workflow) + def test_an_exact_match_alone_is_not_the_invariant(self): + """Any tag satisfies --exact-match, including a moving or descriptive + one. A tag literally named `snapshot` parked on a drifted main reads + as a clean pass, which is the exact failure this workflow exists to + catch. Found by the sockguard lane, 2026-08-21.""" + workflow = self.read_workflow() + + self.assertIn("[0-9]+\\.[0-9]+\\.[0-9]+", workflow) + self.assertIn("not a release version tag", workflow) + + # Prerelease detection keys on the hyphen AFTER the version, not any + # hyphen anywhere — the old `case $tag in *-*)` called `my-tag` a + # prerelease and would have accepted it under allow-prerelease. + self.assertNotIn('case "$tag" in', workflow) + self.assertIn("^v?[0-9]+\\.[0-9]+\\.[0-9]+-", workflow) + + def test_the_merge_to_tag_window_is_retried_not_reported_as_drift(self): + """A promotion merges before its tag is pushed. A run landing in that + window sees an untagged main and reports drift that resolves itself + seconds later, which trains people to ignore the one check whose job + is being noticed.""" + workflow = self.read_workflow() + + self.assertIn("for attempt in 1 2 3", workflow) + self.assertIn("git fetch --tags --force", workflow) + self.assertIn("sleep 20", workflow) + + # The retry must not become a way to pass. A failed refetch is warned + # about and the loop still decides on the refs it has. + self.assertIn("::warning::could not refetch tags", workflow) + self.assertNotIn("exit 0", workflow) + def test_a_prerelease_on_main_fails_by_default(self): """A release candidate on the default branch is the exact drift this exists to catch: drydock's main sat on v1.7.0-rc.2.""" diff --git a/.github/tests/starchart_refresh_contract_test.py b/.github/tests/starchart_refresh_contract_test.py index 8fb137f..8962cf7 100644 --- a/.github/tests/starchart_refresh_contract_test.py +++ b/.github/tests/starchart_refresh_contract_test.py @@ -173,17 +173,42 @@ def test_both_themes_are_written_and_committed_together(self): # Both derivations strip a .svg suffix, so the input has to have one. self.assertIn("!out.endsWith('.svg')", workflow) - def test_the_documented_trigger_is_the_release_cut_not_a_cron(self): - """A committed artifact refreshed on a schedule mutates underneath a - tag, which is what 'main is the released version' forbids.""" + def test_the_documented_trigger_is_a_dispatch_not_a_cron_or_a_release(self): + """Two ways to get this wrong, and the second one looks right. + + A cron mutates a committed artifact underneath a tag, which 'main is + the released version' forbids. And `release: [published]` never fires + at all: GitHub suppresses workflow runs for events caused by + GITHUB_TOKEN, which is what every repo here publishes releases with, + so a caller wired that way is green everywhere and refreshes nothing. + This file told three repos to do exactly that on 2026-08-21 before the + sockguard lane caught it, so the example is pinned by a test now.""" workflow = self.read_workflow() example = workflow.split("# on:\n", 1)[1].split("# permissions:", 1)[0] - self.assertIn("release:", example) - self.assertIn("types: [published]", example) + self.assertIn("workflow_dispatch:", example) self.assertIn('# accent: "#49bcfb"', workflow) - self.assertNotIn("cron", example) - self.assertNotIn("schedule:", example) + for dead in ("release:", "types: [published]", "cron", "schedule:"): + self.assertNotIn(dead, example) + + def test_the_suppression_trap_is_documented_not_just_avoided(self): + """Removing the bad example only stops it being copied from here. The + reason has to travel with it, or the next person reaches for the + release trigger from first principles and it fails the same silent + way.""" + workflow = self.read_workflow() + + for expected in ( + "GITHUB_TOKEN", + "gh workflow run", + "workflow_dispatch` and", + "repository_dispatch", + ): + self.assertIn(expected, workflow) + + # The failure mode named, so it reads as a trap rather than a + # preference: wired that way it lints clean and never runs. + self.assertIn("refreshes nothing", workflow) def test_the_embedded_renderer_names_its_source(self): """The same renderer exists here and in ops. Hand-copying is how they diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml index c4bb47e..361b473 100644 --- a/.github/workflows/main-is-released.yml +++ b/.github/workflows/main-is-released.yml @@ -73,20 +73,50 @@ jobs: exit 1 fi - if ! tag="$(git describe --exact-match --tags HEAD 2>/dev/null)"; then + # A promotion merges before its tag is pushed, so a run landing in + # that window sees an untagged main and reports drift that resolves + # itself seconds later. Refetch and retry before believing it. This + # cannot mask real drift: a genuinely untagged main is still + # untagged on the last attempt. + tag="" + for attempt in 1 2 3; do + if tag="$(git describe --exact-match --tags HEAD 2>/dev/null)"; then + break + fi + tag="" + [ "$attempt" -eq 3 ] && break + echo "main is untagged on attempt ${attempt}; refetching tags in case a promotion is mid-cut" + sleep 20 + # A failed refetch is reported, never swallowed into a pass: the + # loop still decides on whatever refs we actually have. + git fetch --tags --force --quiet origin \ + || echo "::warning::could not refetch tags on attempt ${attempt}; the verdict below uses the refs currently available on the runner" + done + + if [ -z "$tag" ]; then latest="$(git describe --tags --abbrev=0 HEAD 2>/dev/null || echo '')" ahead="$(git rev-list --count "${latest}..HEAD" 2>/dev/null || echo '?')" echo "::error::main is not a tagged release. Newest reachable tag is ${latest}, and main is ${ahead} commit(s) past it. Either cut a release or move the unshipped work to a dev branch." >&2 exit 1 fi - case "$tag" in - *-*) - if [ "$ALLOW_PRERELEASE" != "true" ]; then - echo "::error::main points at prerelease ${tag}. Prereleases belong on the dev branch; main carries what users actually run." >&2 - exit 1 - fi - echo "::warning::main points at prerelease ${tag}, accepted because allow-prerelease is set" ;; - esac + # An exact match alone is not the invariant. Any tag satisfies it, + # including one literally named "snapshot" or "latest" parked on a + # drifted main — which reads as a pass and is the failure this + # workflow exists to catch. Require a release-shaped tag. + if ! printf '%s' "$tag" | grep -Eq '^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$'; then + echo "::error::main points at ${tag}, which is not a release version tag (expected vMAJOR.MINOR.PATCH). A moving or descriptive tag satisfies an exact-match check while main carries unshipped work." >&2 + exit 1 + fi + + # Prerelease is the part AFTER the version, so match on that rather + # than on any hyphen anywhere in the tag. + if printf '%s' "$tag" | grep -Eq '^v?[0-9]+\.[0-9]+\.[0-9]+-'; then + if [ "$ALLOW_PRERELEASE" != "true" ]; then + echo "::error::main points at prerelease ${tag}. Prereleases belong on the dev branch; main carries what users actually run." >&2 + exit 1 + fi + echo "::warning::main points at prerelease ${tag}, accepted because allow-prerelease is set" + fi echo "main is released at ${tag}" diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index 3caaf04..e593394 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -8,8 +8,6 @@ name: Star Chart Refresh # Callers declare their own triggers and pin this file by full commit SHA: # # on: -# release: -# types: [published] # workflow_dispatch: # permissions: {} # jobs: @@ -18,13 +16,44 @@ name: Star Chart Refresh # contents: write # uses: CodesWhat/.github/.github/workflows/starchart-refresh.yml@ # with: -# branch: dev/v1.7 +# branch: ${{ github.ref_name }} # accent: "#49bcfb" # -# The trigger is the release cut, not a cron. A committed artifact refreshed -# on a schedule mutates underneath a tag, which is exactly what "main is the -# released version" forbids. Regenerating at the cut means the chart in a -# released README is as of that release. +# The refresh belongs to the release cut, not to a cron. A committed artifact +# refreshed on a schedule mutates underneath a tag, which is exactly what +# "main is the released version" forbids. +# +# DO NOT trigger it with `release: [published]`. That looks right and never +# runs. GitHub suppresses workflow runs for events caused by GITHUB_TOKEN, and +# every repo here publishes its release with that credential — GoReleaser with +# `GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}` (portwing release.yml) or +# `gh release create` with `GH_TOKEN: ${{ github.token }}` (drydock +# release-cut.yml). A caller wired that way reads as correctly configured, is +# green in every lint, and refreshes nothing, forever. Found 2026-08-21 by the +# sockguard lane after this file had already told three repos to do it. +# +# The release-cut workflow dispatches this one instead: +# +# - name: Dispatch starchart refresh +# env: +# GH_TOKEN: ${{ github.token }} +# run: gh workflow run starchart.yml --ref "$BRANCH" +# +# That works with no new credential because `workflow_dispatch` and +# `repository_dispatch` are the two dispatch events that always create a run +# even when GITHUB_TOKEN caused them. They are not the only exceptions — +# `pull_request` with opened/synchronize/reopened creates a run in an +# approval-required state rather than being suppressed outright — but they +# are the two that fire unattended, which is what a release cut needs. +# The dispatch step must fail loudly rather than `|| true`: by the time it +# runs the release is already published, so a swallowed error is the same +# silent-success shape this whole workflow exists to remove. +# +# Prefer dispatching BEFORE the tag is cut where the flow allows it, so the +# released README ships the chart it claims to. Dispatching after publish is +# an accepted tradeoff — the chart then lands on the dev branch and main's +# copy is one cut stale — because the requirement is that regeneration is +# tied to the cut rather than to wall-clock time, and that holds either way. # # The generator is embedded rather than checked out from a second repository # so that the caller's SHA pin covers every line of behaviour, with nothing From 0dd3d7708c015856339433855739937fa036ee60 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Thu, 27 Aug 2026 00:45:01 -0400 Subject: [PATCH 19/44] chore: gitignore .claude/ so a nested worktree can't be staged as a gitlink (#38) --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index d66d040..5c2af00 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,6 @@ __pycache__/ # Local planning/scratch workspace — not for commit .planning/ profile/font_reference.svg + +# Agent worktrees / local agent state +.claude/ From 54f1b8651dd78966fea6f9b29da37d3cb1583f1f Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Thu, 27 Aug 2026 00:49:19 -0400 Subject: [PATCH 20/44] fix(starchart): the documented dispatch step needs actions:write (#39) * fix(starchart): the documented dispatch step needs actions:write portwing v0.9.7 shipped this snippet as written and the first real cut died on HTTP 403: creating a workflow dispatch is an Actions API write, and contents:write does not imply it. A PAT needs the scope too. Records the tag-push trigger as the other working option, and the evidence that a GITHUB_TOKEN dispatch does create a run, since that was reported as false and it's load-bearing for every cut-dispatched caller in the org. * docs(starchart): cite GitHub's own wording on the dispatch exception * test(starchart): assert the refuted-claim verdict, not just its evidence The contract test named portkey-admin-mcp and github-actions[bot] and stopped there, so a rewrite that kept both source names and reversed the conclusion passed. Verified by mutation: flipping "That does not hold:" to "That is confirmed:" left the old assertions green and now fails. Asserts against the flattened comment prose for the same reason the tag-trigger test does, so the assertions pin the claim rather than the line width. --- .../tests/starchart_refresh_contract_test.py | 63 +++++++++++++++++++ .github/workflows/starchart-refresh.yml | 30 +++++++++ 2 files changed, 93 insertions(+) diff --git a/.github/tests/starchart_refresh_contract_test.py b/.github/tests/starchart_refresh_contract_test.py index 8962cf7..23fa491 100644 --- a/.github/tests/starchart_refresh_contract_test.py +++ b/.github/tests/starchart_refresh_contract_test.py @@ -210,6 +210,69 @@ def test_the_suppression_trap_is_documented_not_just_avoided(self): # preference: wired that way it lints clean and never runs. self.assertIn("refreshes nothing", workflow) + def test_the_dispatch_snippet_carries_the_permission_it_needs(self): + """The snippet shipped without `actions: write` and portwing's first + real cut died on HTTP 403. Creating a dispatch is an Actions API + write, and `contents: write` does not imply it, so a reader who + copies the snippet and reasons about permissions from the commit it + performs gets it wrong. The scope has to be IN the snippet, not + described somewhere below it.""" + workflow = self.read_workflow() + + snippet = workflow.split("# - name: Dispatch starchart refresh", 1)[1] + snippet = snippet.split("gh workflow run", 1)[0] + self.assertIn("actions: write", snippet) + + # And the reason, so nobody trims it back out as redundant. + self.assertIn("does not imply", workflow) + self.assertIn("403", workflow) + + def test_the_silent_dispatch_claim_is_recorded_as_refuted(self): + """`workflow_dispatch` being exempt from GITHUB_TOKEN suppression is + load-bearing for every cut-dispatched caller in the org. It was + reported as false on 2026-08-21. Leaving that unrecorded means the + next agent re-derives the doubt and rips out a working trigger, so + the evidence lives here.""" + workflow = self.read_workflow() + + self.assertIn("portkey-admin-mcp", workflow) + self.assertIn("github-actions[bot]", workflow) + + # Naming the evidence is not the same as recording the verdict: a + # rewrite that keeps both source names and reverses the conclusion + # passes an evidence-only assertion. Flattened for the same reason + # the tag-trigger test flattens. + prose = " ".join( + line.lstrip("#").strip() + for line in workflow.split("\n") + if line.startswith("#") + ) + self.assertIn("That does not hold:", prose) + self.assertIn( + "Suppression and a missing scope look similar and are not", prose + ) + self.assertIn( + "exception of `workflow_dispatch` and `repository_dispatch`", prose + ) + + def test_the_tag_push_alternative_is_documented_with_its_own_trap(self): + """A repo that would rather not widen a PAT scope has a second + working trigger. Naming it without naming the assertion is how the + dead `release:` trigger survives next to a live tag trigger, since + the two read as interchangeable.""" + workflow = self.read_workflow() + + self.assertIn('tags: ["v*"]', workflow) + # Flattened: the comment wraps, and an assertion that a phrase sits + # on one line pins the line width rather than the claim. + prose = " ".join( + line.lstrip("#").strip() + for line in workflow.split("\n") + if line.startswith("#") + ) + self.assertIn("assert BOTH that the tag trigger is present", prose) + self.assertIn("`release:` is absent", prose) + def test_the_embedded_renderer_names_its_source(self): """The same renderer exists here and in ops. Hand-copying is how they drift, so the block is generated and says so.""" diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index e593394..41b9d0a 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -35,6 +35,8 @@ name: Star Chart Refresh # The release-cut workflow dispatches this one instead: # # - name: Dispatch starchart refresh +# permissions: +# actions: write # REQUIRED. contents: write does not imply it. # env: # GH_TOKEN: ${{ github.token }} # run: gh workflow run starchart.yml --ref "$BRANCH" @@ -45,10 +47,38 @@ name: Star Chart Refresh # `pull_request` with opened/synchronize/reopened creates a run in an # approval-required state rather than being suppressed outright — but they # are the two that fire unattended, which is what a release cut needs. +# # The dispatch step must fail loudly rather than `|| true`: by the time it # runs the release is already published, so a swallowed error is the same # silent-success shape this whole workflow exists to remove. # +# `actions: write` was missing from this snippet until 2026-08-21 and it is +# the difference between a working cut and a dead one. Creating a workflow +# dispatch is an Actions API write, so a job that can commit still cannot +# dispatch. portwing v0.9.7 shipped this step as written and the first real +# cut failed with `HTTP 403: Resource not accessible by personal access +# token`, because it used RELEASE_PAT, which is Contents RW. A PAT needs the +# scope too, not just the job. +# +# The failure is at least loud. It was reported as a silent no-op — the +# dispatch succeeding and creating no run — which would have made +# `${{ github.token }}` unusable here. That does not hold: +# portkey-admin-mcp's `auto-tag.yml` dispatches `release.yml` with +# `${{ github.token }}` and `permissions: {contents: write, actions: write}`, +# and there are four `github-actions[bot]`-actored `workflow_dispatch` runs +# on record between 2026-08-04 and 2026-08-10 with real success and failure +# conclusions. Suppression and a missing scope look similar and are not: one +# is fixed by adding the scope, the other cannot be fixed. GitHub's +# events-that-trigger-workflows reference says it outright: "With the +# exception of `workflow_dispatch` and `repository_dispatch`, other +# `GITHUB_TOKEN`-triggered events do not create workflow runs at all." +# +# `on: push: tags: ["v*"]` is the other working trigger and needs no new +# scope anywhere, because the cut already pushes the tag with a PAT so that +# downstream workflows fire. portwing moved to it in #190. If you take that +# route, assert BOTH that the tag trigger is present and that `release:` is +# absent — they look interchangeable and only one of them runs. +# # Prefer dispatching BEFORE the tag is cut where the flow allows it, so the # released README ships the chart it claims to. Dispatching after publish is # an accepted tradeoff — the chart then lands on the dev branch and main's From 0151d3e7c68109591a35eb9282a68ceb77826f1e Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Thu, 27 Aug 2026 01:15:10 -0400 Subject: [PATCH 21/44] chore(renovate): tidy go.sum after a gomod update (#40) Renovate writes the new go.sum hashes and leaves the superseded ones behind. `go build` passes because go.sum only has to be sufficient, so the failure surfaces later in the GoReleaser gate, whose `go mod tidy` before-hook removes the stale lines and dirties the tree against a clean-tree assertion. Diagnosed on sockguard #343 by that lane: a go-containerregistry 0.21.8 -> 0.21.9 bump pulled a transitive golang.org/x/net 0.57 -> 0.58 and go.sum ended up carrying all four versions. Fixed in the shared preset rather than per-repo. sockguard and portwing are the two Go consumers, both extend this file with no local postUpdateOptions, so portwing would hit the identical failure on its next transitive bump. Only gomodTidy. gomodUpdateImportPaths was suggested alongside it but addresses major-version module path rewrites, which is a different problem with no observed failure here, and it changes behaviour on every major bump across both repos. --- .../tests/renovate_config_contract_test.py | 33 +++++++++++++++++++ renovate-config.json | 3 ++ 2 files changed, 36 insertions(+) create mode 100644 .github/tests/renovate_config_contract_test.py diff --git a/.github/tests/renovate_config_contract_test.py b/.github/tests/renovate_config_contract_test.py new file mode 100644 index 0000000..66dc2f8 --- /dev/null +++ b/.github/tests/renovate_config_contract_test.py @@ -0,0 +1,33 @@ +import json +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[2] + + +class RenovateConfigContractTest(unittest.TestCase): + def read_config(self): + with (ROOT / "renovate-config.json").open() as config_file: + return json.load(config_file) + + def test_gomod_updates_are_tidied(self): + """Renovate writes the new go.sum hashes and leaves the superseded + ones in place. `go build` tolerates that, because go.sum only has to + be sufficient — so the break lands later, in the GoReleaser gate, + whose `go mod tidy` removes the stale lines and dirties the tree + against a clean-tree assertion. Measured on sockguard #343, where a + go-containerregistry 0.21.8 to 0.21.9 bump pulled a transitive + golang.org/x/net 0.57 to 0.58 and go.sum ended up carrying all four. + + Every Go repo in the org consumes this preset and none sets its own + `postUpdateOptions`, so removing this reintroduces the failure on + every future transitive bump, in a job that names neither Renovate + nor go.sum.""" + config = self.read_config() + + self.assertIn("gomodTidy", config.get("postUpdateOptions", [])) + + +if __name__ == "__main__": + unittest.main() diff --git a/renovate-config.json b/renovate-config.json index 3033de7..1de927c 100644 --- a/renovate-config.json +++ b/renovate-config.json @@ -12,6 +12,9 @@ "minimumReleaseAge": "14 days", "internalChecksFilter": "strict", "skipInstalls": false, + "postUpdateOptions": [ + "gomodTidy" + ], "labels": [ "dependencies" ], From eb749855de10603768b26ac30163fb3f4edb8e9d Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Thu, 27 Aug 2026 06:43:24 -0400 Subject: [PATCH 22/44] chore(renovate): move the vite ecosystem as one group (#42) The preset groups `minor` and `patch` per manager and leaves majors to split into one PR each. That works everywhere except a peer-locked set, where a major arriving alone has no resolvable outcome at all. careerrat #208 is the worked example: `@vitejs/plugin-react` 6.1.0 peer-requires `vite ^8.0.0`, `vite` is pinned at 6.4.3, and no vite major PR exists for it to land against. The branch is deadlocked no matter how many times it rebases, and `renovate/artifacts`, `tests`, `web-build`, `website-build` and `windows-package-smoke` all fail on it every run. Grouping every update type, not just non-major, is the point: the majors are exactly the ones that have to travel together. The rule sits last so it wins over the non-major group for the packages it names. Affects the three repos that declare any of these, checked against every tracked package.json: careerrat (vite 6.4.3, @vitejs/plugin-react 4.7.0, vitest 3.2.7), drydock (vite 7.3.6/8.2.1/8.2.2, @vitejs/plugin-vue 6.0.8, vitest 4.1.10/4.1.11), mailbox0 (vite ^6.3.5, @vitejs/plugin-react ^4.7.0, vitest ^1.0.4 and 3.2.4, @vitest/ui ^1.0.4). Presets resolve from this repo's default branch, so it takes effect on all three the moment it reaches main. --- renovate-config.json | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/renovate-config.json b/renovate-config.json index 1de927c..541b88b 100644 --- a/renovate-config.json +++ b/renovate-config.json @@ -36,6 +36,17 @@ ], "groupName": "non-major ({{manager}})", "groupSlug": "non-major-{{manager}}" + }, + { + "description": "Move Vite, its official plugins, and Vitest as one unit. They peer-lock on each other, so a major that arrives alone has no resolvable outcome: @vitejs/plugin-react 6 peer-requires vite ^8, and a solo PR for it can never satisfy that against a pinned vite 6, no matter how often it rebases. This matches every update type, not just minor and patch, because the majors are exactly the ones that have to travel together.", + "matchPackageNames": [ + "vite", + "@vitejs/**", + "vitest", + "@vitest/**" + ], + "groupName": "vite ecosystem", + "groupSlug": "vite-ecosystem" } ] } From eddc1af1ec68539b43dc5a23891b3bf00758c66c Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 30 Aug 2026 00:40:46 -0400 Subject: [PATCH 23/44] chore(renovate): scope Portwing lock maintenance exception (#44) * chore(renovate): scope Portwing lock maintenance exception * fix(renovate): use exact Portwing repository match * test(renovate): run config contract in validation --- .../tests/renovate_config_contract_test.py | 21 +++++++++++++++++++ .github/workflows/standards-validation.yml | 1 + renovate-config.json | 10 +++++++++ scripts/validate.sh | 1 + 4 files changed, 33 insertions(+) diff --git a/.github/tests/renovate_config_contract_test.py b/.github/tests/renovate_config_contract_test.py index 66dc2f8..ac1e6f4 100644 --- a/.github/tests/renovate_config_contract_test.py +++ b/.github/tests/renovate_config_contract_test.py @@ -28,6 +28,27 @@ def test_gomod_updates_are_tidied(self): self.assertIn("gomodTidy", config.get("postUpdateOptions", [])) + def test_portwing_lock_maintenance_is_disabled_exactly(self): + config = self.read_config() + + matches = [ + rule + for rule in config.get("packageRules", []) + if rule.get("matchRepositories") == ["CodesWhat/portwing"] + ] + + self.assertEqual(1, len(matches)) + self.assertEqual(["lockFileMaintenance"], matches[0].get("matchUpdateTypes")) + self.assertIs(matches[0].get("enabled"), False) + + def test_validation_runs_this_contract(self): + command = "python3 .github/tests/renovate_config_contract_test.py" + validation = (ROOT / "scripts/validate.sh").read_text() + workflow = (ROOT / ".github/workflows/standards-validation.yml").read_text() + + self.assertEqual(1, validation.count(command)) + self.assertEqual(1, workflow.count(command)) + if __name__ == "__main__": unittest.main() diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 425ef4e..703d696 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -53,6 +53,7 @@ jobs: python3 .github/tests/greptile_config_contract_test.py python3 .github/tests/quality_report_contract_test.py python3 .github/tests/reusable_ci_contract_test.py + python3 .github/tests/renovate_config_contract_test.py python3 .github/tests/starchart_refresh_contract_test.py python3 .github/tests/main_is_released_contract_test.py diff --git a/renovate-config.json b/renovate-config.json index 541b88b..f0a7940 100644 --- a/renovate-config.json +++ b/renovate-config.json @@ -47,6 +47,16 @@ ], "groupName": "vite ecosystem", "groupSlug": "vite-ecosystem" + }, + { + "description": "Disable npm lock maintenance for Portwing because native packages are platform-specific", + "matchRepositories": [ + "CodesWhat/portwing" + ], + "matchUpdateTypes": [ + "lockFileMaintenance" + ], + "enabled": false } ] } diff --git a/scripts/validate.sh b/scripts/validate.sh index 5d02c10..e6d9504 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -16,6 +16,7 @@ python3 .github/tests/greptile_summon_contract_test.py python3 .github/tests/greptile_config_contract_test.py python3 .github/tests/quality_report_contract_test.py python3 .github/tests/reusable_ci_contract_test.py +python3 .github/tests/renovate_config_contract_test.py echo "==> compile python" python3 -m compileall -q . From d0f3e5bc9d8ad109970839192f1ccd0297ab5b2e Mon Sep 17 00:00:00 2001 From: scttbnsn <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 30 Aug 2026 01:36:30 -0400 Subject: [PATCH 24/44] fix(renovate): scope lock maintenance to npm --- .github/tests/renovate_config_contract_test.py | 1 + renovate-config.json | 3 +++ 2 files changed, 4 insertions(+) diff --git a/.github/tests/renovate_config_contract_test.py b/.github/tests/renovate_config_contract_test.py index ac1e6f4..831561c 100644 --- a/.github/tests/renovate_config_contract_test.py +++ b/.github/tests/renovate_config_contract_test.py @@ -38,6 +38,7 @@ def test_portwing_lock_maintenance_is_disabled_exactly(self): ] self.assertEqual(1, len(matches)) + self.assertEqual(["npm"], matches[0].get("matchManagers")) self.assertEqual(["lockFileMaintenance"], matches[0].get("matchUpdateTypes")) self.assertIs(matches[0].get("enabled"), False) diff --git a/renovate-config.json b/renovate-config.json index f0a7940..0258361 100644 --- a/renovate-config.json +++ b/renovate-config.json @@ -53,6 +53,9 @@ "matchRepositories": [ "CodesWhat/portwing" ], + "matchManagers": [ + "npm" + ], "matchUpdateTypes": [ "lockFileMaintenance" ], From 0aa77c27e291875301f033d155b92f7944c69c7b Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Mon, 7 Sep 2026 08:06:05 -0400 Subject: [PATCH 25/44] docs(onboarding): add the .planning/ gitignore checkbox (#46) --- REPOSITORY_ONBOARDING.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index 40809ad..84db9ce 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -40,6 +40,12 @@ repositories. Language-specific tests do not. Keep the catch-all even if narrower path rules are added later. All three accounts must remain owners of paths not matched by a narrower rule. +- [ ] Add `.planning/` to the root `.gitignore` before anything is written + there. It is the only home for internal planning: roadmaps with internal + sequencing, competitor analysis, evals, mockups, handoff notes, archived + scratch. Nothing tracked may read from it, since a fresh clone has none of + it. Verify on the default branch, not with `git check-ignore`, which also + passes off a local exclude. Shape: `standards/planning.md` in `ops`. - [ ] Add a root `AGENTS.md`. Make it specific enough for a new contributor or coding agent to work without reverse-engineering the repository. Include the repository purpose and layout, exact build/test/lint commands, test From 49a598298910a251260304a38348fd5d38690f25 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:34:27 -0400 Subject: [PATCH 26/44] fix(quality): isolate validation and pace hosted work (#48) Batch items: - docs(quality): use routine CI checks and monthly cloud reporting - docs(workflow): pace reviews and deployments through admission - ci(quality): require review admission and pace dependency arrivals - fix(validation): restrict source checks to tracked files - refactor(profile): remove unused import and clarify line names Validation: all 100 tests and the full local validator pass. Standards Validation, CodeQL and Profile Assets passed on the reviewed head. CodeRabbit withdrew the only finding after reproduction; Greptile found no actionable defects. Hosted provider behavior remains pilot follow-through after landing. --- .coderabbit.yaml | 9 +- .../tests/community_health_contract_test.py | 9 +- .github/tests/tracked_validation_test.py | 102 ++++++++++++ .github/workflows/standards-validation.yml | 9 +- AGENTS.md | 13 +- REPOSITORY_ONBOARDING.md | 150 ++++++++++++------ renovate.json | 6 +- scripts/generate_profile_svg.py | 5 +- scripts/validate.sh | 11 +- scripts/validate_tracked_files.py | 59 +++++++ 10 files changed, 300 insertions(+), 73 deletions(-) create mode 100644 .github/tests/tracked_validation_test.py create mode 100644 scripts/validate_tracked_files.py diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 3cc6afa..98d186d 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -1,10 +1,13 @@ -# Review feature PRs that follow the CodesWhat dev-branch flow. CodeRabbit -# reviews the default branch without an explicit base-branch entry. +# Request the first review only after the coordinator admits a stable candidate. +# Later fix batches need an explicit review request; pushes do not spend capacity. language: en-US reviews: auto_review: - enabled: true + enabled: false + auto_incremental_review: false drafts: false + labels: + - "review-ready" base_branches: - "^dev/.*$" diff --git a/.github/tests/community_health_contract_test.py b/.github/tests/community_health_contract_test.py index 69c2020..d62de0f 100644 --- a/.github/tests/community_health_contract_test.py +++ b/.github/tests/community_health_contract_test.py @@ -171,11 +171,10 @@ def test_standards_workflow_pins_actions_and_runs_every_contract(self): for expected in ( "persist-credentials: false", "community_health_contract_test.py", - "python3 -m compileall -q .", - "YAML.parse_file", - "json.load", - "markdownlint-cli2@0.23.2", - "markdownlint-profile.yaml", + "python3 .github/tests/tracked_validation_test.py", + "python3 scripts/validate_tracked_files.py python", + "python3 scripts/validate_tracked_files.py data", + "python3 scripts/validate_tracked_files.py markdown", "actionlint", "zizmorcore/zizmor-action@", "github/codeql-action/init@", diff --git a/.github/tests/tracked_validation_test.py b/.github/tests/tracked_validation_test.py new file mode 100644 index 0000000..b657ab1 --- /dev/null +++ b/.github/tests/tracked_validation_test.py @@ -0,0 +1,102 @@ +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +VALIDATOR = ROOT / "scripts/validate_tracked_files.py" + + +class TrackedValidationTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="tracked-validation-") + self.addCleanup(self.temp.cleanup) + self.repo = Path(self.temp.name) + subprocess.run( + ["git", "init", "--quiet", str(self.repo)], check=True, + capture_output=True, + ) + self.write(".gitignore", ".planning/\n.claude/\n__pycache__/\n", tracked=True) + + def write(self, name, content, tracked=False): + path = self.repo / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + if tracked: + subprocess.run( + ["git", "add", "--", name], cwd=self.repo, check=True, + capture_output=True, + ) + + def run_validation(self, kind): + return subprocess.run( + [sys.executable, str(VALIDATOR), kind], cwd=self.repo, + capture_output=True, text=True, timeout=60, + ) + + def assert_valid(self, kind): + result = self.run_validation(kind) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + def assert_invalid(self, kind, diagnostic): + result = self.run_validation(kind) + self.assertNotEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn(diagnostic, result.stdout + result.stderr) + + def test_ignored_and_untracked_files_are_not_validation_inputs(self): + for directory in (".planning", ".claude/worktrees/other", "scratch"): + for suffix, content in ( + ("py", "def broken(:\n"), ("json", "{broken"), + ("yml", "broken: ["), ("yaml", "broken: ["), + ("md", "no heading\n"), + ): + self.write(f"{directory}/bad.{suffix}", content) + self.write("scripts/space [x]\nname.py", "answer = 42\n", tracked=True) + self.write(".github/data [x].json", '{"ok": true}\n', tracked=True) + self.write(".github/data.yml", "ok: true\n", tracked=True) + self.write("docs/a [x].md", "# Valid\n", tracked=True) + for kind in ("python", "data", "markdown"): + with self.subTest(kind=kind): + self.assert_valid(kind) + + def test_invalid_tracked_python_fails(self): + self.write(".github/bad [x].py", "def broken(:\n", tracked=True) + self.assert_invalid("python", "SyntaxError") + + def test_invalid_tracked_json_fails(self): + self.write(".github/bad [x].json", "{broken", tracked=True) + self.assert_invalid("data", "JSONDecodeError") + + def test_invalid_tracked_yaml_fails(self): + for suffix in ("yml", "yaml"): + with self.subTest(suffix=suffix): + name = f".github/bad.{suffix}" + self.write(name, "broken: [", tracked=True) + self.assert_invalid("data", "Psych::SyntaxError") + self.write(name, "ok: true\n", tracked=True) + + def test_invalid_tracked_markdown_paths_are_literal(self): + for name in ("docs/bad [x].md", ".github/hidden.md", "#note.md"): + with self.subTest(name=name): + self.write(name, "no heading\n", tracked=True) + self.assert_invalid("markdown", "MD041") + self.write(name, "# Valid\n", tracked=True) + + def test_profile_keeps_its_separate_rules(self): + self.write("profile/README.md", "
Profile
\n", tracked=True) + config = ".github/markdownlint-profile.yaml" + self.write(config, (ROOT / config).read_text(), tracked=True) + self.assert_valid("markdown") + self.write("profile/README.md", "
Profile
\n", tracked=True) + self.assert_invalid("markdown", "MD009") + + def test_empty_tracked_input_sets_succeed(self): + for kind in ("python", "data", "markdown"): + with self.subTest(kind=kind): + self.assert_valid(kind) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 703d696..112817f 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -41,15 +41,15 @@ jobs: run: | python3 .github/tests/community_health_contract_test.py python3 .github/tests/greptile_summon_contract_test.py + python3 .github/tests/tracked_validation_test.py - name: Compile Python - run: python3 -m compileall -q . + run: python3 scripts/validate_tracked_files.py python - name: Parse YAML and JSON run: | set -euo pipefail - ruby -e 'require "yaml"; Dir.glob("**/*.{yml,yaml}", File::FNM_DOTMATCH).sort.each { |path| YAML.parse_file(path) }' - python3 -c 'import json; from pathlib import Path; [json.load(path.open()) for path in Path(".").rglob("*.json")]' + python3 scripts/validate_tracked_files.py data python3 .github/tests/greptile_config_contract_test.py python3 .github/tests/quality_report_contract_test.py python3 .github/tests/reusable_ci_contract_test.py @@ -60,8 +60,7 @@ jobs: - name: Lint Markdown run: | set -euo pipefail - npx --yes markdownlint-cli2@0.23.2 "**/*.md" "#profile/README.md" - npx --yes markdownlint-cli2@0.23.2 "profile/README.md" --config .github/markdownlint-profile.yaml + python3 scripts/validate_tracked_files.py markdown - name: Validate workflows with actionlint run: | diff --git a/AGENTS.md b/AGENTS.md index 0d27337..956f396 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,9 +30,16 @@ contract tests that pin the shapes other repositories depend on. Verify promotions with tree equality (`git diff --quiet origin/main origin/dev/repository-standards`), never commit ancestry. -- CodeRabbit auto-reviews PRs against `dev/*` branches only (scoped in - `.coderabbit.yaml`); summon it explicitly anywhere else and read its - inline comments before merging. +- Admit new hosted review/heavy CI work through the shared capacity roster. + Keep preparation local while queued. After admission, add `review-ready` for + the first CodeRabbit review; request subsequent fix-batch reviews explicitly. + Freeze pushes while review runs, read its output and verify the covered head. + `.coderabbit.yaml` keeps default/dev targets but disables automatic review on + ordinary pushes. Required review and protection remain effective. +- Approve ordinary dependency updates in the Renovate dashboard only after + admission. This repo's wrapper limits ordinary PRs/branches to one at a time + and one new PR per hour. The shared preset is unchanged; urgent vulnerability + updates keep their separate handling. - Commits are plain Conventional Commits, `(scope): `, no emoji, no AI attribution trailers. - Never weaken branch protection or rulesets to land a change. diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index 84db9ce..06068c5 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -107,27 +107,67 @@ repositories. Language-specific tests do not. - [ ] Confirm the Renovate GitHub app can access the repository. App access is managed at the organization level; do not widen a public-only installation to private repositories as an onboarding shortcut. -- [ ] Add a root `.coderabbit.yaml` based on a current CodesWhat product, then - replace its product-specific tone, ignored paths, and path instructions. - Keep automatic review enabled. If PRs target a non-default integration - branch, include that branch under `reviews.auto_review.base_branches` and - request an explicit CodeRabbit review on the first PR to prove it works. +- [ ] Where CodeRabbit is adopted, use a root `.coderabbit.yaml` appropriate to + the repository. Adopt intentional admission rather than automatically spending + review capacity on every in-progress push. Scope opt-in and incremental-review + changes through normal review, preserving required review evidence. Verify + non-default integration targets and stacked PR behavior before relying on them. - [ ] Confirm CodeRabbit can access the repository and posts an actual review comment. A green check without review output is not enough for this test. - Automated Pro-level reviews are free on public repositories only; on - private repositories the free plan rate-limits automated reviews, and they - have not fired for this organization in practice. Organization policy: on a - private repository skip both CodeRabbit items, use cross-account human - review, and add the config when the repository goes public. + Inspect the effective plan, selected-file limit and remaining capacity; public + repository visibility is not a promise of unlimited review. A quota-only green + check is not delivered review. Required non-author approval still applies, and + multiple accounts operated by one person are not independent human review. - [ ] Keep `greptile.json` at exactly `{"skipReview": "AUTOMATIC"}` (contract-tested in this repository) so Greptile never reviews unbidden. A repository that wants opt-in second opinions adds a label-gated caller workflow (`.github/workflows/greptile.yml`, firing on the `second-opinion` label) that calls this repository's `greptile-summon.yml` at a pinned full commit SHA. Pair the caller with a CodeRabbit `labeling_instructions` entry - for `second-opinion` and `auto_apply_labels` enabled, so applying the label - is criteria-driven rather than left to memory. The label is Greptile's only - trigger; never wire it to review every PR directly. + for `second-opinion` without automatic label application. Applying it is an + explicit, consequence-based admission decision with available capacity. + The label is Greptile's only automatic caller trigger; do not wire it to + review every PR directly. Inspect the provider's resolved configuration and + delivered review rather than assuming a legacy file or summon proves coverage. + +### Capacity and queued development + +Public projects use queue-first development, with adoption work recorded in +their private internal roadmaps. Begin with one newly admitted hosted-review or +heavy-CI candidate across public projects for a seven-day measured pilot. Finish +existing in-flight work safely. A named coordinator records the candidate's +owner, head/base, dependencies, local verification, services, review-pass count, +blocked reason and next eligible time before new expensive work starts. + +Keep one active change per repo and at most one small dependent successor local. +Pilot two-layer stacks for genuine dependencies; verify trunk, bot and merge +compatibility. Draft and stacked PRs can still run CI and deploys. Keep diffs +small, aiming around 25 changed files and within the actual reviewer limit; +batching many unrelated items into one oversized PR is not admission control. + +Freeze pushes during review, then submit one batch of fixes per pass. Prioritize +finishing admitted work over opening another PR. Keep the three-pass cap, all +required checks and valid approvals. Record cooldowns and wait for recovery +without repeated review summons, workflow reruns or indefinite polling. Review +capacity after the pilot using actual service pools before expanding concurrency. + +Admit one new deployment-producing web candidate per shared deployment pool +initially. Pilot ordinary dependency arrivals at one concurrent PR and one new +PR/hour per repo, with staggered schedules or dashboard admission and urgent +vulnerability handling retained. Retain the monthly Qlty reporting policy below. +Provider settings, bot controls and required CI changes need scoped reviewed +rollouts; documentation alone does not configure them. Metadata-only projects +record applicable controls without installing irrelevant tools or paid services. + +This shared repository pilots the controls in its own configuration, without +changing the live Renovate preset for consumers. The coordinator approves an +ordinary dependency update in the dashboard only after admission; the local +wrapper permits one ordinary PR/branch and one new PR per hour. Urgent +vulnerability handling remains separate. After admitting a stable review +candidate, apply `review-ready` for its first CodeRabbit review. Later fix +batches use an explicit review request; pushes do not automatically start +another review. Verify the provider's resolved configuration and delivered head +after landing these settings before claiming the pilot is operational. ### Local gates @@ -294,41 +334,55 @@ Add these only when the behavior exists: ### Qlty -Qlty appears in three places. The committed configuration and the repository-run -gates are the alignment surface; the Qlty Cloud GitHub App is not. - -- [ ] Commit `.qlty/qlty.toml` (`config_version = "0"`) with the organization - exclude baseline for generated, minified, and vendored paths. Drydock's file - is the reference posture and Portwing's is its Go-repo mirror; start from the - closer of the two. Do not copy the trivy plugin block from either reference: - trivy is deprecated in favor of Grype and its removal from both files is - tracked (drydock#753, portwing#135). The trufflehog plugin stays. The same - file drives the local CLI and Qlty Cloud, so changes to it are quality-gate - changes, not formatting. -- [ ] Add the repository's Qlty gate script (`scripts/qlty-check-gate.sh all`) - to `pre-push`, fail-fast like every other local gate. An advisory smells - gate may run alongside it (Drydock pattern) but must not mask the gating - script's failure. -- [ ] Gate Qlty in CI with the repository-run check, which needs no Qlty Cloud - account. Go repositories call `go-ci.yml` with `run-qlty` enabled, - `qlty-egress-policy: block`, and the proven endpoint allowlist — copy the - allowlist from Portwing's `ci-verify.yml` rather than re-deriving it, and do - not widen it. Node repositories run the SHA-pinned - `qltysh/qlty-action/install` plus the same gate script inside their own - workflow (Drydock pattern). - -The Qlty Cloud GitHub App's statuses (`qlty check`, `qlty coverage`, -`qlty coverage diff`) currently error organization-wide with out-of-minutes -billing failures. Treat them as non-gating: never add them to required status -checks, and do not chase these failures on PRs — the repository-run gate above -is the enforced check. Coverage reporting is Codecov's job (decided -2026-08-16): upload coverage to Codecov and carry its badge in the README. -The Qlty Cloud App and its maintainability badge stay installed, but its -coverage upload is not the coverage system and its checks stay non-required. -Qlty Cloud enrollment and usage data are not an organization-wide -prerequisite; do not make a Cloud upload or check required -until the repository is enrolled and the check has proved stable. Local Qlty -checks may still be stricter than this baseline. +Public projects run routine quality checks in their own CI and useful local +hooks. Keep Qlty CLI where it aggregates useful checks; effective native tools +are also valid. Qlty Cloud supplies periodic reporting for existing dashboards +and README metrics. A Cloud subscription is not needed for standalone CLI checks. + +- [ ] Record adoption work or a concrete applicability decision in the project's + private internal roadmap, with an owner, next action and checkable completion + conditions. Metadata-only repositories do not need a new scanner or dashboard + without a useful signal. +- [ ] Where Qlty CLI is used, commit `.qlty/qlty.toml` with exclusions for + generated, minified and vendored paths. Review changes to shared CLI/Cloud + configuration as quality-gate changes. Preserve useful existing checks rather + than duplicating them through another tool. +- [ ] Run the repository's quality gate in CI and useful local hooks. Advisory + duplication/complexity reports must not mask a gate failure. The shared + `go-ci.yml` supports `run-qlty`, which invokes `scripts/ci/go-qlty.sh` in the + caller repository. Keep the existing input default and check name; consumers + adopt changes through deliberate full-SHA pin updates. Node repositories can + use the SHA-pinned `qltysh/qlty-action/install` and their own gate script. +- [ ] For existing Qlty Cloud maintainability reporting, set default-branch + Analysis Frequency to `1 month` in Project Settings > General. A manual scan + for a release or important change is acceptable within the usage budget. The + README maintainability grade represents the last completed scan and may be up + to a month behind the current default branch. +- [ ] Avoid redundant hosted PR analysis after equivalent repository-owned CI + gates are verified. Verify the control stops analysis compute; turning off + comments or commit statuses alone does not establish that scans stop. Do not + weaken branch protection. Any replacement for a required gate goes through a + reviewed repository change and must be verified on the intended commit first. +- [ ] Preserve useful coverage reporting, enforcement and badges, including + Codecov where already adopted. Each Qlty coverage upload costs one standard + analysis minute, including each separately uploaded server-merge part. Count + all workspace scans, uploads, runner multipliers and retries before claiming + the allowance is sufficient. Do not silently reduce PR coverage enforcement + to save reporting minutes. +- [ ] Verify provider-side commit identity, actual analysis/coverage content and + badge freshness after changing settings. Classify quota failures separately + from real analysis/upload failures; a successful upload step or status alone + does not establish delivery or a completed scan. + +This operating policy retains useful Qlty CLI and periodic Cloud reporting. It +does not introduce Sonar, require a paid upgrade, or automatically enroll every +repository in a hosted service. The reusable workflows keep their existing +interfaces and opt-in defaults; a caller's workflow does not configure Qlty +Cloud's service-side scheduling. + +See Qlty's [analysis frequency](https://docs.qlty.sh/cloud/analysis-frequency), +[analysis-minute accounting](https://docs.qlty.sh/cloud/billing/analysis-minutes), +and [CLI versus Cloud](https://docs.qlty.sh/cli-vs-cloud) documentation. ## 5. Add delivery controls only for shipped artifacts diff --git a/renovate.json b/renovate.json index 6bba2f8..3e6d303 100644 --- a/renovate.json +++ b/renovate.json @@ -1,4 +1,8 @@ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "extends": ["local>CodesWhat/.github:renovate-config"] + "extends": ["local>CodesWhat/.github:renovate-config"], + "dependencyDashboardApproval": true, + "prConcurrentLimit": 1, + "prHourlyLimit": 1, + "branchConcurrentLimit": 1 } diff --git a/scripts/generate_profile_svg.py b/scripts/generate_profile_svg.py index 436b7c6..06b4025 100644 --- a/scripts/generate_profile_svg.py +++ b/scripts/generate_profile_svg.py @@ -4,7 +4,6 @@ Creates dark_mode.svg and light_mode.svg. """ -import re from pathlib import Path @@ -92,7 +91,7 @@ def generate_svg(mode="dark"): ] # Wordmark auto-scales to fit the canvas, capped at the logo font size - wordmark_max_len = max(len(l.rstrip()) for l in wordmark_art) + wordmark_max_len = max(len(line.rstrip()) for line in wordmark_art) wordmark_font_size = round(min(font_size, (width - 40) / (0.6 * wordmark_max_len)), 1) wordmark_char_width = wordmark_font_size * 0.6 wordmark_line_height = round(wordmark_font_size * 1.2) @@ -145,7 +144,7 @@ def generate_svg(mode="dark"): # Art lines have ragged lengths; center the block as a whole off the # widest line so every line shares one left edge - art_max_len = max(len(l) for l in logo_art) + art_max_len = max(len(line) for line in logo_art) art_start_x = (width - art_max_len * char_width) / 2 solid_chars = set('█▓▌▐▄▀') diff --git a/scripts/validate.sh b/scripts/validate.sh index e6d9504..8f5f86f 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -17,17 +17,18 @@ python3 .github/tests/greptile_config_contract_test.py python3 .github/tests/quality_report_contract_test.py python3 .github/tests/reusable_ci_contract_test.py python3 .github/tests/renovate_config_contract_test.py +python3 .github/tests/starchart_refresh_contract_test.py +python3 .github/tests/main_is_released_contract_test.py +python3 .github/tests/tracked_validation_test.py echo "==> compile python" -python3 -m compileall -q . +python3 scripts/validate_tracked_files.py python echo "==> parse yaml and json" -ruby -e 'require "yaml"; Dir.glob("**/*.{yml,yaml}", File::FNM_DOTMATCH).sort.each { |path| YAML.parse_file(path) }' -python3 -c 'import json; from pathlib import Path; [json.load(path.open()) for path in Path(".").rglob("*.json")]' +python3 scripts/validate_tracked_files.py data echo "==> markdownlint" -npx --yes markdownlint-cli2@0.23.2 "**/*.md" "#profile/README.md" -npx --yes markdownlint-cli2@0.23.2 "profile/README.md" --config .github/markdownlint-profile.yaml +python3 scripts/validate_tracked_files.py markdown echo "==> actionlint" if command -v actionlint >/dev/null 2>&1; then diff --git a/scripts/validate_tracked_files.py b/scripts/validate_tracked_files.py new file mode 100644 index 0000000..347903d --- /dev/null +++ b/scripts/validate_tracked_files.py @@ -0,0 +1,59 @@ +import argparse +import json +import os +from pathlib import Path +import py_compile +import subprocess +import sys + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("kind", choices=("python", "data", "markdown")) + kind = parser.parse_args().kind + root = subprocess.check_output( + ["git", "rev-parse", "--show-toplevel"], text=True, + ).strip() + os.chdir(root) + # NUL delimiters preserve filenames containing spaces or newlines. + paths = [ + Path(os.fsdecode(path)) + for path in subprocess.check_output(["git", "ls-files", "-z"]).split(b"\0") + if path + ] + + if kind == "python": + for path in paths: + if path.suffix == ".py": + py_compile.compile(str(path), doraise=True) + elif kind == "data": + for path in paths: + if path.suffix == ".json": + with path.open() as source: + json.load(source) + yaml_paths = [str(path) for path in paths if path.suffix in (".yml", ".yaml")] + if yaml_paths: + subprocess.run( + ["ruby", "-e", 'require "yaml"; ARGV.each { |path| YAML.parse_file(path) }', + "--", *yaml_paths], check=True, + ) + else: + profile = Path("profile/README.md") + markdown = [path for path in paths if path.suffix == ".md" and path != profile] + command = ["npx", "--yes", "markdownlint-cli2@0.23.2", "--no-globs"] + if markdown: + subprocess.run( + [*command, *[":./" + str(path) for path in markdown]], check=True, + ) + if profile in paths: + subprocess.run( + [*command, ":./" + str(profile), + "--config", ".github/markdownlint-profile.yaml"], check=True, + ) + + +if __name__ == "__main__": + try: + main() + except subprocess.CalledProcessError as error: + sys.exit(error.returncode) From 2684d4d44215c67c52826ca72eedbd1706ebb367 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:36:13 -0400 Subject: [PATCH 27/44] chore(renovate): target dev/repository-standards (#50) Without a base branch pattern Renovate opens PRs against main, which in this repo only moves through promotion PRs. Point it at the integration branch, the same way the onboarding checklist tells other repos to. --- renovate.json | 1 + 1 file changed, 1 insertion(+) diff --git a/renovate.json b/renovate.json index 3e6d303..976ab53 100644 --- a/renovate.json +++ b/renovate.json @@ -1,6 +1,7 @@ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": ["local>CodesWhat/.github:renovate-config"], + "baseBranchPatterns": ["dev/repository-standards"], "dependencyDashboardApproval": true, "prConcurrentLimit": 1, "prHourlyLimit": 1, From 488b322d1583a3ebbdd8fd89346322d508746389 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:44:41 -0400 Subject: [PATCH 28/44] docs(onboarding): align checklist with contextual guidance (#51) * docs(onboarding): align checklist with contextual guidance - docs(onboarding): present the integration branch, Renovate, Lefthook and Qlty as recommended recipes and accept effective existing alternatives - docs(onboarding): replace the retired queue section with pacing guidance - docs(onboarding): drop the reset-main migration option; published history is preserved - docs(onboarding): grant contents: read on the main-is-released calling job, since a reusable workflow cannot raise its caller's permissions - docs(onboarding): make Star History the chart choice and keep starchart-refresh for existing pins until they migrate - docs(agents): account for content landed on main before the ours reconcile - docs(workflows): show the job-level grant in the main-is-released caller comment (comment only, interface unchanged) * fix(validation): ignore repo-local git env and lock suite parity - fix(validation): strip git's repo-local variables from the validator's git calls so an inherited GIT_INDEX_FILE or GIT_DIR cannot redirect them - test(validation): cover a bogus GIT_INDEX_FILE against a temp repo - test(contracts): assert validate.sh and Standards Validation run the same contract suites as the files in .github/tests * docs(onboarding): wrap long lines * test(contracts): match only executable suite commands --- .../tests/community_health_contract_test.py | 11 + .github/tests/tracked_validation_test.py | 25 +- .github/workflows/main-is-released.yml | 2 + AGENTS.md | 21 +- REPOSITORY_ONBOARDING.md | 219 ++++++++++-------- scripts/validate_tracked_files.py | 13 +- 6 files changed, 178 insertions(+), 113 deletions(-) diff --git a/.github/tests/community_health_contract_test.py b/.github/tests/community_health_contract_test.py index d62de0f..1ceab2e 100644 --- a/.github/tests/community_health_contract_test.py +++ b/.github/tests/community_health_contract_test.py @@ -183,6 +183,17 @@ def test_standards_workflow_pins_actions_and_runs_every_contract(self): ): self.assertIn(expected, workflow) + def test_local_validation_runs_every_ci_contract_suite(self): + pattern = r"(?m)^[ \t]*python3[ \t]+\.github/tests/([A-Za-z0-9_]+_test\.py)[ \t]*$" + ci = set(re.findall( + pattern, self.read_text(".github/workflows/standards-validation.yml"), + )) + local = set(re.findall(pattern, self.read_text("scripts/validate.sh"))) + present = {path.name for path in (ROOT / ".github/tests").glob("*_test.py")} + + self.assertEqual(ci, local) + self.assertEqual(present, ci) + def test_zizmor_action_owns_its_supported_cli_version(self): workflow = self.read_text(".github/workflows/standards-validation.yml") zizmor_step = workflow.split( diff --git a/.github/tests/tracked_validation_test.py b/.github/tests/tracked_validation_test.py index b657ab1..7154d67 100644 --- a/.github/tests/tracked_validation_test.py +++ b/.github/tests/tracked_validation_test.py @@ -1,4 +1,5 @@ from pathlib import Path +import os import subprocess import sys import tempfile @@ -9,6 +10,13 @@ VALIDATOR = ROOT / "scripts/validate_tracked_files.py" +def git_env(): + names = subprocess.check_output( + ["git", "rev-parse", "--local-env-vars"], text=True, + ).split() + return {key: value for key, value in os.environ.items() if key not in names} + + class TrackedValidationTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory(prefix="tracked-validation-") @@ -16,7 +24,7 @@ def setUp(self): self.repo = Path(self.temp.name) subprocess.run( ["git", "init", "--quiet", str(self.repo)], check=True, - capture_output=True, + capture_output=True, env=git_env(), ) self.write(".gitignore", ".planning/\n.claude/\n__pycache__/\n", tracked=True) @@ -27,13 +35,13 @@ def write(self, name, content, tracked=False): if tracked: subprocess.run( ["git", "add", "--", name], cwd=self.repo, check=True, - capture_output=True, + capture_output=True, env=git_env(), ) - def run_validation(self, kind): + def run_validation(self, kind, env=None): return subprocess.run( [sys.executable, str(VALIDATOR), kind], cwd=self.repo, - capture_output=True, text=True, timeout=60, + capture_output=True, text=True, timeout=60, env=env, ) def assert_valid(self, kind): @@ -92,6 +100,15 @@ def test_profile_keeps_its_separate_rules(self): self.write("profile/README.md", "
Profile
\n", tracked=True) self.assert_invalid("markdown", "MD009") + def test_repo_local_git_environment_is_ignored(self): + self.write(".github/bad.json", "{broken", tracked=True) + env = {**os.environ, "GIT_INDEX_FILE": str(self.repo / "bogus-index")} + result = self.run_validation("data", env=env) + self.assertNotEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn("JSONDecodeError", result.stdout + result.stderr) + self.write(".github/bad.json", '{"ok": true}\n', tracked=True) + self.assertEqual(0, self.run_validation("data", env=env).returncode) + def test_empty_tracked_input_sets_succeed(self): for kind in ("python", "data", "markdown"): with self.subTest(kind=kind): diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml index 361b473..0c55677 100644 --- a/.github/workflows/main-is-released.yml +++ b/.github/workflows/main-is-released.yml @@ -14,6 +14,8 @@ name: Main Is Released # permissions: {} # jobs: # released: +# permissions: +# contents: read # A reusable workflow cannot raise its caller's grant. # uses: CodesWhat/.github/.github/workflows/main-is-released.yml@ # # Continuously deployed repositories that never tag (a website, a meta repo) diff --git a/AGENTS.md b/AGENTS.md index 956f396..acd5c33 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,21 +25,26 @@ contract tests that pin the shapes other repositories depend on. with safe defaults, never repurpose an existing input, and let consumers adopt by rolling their pin deliberately. - PRs target `dev/repository-standards`. `main` advances only through - promotion PRs. Reconcile before promoting: + promotion PRs. Before reconciling, account for released content: + `git log --oneline origin/dev/repository-standards..origin/main` should list + only the previous promotion's squash commit. Any other commit is content that + landed on `main` directly; forward-port it to dev through a normal reviewed PR + first, because the `ours` merge keeps dev's tree and silently drops it. Then + reconcile: `git merge -s ours origin/main -m "chore(sync): reconcile main before promotion"`. Verify promotions with tree equality (`git diff --quiet origin/main origin/dev/repository-standards`), never commit ancestry. -- Admit new hosted review/heavy CI work through the shared capacity roster. - Keep preparation local while queued. After admission, add `review-ready` for - the first CodeRabbit review; request subsequent fix-batch reviews explicitly. +- There is no shared admission queue; pace hosted review and heavy CI with + the maintainer directly. Add `review-ready` for a PR's first CodeRabbit + review and request subsequent fix-batch reviews explicitly. Freeze pushes while review runs, read its output and verify the covered head. `.coderabbit.yaml` keeps default/dev targets but disables automatic review on ordinary pushes. Required review and protection remain effective. -- Approve ordinary dependency updates in the Renovate dashboard only after - admission. This repo's wrapper limits ordinary PRs/branches to one at a time - and one new PR per hour. The shared preset is unchanged; urgent vulnerability - updates keep their separate handling. +- Approve ordinary dependency updates in the Renovate dashboard one at a time. + This repo's wrapper targets `dev/repository-standards` and limits ordinary + PRs/branches to one at a time and one new PR per hour. The shared preset is + unchanged; urgent vulnerability updates keep their separate handling. - Commits are plain Conventional Commits, `(scope): `, no emoji, no AI attribution trailers. - Never weaken branch protection or rulesets to land a change. diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index 06068c5..a95300b 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -10,14 +10,22 @@ This document defines the target state for a repository being onboarded. Its presence in the standards repository does not certify that an existing repository has already passed the checklist. +Each item is either a requirement, which applies when its trigger does and +protects a named outcome, or a recommended recipe. A repository that already +meets the outcome another way keeps its choice: effective existing alternatives +are accepted without a waiver. Established products keep their current release +and verification contracts until a scoped change updates them. + ## 1. Classify the repository - [ ] Record its purpose, owner, visibility, and lifecycle: public product, public infrastructure, permanently private, or pre-public. -- [ ] Set `main` as the default branch and create one active development or - integration branch. Ordinary changes merge from a feature or fix branch into - that branch. `main` advances only through a reviewed PR from the active - branch, never from an independent commit or feature branch. +- [ ] Set `main` as the default branch and record the repository's branch and + release model in `AGENTS.md`. Recommended recipe for a tagged product: one + active development or integration branch that ordinary changes merge into, + with `main` advancing only through a reviewed promotion PR. Trunk development + with immutable release tags, or a site that verifies its deployed commit, is + equally acceptable when it fits the artifact. - [ ] Decide whether it publishes any artifact: a binary, package, container, website, documentation site, Homebrew formula or cask, or GitHub release. - [ ] Inventory its languages, package managers, generated files, external @@ -88,7 +96,9 @@ repositories. Language-specific tests do not. ### Dependency updates and automated review -- [ ] Add `renovate.json` with the organization preset: +- [ ] Give the repository an automated dependency-update path that includes + the lockfile changes. Recommended recipe: `renovate.json` with the + organization preset: ```json { @@ -97,16 +107,18 @@ repositories. Language-specific tests do not. } ``` -- [ ] If the repository uses an integration branch, add exactly one - `baseBranchPatterns` entry for the active branch. Rotate it when the next + A working Dependabot or equivalent setup is an accepted alternative. + +- [ ] With Renovate on a repository that uses an integration branch, add exactly + one `baseBranchPatterns` entry for the active branch. Rotate it when the next integration branch is cut. Do not use a pattern that matches old and current branches because Renovate will open a duplicate PR set against every match. - [ ] Add only repository-specific Renovate overrides that have a written reason. Keep lockfile updates enabled and verify dependency PRs contain the lockfile changes required by a clean install. -- [ ] Confirm the Renovate GitHub app can access the repository. App access is - managed at the organization level; do not widen a public-only installation - to private repositories as an onboarding shortcut. +- [ ] When using Renovate, confirm its GitHub app can access the repository. App + access is managed at the organization level; do not widen a public-only + installation to private repositories as an onboarding shortcut. - [ ] Where CodeRabbit is adopted, use a root `.coderabbit.yaml` appropriate to the repository. Adopt intentional admission rather than automatically spending review capacity on every in-progress push. Scope opt-in and incremental-review @@ -130,77 +142,78 @@ repositories. Language-specific tests do not. review every PR directly. Inspect the provider's resolved configuration and delivered review rather than assuming a legacy file or summon proves coverage. -### Capacity and queued development - -Public projects use queue-first development, with adoption work recorded in -their private internal roadmaps. Begin with one newly admitted hosted-review or -heavy-CI candidate across public projects for a seven-day measured pilot. Finish -existing in-flight work safely. A named coordinator records the candidate's -owner, head/base, dependencies, local verification, services, review-pass count, -blocked reason and next eligible time before new expensive work starts. - -Keep one active change per repo and at most one small dependent successor local. -Pilot two-layer stacks for genuine dependencies; verify trunk, bot and merge -compatibility. Draft and stacked PRs can still run CI and deploys. Keep diffs -small, aiming around 25 changed files and within the actual reviewer limit; -batching many unrelated items into one oversized PR is not admission control. - -Freeze pushes during review, then submit one batch of fixes per pass. Prioritize -finishing admitted work over opening another PR. Keep the three-pass cap, all -required checks and valid approvals. Record cooldowns and wait for recovery -without repeated review summons, workflow reruns or indefinite polling. Review -capacity after the pilot using actual service pools before expanding concurrency. - -Admit one new deployment-producing web candidate per shared deployment pool -initially. Pilot ordinary dependency arrivals at one concurrent PR and one new -PR/hour per repo, with staggered schedules or dashboard admission and urgent -vulnerability handling retained. Retain the monthly Qlty reporting policy below. -Provider settings, bot controls and required CI changes need scoped reviewed -rollouts; documentation alone does not configure them. Metadata-only projects -record applicable controls without installing irrelevant tools or paid services. - -This shared repository pilots the controls in its own configuration, without -changing the live Renovate preset for consumers. The coordinator approves an -ordinary dependency update in the dashboard only after admission; the local -wrapper permits one ordinary PR/branch and one new PR per hour. Urgent -vulnerability handling remains separate. After admitting a stable review -candidate, apply `review-ready` for its first CodeRabbit review. Later fix -batches use an explicit review request; pushes do not automatically start -another review. Verify the provider's resolved configuration and delivered head -after landing these settings before claiming the pilot is operational. +### Capacity and pacing + +There is no shared admission queue. Pace hosted review, heavy CI and +deployments so one project does not starve the shared pools, and coordinate +timing with the maintainer directly. Keep queued development in the project's +private internal roadmap. + +Keep one active change per repository and at most one small dependent successor +local. Keep diffs small, aiming around 25 changed files and within the actual +reviewer limit; batching many unrelated items into one oversized PR is not +pacing. + +Freeze pushes during review, then submit one batch of fixes per pass. Finish +open work before opening another PR. Keep the three-pass cap, all required +checks and valid approvals. When a provider is in cooldown, wait for recovery +without repeated review summons, workflow reruns or indefinite polling. + +Ordinary dependency arrivals run at one concurrent PR and one new PR per hour +per repository, through staggered schedules or dashboard approval, with urgent +vulnerability handling kept separate. Provider settings, bot controls and +required CI changes need scoped reviewed rollouts; documentation alone does not +configure them. Metadata-only projects record applicable controls without +installing irrelevant tools or paid services. The Qlty reporting policy is in +section 4. + +This repository runs those controls in its own configuration without changing +the Renovate preset that consumers extend. Its wrapper targets the integration +branch and allows one ordinary PR and branch at a time and one new PR per hour, +and dashboard updates are approved one at a time. Apply `review-ready` for a +PR's first CodeRabbit review. Later fix batches use an explicit review request, +because pushes do not start another review. ### Local gates -- [ ] Add a root `lefthook.yml` and document how contributors install Lefthook. -- [ ] Add a `commit-msg` command that enforces plain Conventional Commits: +Run the checks CI enforces locally before pushing. Recommended recipe: a root +`lefthook.yml` with the hooks below, with install steps in `AGENTS.md`. An +existing hook runner such as Husky or pre-commit, or a documented validation +script, is accepted when it covers the same checks. + +- [ ] Enforce the repository's commit convention at `commit-msg`. Without an + existing convention, use plain Conventional Commits: `(scope): `. Allowed types are `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, and `revert`. Do not weaken or bypass an existing commit-message hook. -- [ ] Make `pre-push` sequential and fail-fast. Start with a clean-tree check, - then run the same formatter/linter, tests, build, and workflow-security checks - that CI enforces. A missing optional local tool may be reported and left to - CI, but a tool that is installed must not have its failure swallowed. +- [ ] Make the pre-push check sequential and fail-fast. Start with a clean-tree + check, then run the same formatter/linter, tests, build, and workflow-security + checks that CI enforces. A missing optional local tool may be reported and + left to CI, but a tool that is installed must not have its failure swallowed. - [ ] Add language formatters to `pre-commit` only when they can safely operate on staged files. Verify the hook does not rewrite unrelated work. -Qlty spans local and CI gates; the full baseline, including why Qlty Cloud -checks stay non-required, is in the Qlty subsection of section 4. +Qlty is optional. Its recommended use across local and CI gates, including why +Qlty Cloud checks stay non-required, is in the Qlty subsection of section 4. ## 3. Protect `main` -`main` is the released version, not the newest work. It always equals what -users currently have: the GA tag on a versioned product, production on a -continuously deployed site. It is never the GA tag plus merged work that has -not shipped. The next version lives on its own branch, `dev/vX.Y`, which is -the integration target for every feature pull request, and prereleases are -tagged there rather than on `main`. +The recommended model for a tagged product makes `main` the released +version, not the newest work. It always equals what users currently have, the +GA tag, and is never the GA tag plus merged work that has not shipped. In that +recipe the next version lives on its own branch, `dev/vX.Y`, which is the +integration target for feature pull requests, and prereleases are tagged there +rather than on `main`. A continuously deployed site verifies its deployed commit +instead, and a trunk model identifies releases through immutable tags and +artifacts. The branch ruleset below applies to every model. The reason is measurement accuracy rather than tidiness. OpenSSF Scorecard, CodeQL default-branch analysis, Dependabot alerts, README badges, and every published vulnerability report describe the default branch and nothing else. Unshipped work on `main` makes all of them describe software no user runs. -One invariant covers it, and it is mechanical rather than a judgement call: +For a released-`main` repository, one invariant covers it, and it is +mechanical rather than a judgement call: ```sh git describe --exact-match origin/main @@ -218,13 +231,13 @@ drifts, and an incorrect README is a defect in the released version like any other. Fix it on a hotfix branch and cut a patch release. For that to stay honest, a documentation-only release must skip artifact publication — GoReleaser, signing, deb/rpm, Homebrew, npm — or maintainers will route around -the rule. Generated assets committed to the repository, such as a star-history -chart, regenerate at the release cut rather than on a schedule that commits to -a branch, so they cannot change underneath a tag. +the rule. Generated assets committed to the repository, such as a chart +SVG, regenerate at the release cut rather than on a schedule that commits to a +branch, so they cannot change underneath a tag. Adopting this on a repository whose `main` is already ahead of its newest tag -means either cutting a release or resetting `main` to the last released tag. -That is the maintainer's decision, because it changes what every user sees. +means cutting a release at the next appropriate boundary. Never move published +history backward to adopt the model. Create an active branch ruleset named `Main branch protection`, targeting only the default branch. Its baseline is: @@ -299,38 +312,45 @@ Add these only when the behavior exists: with a clear enforced or advisory threshold. - [ ] Translation synchronization only for a repository with a translation source of truth and configured provider credentials. -- [ ] Release-invariant enforcement for a repository that tags releases. Call - this repository's `main-is-released.yml` at a pinned full commit SHA from a - thin caller on `schedule` plus `push` to `main` plus `workflow_dispatch`. The - called workflow declares `contents: read` itself, and a reusable workflow can - only narrow what the caller grants, so the caller needs no `permissions` - block beyond the top-level `permissions: {}` — a job-level grant would only - widen the ceiling it runs under. It asserts the section 3 invariant: an +- [ ] Release-invariant enforcement for a repository that defines `main` as its + tagged release. Call this repository's `main-is-released.yml` at a pinned + full commit SHA from a thin caller on `schedule` plus `push` to `main` plus + `workflow_dispatch`. A reusable workflow cannot raise the permissions its + caller grants, so a caller with top-level `permissions: {}` must grant + `contents: read` on the calling job: + + ```yaml + on: + schedule: [{cron: "23 7 * * *"}] + push: + branches: [main] + workflow_dispatch: + permissions: {} + jobs: + released: + permissions: + contents: read + uses: CodesWhat/.github/.github/workflows/main-is-released.yml@ + ``` + + It asserts the section 3 invariant: an untagged `main` head fails, and so does a prerelease tag unless the caller passes `allow-prerelease: true`. A repository that never tags, such as a continuously deployed site or a meta repository, should not call this at all rather than call it with a carve-out; for those, "`main` equals production" is enforced by the deploy. -- [ ] Star-history chart refresh for a public repository whose README carries a - Star History section. Call this repository's `starchart-refresh.yml` at a - pinned full commit SHA from a thin caller on `release: [published]` plus - `workflow_dispatch`, granting the job `contents: write` and passing the - active integration branch as `branch` and the repository's logo colour as - `accent`. It regenerates a first-party SVG pair from GitHub's stargazer - timestamps and commits only when the chart actually changed. The trigger is - the release cut rather than a schedule because a committed artifact - refreshed on a cron mutates underneath a tag, which section 3 forbids. The - chart is a committed artifact rather than a live route or a third-party - embed on purpose: it needs no secret and makes no request at render time, so - a stale one is visible and a missing one is a visibly broken image, where a - route that loses its credential serves a plausible placeholder at HTTP 200 - indefinitely. Two files ship, `star-history.svg` and `star-history-dark.svg`, - because GitHub's theme toggle does not reach a media query inside an - ``-embedded SVG but does drive a `` element in the README, so - the markup chooses and the `` stays the fallback for anything that does - not understand ``. Do not embed `star-history.com` or - `warpchart.dev`; both are retired organization-wide, and adopting the chart - means removing what it replaced in the same change. +- [ ] A star chart is optional. A public repository that shows one uses Star + History: open it for the actual owner and repository, copy its current README + snippet, and verify the rendered README in both themes while signed out. + Generate a fresh snippet for that repository and never paste a raw GitHub + credential into the README. A hosted chart is live presentation rather than + a release artifact, so it needs no refresh workflow. +- [ ] A repository that still commits a first-party star-history SVG pair keeps + its pinned `starchart-refresh.yml` caller, on `release: [published]` plus + `workflow_dispatch` with the job granted `contents: write`, until it moves to + Star History through its own reviewed change. Trace other consumers of the + committed SVGs, such as a website, before removing them or the caller. The + reusable workflow keeps its interface for existing pins. ### Qlty @@ -419,10 +439,11 @@ and [CLI versus Cloud](https://docs.qlty.sh/cli-vs-cloud) documentation. Actions workflows are present. - [ ] Install dependencies from a clean checkout, run the full local hook pipeline, and run the production build. -- [ ] Open a feature-to-active-branch PR, then an active-branch-to-`main` PR. - Use the branch selected in section 1. Wait for all CI and an explicit - CodeRabbit review on both, address every actionable finding, and obtain the - required non-author and code-owner approvals. +- [ ] Open a feature PR into the repository's integration target and, when it + promotes to `main`, a promotion PR. Use the model recorded in section 1. Wait + for all CI and the delivered review the repository requires on each, address + every actionable finding, and obtain the required non-author and code-owner + approvals. - [ ] Confirm the PR cannot merge while a required job is pending or failing. Never weaken branch protection to perform this test or to clear `REVIEW_REQUIRED`. diff --git a/scripts/validate_tracked_files.py b/scripts/validate_tracked_files.py index 347903d..ee904ff 100644 --- a/scripts/validate_tracked_files.py +++ b/scripts/validate_tracked_files.py @@ -7,18 +7,27 @@ import sys +def git_env(): + """Environment without git's repo-local variables (GIT_DIR, GIT_INDEX_FILE, ...).""" + names = subprocess.check_output( + ["git", "rev-parse", "--local-env-vars"], text=True, env=os.environ.copy(), + ).split() + return {key: value for key, value in os.environ.items() if key not in names} + + def main(): parser = argparse.ArgumentParser() parser.add_argument("kind", choices=("python", "data", "markdown")) kind = parser.parse_args().kind + env = git_env() root = subprocess.check_output( - ["git", "rev-parse", "--show-toplevel"], text=True, + ["git", "rev-parse", "--show-toplevel"], text=True, env=env, ).strip() os.chdir(root) # NUL delimiters preserve filenames containing spaces or newlines. paths = [ Path(os.fsdecode(path)) - for path in subprocess.check_output(["git", "ls-files", "-z"]).split(b"\0") + for path in subprocess.check_output(["git", "ls-files", "-z"], env=env).split(b"\0") if path ] From 9d54f4908d5cba6a9401d3c11cce3990e6b282dc Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:56:37 -0400 Subject: [PATCH 29/44] chore(deps): update non-major (github-actions) (#53) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/go-ci.yml | 30 +++++++++---------- .github/workflows/greptile-summon.yml | 2 +- .github/workflows/main-is-released.yml | 2 +- .github/workflows/node-ci.yml | 16 +++++----- .github/workflows/profile-assets.yml | 2 +- .../workflows/quality-report-aggregate.yml | 6 ++-- .github/workflows/release-gate.yml | 2 +- .github/workflows/standards-validation.yml | 12 ++++---- .github/workflows/starchart-refresh.yml | 2 +- 9 files changed, 37 insertions(+), 37 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 8e14b1c..637fdd7 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -177,7 +177,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.test-egress-policy }} allowed-endpoints: ${{ inputs.test-allowed-endpoints }} @@ -200,7 +200,7 @@ jobs: - name: Upload Go test artifacts if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: go-test-${{ github.run_id }}-${{ github.run_attempt }} path: artifacts/go-test/ @@ -217,7 +217,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.lint-egress-policy }} allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} @@ -248,7 +248,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.govulncheck-egress-policy }} allowed-endpoints: ${{ inputs.govulncheck-allowed-endpoints }} @@ -280,7 +280,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.workflow-security-egress-policy }} allowed-endpoints: ${{ inputs.workflow-security-allowed-endpoints }} @@ -291,7 +291,7 @@ jobs: persist-credentials: false - name: Run zizmor - uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 + uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 with: token: ${{ github.token }} advanced-security: false @@ -307,7 +307,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.commit-message-egress-policy }} allowed-endpoints: ${{ inputs.commit-message-allowed-endpoints }} @@ -334,7 +334,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.goreleaser-egress-policy }} allowed-endpoints: ${{ inputs.goreleaser-allowed-endpoints }} @@ -367,7 +367,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.codeql-egress-policy }} allowed-endpoints: ${{ inputs.codeql-allowed-endpoints }} @@ -378,7 +378,7 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 with: languages: actions, go queries: security-and-quality @@ -395,7 +395,7 @@ jobs: run: ./scripts/ci/go-codeql-build.sh - name: Analyze with CodeQL - uses: github/codeql-action/analyze@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 qlty: name: Qlty Check @@ -407,7 +407,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.qlty-egress-policy }} allowed-endpoints: ${{ inputs.qlty-allowed-endpoints }} @@ -418,7 +418,7 @@ jobs: persist-credentials: false - name: Set up Qlty - uses: qltysh/qlty-action/install@08a0a862c159eae9b9003081da6663d96efef637 # v2.3.0 + uses: qltysh/qlty-action/install@c9b09987143d1e4ac955f4803c7bea742102feb5 # v2.4.0 - name: Run repository Qlty gate env: @@ -439,7 +439,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.fuzz-egress-policy }} allowed-endpoints: ${{ inputs.fuzz-allowed-endpoints }} @@ -464,7 +464,7 @@ jobs: - name: Upload Go fuzz artifacts if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: go-fuzz-${{ matrix.fuzzer.name }}-${{ github.run_id }}-${{ github.run_attempt }} path: artifacts/go-fuzz/ diff --git a/.github/workflows/greptile-summon.yml b/.github/workflows/greptile-summon.yml index 3484f9b..884702c 100644 --- a/.github/workflows/greptile-summon.yml +++ b/.github/workflows/greptile-summon.yml @@ -32,7 +32,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: block allowed-endpoints: > diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml index 0c55677..fa41459 100644 --- a/.github/workflows/main-is-released.yml +++ b/.github/workflows/main-is-released.yml @@ -46,7 +46,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: block allowed-endpoints: > diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index c953151..18f2ec6 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -92,7 +92,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.lint-egress-policy }} allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} @@ -103,7 +103,7 @@ jobs: persist-credentials: false - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ inputs.node-version }} cache: npm @@ -124,7 +124,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.test-egress-policy }} allowed-endpoints: ${{ inputs.test-allowed-endpoints }} @@ -135,7 +135,7 @@ jobs: persist-credentials: false - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ inputs.node-version }} cache: npm @@ -148,7 +148,7 @@ jobs: - name: Upload Node test artifacts if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: node-test-${{ github.run_id }}-${{ github.run_attempt }} path: artifacts/node-test/ @@ -165,7 +165,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: ${{ inputs.build-egress-policy }} allowed-endpoints: ${{ inputs.build-allowed-endpoints }} @@ -176,7 +176,7 @@ jobs: persist-credentials: false - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ inputs.node-version }} cache: npm @@ -189,7 +189,7 @@ jobs: - name: Upload Node build artifacts if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: node-build-${{ github.run_id }}-${{ github.run_attempt }} path: artifacts/node-build/ diff --git a/.github/workflows/profile-assets.yml b/.github/workflows/profile-assets.yml index 0fd6154..8a094b2 100644 --- a/.github/workflows/profile-assets.yml +++ b/.github/workflows/profile-assets.yml @@ -38,7 +38,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: block allowed-endpoints: github.com:443 diff --git a/.github/workflows/quality-report-aggregate.yml b/.github/workflows/quality-report-aggregate.yml index 86ef420..5bcd128 100644 --- a/.github/workflows/quality-report-aggregate.yml +++ b/.github/workflows/quality-report-aggregate.yml @@ -79,7 +79,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: audit @@ -107,7 +107,7 @@ jobs: - name: Download normalized target results id: download if: always() - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: pattern: ${{ inputs.result_artifact_pattern }} path: quality-result-artifacts @@ -147,7 +147,7 @@ jobs: - name: Upload normalized quality report if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: quality-report-${{ inputs.track }}-${{ github.run_id }}-${{ github.run_attempt }} path: | diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index f86ff64..9994394 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -34,7 +34,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: block allowed-endpoints: api.github.com:443 diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 112817f..5bb4428 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -23,7 +23,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: audit @@ -33,7 +33,7 @@ jobs: persist-credentials: false - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 @@ -69,7 +69,7 @@ jobs: "$RUNNER_TEMP/actionlint" -color - name: Validate workflows with zizmor - uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 + uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 with: advanced-security: false annotations: true @@ -88,7 +88,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: audit @@ -98,11 +98,11 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 with: languages: python - name: Analyze - uses: github/codeql-action/analyze@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 with: category: /language:python diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index 41b9d0a..cc018c5 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -135,7 +135,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 with: egress-policy: block allowed-endpoints: > From 4d3b129e9d432a774cd761e28f8628309c6b4627 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 09:24:44 -0400 Subject: [PATCH 30/44] chore(deps): update dependency ubuntu to v26 (#55) * chore(deps): update dependency ubuntu to v26 * test(contracts): expect ubuntu-26.04 runners The workflows move to the GA ubuntu-26.04 image in this PR, so the contract tests that pin the runner label move with them. * ci(actionlint): declare the ubuntu-26.04 runner label actionlint 1.7.12 predates the GA ubuntu-26.04 label and rejects it. Declare it in .github/actionlint.yaml until a release knows it, and test that the config never ignores findings. * test(contracts): pin the actionlint config to the one label --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: scttbnsn <80784472+scttbnsn@users.noreply.github.com> --- .github/actionlint.yaml | 6 ++++++ .../tests/community_health_contract_test.py | 14 +++++++++++++- .github/tests/greptile_summon_contract_test.py | 2 +- .../tests/main_is_released_contract_test.py | 2 +- .github/tests/reusable_ci_contract_test.py | 2 +- .../tests/starchart_refresh_contract_test.py | 2 +- .github/workflows/go-ci.yml | 18 +++++++++--------- .github/workflows/greptile-summon.yml | 2 +- .github/workflows/main-is-released.yml | 2 +- .github/workflows/node-ci.yml | 6 +++--- .github/workflows/profile-assets.yml | 2 +- .github/workflows/quality-report-aggregate.yml | 2 +- .github/workflows/release-gate.yml | 2 +- .github/workflows/standards-validation.yml | 4 ++-- .github/workflows/starchart-refresh.yml | 2 +- 15 files changed, 43 insertions(+), 25 deletions(-) create mode 100644 .github/actionlint.yaml diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..6b2b66d --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,6 @@ +# actionlint 1.7.12 predates GitHub's ubuntu-26.04 hosted runner label, which +# went GA on 2026-09-17. Declare it here so actionlint doesn't flag it, and +# delete this file once an actionlint release knows the label. +self-hosted-runner: + labels: + - ubuntu-26.04 diff --git a/.github/tests/community_health_contract_test.py b/.github/tests/community_health_contract_test.py index 1ceab2e..8596696 100644 --- a/.github/tests/community_health_contract_test.py +++ b/.github/tests/community_health_contract_test.py @@ -136,7 +136,7 @@ def test_standards_workflow_has_unconditional_stable_jobs(self): self.assertIn("concurrency:", workflow) self.assertIn("group: standards-validation-", workflow) self.assertIn("cancel-in-progress: true", workflow) - self.assertIn("runs-on: ubuntu-24.04", workflow) + self.assertIn("runs-on: ubuntu-26.04", workflow) self.assertNotIn("matrix:", workflow) self.assertNotIn("continue-on-error:", workflow) self.assertNotIn("\n if:", workflow) @@ -211,6 +211,18 @@ def test_linter_configs_do_not_suppress_workflow_findings(self): self.assertEqual(2, markdown_config.count(": false")) self.assertFalse((ROOT / ".github/zizmor.yml").exists()) + # actionlint config may only declare the hosted runner label actionlint + # doesn't know yet. Anything else, including ignores or a wildcard + # label, would suppress real findings. + actionlint_config = [ + line for line in self.read_text(".github/actionlint.yaml").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + self.assertEqual( + ["self-hosted-runner:", " labels:", " - ubuntu-26.04"], + actionlint_config, + ) + def test_profile_generator_has_one_canonical_location(self): self.assertFalse((ROOT / "generate_svg.py").exists()) self.assertTrue((ROOT / "scripts/generate_profile_svg.py").is_file()) diff --git a/.github/tests/greptile_summon_contract_test.py b/.github/tests/greptile_summon_contract_test.py index 7584077..0cc964d 100644 --- a/.github/tests/greptile_summon_contract_test.py +++ b/.github/tests/greptile_summon_contract_test.py @@ -19,7 +19,7 @@ def test_reusable_workflow_has_exact_head_inputs_and_narrow_permissions(self): " type: string\n", " focus:\n", "permissions: {}", - " runs-on: ubuntu-24.04", + " runs-on: ubuntu-26.04", " timeout-minutes: 5", " pull-requests: write", "uses: step-security/harden-runner@", diff --git a/.github/tests/main_is_released_contract_test.py b/.github/tests/main_is_released_contract_test.py index 3a6fbc5..ff1a826 100644 --- a/.github/tests/main_is_released_contract_test.py +++ b/.github/tests/main_is_released_contract_test.py @@ -14,7 +14,7 @@ def test_reusable_workflow_shape_and_read_only_permissions(self): for expected in ( " workflow_call:\n", "permissions: {}", - " runs-on: ubuntu-24.04", + " runs-on: ubuntu-26.04", "uses: step-security/harden-runner@", "egress-policy: block", "github.com:443", diff --git a/.github/tests/reusable_ci_contract_test.py b/.github/tests/reusable_ci_contract_test.py index b4fc0fa..bf3e762 100644 --- a/.github/tests/reusable_ci_contract_test.py +++ b/.github/tests/reusable_ci_contract_test.py @@ -211,7 +211,7 @@ def test_central_jobs_have_exact_names_fixed_commands_and_per_job_egress(self): ) for workflow in (go, node, self.read_workflow(WORKFLOWS["release"])): - self.assertIn("runs-on: ubuntu-24.04", workflow) + self.assertIn("runs-on: ubuntu-26.04", workflow) for action in re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE): self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$") for run_block in re.findall(r"run: \|\n((?: {10}.*\n|\n)+)", workflow): diff --git a/.github/tests/starchart_refresh_contract_test.py b/.github/tests/starchart_refresh_contract_test.py index 23fa491..e611d67 100644 --- a/.github/tests/starchart_refresh_contract_test.py +++ b/.github/tests/starchart_refresh_contract_test.py @@ -24,7 +24,7 @@ def test_reusable_workflow_shape_and_narrow_permissions(self): " max-pages:\n", " type: number\n", "permissions: {}", - " runs-on: ubuntu-24.04", + " runs-on: ubuntu-26.04", " timeout-minutes: 10", "uses: step-security/harden-runner@", "egress-policy: block", diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 637fdd7..3c3aac8 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -170,7 +170,7 @@ jobs: test: name: ${{ inputs.test-check-name }} if: inputs.run-test - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 permissions: contents: read @@ -210,7 +210,7 @@ jobs: lint: name: ${{ inputs.lint-check-name }} if: inputs.run-lint - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 permissions: contents: read @@ -241,7 +241,7 @@ jobs: govulncheck: name: Govulncheck if: inputs.run-govulncheck - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 permissions: contents: read @@ -272,7 +272,7 @@ jobs: workflow-security: name: Workflow Security if: inputs.run-workflow-security - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 10 permissions: actions: read @@ -300,7 +300,7 @@ jobs: commit-message: name: Commit Message if: inputs.run-commit-message && github.event_name == 'pull_request' - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 10 permissions: contents: read @@ -327,7 +327,7 @@ jobs: goreleaser: name: GoReleaser Config if: inputs.run-goreleaser - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 permissions: contents: read @@ -358,7 +358,7 @@ jobs: codeql: name: CodeQL Analysis if: inputs.run-codeql - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 60 permissions: actions: read @@ -400,7 +400,7 @@ jobs: qlty: name: Qlty Check if: inputs.run-qlty - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 permissions: contents: read @@ -428,7 +428,7 @@ jobs: fuzz: name: "Go Fuzz (${{ matrix.fuzzer.name }})" if: inputs.fuzzers-json != '' && fromJSON(inputs.fuzzers-json)[0] != null - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 15 permissions: contents: read diff --git a/.github/workflows/greptile-summon.yml b/.github/workflows/greptile-summon.yml index 884702c..e50a5d7 100644 --- a/.github/workflows/greptile-summon.yml +++ b/.github/workflows/greptile-summon.yml @@ -22,7 +22,7 @@ permissions: {} jobs: summon: name: Summon Greptile - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 concurrency: group: greptile-summon-${{ github.repository }}-${{ inputs.pr_number }}-${{ inputs.head_sha }} diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml index fa41459..e62e66e 100644 --- a/.github/workflows/main-is-released.yml +++ b/.github/workflows/main-is-released.yml @@ -39,7 +39,7 @@ permissions: {} jobs: released: name: Main Is Released - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: contents: read # Read main and its tags. diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index 18f2ec6..8b9a292 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -85,7 +85,7 @@ jobs: lint: name: ${{ inputs.lint-check-name }} if: inputs.run-lint - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 permissions: contents: read @@ -117,7 +117,7 @@ jobs: test: name: ${{ inputs.test-check-name }} if: inputs.run-test - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 permissions: contents: read @@ -158,7 +158,7 @@ jobs: build: name: ${{ inputs.build-check-name }} if: inputs.run-build - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 permissions: contents: read diff --git a/.github/workflows/profile-assets.yml b/.github/workflows/profile-assets.yml index 8a094b2..51ae0eb 100644 --- a/.github/workflows/profile-assets.yml +++ b/.github/workflows/profile-assets.yml @@ -31,7 +31,7 @@ concurrency: jobs: validate: name: Profile Assets - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: contents: read diff --git a/.github/workflows/quality-report-aggregate.yml b/.github/workflows/quality-report-aggregate.yml index 5bcd128..c0d5515 100644 --- a/.github/workflows/quality-report-aggregate.yml +++ b/.github/workflows/quality-report-aggregate.yml @@ -64,7 +64,7 @@ jobs: aggregate: name: Quality Report Aggregate if: always() - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 10 permissions: actions: read diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index 9994394..ed9a61e 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -27,7 +27,7 @@ permissions: {} jobs: gate: name: Release Gate - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 360 permissions: actions: read diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 5bb4428..3676294 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -15,7 +15,7 @@ concurrency: jobs: validation: name: Standards Validation - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 10 permissions: actions: read # Read workflow metadata @@ -79,7 +79,7 @@ jobs: codeql: name: CodeQL - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 10 permissions: actions: read # Read workflow metadata diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index cc018c5..72ba8d5 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -125,7 +125,7 @@ permissions: {} jobs: refresh: name: Star Chart Refresh - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 10 concurrency: group: starchart-refresh-${{ github.repository }}-${{ inputs.branch }} From 5d1b5817077e17c42bb32b8b72ca0c66d0dd321b Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:13:37 -0400 Subject: [PATCH 31/44] fix(ci): update harden-runner for hosted runner DNS fix (#57) --- .github/workflows/go-ci.yml | 18 +++++++++--------- .github/workflows/greptile-summon.yml | 2 +- .github/workflows/main-is-released.yml | 2 +- .github/workflows/node-ci.yml | 6 +++--- .github/workflows/profile-assets.yml | 2 +- .github/workflows/quality-report-aggregate.yml | 2 +- .github/workflows/release-gate.yml | 2 +- .github/workflows/standards-validation.yml | 4 ++-- .github/workflows/starchart-refresh.yml | 2 +- 9 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 3c3aac8..18532f0 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -177,7 +177,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.test-egress-policy }} allowed-endpoints: ${{ inputs.test-allowed-endpoints }} @@ -217,7 +217,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.lint-egress-policy }} allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} @@ -248,7 +248,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.govulncheck-egress-policy }} allowed-endpoints: ${{ inputs.govulncheck-allowed-endpoints }} @@ -280,7 +280,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.workflow-security-egress-policy }} allowed-endpoints: ${{ inputs.workflow-security-allowed-endpoints }} @@ -307,7 +307,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.commit-message-egress-policy }} allowed-endpoints: ${{ inputs.commit-message-allowed-endpoints }} @@ -334,7 +334,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.goreleaser-egress-policy }} allowed-endpoints: ${{ inputs.goreleaser-allowed-endpoints }} @@ -367,7 +367,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.codeql-egress-policy }} allowed-endpoints: ${{ inputs.codeql-allowed-endpoints }} @@ -407,7 +407,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.qlty-egress-policy }} allowed-endpoints: ${{ inputs.qlty-allowed-endpoints }} @@ -439,7 +439,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.fuzz-egress-policy }} allowed-endpoints: ${{ inputs.fuzz-allowed-endpoints }} diff --git a/.github/workflows/greptile-summon.yml b/.github/workflows/greptile-summon.yml index e50a5d7..755aad6 100644 --- a/.github/workflows/greptile-summon.yml +++ b/.github/workflows/greptile-summon.yml @@ -32,7 +32,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: block allowed-endpoints: > diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml index e62e66e..d83f8b8 100644 --- a/.github/workflows/main-is-released.yml +++ b/.github/workflows/main-is-released.yml @@ -46,7 +46,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: block allowed-endpoints: > diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index 8b9a292..3f1ceab 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -92,7 +92,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.lint-egress-policy }} allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} @@ -124,7 +124,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.test-egress-policy }} allowed-endpoints: ${{ inputs.test-allowed-endpoints }} @@ -165,7 +165,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: ${{ inputs.build-egress-policy }} allowed-endpoints: ${{ inputs.build-allowed-endpoints }} diff --git a/.github/workflows/profile-assets.yml b/.github/workflows/profile-assets.yml index 51ae0eb..8b80126 100644 --- a/.github/workflows/profile-assets.yml +++ b/.github/workflows/profile-assets.yml @@ -38,7 +38,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: block allowed-endpoints: github.com:443 diff --git a/.github/workflows/quality-report-aggregate.yml b/.github/workflows/quality-report-aggregate.yml index c0d5515..efa6c67 100644 --- a/.github/workflows/quality-report-aggregate.yml +++ b/.github/workflows/quality-report-aggregate.yml @@ -79,7 +79,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index ed9a61e..5fce3a0 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -34,7 +34,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: block allowed-endpoints: api.github.com:443 diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 3676294..676b368 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -23,7 +23,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit @@ -88,7 +88,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index 72ba8d5..997fae1 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -135,7 +135,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: block allowed-endpoints: > From 96a60745a3bfeb5cf5eb1e24702f388aaeacd9fd Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:32:09 -0400 Subject: [PATCH 32/44] docs(profile): add CodesWhat brand line and site link (#58) --- profile/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/profile/README.md b/profile/README.md index 0310c13..0a72ab6 100644 --- a/profile/README.md +++ b/profile/README.md @@ -4,3 +4,6 @@ CodesWhat? GitHub Profile + +[CodesWhat](https://codeswhat.com): small, sharp tools from one developer +and a lot of agents. From eaa21ccb25108b99ff12e9c9399f6285eb7d8c42 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:38:39 -0500 Subject: [PATCH 33/44] chore(deps): update non-major (github-actions) (#61) * chore(deps): update non-major (github-actions) * docs(ci): note PyPI endpoints for zizmor block mode --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: scttbnsn <80784472+scttbnsn@users.noreply.github.com> --- .github/workflows/go-ci.yml | 13 ++++++++----- .github/workflows/standards-validation.yml | 6 +++--- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 18532f0..8ece72a 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -109,7 +109,10 @@ on: type: string default: audit workflow-security-allowed-endpoints: - description: Harden Runner allowlist for workflow security + description: >- + Harden Runner allowlist for workflow security. zizmor-action installs + zizmor from PyPI, so block mode must allow pypi.org:443 and + files.pythonhosted.org:443. required: false type: string default: "" @@ -291,7 +294,7 @@ jobs: persist-credentials: false - name: Run zizmor - uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 with: token: ${{ github.token }} advanced-security: false @@ -378,7 +381,7 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 with: languages: actions, go queries: security-and-quality @@ -395,7 +398,7 @@ jobs: run: ./scripts/ci/go-codeql-build.sh - name: Analyze with CodeQL - uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + uses: github/codeql-action/analyze@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 qlty: name: Qlty Check @@ -418,7 +421,7 @@ jobs: persist-credentials: false - name: Set up Qlty - uses: qltysh/qlty-action/install@c9b09987143d1e4ac955f4803c7bea742102feb5 # v2.4.0 + uses: qltysh/qlty-action/install@ebcd284bf32e36a030afe15f1e136c7be08b9506 # v2.5.0 - name: Run repository Qlty gate env: diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 676b368..bf4afa7 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -69,7 +69,7 @@ jobs: "$RUNNER_TEMP/actionlint" -color - name: Validate workflows with zizmor - uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 with: advanced-security: false annotations: true @@ -98,11 +98,11 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 with: languages: python - name: Analyze - uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + uses: github/codeql-action/analyze@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 with: category: /language:python From 0df1d2e39e8250d619452ee991f14790cdfe71a8 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:08:12 -0500 Subject: [PATCH 34/44] fix(quality-report): harden aggregation and wire-check contract tests (#63) * fix(quality-report): reject overflowing numbers, oversized JSON, partial fast-check repro * test(ci): assert every contract test is wired into validate.sh and CI * ci(validation): verify actionlint tarball against a pinned sha256 * fix(quality-report): pin int digit limit in tests, mirror fast-check rule in schema --- .github/tests/quality_report_contract_test.py | 111 +++++++++++++++++- .github/tests/test_wiring_contract_test.py | 24 ++++ .github/workflows/standards-validation.yml | 6 +- quality-report/v1/quality_report.py | 26 +++- quality-report/v1/schema.json | 86 ++++++++++++++ scripts/validate.sh | 1 + 6 files changed, 246 insertions(+), 8 deletions(-) create mode 100644 .github/tests/test_wiring_contract_test.py diff --git a/.github/tests/quality_report_contract_test.py b/.github/tests/quality_report_contract_test.py index 6fabc70..a423769 100644 --- a/.github/tests/quality_report_contract_test.py +++ b/.github/tests/quality_report_contract_test.py @@ -1,4 +1,5 @@ import json +import os from pathlib import Path import runpy import shutil @@ -339,6 +340,110 @@ def test_passed_fuzz_target_requires_its_full_declared_budget(self): ): QUALITY_REPORT["validate_target"](target, "fuzz", "$.target") + def test_overflowing_elapsed_seconds_is_a_contract_error(self): + target = { + "name": "internal/docker/FuzzDecodeStats", + "outcome": "passed", + "metrics": {"budget_seconds": 300, "elapsed_seconds": 10**400}, + } + + with self.assertRaisesRegex( + QUALITY_REPORT["ContractError"], "elapsed_seconds" + ): + QUALITY_REPORT["validate_target"](target, "fuzz", "$.target") + + def test_oversized_integer_json_is_a_contract_error(self): + original_limit = sys.get_int_max_str_digits() + self.addCleanup(sys.set_int_max_str_digits, original_limit) + sys.set_int_max_str_digits(4300) + + with self.assertRaisesRegex(QUALITY_REPORT["ContractError"], "invalid JSON"): + QUALITY_REPORT["load_json_text"]('{"a":' + "1" * 5000 + "}", "oversized") + + def test_oversized_integer_target_still_emits_an_error_report(self): + def oversize_target(input_dir): + target = next(input_dir.rglob("target-result.json")) + target.write_text('{"a":' + "1" * 5000 + "}", encoding="utf-8") + + result, report, summary = self.aggregate( + "complete", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + input_mutator=oversize_target, + env={**os.environ, "PYTHONINTMAXSTRDIGITS": "4300"}, + ) + + self.assertNotEqual(0, result.returncode) + self.assertEqual("error", report["outcome"]) + self.assertTrue( + any("invalid JSON" in error for error in report["errors"]), + report["errors"], + ) + self.assertEqual(0, self.validate_report(report).returncode) + + def test_schema_requires_seed_and_path_for_fast_check_failures(self): + definitions = json.loads(SCHEMA.read_text())["$defs"] + failed = { + "if": { + "properties": {"outcome": {"enum": ["failed", "crashed", "flaked"]}}, + "required": ["outcome"], + }, + "then": {"properties": {"reproduction": {"required": ["seed", "path"]}}}, + } + + def fast_check(properties): + return { + "if": { + "properties": {"tool": {"const": "fast-check"}}, + "required": ["tool"], + }, + "then": {"properties": properties}, + } + + self.assertIn( + fast_check({"target": failed}), definitions["targetResult"]["allOf"] + ) + self.assertIn( + fast_check({"targets": {"items": failed}}), + definitions["report"]["allOf"], + ) + self.assertEqual( + {"seed", "path", "corpus"}, + set(definitions["reproduction"]["properties"]), + ) + self.assertEqual(1, definitions["reproduction"]["minProperties"]) + + def test_fast_check_failures_require_seed_and_path(self): + def target(reproduction): + return { + "name": "src/fuzz/decode", + "outcome": "failed", + "metrics": None, + "diagnostic": "property failed", + "reproduction": reproduction, + } + + for reproduction in ({"path": "[0]"}, {"seed": "42"}): + with self.subTest(reproduction=reproduction): + with self.assertRaisesRegex( + QUALITY_REPORT["ContractError"], + r"\$\.target\.reproduction: fast-check failures require seed and path", + ): + QUALITY_REPORT["validate_target"]( + target(reproduction), "fuzz", "$.target", "fast-check" + ) + + QUALITY_REPORT["validate_target"]( + target({"seed": "42", "path": "[0]"}), "fuzz", "$.target", "fast-check" + ) + QUALITY_REPORT["validate_target"]( + target({"corpus": "corpus/crash-1"}), "fuzz", "$.target", "go-fuzz" + ) + def test_validator_requires_time_and_offset_in_timestamps(self): for timestamp in ("2026-08-14", "2026-08-14T15:00:00"): with self.subTest(timestamp=timestamp): @@ -612,7 +717,9 @@ def test_standards_validation_runs_this_contract(self): workflow.count("python3 .github/tests/quality_report_contract_test.py"), ) - def aggregate(self, fixture, *, track, tool, expected, input_mutator=None): + def aggregate( + self, fixture, *, track, tool, expected, input_mutator=None, env=None + ): self.assertTrue(SCRIPT.is_file(), f"missing aggregator: {SCRIPT}") with tempfile.TemporaryDirectory() as temp_dir: input_dir = Path(temp_dir) / "input" @@ -666,7 +773,7 @@ def aggregate(self, fixture, *, track, tool, expected, input_mutator=None): str(summary_path), ] result = subprocess.run( - command, capture_output=True, text=True, timeout=30 + command, capture_output=True, text=True, timeout=30, env=env ) report_path = output_dir / "report.json" summary_file = output_dir / "summary.md" diff --git a/.github/tests/test_wiring_contract_test.py b/.github/tests/test_wiring_contract_test.py new file mode 100644 index 0000000..1238399 --- /dev/null +++ b/.github/tests/test_wiring_contract_test.py @@ -0,0 +1,24 @@ +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +TESTS = ROOT / ".github" / "tests" +VALIDATE = ROOT / "scripts" / "validate.sh" +WORKFLOW = ROOT / ".github" / "workflows" / "standards-validation.yml" + + +class TestWiringContractTest(unittest.TestCase): + def test_every_contract_test_runs_once_in_validate_and_ci(self): + tests = sorted(path.name for path in TESTS.glob("*_test.py")) + self.assertIn("test_wiring_contract_test.py", tests) + for label, path in (("validate.sh", VALIDATE), ("standards-validation.yml", WORKFLOW)): + lines = [line.strip() for line in path.read_text(encoding="utf-8").splitlines()] + for name in tests: + command = "python3 .github/tests/{0}".format(name) + with self.subTest(file=label, test=name): + self.assertEqual(1, lines.count(command), command) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index bf4afa7..8d4e464 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -42,6 +42,7 @@ jobs: python3 .github/tests/community_health_contract_test.py python3 .github/tests/greptile_summon_contract_test.py python3 .github/tests/tracked_validation_test.py + python3 .github/tests/test_wiring_contract_test.py - name: Compile Python run: python3 scripts/validate_tracked_files.py python @@ -65,7 +66,10 @@ jobs: - name: Validate workflows with actionlint run: | set -euo pipefail - bash <(curl -fsSL https://raw.githubusercontent.com/rhysd/actionlint/914e7df21a07ef503a81201c76d2b11c789d3fca/scripts/download-actionlint.bash) 1.7.12 "$RUNNER_TEMP" + archive="$RUNNER_TEMP/actionlint_1.7.12_linux_amd64.tar.gz" + curl -fsSL -o "$archive" https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz + echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 $archive" | sha256sum -c - + tar -xzf "$archive" -C "$RUNNER_TEMP" actionlint "$RUNNER_TEMP/actionlint" -color - name: Validate workflows with zizmor diff --git a/quality-report/v1/quality_report.py b/quality-report/v1/quality_report.py index 1c4a4c2..319c12a 100644 --- a/quality-report/v1/quality_report.py +++ b/quality-report/v1/quality_report.py @@ -78,7 +78,7 @@ def load_json_text(text, source): object_pairs_hook=reject_duplicate_keys, parse_constant=reject_constant, ) - except (json.JSONDecodeError, ContractError) as error: + except (ValueError, ContractError) as error: raise ContractError("{0}: invalid JSON: {1}".format(source, error)) from error @@ -139,7 +139,11 @@ def require_integer(value, path, *, minimum=0): def require_number(value, path, *, minimum=0): if isinstance(value, bool) or not isinstance(value, (int, float)): raise ContractError("{0}: expected number >= {1}".format(path, minimum)) - if not math.isfinite(value) or value < minimum: + try: + valid = math.isfinite(value) and value >= minimum + except OverflowError: + valid = False + if not valid: raise ContractError("{0}: expected finite number >= {1}".format(path, minimum)) return value @@ -223,7 +227,7 @@ def validate_reproduction(value, path): require_string(item, "{0}.{1}".format(path, field)) -def validate_target(target, track, path): +def validate_target(target, track, path, tool=None): require_object( target, path, @@ -272,6 +276,16 @@ def validate_target(target, track, path): ) if "reproduction" in target: validate_reproduction(target["reproduction"], path + ".reproduction") + if ( + tool == "fast-check" + and outcome in {"failed", "crashed", "flaked"} + and not {"seed", "path"} <= set(target["reproduction"]) + ): + raise ContractError( + "{0}.reproduction: fast-check failures require seed and path".format( + path + ) + ) def validate_target_document(document, path="$"): @@ -290,7 +304,7 @@ def validate_target_document(document, path="$"): ) if tool not in TRACK_TOOLS[track]: raise ContractError("{0}.tool: {1} is not a {2} tool".format(path, tool, track)) - validate_target(document["target"], track, path + ".target") + validate_target(document["target"], track, path + ".target", tool) return document @@ -456,7 +470,9 @@ def validate_report(document, path="$"): raise ContractError(path + ".targets: expected array") names = [] for index, target in enumerate(targets): - validate_target(target, track, "{0}.targets[{1}]".format(path, index)) + validate_target( + target, track, "{0}.targets[{1}]".format(path, index), tool + ) names.append(target["name"]) if len(names) != len(set(names)): raise ContractError(path + ".targets: duplicate target name") diff --git a/quality-report/v1/schema.json b/quality-report/v1/schema.json index 2ce2acc..000e2ec 100644 --- a/quality-report/v1/schema.json +++ b/quality-report/v1/schema.json @@ -355,6 +355,48 @@ } } } + }, + { + "if": { + "properties": { + "tool": { + "const": "fast-check" + } + }, + "required": [ + "tool" + ] + }, + "then": { + "properties": { + "target": { + "if": { + "properties": { + "outcome": { + "enum": [ + "failed", + "crashed", + "flaked" + ] + } + }, + "required": [ + "outcome" + ] + }, + "then": { + "properties": { + "reproduction": { + "required": [ + "seed", + "path" + ] + } + } + } + } + } + } } ] }, @@ -699,6 +741,50 @@ } } } + }, + { + "if": { + "properties": { + "tool": { + "const": "fast-check" + } + }, + "required": [ + "tool" + ] + }, + "then": { + "properties": { + "targets": { + "items": { + "if": { + "properties": { + "outcome": { + "enum": [ + "failed", + "crashed", + "flaked" + ] + } + }, + "required": [ + "outcome" + ] + }, + "then": { + "properties": { + "reproduction": { + "required": [ + "seed", + "path" + ] + } + } + } + } + } + } + } } ] } diff --git a/scripts/validate.sh b/scripts/validate.sh index 8f5f86f..7fb6f26 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -20,6 +20,7 @@ python3 .github/tests/renovate_config_contract_test.py python3 .github/tests/starchart_refresh_contract_test.py python3 .github/tests/main_is_released_contract_test.py python3 .github/tests/tracked_validation_test.py +python3 .github/tests/test_wiring_contract_test.py echo "==> compile python" python3 scripts/validate_tracked_files.py python From 355fbd1722f7ab40a70a8aedaf0740542efca4b8 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:55:46 -0500 Subject: [PATCH 35/44] fix(ci): namespace artifact names and page release-gate runs (#65) * fix(ci): namespace reusable workflow artifact names per invocation Add an optional artifact-namespace input to go-ci and node-ci, appended to artifact names only when set. Go fuzz artifacts add the matrix job index when a fuzzer name repeats across packages. * fix(release-gate): page through workflow runs before filtering Fetch up to five pages of 100 runs per poll so a target run older than the newest 100 is still found. Input description now says push runs, since tag pushes pass the filter too. --- .github/tests/reusable_ci_contract_test.py | 162 +++++++++++++++++++-- .github/workflows/go-ci.yml | 25 +++- .github/workflows/node-ci.yml | 10 +- .github/workflows/release-gate.yml | 22 ++- 4 files changed, 198 insertions(+), 21 deletions(-) diff --git a/.github/tests/reusable_ci_contract_test.py b/.github/tests/reusable_ci_contract_test.py index bf3e762..9804f2d 100644 --- a/.github/tests/reusable_ci_contract_test.py +++ b/.github/tests/reusable_ci_contract_test.py @@ -45,7 +45,7 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) "qlty", "fuzz", ) - ) + ) + ["artifact-namespace"] node_inputs = [ "module-directory", "node-version", @@ -56,7 +56,7 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) "run-lint", "run-test", "run-build", - ] + self.egress_inputs(("lint", "test", "build")) + ] + self.egress_inputs(("lint", "test", "build")) + ["artifact-namespace"] release_inputs = [ "target-sha", "workflow-files-json", @@ -128,6 +128,8 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) ): self.assert_input("go", input_name, "boolean", default="false") + self.assert_input("go", "artifact-namespace", "string", default="") + self.assert_input("node", "artifact-namespace", "string", default="") self.assert_input("node", "module-directory", "string", default=".") self.assert_input("node", "node-version", "string", default="24") self.assert_input("node", "lockfile-path", "string", default="package-lock.json") @@ -233,7 +235,38 @@ def test_artifact_uploads_are_central_and_fixed(self): upload_count = workflow.count("actions/upload-artifact@") self.assertEqual(upload_count, workflow.count("if-no-files-found: ignore")) self.assertEqual(upload_count, workflow.count("retention-days: 14")) - self.assertEqual(upload_count, workflow.count("if: always()")) + # The fuzz naming step also runs under always() so the upload has a name. + self.assertEqual( + upload_count + workflow.count("id: fuzz-artifact"), + workflow.count("if: always()"), + ) + + def test_artifact_names_carry_the_optional_namespace(self): + go = self.read_workflow(WORKFLOWS["go"]) + node = self.read_workflow(WORKFLOWS["node"]) + suffix = "${{ inputs.artifact-namespace != '' && format('-{0}', inputs.artifact-namespace) || '' }}" + run = "${{ github.run_id }}-${{ github.run_attempt }}" + + for workflow, names in ( + (go, (f"go-test-{run}", f"go-fuzz-${{{{ steps.fuzz-artifact.outputs.name }}}}-{run}")), + (node, (f"node-test-{run}", f"node-build-{run}")), + ): + for name in names: + self.assertIn(f" name: {name}{suffix}\n", workflow) + + step = self.fuzz_naming_step() + self.assertIn("id: fuzz-artifact", step) + self.assertIn("FUZZERS_JSON: ${{ inputs.fuzzers-json }}", step) + self.assertIn("FUZZER: ${{ matrix.fuzzer.name }}", step) + self.assertIn("JOB_INDEX: ${{ strategy.job-index }}", step) + self.assertNotIn("${{", self.fuzz_naming_script()) + + def test_fuzz_artifact_name_is_unchanged_unless_the_fuzzer_name_repeats(self): + unique = json.dumps([{"name": "FuzzA", "pkg": "./a"}, {"name": "FuzzB", "pkg": "./b"}]) + duplicate = json.dumps([{"name": "FuzzA", "pkg": "./a"}, {"name": "FuzzA", "pkg": "./b"}]) + + self.assertEqual("FuzzA", self.run_fuzz_naming(unique, "FuzzA", "0")) + self.assertEqual("FuzzA-1", self.run_fuzz_naming(duplicate, "FuzzA", "1")) def test_release_gate_checks_every_workflow_by_exact_sha_push_and_nonempty_branch(self): exact_success = { @@ -264,10 +297,63 @@ def test_release_gate_checks_every_workflow_by_exact_sha_push_and_nonempty_branc def test_release_gate_keeps_authoritative_client_side_run_filtering(self): release = self.read_workflow(WORKFLOWS["release"]) - self.assertIn("/runs?per_page=100\"", release) + self.assertIn("for page in 1 2 3 4 5; do", release) + self.assertIn("/runs?per_page=100&page=${page}\"", release) + self.assertIn("-lt 100 ]; then", release) self.assertNotRegex(release, r"runs\?[^\"\n]*(?:event|head_sha)=") self.assertIn("spuriously returning 0 results since 2026-04-27", release) + def test_release_gate_finds_a_target_run_on_a_later_page(self): + filler = { + "head_sha": "b" * 40, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + exact_success = {**filler, "head_sha": TARGET_SHA} + result = self.run_release_gate( + {"ci-verify.yml": [filler] * 100}, + extra_pages_by_workflow={"ci-verify.yml": [[exact_success]]}, + ) + + self.assertEqual(0, result.returncode, result.stderr) + self.assertIn(f"Found successful CI Verify push run for {TARGET_SHA}.", result.stdout) + self.assertEqual(2, len(result.requests), result.requests) + self.assertTrue(result.requests[1].endswith("/runs?per_page=100&page=2")) + + def test_release_gate_stops_paging_after_a_short_page(self): + short_page = [ + { + "head_sha": "b" * 40, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + ] * 99 + result = self.run_release_gate({"ci-verify.yml": short_page}) + + self.assertNotEqual(0, result.returncode) + self.assertEqual(1, len(result.requests), result.requests) + self.assertTrue(result.requests[0].endswith("/runs?per_page=100&page=1")) + + def test_release_gate_caps_paging_at_five_pages(self): + filler = { + "head_sha": "b" * 40, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + result = self.run_release_gate( + {"ci-verify.yml": [filler] * 100}, + extra_pages_by_workflow={"ci-verify.yml": [[filler] * 100] * 5}, + ) + + self.assertNotEqual(0, result.returncode) + self.assertEqual(5, len(result.requests), result.requests) + def test_release_gate_uses_one_shared_poll_budget_for_every_workflow(self): in_progress = { "head_sha": TARGET_SHA, @@ -428,6 +514,40 @@ def assert_job_egress(self, workflow, job_name): def fixed_scripts(self, workflow): return re.findall(r"^\s+run: (\./scripts/ci/[^\s]+)$", workflow, re.MULTILINE) + def fuzz_naming_step(self): + go = self.read_workflow(WORKFLOWS["go"]) + marker = " - name: Name Go fuzz artifact\n" + self.assertIn(marker, go) + return go.split(marker, 1)[1].split("\n - name:", 1)[0] + + def fuzz_naming_script(self): + block = self.fuzz_naming_step().split(" run: |\n", 1)[1] + return "\n".join(line[10:] for line in block.splitlines()) + + def run_fuzz_naming(self, fuzzers_json, fuzzer, job_index): + with tempfile.TemporaryDirectory() as temp_dir: + output = Path(temp_dir) / "output" + output.write_text("") + env = os.environ.copy() + env.update( + { + "FUZZERS_JSON": fuzzers_json, + "FUZZER": fuzzer, + "JOB_INDEX": job_index, + "GITHUB_OUTPUT": str(output), + } + ) + result = subprocess.run( + ["bash", "-c", self.fuzz_naming_script()], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(0, result.returncode, result.stderr) + return output.read_text().strip().removeprefix("name=") + def release_gate_script(self): workflow = self.read_workflow(WORKFLOWS["release"]) marker = " - name: Verify required CI workflows\n" @@ -453,6 +573,7 @@ def run_release_gate( max_attempts="1", api_url="https://api.github.com", runs_sequences_by_workflow=None, + extra_pages_by_workflow=None, ): with tempfile.TemporaryDirectory() as temp_dir: temp = Path(temp_dir) @@ -478,6 +599,14 @@ def run_release_gate( ) (fixtures / f"{workflow_id}.last").write_text(str(len(runs_sequence))) + # Extra pages (2, 3, ...) served for the first poll of a workflow. + for workflow_file, pages in (extra_pages_by_workflow or {}).items(): + workflow_id = metadata[workflow_file][0] + for page, runs in enumerate(pages, start=2): + (fixtures / f"{workflow_id}.1.p{page}.json").write_text( + json.dumps({"workflow_runs": runs}) + ) + curl = fake_bin / "curl" curl.write_text( "#!/usr/bin/env bash\n" @@ -485,19 +614,29 @@ def run_release_gate( "case \"$url\" in\n" " */actions/workflows/ci-verify.yml) printf '%s' '{\"id\":123,\"name\":\"CI Verify\",\"path\":\".github/workflows/ci-verify.yml\"}' ;;\n" " */actions/workflows/e2e-playwright.yml) printf '%s' '{\"id\":456,\"name\":\"E2E Playwright\",\"path\":\".github/workflows/e2e-playwright.yml\"}' ;;\n" - " */actions/workflows/123/runs?per_page=100) workflow_id=123 ;;\n" - " */actions/workflows/456/runs?per_page=100) workflow_id=456 ;;\n" + " */actions/workflows/123/runs?per_page=100\\&page=*) workflow_id=123 ;;\n" + " */actions/workflows/456/runs?per_page=100\\&page=*) workflow_id=456 ;;\n" " *) printf 'unexpected URL: %s\\n' \"$url\" >&2; exit 22 ;;\n" "esac\n" "if [ -n \"${workflow_id:-}\" ]; then\n" + " printf '%s\\n' \"$url\" >> \"$RUNS_FIXTURES/requests.log\"\n" + " page=\"${url##*page=}\"\n" " count_file=\"$RUNS_FIXTURES/$workflow_id.count\"\n" " count=0\n" " [ ! -f \"$count_file\" ] || count=$(cat \"$count_file\")\n" - " count=$((count + 1))\n" - " printf '%s' \"$count\" > \"$count_file\"\n" + " if [ \"$page\" = 1 ]; then\n" + " count=$((count + 1))\n" + " printf '%s' \"$count\" > \"$count_file\"\n" + " fi\n" " last=$(cat \"$RUNS_FIXTURES/$workflow_id.last\")\n" " [ \"$count\" -le \"$last\" ] || count=\"$last\"\n" - " cat \"$RUNS_FIXTURES/$workflow_id.$count.json\"\n" + " if [ \"$page\" = 1 ]; then\n" + " cat \"$RUNS_FIXTURES/$workflow_id.$count.json\"\n" + " elif [ -f \"$RUNS_FIXTURES/$workflow_id.$count.p$page.json\" ]; then\n" + " cat \"$RUNS_FIXTURES/$workflow_id.$count.p$page.json\"\n" + " else\n" + " printf '%s' '{\"workflow_runs\":[]}'\n" + " fi\n" "fi\n" ) curl.chmod(0o755) @@ -522,7 +661,7 @@ def run_release_gate( "WORKFLOW_FILES_JSON": workflow_files_json, } ) - return subprocess.run( + result = subprocess.run( ["bash", "-c", self.release_gate_script()], cwd=ROOT, env=env, @@ -530,6 +669,9 @@ def run_release_gate( text=True, check=False, ) + log = fixtures / "requests.log" + result.requests = log.read_text().splitlines() if log.exists() else [] + return result if __name__ == "__main__": diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index 8ece72a..b993976 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -167,6 +167,12 @@ on: type: string default: "" + artifact-namespace: + description: Artifact-safe suffix appended to uploaded artifact names. Set a distinct value when calling this workflow more than once in a run or from a matrix. + required: false + type: string + default: "" + permissions: {} jobs: @@ -205,7 +211,7 @@ jobs: if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: go-test-${{ github.run_id }}-${{ github.run_attempt }} + name: go-test-${{ github.run_id }}-${{ github.run_attempt }}${{ inputs.artifact-namespace != '' && format('-{0}', inputs.artifact-namespace) || '' }} path: artifacts/go-test/ if-no-files-found: ignore retention-days: 14 @@ -465,11 +471,26 @@ jobs: PKG: ${{ matrix.fuzzer.pkg }} run: ./scripts/ci/go-fuzz.sh + - name: Name Go fuzz artifact + id: fuzz-artifact + if: always() + env: + FUZZERS_JSON: ${{ inputs.fuzzers-json }} + FUZZER: ${{ matrix.fuzzer.name }} + JOB_INDEX: ${{ strategy.job-index }} + run: | + duplicates="$(printf '%s' "${FUZZERS_JSON}" | jq --arg name "${FUZZER}" '[.[] | select(.name == $name)] | length')" + if [ "${duplicates}" -gt 1 ]; then + echo "name=${FUZZER}-${JOB_INDEX}" >> "${GITHUB_OUTPUT}" + else + echo "name=${FUZZER}" >> "${GITHUB_OUTPUT}" + fi + - name: Upload Go fuzz artifacts if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: go-fuzz-${{ matrix.fuzzer.name }}-${{ github.run_id }}-${{ github.run_attempt }} + name: go-fuzz-${{ steps.fuzz-artifact.outputs.name }}-${{ github.run_id }}-${{ github.run_attempt }}${{ inputs.artifact-namespace != '' && format('-{0}', inputs.artifact-namespace) || '' }} path: artifacts/go-fuzz/ if-no-files-found: ignore retention-days: 14 diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index 3f1ceab..7b6ff12 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -79,6 +79,12 @@ on: type: string default: "" + artifact-namespace: + description: Artifact-safe suffix appended to uploaded artifact names. Set a distinct value when calling this workflow more than once in a run or from a matrix. + required: false + type: string + default: "" + permissions: {} jobs: @@ -150,7 +156,7 @@ jobs: if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: node-test-${{ github.run_id }}-${{ github.run_attempt }} + name: node-test-${{ github.run_id }}-${{ github.run_attempt }}${{ inputs.artifact-namespace != '' && format('-{0}', inputs.artifact-namespace) || '' }} path: artifacts/node-test/ if-no-files-found: ignore retention-days: 14 @@ -191,7 +197,7 @@ jobs: if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: node-build-${{ github.run_id }}-${{ github.run_attempt }} + name: node-build-${{ github.run_id }}-${{ github.run_attempt }}${{ inputs.artifact-namespace != '' && format('-{0}', inputs.artifact-namespace) || '' }} path: artifacts/node-build/ if-no-files-found: ignore retention-days: 14 diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index 5fce3a0..c4b591f 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -4,7 +4,7 @@ on: workflow_call: inputs: target-sha: - description: Full commit SHA whose branch push runs must have succeeded + description: Full commit SHA whose push runs (branch or tag) must have succeeded required: true type: string workflow-files-json: @@ -117,12 +117,20 @@ jobs: workflow_id="${workflow_ids[${index}]}" workflow_name="${workflow_names[${index}]}" # GitHub's `?head_sha=` and `?event=` query filters have been spuriously returning 0 results since 2026-04-27. - # Filter the latest 100 runs client-side instead. - runs_url="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_id}/runs?per_page=100" - runs_json="$(curl --proto '=https' --tlsv1.2 --retry 3 --fail --silent --show-error \ - -H "Authorization: Bearer ${GH_TOKEN}" \ - -H "Accept: application/vnd.github+json" \ - "${runs_url}")" + # Filter the latest runs client-side instead, paging up to 5 x 100 so an older target run is still found. + runs_pages=() + for page in 1 2 3 4 5; do + runs_url="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_id}/runs?per_page=100&page=${page}" + page_json="$(curl --proto '=https' --tlsv1.2 --retry 3 --fail --silent --show-error \ + -H "Authorization: Bearer ${GH_TOKEN}" \ + -H "Accept: application/vnd.github+json" \ + "${runs_url}")" + runs_pages+=("${page_json}") + if [ "$(echo "${page_json}" | jq '.workflow_runs | length')" -lt 100 ]; then + break + fi + done + runs_json="$(printf '%s\n' "${runs_pages[@]}" | jq -s '{workflow_runs: (map(.workflow_runs) | add)}')" filtered="$(echo "${runs_json}" | jq --arg sha "${TARGET_SHA}" '{ workflow_runs: [.workflow_runs[] | select( From e70acea0dc0d1f4a9091e64295146a0a18b8b642 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:16:54 -0500 Subject: [PATCH 36/44] chore(deps): update dependency node to v26 (#67) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/standards-validation.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 8d4e464..25e1fb1 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -35,7 +35,7 @@ jobs: - name: Set up Node.js uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version: 24 + node-version: 26 - name: Validate community health contract run: | From 989047151a6a36432822ac2d03be0fbecb067a5f Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:17:12 -0500 Subject: [PATCH 37/44] feat(actions): add shared changes-gate composite action (#70) * feat(actions): add shared changes-gate composite action * fix(actions): verify changes-gate listing is complete before skipping * docs(actions): wrap changes-gate README line * fix(actions): support bracket classes and ./ prefixes in changes-gate globs --- .github/tests/changes_gate_contract_test.py | 406 ++++++++++++++++++++ .github/workflows/standards-validation.yml | 1 + actions/changes-gate/README.md | 70 ++++ actions/changes-gate/action.yml | 31 ++ actions/changes-gate/changes_gate.py | 262 +++++++++++++ scripts/validate.sh | 1 + 6 files changed, 771 insertions(+) create mode 100644 .github/tests/changes_gate_contract_test.py create mode 100644 actions/changes-gate/README.md create mode 100644 actions/changes-gate/action.yml create mode 100644 actions/changes-gate/changes_gate.py diff --git a/.github/tests/changes_gate_contract_test.py b/.github/tests/changes_gate_contract_test.py new file mode 100644 index 0000000..3e42838 --- /dev/null +++ b/.github/tests/changes_gate_contract_test.py @@ -0,0 +1,406 @@ +import contextlib +import http.server +import importlib.util +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +ACTION_DIR = ROOT / "actions" / "changes-gate" + +spec = importlib.util.spec_from_file_location("changes_gate", ACTION_DIR / "changes_gate.py") +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) + +PATTERNS = "Sources/**\n" + + +def entry(name, previous=None): + item = {"filename": name} + if previous is not None: + item["previous_filename"] = previous + return item + + +API = "https://api.github.com" + + +def pager(files, changed=None): + """Mock HTTP layer: the PR read plus the files listing in pages of 100.""" + total = len(files) if changed is None else changed + + def fetch(url, auth): + if url.endswith("/pulls/7"): + return {"changed_files": total}, None + page = 1 + if "&page=" in url: + page = int(url.rsplit("&page=", 1)[1]) + chunk = files[(page - 1) * 100:page * 100] + link = None + if page * 100 < len(files): + link = '<{0}/repos/CodesWhat/example/pulls/7/files?per_page=100&page={1}>; rel="next"'.format( + API, page + 1) + return chunk, link + return fetch + + +def run_gate(event, files=None, patterns=PATTERNS, fetch=None, number=7, changed=None): + with tempfile.TemporaryDirectory() as tmp: + event_path = Path(tmp) / "event.json" + event_path.write_text(json.dumps({"pull_request": {"number": number}})) + out_path = Path(tmp) / "output" + env = { + "CHANGES_GATE_EVENT_NAME": event, + "CHANGES_GATE_PATTERNS": patterns, + "CHANGES_GATE_AUTH": "secret-value", + "GITHUB_REPOSITORY": "CodesWhat/example", + "GITHUB_EVENT_PATH": str(event_path), + "GITHUB_OUTPUT": str(out_path), + } + buf = io.StringIO() + with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf): + gate.main(env, fetch or pager(files or [], changed)) + output = out_path.read_text() if out_path.exists() else "" + return output, buf.getvalue() + + +def failing(url, auth): + raise OSError("boom") + + +class ChangesGateContractTest(unittest.TestCase): + def assertRun(self, expected, output): + self.assertEqual("run={0}\n".format(expected), output) + + def test_non_pr_events_run(self): + for event in ("push", "schedule", "workflow_dispatch", "merge_group", + "workflow_call", "something_new", ""): + with self.subTest(event=event): + out, _ = run_gate(event, [entry("docs/a.md")], fetch=failing) + self.assertRun("true", out) + + def test_docs_only_pr_skips(self): + for event in ("pull_request", "pull_request_target"): + with self.subTest(event=event): + out, log = run_gate(event, [entry("docs/a.md"), entry("README.md")]) + self.assertRun("false", out) + self.assertIn("examined=2 matched=0 run=false", log) + + def test_matching_pr_runs(self): + out, _ = run_gate("pull_request", [entry("docs/a.md"), entry("Sources/App.swift")]) + self.assertRun("true", out) + + def test_case_insensitive(self): + out, _ = run_gate("pull_request", [entry("sources/App.swift")]) + self.assertRun("true", out) + + def test_rename_previous_filename_matches(self): + out, _ = run_gate("pull_request", [entry("docs/App.swift", previous="Sources/App.swift")]) + self.assertRun("true", out) + + def test_globstar_and_single_star(self): + out, _ = run_gate("pull_request", [entry("a/b/c/x.go")], patterns="**/*.go") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("x.go")], patterns="**/*.go") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("a/b/x.go")], patterns="*.go") + self.assertRun("false", out) + + def test_comments_and_blank_lines_ignored(self): + out, _ = run_gate("pull_request", [entry("docs/a.md")], + patterns="# note\n\n \nSources/**\n") + self.assertRun("false", out) + + def test_exclude_pattern(self): + patterns = "Sources/**\n!Sources/**/*.md\n" + out, _ = run_gate("pull_request", [entry("Sources/README.md")], patterns=patterns) + self.assertRun("false", out) + out, _ = run_gate("pull_request", [entry("Sources/README.md"), entry("Sources/a.swift")], + patterns=patterns) + self.assertRun("true", out) + + def test_api_error_runs(self): + out, _ = run_gate("pull_request", fetch=failing) + self.assertRun("true", out) + + def test_unparsable_response_runs(self): + for bad in ({"message": "nope"}, [{"nofile": 1}], [{"filename": 5}], + [{"filename": "a", "previous_filename": 3}], "text"): + with self.subTest(bad=bad): + out, _ = run_gate("pull_request", fetch=lambda u, a, b=bad: (b, None)) + self.assertRun("true", out) + + def test_three_thousand_file_cap_runs(self): + files = [entry("docs/{0}.md".format(i)) for i in range(3000)] + out, _ = run_gate("pull_request", files) + self.assertRun("true", out) + files = [entry("docs/{0}.md".format(i)) for i in range(2999)] + out, _ = run_gate("pull_request", files) + self.assertRun("false", out) + + def test_bracket_classes(self): + cases = ( + ("Sources/[AB].swift", "Sources/A.swift", "true"), + ("Sources/[AB].swift", "Sources/C.swift", "false"), + ("Sources/[a-c].swift", "Sources/b.swift", "true"), + ("Sources/[a-c].swift", "Sources/d.swift", "false"), + ("Sources/[!A].swift", "Sources/B.swift", "true"), + ("Sources/[!A].swift", "Sources/A.swift", "false"), + ("Sources/[^A].swift", "Sources/B.swift", "true"), + ("Sources/[^A].swift", "Sources/A.swift", "false"), + ("Sources/[ab].swift", "Sources/A.swift", "true"), + ("Sources/[A-C].swift", "Sources/b.swift", "true"), + ("Sources[x]a", "Sources/a", "false"), + ("Sources[!x]a", "Sources/a", "false"), + ("Sources/[]].swift", "Sources/].swift", "true"), + ) + for pattern, name, expected in cases: + with self.subTest(pattern=pattern, name=name): + out, _ = run_gate("pull_request", [entry(name)], patterns=pattern) + self.assertRun(expected, out) + + def test_unparseable_glob_runs(self): + for pattern in ("Sources/[AB.swift", "Sources/[", "Sources/[z-a].swift", "!Sources/[x"): + with self.subTest(pattern=pattern): + out, _ = run_gate("pull_request", [entry("docs/a.md")], + patterns="Sources/**\n" + pattern) + self.assertRun("true", out) + + def test_leading_dot_slash_and_trailing_slash(self): + for pattern in ("./Sources/**", "././Sources/**", "Sources/", "./Sources/"): + with self.subTest(pattern=pattern): + out, _ = run_gate("pull_request", [entry("Sources/a/b.swift")], patterns=pattern) + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("docs/a.md")], patterns=pattern) + self.assertRun("false", out) + out, _ = run_gate("pull_request", [entry("Sources/a.md")], + patterns="Sources/**\n!./Sources/*.md") + self.assertRun("false", out) + + def test_exclude_overrides_include(self): + patterns = "**/*.swift\n!Sources/Generated/**\n" + out, _ = run_gate("pull_request", [entry("Sources/Generated/A.swift")], patterns=patterns) + self.assertRun("false", out) + out, _ = run_gate("pull_request", [entry("sources/generated/A.swift")], patterns=patterns) + self.assertRun("false", out) + + def test_regex_metacharacters_are_literal(self): + cases = ( + ("a+b.txt", "a+b.txt", "true"), ("a+b.txt", "aab.txt", "false"), + ("a(b).txt", "a(b).txt", "true"), ("a(b).txt", "ab.txt", "false"), + ("a.txt", "axtxt", "false"), + ("a$b", "a$b", "true"), ("^a", "^a", "true"), ("^a", "a", "false"), + ("a|b", "a|b", "true"), ("a|b", "a", "false"), + ) + for pattern, name, expected in cases: + with self.subTest(pattern=pattern, name=name): + out, _ = run_gate("pull_request", [entry(name)], patterns=pattern) + self.assertRun(expected, out) + + def test_odd_repository_rejected_without_fetching(self): + for repo in ("Cod esWhat/x", "a/b/c", "../x", "x/..", "a;b/c", "a/b\nc", "noslash", ""): + with self.subTest(repo=repo): + calls = [] + + def fetch(url, auth): + calls.append(url) + return [], None + with tempfile.TemporaryDirectory() as tmp: + event = Path(tmp) / "event.json" + event.write_text(json.dumps({"pull_request": {"number": 7}})) + out_path = Path(tmp) / "output" + env = { + "CHANGES_GATE_EVENT_NAME": "pull_request", + "CHANGES_GATE_PATTERNS": PATTERNS, + "CHANGES_GATE_AUTH": "secret-value", + "GITHUB_REPOSITORY": repo, + "GITHUB_EVENT_PATH": str(event), + "GITHUB_OUTPUT": str(out_path), + } + with contextlib.redirect_stdout(io.StringIO()): + gate.main(env, fetch) + self.assertRun("true", out_path.read_text()) + self.assertEqual([], calls) + + def test_truncated_listing_runs(self): + out, _ = run_gate("pull_request", [entry("docs/a.md")], changed=101) + self.assertRun("true", out) + + def test_empty_listing_with_nonzero_count_runs(self): + out, _ = run_gate("pull_request", [], changed=3) + self.assertRun("true", out) + + def test_count_matches_empty_listing_skips(self): + out, _ = run_gate("pull_request", [], changed=0) + self.assertRun("false", out) + + def test_changed_files_at_cap_runs(self): + out, _ = run_gate("pull_request", [entry("docs/a.md")], changed=3000) + self.assertRun("true", out) + + def test_short_page_with_rel_next_runs(self): + base = pager([entry("docs/a.md")]) + + def fetch(url, auth): + data, _ = base(url, auth) + if url.endswith("/pulls/7"): + return data, None + return data, '<{0}/repos/CodesWhat/example/pulls/7/files?page=2>; rel="next"'.format(API) + out, _ = run_gate("pull_request", fetch=fetch) + self.assertRun("true", out) + + def test_malformed_link_header_runs(self): + base = pager([entry("docs/a.md")]) + for link in ("garbage", '; rel="next", ???', " + with: + patterns: | + Sources/** + Package.swift + !**/*.md + + macos-build: + needs: changes + if: needs.changes.outputs.run == 'true' + runs-on: macos-26 + steps: + - run: echo "expensive work" +``` + +Pin the action to a full commit SHA. No checkout is needed. + +## Contract + +- `patterns` (required): newline-separated globs. `**` matches across + directories. `*`, `?` and `[abc]`, `[a-z]`, `[!x]` classes stay inside one + path segment. + A leading `./` is ignored and a trailing `/` means `/**`. An unparseable + glob (an unclosed `[`) makes the result `true`. `#` comments and + blank lines are ignored. A leading `!` excludes. Matching is + case-insensitive. +- `github-token`: defaults to `github.token`. +- Output `run` is exactly `true` or `false`. + +`pull_request` and `pull_request_target` evaluate the PR's changed files +(`filename` and, for renames, `previous_filename`). Every other event +returns `true`. The result is also `true` when the pattern list has no +includes, the API errors or times out, the response can't be parsed, or the +PR has 3000 or more files. It also returns `true` when the files listed +don't add up to the PR's `changed_files` count, or when pagination (the +`Link` header) is malformed or inconsistent. `false` only means the listing +completed and nothing matched. + +The script is Python 3 standard library only, reads everything from +environment variables, and logs only counts and the decision, never file +names or patterns. + +## Why a job-level gate + +A workflow-level `paths:` filter means the workflow never starts, so a +required status check from it stays pending forever and blocks the merge. A +job skipped by `if:` reports success to a required status check, so the PR +can merge. + +A `code_scanning` ruleset rule is different. A skipped CodeQL job doesn't +produce the SARIF upload that rule waits for, so don't gate CodeQL this way. diff --git a/actions/changes-gate/action.yml b/actions/changes-gate/action.yml new file mode 100644 index 0000000..5d56137 --- /dev/null +++ b/actions/changes-gate/action.yml @@ -0,0 +1,31 @@ +name: Changes gate +description: >- + Decide whether a pull request touched files that matter, so expensive jobs + can be skipped. Outputs run=true on any doubt. + +inputs: + patterns: + description: >- + Newline-separated globs. ** is supported, # comments and blank lines are + ignored, and a leading ! excludes. + required: true + github-token: + description: Token used to list the pull request's changed files. + required: false + default: ${{ github.token }} + +outputs: + run: + description: The string true or false. + value: ${{ steps.gate.outputs.run }} + +runs: + using: composite + steps: + - id: gate + shell: bash + env: + CHANGES_GATE_PATTERNS: ${{ inputs.patterns }} + CHANGES_GATE_AUTH: ${{ inputs.github-token }} + CHANGES_GATE_EVENT_NAME: ${{ github.event_name }} + run: python3 "$GITHUB_ACTION_PATH/changes_gate.py" diff --git a/actions/changes-gate/changes_gate.py b/actions/changes-gate/changes_gate.py new file mode 100644 index 0000000..9a917f4 --- /dev/null +++ b/actions/changes-gate/changes_gate.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Decide whether a pull request changed files matching a pattern list. + +Everything comes from environment variables. The only thing ever written to +the log is counts and the decision, and the only thing ever written to +GITHUB_OUTPUT is run=true or run=false. Any doubt resolves to true. +""" +import json +import os +import re +import sys +import time +import urllib.request + +PER_PAGE = 100 +FILE_CAP = 3000 +MAX_PAGES = FILE_CAP // PER_PAGE +REQUEST_TIMEOUT = 20 +DEADLINE_SECONDS = 150 + + +class Doubt(Exception): + """Raised for anything that should resolve to run=true.""" + + +def normalize(line): + while line.startswith("./"): + line = line[2:] + if line.endswith("/"): + line += "**" + return line + + +def parse_patterns(text): + """Return (includes, excludes). Raises ValueError on an unparseable glob.""" + includes, excludes = [], [] + for raw in (text or "").splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + target = includes + if line.startswith("!"): + line = line[1:].strip() + target = excludes + line = normalize(line) + if line: + target.append(glob_to_regex(line)) + return includes, excludes + + +def char_class(pattern, start): + """Parse a [...] class opening at start. Return (regex, next index).""" + n = len(pattern) + i = start + 1 + negate = False + if i < n and pattern[i] in "!^": + negate = True + i += 1 + items = [] + first = True + while True: + if i >= n: + raise ValueError("unclosed class") + c = pattern[i] + if c == "]" and not first: + i += 1 + break + first = False + if i + 2 < n and pattern[i + 1] == "-" and pattern[i + 2] != "]": + lo, hi = c, pattern[i + 2] + if lo > hi: + raise ValueError("bad range") + items.append(re.escape(lo) + "-" + re.escape(hi)) + i += 3 + else: + items.append(re.escape(c)) + i += 1 + body = "".join(items) + if negate: + return "[^/" + body + "]", i + return "(?!/)[" + body + "]", i + + +def glob_to_regex(pattern): + out = [] + i = 0 + n = len(pattern) + while i < n: + c = pattern[i] + if c == "*": + if pattern.startswith("**", i): + i += 2 + if i < n and pattern[i] == "/": + i += 1 + out.append("(?:.*/)?") + else: + out.append(".*") + continue + out.append("[^/]*") + elif c == "?": + out.append("[^/]") + elif c == "[": + piece, i = char_class(pattern, i) + out.append(piece) + continue + else: + out.append(re.escape(c)) + i += 1 + return re.compile("".join(out), re.IGNORECASE | re.DOTALL) + + +def matches(name, includes, excludes): + if not any(r.fullmatch(name) for r in includes): + return False + return not any(r.fullmatch(name) for r in excludes) + + +def fetch_page(url, auth): + """GET url and return (parsed JSON, Link header or None).""" + request = urllib.request.Request( + url, + headers={ + "Authorization": "Bearer " + auth, + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "codeswhat-changes-gate", + }, + ) + with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: + if response.status != 200: + raise Doubt("status") + return json.loads(response.read().decode("utf-8")), response.headers.get("Link") + + +LINK_PART = re.compile(r'\s*<([^<>\s]+)>\s*((?:;\s*[A-Za-z]+\s*=\s*(?:"[^"]*"|[^\s;,"]+)\s*)*)') +REL = re.compile(r';\s*rel\s*=\s*"?([^";,]*)"?', re.IGNORECASE) + + +def next_link(header): + """Return the rel="next" URL, None if absent. Malformed raises Doubt.""" + if header is None or not header.strip(): + return None + found = None + pos = 0 + while pos < len(header): + match = LINK_PART.match(header, pos) + if not match: + raise Doubt("link") + rel = REL.search(match.group(2)) + if rel and "next" in rel.group(1).lower().split(): + found = match.group(1) + pos = match.end() + if pos < len(header): + if header[pos] != ",": + raise Doubt("link") + pos += 1 + return found + + +def expected_count(api, repo, number, auth, fetch): + data, _ = fetch("{0}/repos/{1}/pulls/{2}".format(api, repo, number), auth) + count = data.get("changed_files") if isinstance(data, dict) else None + if isinstance(count, bool) or not isinstance(count, int) or count < 0: + raise Doubt("count") + if count >= FILE_CAP: + raise Doubt("cap") + return count + + +def list_names(api, repo, number, auth, fetch): + expected = expected_count(api, repo, number, auth, fetch) + names = [] + files = 0 + started = time.monotonic() + url = "{0}/repos/{1}/pulls/{2}/files?per_page={3}".format(api, repo, number, PER_PAGE) + for _ in range(MAX_PAGES + 1): + if time.monotonic() - started > DEADLINE_SECONDS: + raise Doubt("deadline") + data, link = fetch(url, auth) + if not isinstance(data, list): + raise Doubt("shape") + for item in data: + if not isinstance(item, dict) or not isinstance(item.get("filename"), str): + raise Doubt("shape") + files += 1 + names.append(item["filename"]) + previous = item.get("previous_filename") + if previous is not None: + if not isinstance(previous, str): + raise Doubt("shape") + names.append(previous) + if files >= FILE_CAP: + raise Doubt("cap") + url = next_link(link) + if url is None: + if files != expected: + raise Doubt("incomplete") + return names + if len(data) < PER_PAGE or not url.startswith(api + "/"): + raise Doubt("link") + raise Doubt("cap") + + +def pull_number(env): + try: + with open(env["GITHUB_EVENT_PATH"], encoding="utf-8") as handle: + number = json.load(handle)["pull_request"]["number"] + except (KeyError, OSError, ValueError, TypeError): + raise Doubt("event") + if isinstance(number, bool) or not isinstance(number, int) or number <= 0: + raise Doubt("event") + return number + + +def decide(env, fetch=fetch_page): + """Return (run, examined, matched).""" + if env.get("CHANGES_GATE_EVENT_NAME") not in ("pull_request", "pull_request_target"): + return True, 0, 0 + try: + includes, excludes = parse_patterns(env.get("CHANGES_GATE_PATTERNS", "")) + except (ValueError, re.error): + return True, 0, 0 + if not includes: + return True, 0, 0 + repo = env.get("GITHUB_REPOSITORY", "") + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo) or any( + part in (".", "..") for part in repo.split("/")): + return True, 0, 0 + api = (env.get("GITHUB_API_URL") or "https://api.github.com").rstrip("/") + auth = env.get("CHANGES_GATE_AUTH", "") + if not auth: + return True, 0, 0 + try: + number = pull_number(env) + names = list_names(api, repo, number, auth, fetch) + except Exception: + return True, 0, 0 + matched = sum(1 for name in names if matches(name, includes, excludes)) + return matched > 0, len(names), matched + + +def write_output(path, run): + if not path: + return + with open(path, "a", encoding="utf-8") as handle: + handle.write("run={0}\n".format("true" if run else "false")) + + +def main(env=None, fetch=fetch_page): + env = os.environ if env is None else env + try: + run, examined, matched = decide(env, fetch) + except Exception: + run, examined, matched = True, 0, 0 + print("changes-gate: examined={0} matched={1} run={2}".format( + examined, matched, "true" if run else "false")) + write_output(env.get("GITHUB_OUTPUT"), run) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validate.sh b/scripts/validate.sh index 7fb6f26..85ae8bf 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -20,6 +20,7 @@ python3 .github/tests/renovate_config_contract_test.py python3 .github/tests/starchart_refresh_contract_test.py python3 .github/tests/main_is_released_contract_test.py python3 .github/tests/tracked_validation_test.py +python3 .github/tests/changes_gate_contract_test.py python3 .github/tests/test_wiring_contract_test.py echo "==> compile python" From 8d7814b6b85a8f9e6881b08b219886951bacee9e Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:18:19 -0500 Subject: [PATCH 38/44] feat(ci): default node-ci to Node 26 (#69) --- .github/tests/reusable_ci_contract_test.py | 2 +- .github/workflows/node-ci.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/tests/reusable_ci_contract_test.py b/.github/tests/reusable_ci_contract_test.py index 9804f2d..22e18f9 100644 --- a/.github/tests/reusable_ci_contract_test.py +++ b/.github/tests/reusable_ci_contract_test.py @@ -131,7 +131,7 @@ def test_workflow_call_interfaces_are_typed_and_have_no_outputs_or_secrets(self) self.assert_input("go", "artifact-namespace", "string", default="") self.assert_input("node", "artifact-namespace", "string", default="") self.assert_input("node", "module-directory", "string", default=".") - self.assert_input("node", "node-version", "string", default="24") + self.assert_input("node", "node-version", "string", default="26") self.assert_input("node", "lockfile-path", "string", default="package-lock.json") self.assert_input("node", "lint-check-name", "string", default="Node Lint") self.assert_input("node", "test-check-name", "string", default="Node Test") diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index 7b6ff12..3496b49 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -12,7 +12,7 @@ on: description: Node.js version used by enabled jobs required: false type: string - default: 24 + default: 26 lockfile-path: description: Repository-relative npm lockfile path or multiline paths required: false From 27ffcbe5d1021057ea620f7a53ca93a7543e8f33 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:22:32 -0500 Subject: [PATCH 39/44] feat(actions): add tree-receipt verify and record actions (#73) Run expensive verification once per tree. record writes a commit status naming the tested tree after a real run, and verify reuses it only when the workflow, tree, creator, run and jobs all check out. Any doubt falls back to a full run. --- .github/tests/tree_receipt_contract_test.py | 644 ++++++++++++++++++++ .github/workflows/standards-validation.yml | 1 + actions/tree-receipt/README.md | 138 +++++ actions/tree-receipt/record/action.yml | 28 + actions/tree-receipt/record/record.py | 138 +++++ actions/tree-receipt/verify/action.yml | 33 + actions/tree-receipt/verify/verify.py | 275 +++++++++ scripts/validate.sh | 1 + 8 files changed, 1258 insertions(+) create mode 100644 .github/tests/tree_receipt_contract_test.py create mode 100644 actions/tree-receipt/README.md create mode 100644 actions/tree-receipt/record/action.yml create mode 100644 actions/tree-receipt/record/record.py create mode 100644 actions/tree-receipt/verify/action.yml create mode 100644 actions/tree-receipt/verify/verify.py diff --git a/.github/tests/tree_receipt_contract_test.py b/.github/tests/tree_receipt_contract_test.py new file mode 100644 index 0000000..2b362d0 --- /dev/null +++ b/.github/tests/tree_receipt_contract_test.py @@ -0,0 +1,644 @@ +import contextlib +import datetime +import http.server +import importlib.util +import io +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import threading +import unittest +import urllib.error + + +ROOT = Path(__file__).resolve().parents[2] +BASE = ROOT / "actions" / "tree-receipt" + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +verify = load("tree_receipt_verify", BASE / "verify" / "verify.py") +record = load("tree_receipt_record", BASE / "record" / "record.py") + +REPO = "CodesWhat/example" +SERVER = "https://github.com" +API = "https://api.github.com" +WF = ".github/workflows/ci.yml" +WF_REF = "{0}/{1}@refs/pull/7/merge".format(REPO, WF) +TREE = "a" * 40 +OTHER_TREE = "b" * 40 +HEAD = "1" * 40 +PARENT_A = "2" * 40 +PARENT_B = "3" * 40 +NOW = datetime.datetime(2026, 11, 22, 12, 0, 0, tzinfo=datetime.timezone.utc) +FRESH = "2026-11-21T12:00:00Z" +OLD = "2026-11-01T12:00:00Z" + + +def run_url(run_id=500): + return "{0}/{1}/actions/runs/{2}".format(SERVER, REPO, run_id) + + +def status(tree=TREE, context="tree-receipt/" + WF, state="success", + login="github-actions[bot]", target="default"): + return { + "context": context, "state": state, "description": "tree=" + tree, + "creator": {"login": login}, + "target_url": run_url() if target == "default" else target, + } + + +def run_obj(sha, **over): + data = { + "repository": {"full_name": REPO}, "path": WF + "@refs/pull/7/merge", + "conclusion": "success", "status": "completed", "head_sha": sha, + "created_at": FRESH, + } + data.update(over) + return data + + +def jobs(*conclusions): + items = [{"conclusion": c} for c in conclusions] + return {"total_count": len(items), "jobs": items} + + +class Pages: + def __init__(self, *pages): + self.pages = pages + + +class Api: + """Mock fetch: routes keyed by path, optionally paged.""" + + def __init__(self, routes): + self.routes = routes + self.calls = [] + + def __call__(self, url, auth): + self.calls.append(url) + assert url.startswith(API), url + rest = url[len(API):] + path, _, query = rest.partition("?") + page = 1 + match = re.search(r"(?:^|&)page=([0-9]+)", query) + if match: + page = int(match.group(1)) + if path not in self.routes: + raise urllib.error.HTTPError(url, 404, "nf", {}, None) + value = self.routes[path] + if isinstance(value, Exception): + raise value + if isinstance(value, Pages): + return value.pages[page - 1] if page <= len(value.pages) else [] + return value + + +def git_stub(tree=TREE, head=HEAD, parents=(PARENT_A,)): + def git(args): + if args == ["rev-parse", "HEAD^{tree}"]: + return tree + if args == ["rev-parse", "HEAD"]: + return head + if args == ["rev-parse", "HEAD^@"]: + return "\n".join(parents) + raise AssertionError(args) + return git + + +def stat_path(sha): + return "/repos/{0}/commits/{1}/statuses".format(REPO, sha) + + +def run_path(run_id=500): + return "/repos/{0}/actions/runs/{1}".format(REPO, run_id) + + +def good_routes(sha=PARENT_A, run_id=500): + return { + "/repos/{0}/commits/{1}/pulls".format(REPO, HEAD): [], + stat_path(sha): [status(target=run_url(run_id))], + run_path(run_id): run_obj(sha), + run_path(run_id) + "/jobs": jobs("success", "skipped"), + } + + +def base_env(tmp, event="push", pr_head=None, **extra): + env = { + "TREE_RECEIPT_EVENT_NAME": event, + "TREE_RECEIPT_AUTH": "secret-value", + "GITHUB_REPOSITORY": REPO, + "GITHUB_WORKFLOW_REF": WF_REF, + "GITHUB_SERVER_URL": SERVER, + "GITHUB_API_URL": API, + "GITHUB_OUTPUT": str(Path(tmp) / "output"), + "GITHUB_EVENT_PATH": str(Path(tmp) / "event.json"), + "GITHUB_RUN_ID": "900", + "GITHUB_SHA": HEAD, + } + pr = {"head": {"sha": pr_head or HEAD, "repo": {"full_name": REPO}}, + "base": {"repo": {"full_name": REPO}}} + Path(env["GITHUB_EVENT_PATH"]).write_text(json.dumps({"pull_request": pr})) + env.update(extra) + return env + + +def run_verify(routes, event="push", git=None, pr_head=None, now=NOW, **extra): + with tempfile.TemporaryDirectory() as tmp: + env = base_env(tmp, event, pr_head, **extra) + api = Api(routes) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + verify.main(env, git or git_stub(), api, now) + out = Path(env["GITHUB_OUTPUT"]).read_text() + return out, buf.getvalue(), api + + +def reuse_of(out): + return re.search(r"^reuse=(.*)$", out, re.M).group(1) + + +class VerifyTests(unittest.TestCase): + def assertReuse(self, expected, out): + self.assertEqual(expected, reuse_of(out), out) + + def test_valid_receipt_on_parent_reuses(self): + out, log, _ = run_verify(good_routes()) + self.assertReuse("true", out) + self.assertIn("evidence-run=" + run_url() + "\n", out) + self.assertIn("candidate=" + PARENT_A, log) + self.assertIn("created_at=" + FRESH, log) + self.assertNotIn("secret-value", log) + + def test_pull_request_uses_head_sha(self): + out, _, api = run_verify(good_routes(PARENT_B), event="pull_request", pr_head=PARENT_B) + self.assertReuse("true", out) + self.assertFalse(any("/pulls" in c for c in api.calls)) + + def test_tree_mismatch(self): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(tree=OTHER_TREE)] + self.assertReuse("false", run_verify(routes)[0]) + + def test_different_workflow_context(self): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(context="tree-receipt/.github/workflows/other.yml")] + self.assertReuse("false", run_verify(routes)[0]) + + def test_run_path_mismatch(self): + routes = good_routes() + routes[run_path(500)] = run_obj(PARENT_A, path=".github/workflows/other.yml") + self.assertReuse("false", run_verify(routes)[0]) + + def test_run_path_without_ref_suffix_accepted(self): + routes = good_routes() + routes[run_path(500)] = run_obj(PARENT_A, path=WF) + self.assertReuse("true", run_verify(routes)[0]) + + def test_creator_not_bot(self): + for login in ("someone", "github-actions", "Github-Actions[bot]", None): + with self.subTest(login=login): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(login=login)] + self.assertReuse("false", run_verify(routes)[0]) + + def test_state_not_success(self): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(state="pending")] + self.assertReuse("false", run_verify(routes)[0]) + + def test_target_url_other_repo_or_malformed(self): + for target in ( + SERVER + "/CodesWhat/other/actions/runs/500", + run_url() + "/attempts/1", + run_url() + "x", + "https://evil.example/{0}/actions/runs/500".format(REPO), + SERVER + "/" + REPO + "/actions/runs/abc", + None, ""): + with self.subTest(target=target): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(target=target)] + self.assertReuse("false", run_verify(routes)[0]) + + def test_run_failures(self): + cases = { + "conclusion": run_obj(PARENT_A, conclusion="failure"), + "status": run_obj(PARENT_A, status="in_progress"), + "head_sha": run_obj(PARENT_A, head_sha=PARENT_B), + "repo": run_obj(PARENT_A, repository={"full_name": "CodesWhat/other"}), + "old": run_obj(PARENT_A, created_at=OLD), + "future": run_obj(PARENT_A, created_at="2026-11-23T12:00:00Z"), + } + for name, obj in cases.items(): + with self.subTest(name=name): + routes = good_routes() + routes[run_path(500)] = obj + self.assertReuse("false", run_verify(routes)[0]) + + def test_max_age_input(self): + out, _, _ = run_verify(good_routes(), TREE_RECEIPT_MAX_AGE_HOURS="12") + self.assertReuse("false", out) + out, _, _ = run_verify(good_routes(), TREE_RECEIPT_MAX_AGE_HOURS="48") + self.assertReuse("true", out) + for bad in ("abc", "0", "-3", "nan"): + with self.subTest(bad=bad): + out, _, _ = run_verify(good_routes(), TREE_RECEIPT_MAX_AGE_HOURS=bad) + self.assertReuse("false", out) + + def test_bad_jobs(self): + for conclusion in ("failure", "cancelled", "timed_out", "action_required", + "startup_failure", None): + with self.subTest(conclusion=conclusion): + routes = good_routes() + routes[run_path(500) + "/jobs"] = jobs("success", conclusion) + self.assertReuse("false", run_verify(routes)[0]) + + def test_incomplete_or_empty_jobs(self): + routes = good_routes() + routes[run_path(500) + "/jobs"] = {"total_count": 3, "jobs": [{"conclusion": "success"}]} + self.assertReuse("false", run_verify(routes)[0]) + routes[run_path(500) + "/jobs"] = jobs() + self.assertReuse("false", run_verify(routes)[0]) + + def test_bad_job_on_second_page(self): + routes = good_routes() + first = {"total_count": 101, "jobs": [{"conclusion": "success"}] * 100} + second = {"total_count": 101, "jobs": [{"conclusion": "failure"}]} + routes[run_path(500) + "/jobs"] = Pages(first, second) + self.assertReuse("false", run_verify(routes)[0]) + + def test_api_error_at_each_step(self): + for key in (stat_path(PARENT_A), run_path(500), run_path(500) + "/jobs"): + with self.subTest(step=key): + routes = good_routes() + routes[key] = OSError("boom") + self.assertReuse("false", run_verify(routes)[0]) + with self.subTest(step=key, missing=True): + routes = good_routes() + del routes[key] + self.assertReuse("false", run_verify(routes)[0]) + + def test_api_error_on_pulls_lookup(self): + routes = good_routes() + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = OSError("boom") + self.assertReuse("false", run_verify(routes)[0]) + + def test_malformed_data(self): + for key, bad in ((stat_path(PARENT_A), {"x": 1}), (stat_path(PARENT_A), ["junk"]), + (run_path(500), []), (run_path(500) + "/jobs", [])): + with self.subTest(key=key, bad=bad): + routes = good_routes() + routes[key] = bad + self.assertReuse("false", run_verify(routes)[0]) + + def test_other_events_never_reuse(self): + for event in ("schedule", "workflow_dispatch", "merge_group", "workflow_call", ""): + with self.subTest(event=event): + out, _, api = run_verify(good_routes(), event=event) + self.assertReuse("false", out) + self.assertEqual([], api.calls) + + def test_no_git_repo(self): + def git(args): + raise subprocess.CalledProcessError(128, "git") + self.assertReuse("false", run_verify(good_routes(), git=git)[0]) + + def test_missing_auth_and_bad_workflow_ref(self): + self.assertReuse("false", run_verify(good_routes(), TREE_RECEIPT_AUTH="")[0]) + self.assertReuse("false", run_verify(good_routes(), GITHUB_WORKFLOW_REF="junk")[0]) + + def test_push_merge_commit_finds_dev_head_receipt(self): + git = git_stub(parents=(PARENT_A, PARENT_B)) + routes = good_routes(PARENT_B) + routes[stat_path(PARENT_A)] = [] + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = [] + out, log, _ = run_verify(routes, git=git) + self.assertReuse("true", out) + self.assertIn("candidate=" + PARENT_B, log) + + def test_push_associated_pr_head(self): + pr_head = "4" * 40 + routes = good_routes(pr_head) + routes[stat_path(PARENT_A)] = [] + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = [ + {"head": {"sha": pr_head}, "title": "secret title", "number": 7}] + out, log, _ = run_verify(routes) + self.assertReuse("true", out) + self.assertNotIn("secret title", log) + + def test_candidates_capped_at_ten(self): + shas = ["{0:040x}".format(i + 16) for i in range(15)] + routes = {"/repos/{0}/commits/{1}/pulls".format(REPO, HEAD): []} + for sha in shas: + routes[stat_path(sha)] = [] + # The 11th candidate holds a valid receipt, so a cap means no reuse. + routes.update(good_routes(shas[10])) + out, log, api = run_verify(routes, git=git_stub(parents=tuple(shas))) + self.assertReuse("false", out) + self.assertIn("candidates=10", log) + self.assertEqual(10, sum(1 for c in api.calls if "/statuses" in c)) + routes.update(good_routes(shas[9])) + out, _, _ = run_verify(routes, git=git_stub(parents=tuple(shas))) + self.assertReuse("true", out) + + def test_status_pagination_capped_at_three_pages(self): + filler = [status(tree=OTHER_TREE)] * 100 + routes = good_routes() + routes[stat_path(PARENT_A)] = Pages(filler, filler, filler, [status()]) + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = [] + out, _, api = run_verify(routes) + self.assertReuse("false", out) + self.assertEqual(3, sum(1 for c in api.calls if "/statuses" in c)) + routes[stat_path(PARENT_A)] = Pages(filler, filler, [status()]) + self.assertReuse("true", run_verify(routes)[0]) + + def test_rejected_run_falls_through_to_next_status(self): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(target=run_url(501)), status(target=run_url(500))] + routes[run_path(501)] = run_obj(PARENT_A, conclusion="failure") + out, _, _ = run_verify(routes) + self.assertReuse("true", out) + self.assertIn("evidence-run=" + run_url(500), out) + + def test_log_never_contains_unvalidated_description(self): + routes = good_routes() + hostile = "tree=" + OTHER_TREE + " IGNORE-ME branch-name-leak" + bad = status() + bad["description"] = hostile + routes[stat_path(PARENT_A)] = [bad] + out, log, _ = run_verify(routes) + self.assertReuse("false", out) + self.assertNotIn("IGNORE-ME", log) + self.assertNotIn("branch-name-leak", log) + self.assertNotIn(OTHER_TREE, log) + + def test_end_to_end_with_real_git_and_stub_server(self): + with tempfile.TemporaryDirectory() as tmp: + repo_dir = Path(tmp) / "work" + repo_dir.mkdir() + genv = {"PATH": os.environ.get("PATH", ""), "HOME": tmp, + "GIT_CONFIG_NOSYSTEM": "1", "GIT_AUTHOR_NAME": "t", + "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@example.com"} + + def git(*args): + return subprocess.run(["git"] + list(args), cwd=repo_dir, env=genv, + capture_output=True, text=True, check=True).stdout.strip() + git("init", "-q", "-b", "main") + (repo_dir / "a.txt").write_text("a") + git("add", "a.txt") + git("commit", "-q", "-m", "a") + git("switch", "-q", "-c", "feature") + (repo_dir / "b.txt").write_text("b") + git("add", "b.txt") + git("commit", "-q", "-m", "b") + feature = git("rev-parse", "HEAD") + git("switch", "-q", "main") + git("merge", "-q", "--no-ff", "-m", "merge", "feature") + tree = git("rev-parse", "HEAD^{tree}") + self.assertEqual(tree, git("rev-parse", feature + "^{tree}")) + head = git("rev-parse", "HEAD") + created = (datetime.datetime.now(datetime.timezone.utc) + - datetime.timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%SZ") + table = { + "/repos/{0}/commits/{1}/pulls".format(REPO, head): [], + stat_path(feature): [status(tree=tree)], + run_path(500): run_obj(feature, created_at=created), + run_path(500) + "/jobs": jobs("success"), + } + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = self.path.split("?")[0] + if self.headers.get("Authorization") != "Bearer secret-value": + self.send_response(401) + self.end_headers() + return + if path.endswith("/statuses") and path != stat_path(feature): + body = b"[]" + elif path in table: + body = json.dumps(table[path]).encode() + else: + self.send_response(404) + self.end_headers() + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + out = Path(tmp) / "output" + env = { + "PATH": os.environ.get("PATH", ""), "HOME": tmp, + "NO_PROXY": "127.0.0.1", "no_proxy": "127.0.0.1", + "TREE_RECEIPT_EVENT_NAME": "push", "TREE_RECEIPT_AUTH": "secret-value", + "TREE_RECEIPT_MAX_AGE_HOURS": "168", + "GITHUB_REPOSITORY": REPO, "GITHUB_WORKFLOW_REF": WF_REF, + "GITHUB_SERVER_URL": SERVER, + "GITHUB_API_URL": "http://127.0.0.1:{0}".format(server.server_address[1]), + "GITHUB_OUTPUT": str(out), + } + proc = subprocess.run( + [sys.executable, "-I", str(BASE / "verify" / "verify.py")], + cwd=repo_dir, env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(0, proc.returncode, proc.stderr) + self.assertEqual("reuse=true\nevidence-run={0}\n".format(run_url()), out.read_text()) + self.assertIn(feature, proc.stdout) + self.assertNotIn("secret-value", proc.stdout + proc.stderr) + # A new commit changes the tree, so the same receipt no longer matches. + (repo_dir / "c.txt").write_text("c") + git("add", "c.txt") + git("commit", "-q", "-m", "c") + out.unlink() + proc = subprocess.run( + [sys.executable, "-I", str(BASE / "verify" / "verify.py")], + cwd=repo_dir, env=env, capture_output=True, text=True, timeout=60) + self.assertEqual("reuse=false\nevidence-run=\n", out.read_text()) + finally: + server.shutdown() + server.server_close() + + def test_action_shape(self): + action = (BASE / "verify" / "action.yml").read_text(encoding="utf-8") + for expected in ("using: composite", 'default: "168"', + "default: ${{ github.token }}", + "value: ${{ steps.verify.outputs.reuse }}", + "value: ${{ steps.verify.outputs.evidence-run }}", + 'run: python3 "$GITHUB_ACTION_PATH/verify.py"'): + self.assertIn(expected, action) + for line in action.splitlines(): + if line.strip().startswith("run:"): + self.assertNotIn("${{", line) + self.assertNotIn("uses:", action) + + +class Recorder: + def __init__(self, fail=False): + self.fail = fail + self.calls = [] + + def __call__(self, url, auth, payload): + self.calls.append((url, auth, payload)) + if self.fail: + raise OSError("boom") + + +def run_record(event="push", tree=TREE, git=None, recorder=None, event_data=None, **extra): + recorder = recorder or Recorder() + with tempfile.TemporaryDirectory() as tmp: + env = base_env(tmp, event, TREE_RECEIPT_TESTED_TREE=tree, **extra) + if event_data is not None: + Path(env["GITHUB_EVENT_PATH"]).write_text(json.dumps(event_data)) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = record.main(env, git or git_stub(), recorder) + return code, buf.getvalue(), recorder + + +class RecordTests(unittest.TestCase): + def test_push_writes_receipt_on_github_sha(self): + code, log, rec = run_record() + self.assertEqual(0, code) + (url, auth, payload), = rec.calls + self.assertEqual("{0}/repos/{1}/statuses/{2}".format(API, REPO, HEAD), url) + self.assertEqual("secret-value", auth) + self.assertEqual({ + "state": "success", "target_url": run_url(900), + "description": "tree=" + TREE, "context": "tree-receipt/" + WF, + }, payload) + self.assertNotIn("secret-value", log) + + def test_pull_request_writes_on_head_sha(self): + head = "5" * 40 + _, _, rec = run_record(event="pull_request", event_data={"pull_request": { + "head": {"sha": head, "repo": {"full_name": REPO}}, + "base": {"repo": {"full_name": REPO}}}}) + self.assertTrue(rec.calls[0][0].endswith("/statuses/" + head)) + + def test_fork_pull_request_skipped(self): + for event in ("pull_request", "pull_request_target"): + with self.subTest(event=event): + code, log, rec = run_record(event=event, event_data={"pull_request": { + "head": {"sha": HEAD, "repo": {"full_name": "someone/example"}}, + "base": {"repo": {"full_name": REPO}}}}) + self.assertEqual(0, code) + self.assertEqual([], rec.calls) + self.assertIn("skipped (fork)", log) + + def test_malformed_pull_request_event_skipped(self): + code, _, rec = run_record(event="pull_request", event_data={"pull_request": {}}) + self.assertEqual(0, code) + self.assertEqual([], rec.calls) + + def test_write_failure_exits_zero(self): + code, log, _ = run_record(recorder=Recorder(fail=True)) + self.assertEqual(0, code) + self.assertIn("write failed", log) + + def test_invalid_tested_tree_rejected(self): + for bad in ("abc", "A" * 40, "g" * 40, "a" * 41, "a" * 40 + "\n--", TREE[:-1]): + with self.subTest(tree=bad): + code, log, rec = run_record(tree=bad) + self.assertEqual(0, code) + self.assertEqual([], rec.calls) + self.assertIn("invalid-tree", log) + + def test_default_tree_from_git(self): + _, _, rec = run_record(tree="", git=git_stub(tree=OTHER_TREE)) + self.assertEqual("tree=" + OTHER_TREE, rec.calls[0][2]["description"]) + + def test_default_tree_git_failure_skips(self): + def git(args): + raise subprocess.CalledProcessError(128, "git") + code, _, rec = run_record(tree="", git=git) + self.assertEqual(0, code) + self.assertEqual([], rec.calls) + + def test_bad_workflow_ref_or_run_id_skips(self): + for extra in ({"GITHUB_WORKFLOW_REF": "junk"}, {"GITHUB_RUN_ID": "abc"}, + {"TREE_RECEIPT_AUTH": ""}, {"GITHUB_REPOSITORY": "a/b/c"}): + with self.subTest(extra=extra): + code, _, rec = run_record(**extra) + self.assertEqual(0, code) + self.assertEqual([], rec.calls) + + def test_end_to_end_with_stub_server(self): + seen = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + seen.append((self.path, self.headers.get("Authorization"), + json.loads(self.rfile.read(length)))) + self.send_response(201) + self.send_header("Content-Length", "2") + self.end_headers() + self.wfile.write(b"{}") + + def log_message(self, *args): + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with tempfile.TemporaryDirectory() as tmp: + env = { + "PATH": os.environ.get("PATH", ""), + "NO_PROXY": "127.0.0.1", "no_proxy": "127.0.0.1", + "TREE_RECEIPT_EVENT_NAME": "push", "TREE_RECEIPT_AUTH": "secret-value", + "TREE_RECEIPT_TESTED_TREE": TREE, + "GITHUB_REPOSITORY": REPO, "GITHUB_WORKFLOW_REF": WF_REF, + "GITHUB_SERVER_URL": SERVER, "GITHUB_RUN_ID": "900", "GITHUB_SHA": HEAD, + "GITHUB_API_URL": "http://127.0.0.1:{0}".format(server.server_address[1]), + } + proc = subprocess.run( + [sys.executable, "-I", str(BASE / "record" / "record.py")], + cwd=tmp, env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(0, proc.returncode, proc.stderr) + (path, auth, payload), = seen + self.assertEqual("/repos/{0}/statuses/{1}".format(REPO, HEAD), path) + self.assertEqual("Bearer secret-value", auth) + self.assertEqual("tree=" + TREE, payload["description"]) + self.assertEqual("tree-receipt/" + WF, payload["context"]) + self.assertNotIn("secret-value", proc.stdout + proc.stderr) + # An unreachable server must still exit 0. + env["GITHUB_API_URL"] = "http://127.0.0.1:1" + proc = subprocess.run( + [sys.executable, "-I", str(BASE / "record" / "record.py")], + cwd=tempfile.gettempdir(), env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(0, proc.returncode, proc.stderr) + self.assertIn("write failed", proc.stdout) + finally: + server.shutdown() + server.server_close() + + def test_action_shape(self): + action = (BASE / "record" / "action.yml").read_text(encoding="utf-8") + for expected in ("using: composite", "default: ${{ github.token }}", + "TREE_RECEIPT_TESTED_TREE: ${{ inputs.tested-tree }}", + 'run: python3 "$GITHUB_ACTION_PATH/record.py"'): + self.assertIn(expected, action) + for line in action.splitlines(): + if line.strip().startswith("run:"): + self.assertNotIn("${{", line) + self.assertNotIn("uses:", action) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 20c464f..59004e6 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -43,6 +43,7 @@ jobs: python3 .github/tests/greptile_summon_contract_test.py python3 .github/tests/tracked_validation_test.py python3 .github/tests/changes_gate_contract_test.py + python3 .github/tests/tree_receipt_contract_test.py python3 .github/tests/test_wiring_contract_test.py - name: Compile Python diff --git a/actions/tree-receipt/README.md b/actions/tree-receipt/README.md new file mode 100644 index 0000000..b390dea --- /dev/null +++ b/actions/tree-receipt/README.md @@ -0,0 +1,138 @@ +# tree-receipt + +Run expensive verification once per tree. In a dev-branch repo the same tree +can run full CI three or four times (feature PR, push to dev, promotion PR, +push to main). These two composite actions let later events reuse the first +run's result and fall back to a full run on any doubt. + +- `verify` runs first. It outputs `reuse=true` only when a trusted earlier + run verified exactly this tree. +- `record` runs last, in a final gate job, and writes the receipt that a later + `verify` looks for. + +Required check names keep reporting. Callers skip the expensive jobs with a +job-level `if`, and a skipped job reports success to branch protection. + +## Usage + +```yaml +permissions: {} + +jobs: + verify: + runs-on: ubuntu-26.04 + permissions: + actions: read + contents: read + pull-requests: read + statuses: read + outputs: + reuse: ${{ steps.receipt.outputs.reuse }} + steps: + - uses: actions/checkout@ + with: + persist-credentials: false + - id: receipt + uses: CodesWhat/.github/actions/tree-receipt/verify@ + + build-and-test: + needs: verify + if: needs.verify.outputs.reuse != 'true' + runs-on: macos-26 + steps: + - uses: actions/checkout@ + with: + persist-credentials: false + - run: echo "expensive work" + + gate: + needs: [verify, build-and-test] + if: always() + runs-on: ubuntu-26.04 + permissions: + contents: read + statuses: write + steps: + - name: Fail on any failed or cancelled job + env: + RESULTS: ${{ join(needs.*.result, ' ') }} + run: | + for result in $RESULTS; do + case "$result" in + success|skipped) ;; + *) echo "a needed job ended as $result"; exit 1 ;; + esac + done + - uses: actions/checkout@ + if: needs.build-and-test.result == 'success' + with: + persist-credentials: false + - uses: CodesWhat/.github/actions/tree-receipt/record@ + if: needs.build-and-test.result == 'success' +``` + +The gate accepts `success` or `skipped` (skipped because the tree was reused) +and fails on anything else. It records only when the expensive jobs actually +ran and passed, so reused evidence is never re-recorded and its age is never +refreshed. If `verify` itself fails, `reuse` is empty, the expensive jobs run, +and the gate fails on the failed `verify` job. + +Pin both actions to a full commit SHA. Both need a checkout, and for +`pull_request` runs that checkout is the synthetic merge commit. That commit's +tree is the one tested, so that is the tree recorded and compared. Pass +`tested-tree` to `record` if the tested tree is not `HEAD` in the gate job's +workspace. + +## Contract + +`verify` inputs: `max-age-hours` (default `168`) and `github-token`. Outputs: +`reuse` (exactly `true` or `false`) and `evidence-run` (the run URL, or empty). + +`verify` looks only at narrow candidates. For `pull_request` that is the PR +head SHA. For `push` it is the pushed commit's parents (so a merge commit finds +the dev head) plus the head SHAs of PRs associated with the pushed commit, up +to 10 commits. Other events (`schedule`, `workflow_dispatch`, `merge_group`, +`workflow_call`) always output `false`. + +A candidate's commit status is accepted only when all of these hold: + +- the context is `tree-receipt/`, so receipts never + cross workflows; +- the state is `success` and the creator is `github-actions[bot]`; +- the description is exactly `tree=`; +- the target URL is a run URL for this repository. + +The run is then checked through the API. It must belong to this repository, +have the same workflow path, be completed with conclusion `success`, have +`head_sha` equal to the candidate, and be younger than `max-age-hours`. No job +in it may be failed, cancelled, timed out, action-required or startup-failed. +The age is the original run's age. Reuse never refreshes it. + +Any API error, malformed data or ambiguity outputs `false`. The log carries +only SHAs, counts, run ids and the decision. + +`record` writes a `success` commit status on the commit the workflow ran for +(the PR head for `pull_request`, else `github.sha`). Context is +`tree-receipt/`, description is `tree=<40-hex tree>`, and the +target URL is this run. It needs `statuses: write`. If the write fails it logs +and exits 0, because a missing receipt only costs a full run later. Fork PRs +never produce receipts, so they always run in full. + +## What must not be gated by reuse + +Equal trees do not make these safe to skip. Leave them outside the reuse gate +so they run on every event: + +- time-sensitive scans: vulnerability and advisory checks, whose answer changes + without the tree changing; +- release-specific checks: signing, notarization, provenance, version and + ancestry checks, hotfix preservation, deploys; +- anything whose inputs live outside the tree: external services, mutable tags + and images. + +Tree equality covers the workflow files, pinned reusable-workflow SHAs and +lockfiles, since they are all in the tree. It does not cover runner image +drift. `max-age-hours` bounds that. + +`code_scanning` ruleset rules still need SARIF for the current commit. Don't +gate CodeQL uploads with this unless the repository's rules allow it. diff --git a/actions/tree-receipt/record/action.yml b/actions/tree-receipt/record/action.yml new file mode 100644 index 0000000..0db0d6e --- /dev/null +++ b/actions/tree-receipt/record/action.yml @@ -0,0 +1,28 @@ +name: Tree receipt record +description: >- + Write a verification receipt for the tree this workflow run just tested. + Run it as the last step of a final gate job, only when every verified job + succeeded. Never fails the job. + +inputs: + tested-tree: + description: >- + 40-hex tree of the commit that was checked out and tested. Defaults to + the tree of HEAD in the workspace. + required: false + default: "" + github-token: + description: Token used to write the commit status. Needs statuses write. + required: false + default: ${{ github.token }} + +runs: + using: composite + steps: + - id: record + shell: bash + env: + TREE_RECEIPT_TESTED_TREE: ${{ inputs.tested-tree }} + TREE_RECEIPT_AUTH: ${{ inputs.github-token }} + TREE_RECEIPT_EVENT_NAME: ${{ github.event_name }} + run: python3 "$GITHUB_ACTION_PATH/record.py" diff --git a/actions/tree-receipt/record/record.py b/actions/tree-receipt/record/record.py new file mode 100644 index 0000000..28d5772 --- /dev/null +++ b/actions/tree-receipt/record/record.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Write a tree receipt: a commit status naming the tree this run tested. + +Everything comes from environment variables. A failure to write is logged and +exits 0, because a missing receipt only costs a full run later. +""" +import json +import os +import re +import subprocess +import sys +import urllib.request + +REQUEST_TIMEOUT = 20 +TREE = re.compile(r"[0-9a-f]{40}") +WORKFLOW_REF = re.compile( + r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/(\.github/workflows/[A-Za-z0-9_./-]+)@\S+") +REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") + + +class Skip(Exception): + """Raised for anything that means no receipt is written.""" + + +def workflow_path(ref): + match = WORKFLOW_REF.fullmatch(ref or "") + if not match: + raise Skip("workflow-ref") + return match.group(1) + + +def read_event(env): + try: + with open(env["GITHUB_EVENT_PATH"], encoding="utf-8") as handle: + data = json.load(handle) + except (KeyError, OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def target_sha(env): + """Return the commit the workflow ran for, or raise Skip for fork PRs.""" + name = env.get("TREE_RECEIPT_EVENT_NAME", "") + if name in ("pull_request", "pull_request_target"): + pr = read_event(env).get("pull_request") + if not isinstance(pr, dict): + raise Skip("event") + head, base = pr.get("head"), pr.get("base") + try: + head_repo = head["repo"]["full_name"] + base_repo = base["repo"]["full_name"] + sha = head["sha"] + except (KeyError, TypeError): + raise Skip("event") + if head_repo != base_repo: + raise Skip("fork") + else: + sha = env.get("GITHUB_SHA", "") + if not isinstance(sha, str) or not TREE.fullmatch(sha): + raise Skip("sha") + return sha + + +def default_git(args): + return subprocess.run(["git"] + args, capture_output=True, text=True, + timeout=30, check=True).stdout.strip() + + +def tested_tree(env, git): + tree = (env.get("TREE_RECEIPT_TESTED_TREE") or "").strip() + if not tree: + try: + tree = git(["rev-parse", "HEAD^{tree}"]) + except Exception: + raise Skip("no-tree") + if not TREE.fullmatch(tree): + raise Skip("invalid-tree") + return tree + + +def post_status(url, auth, payload): + request = urllib.request.Request( + url, + data=json.dumps(payload).encode("utf-8"), + method="POST", + headers={ + "Authorization": "Bearer " + auth, + "Accept": "application/vnd.github+json", + "Content-Type": "application/json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "codeswhat-tree-receipt", + }, + ) + with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: + if response.status != 201: + raise OSError("status") + + +def record(env, git=default_git, post=post_status): + """Return a log line. Raises Skip for deliberate non-writes.""" + repo = env.get("GITHUB_REPOSITORY", "") + if not REPO.fullmatch(repo) or any(p in (".", "..") for p in repo.split("/")): + raise Skip("repository") + auth = env.get("TREE_RECEIPT_AUTH", "") + if not auth: + raise Skip("no-auth") + path = workflow_path(env.get("GITHUB_WORKFLOW_REF")) + sha = target_sha(env) + tree = tested_tree(env, git) + run_id = env.get("GITHUB_RUN_ID", "") + if not re.fullmatch(r"[0-9]+", run_id): + raise Skip("run-id") + server = (env.get("GITHUB_SERVER_URL") or "https://github.com").rstrip("/") + api = (env.get("GITHUB_API_URL") or "https://api.github.com").rstrip("/") + payload = { + "state": "success", + "target_url": "{0}/{1}/actions/runs/{2}".format(server, repo, run_id), + "description": "tree=" + tree, + "context": "tree-receipt/" + path, + } + post("{0}/repos/{1}/statuses/{2}".format(api, repo, sha), auth, payload) + return "recorded commit={0} tree={1} run={2}".format(sha, tree, run_id) + + +def main(env=None, git=default_git, post=post_status): + env = os.environ if env is None else env + try: + line = record(env, git, post) + except Skip as skip: + line = "skipped ({0})".format(skip) + except Exception: + line = "write failed, no receipt recorded" + print("tree-receipt record: " + line) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/actions/tree-receipt/verify/action.yml b/actions/tree-receipt/verify/action.yml new file mode 100644 index 0000000..42e392e --- /dev/null +++ b/actions/tree-receipt/verify/action.yml @@ -0,0 +1,33 @@ +name: Tree receipt verify +description: >- + Decide whether an earlier run already verified this exact tree, so + expensive jobs can be skipped. Outputs reuse=false on any doubt. + +inputs: + max-age-hours: + description: Oldest original run, in hours, that still counts as evidence. + required: false + default: "168" + github-token: + description: Token used to read statuses, runs and pull requests. + required: false + default: ${{ github.token }} + +outputs: + reuse: + description: The string true or false. + value: ${{ steps.verify.outputs.reuse }} + evidence-run: + description: URL of the run whose receipt was accepted, or empty. + value: ${{ steps.verify.outputs.evidence-run }} + +runs: + using: composite + steps: + - id: verify + shell: bash + env: + TREE_RECEIPT_MAX_AGE_HOURS: ${{ inputs.max-age-hours }} + TREE_RECEIPT_AUTH: ${{ inputs.github-token }} + TREE_RECEIPT_EVENT_NAME: ${{ github.event_name }} + run: python3 "$GITHUB_ACTION_PATH/verify.py" diff --git a/actions/tree-receipt/verify/verify.py b/actions/tree-receipt/verify/verify.py new file mode 100644 index 0000000..a40fd33 --- /dev/null +++ b/actions/tree-receipt/verify/verify.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +"""Decide whether an earlier run already verified this exact tree. + +Everything comes from environment variables. The log carries only SHAs, counts, +run ids and the decision, and GITHUB_OUTPUT gets reuse=true or reuse=false. +Any doubt resolves to false. +""" +import datetime +import json +import os +import re +import subprocess +import sys +import time +import urllib.parse +import urllib.request + +REQUEST_TIMEOUT = 20 +DEADLINE_SECONDS = 120 +PER_PAGE = 100 +STATUS_PAGES = 3 +JOB_PAGES = 5 +MAX_CANDIDATES = 10 +MAX_RUN_CHECKS = 5 +BOT = "github-actions[bot]" +HEX40 = re.compile(r"[0-9a-f]{40}") +REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") +WORKFLOW_REF = re.compile( + r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/(\.github/workflows/[A-Za-z0-9_./-]+)@\S+") +BAD_JOB = {"failure", "cancelled", "timed_out", "action_required", "startup_failure"} + + +class Doubt(Exception): + """Raised for anything that should resolve to reuse=false.""" + + +def workflow_path(ref): + match = WORKFLOW_REF.fullmatch(ref or "") + if not match: + raise Doubt("workflow-ref") + return match.group(1) + + +def default_git(args): + return subprocess.run(["git"] + args, capture_output=True, text=True, + timeout=30, check=True).stdout.strip() + + +def fetch_json(url, auth): + request = urllib.request.Request( + url, + headers={ + "Authorization": "Bearer " + auth, + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "codeswhat-tree-receipt", + }, + ) + with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: + if response.status != 200: + raise Doubt("status") + return json.loads(response.read().decode("utf-8")) + + +def read_event(env): + try: + with open(env["GITHUB_EVENT_PATH"], encoding="utf-8") as handle: + data = json.load(handle) + except (KeyError, OSError, ValueError): + raise Doubt("event") + if not isinstance(data, dict): + raise Doubt("event") + return data + + +def current_tree(git): + try: + tree = git(["rev-parse", "HEAD^{tree}"]) + except Exception: + raise Doubt("no-git") + if not HEX40.fullmatch(tree): + raise Doubt("tree") + return tree + + +def candidates(env, git, api, repo, auth, fetch): + name = env.get("TREE_RECEIPT_EVENT_NAME", "") + found = [] + if name == "pull_request": + try: + found.append(read_event(env)["pull_request"]["head"]["sha"]) + except (KeyError, TypeError): + raise Doubt("event") + elif name == "push": + try: + head = git(["rev-parse", "HEAD"]) + parents = git(["rev-parse", "HEAD^@"]).split() + except Exception: + raise Doubt("no-git") + if not HEX40.fullmatch(head): + raise Doubt("head") + found.extend(parents) + pulls = fetch("{0}/repos/{1}/commits/{2}/pulls?per_page={3}".format( + api, repo, head, PER_PAGE), auth) + if not isinstance(pulls, list): + raise Doubt("shape") + for pull in pulls: + try: + found.append(pull["head"]["sha"]) + except (KeyError, TypeError): + raise Doubt("shape") + else: + raise Doubt("event-name") + unique = [] + for sha in found: + if not isinstance(sha, str) or not HEX40.fullmatch(sha): + raise Doubt("sha") + if sha not in unique: + unique.append(sha) + return unique[:MAX_CANDIDATES] + + +def statuses(api, repo, sha, auth, fetch): + out = [] + for page in range(1, STATUS_PAGES + 1): + data = fetch("{0}/repos/{1}/commits/{2}/statuses?per_page={3}&page={4}".format( + api, repo, sha, PER_PAGE, page), auth) + if not isinstance(data, list): + raise Doubt("shape") + out.extend(data) + if len(data) < PER_PAGE: + break + return out + + +def parse_time(text): + if not isinstance(text, str): + raise Doubt("time") + try: + parsed = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ") + except ValueError: + raise Doubt("time") + return parsed.replace(tzinfo=datetime.timezone.utc) + + +def validate_run(api, repo, run_id, sha, path, max_age, now, auth, fetch): + """Return the run's created_at, or None when the run is not good evidence.""" + run = fetch("{0}/repos/{1}/actions/runs/{2}".format(api, repo, run_id), auth) + if not isinstance(run, dict): + raise Doubt("shape") + full = (run.get("repository") or {}).get("full_name") if isinstance( + run.get("repository"), dict) else None + run_path = run.get("path") + if not isinstance(run_path, str): + raise Doubt("shape") + if (full != repo or run_path.split("@", 1)[0] != path + or run.get("conclusion") != "success" or run.get("status") != "completed" + or run.get("head_sha") != sha): + return None + created = parse_time(run.get("created_at")) + age = now - created + if age < datetime.timedelta(0) or age > datetime.timedelta(hours=max_age): + return None + seen = 0 + total = None + for page in range(1, JOB_PAGES + 1): + data = fetch("{0}/repos/{1}/actions/runs/{2}/jobs?per_page={3}&page={4}".format( + api, repo, run_id, PER_PAGE, page), auth) + jobs = data.get("jobs") if isinstance(data, dict) else None + count = data.get("total_count") if isinstance(data, dict) else None + if not isinstance(jobs, list) or isinstance(count, bool) or not isinstance(count, int): + raise Doubt("shape") + total = count + for job in jobs: + if not isinstance(job, dict): + raise Doubt("shape") + conclusion = job.get("conclusion") + if conclusion is None or conclusion in BAD_JOB: + return None + seen += len(jobs) + if seen >= total or len(jobs) < PER_PAGE: + break + if total is None or total == 0 or seen != total: + raise Doubt("jobs-incomplete") + return created + + +def decide(env, git=default_git, fetch=fetch_json, now=None): + """Return (reuse, evidence_url, log_lines).""" + log = [] + repo = env.get("GITHUB_REPOSITORY", "") + if not REPO.fullmatch(repo) or any(p in (".", "..") for p in repo.split("/")): + raise Doubt("repository") + auth = env.get("TREE_RECEIPT_AUTH", "") + if not auth: + raise Doubt("no-auth") + try: + max_age = float(env.get("TREE_RECEIPT_MAX_AGE_HOURS", "168")) + except ValueError: + raise Doubt("max-age") + if not 0 < max_age < 24 * 365: + raise Doubt("max-age") + path = workflow_path(env.get("GITHUB_WORKFLOW_REF")) + api = (env.get("GITHUB_API_URL") or "https://api.github.com").rstrip("/") + server = (env.get("GITHUB_SERVER_URL") or "https://github.com").rstrip("/") + now = now or datetime.datetime.now(datetime.timezone.utc) + started = time.monotonic() + tree = current_tree(git) + cands = candidates(env, git, api, repo, auth, fetch) + log.append("tree={0} candidates={1}".format(tree, len(cands))) + context = "tree-receipt/" + path + description = "tree=" + tree + url_re = re.compile(r"{0}/{1}/actions/runs/([0-9]+)".format( + re.escape(server), re.escape(repo))) + checked = set() + for sha in cands: + if time.monotonic() - started > DEADLINE_SECONDS: + raise Doubt("deadline") + for status in statuses(api, repo, sha, auth, fetch): + if not isinstance(status, dict): + raise Doubt("shape") + creator = status.get("creator") + login = creator.get("login") if isinstance(creator, dict) else None + target = status.get("target_url") + match = url_re.fullmatch(target) if isinstance(target, str) else None + if (status.get("context") != context or status.get("state") != "success" + or login != BOT or status.get("description") != description + or not match): + continue + run_id = match.group(1) + if run_id in checked: + continue + if len(checked) >= MAX_RUN_CHECKS: + log.append("run check limit reached") + return False, "", log + checked.add(run_id) + created = validate_run(api, repo, run_id, sha, path, max_age, now, auth, fetch) + if created is None: + log.append("rejected candidate={0} run={1}".format(sha, run_id)) + continue + evidence = target + log.append("evidence candidate={0} run={1} created_at={2}".format( + sha, evidence, created.strftime("%Y-%m-%dT%H:%M:%SZ"))) + return True, evidence, log + return False, "", log + + +def write_output(path, reuse, evidence): + if not path: + return + with open(path, "a", encoding="utf-8") as handle: + handle.write("reuse={0}\nevidence-run={1}\n".format( + "true" if reuse else "false", evidence)) + + +def main(env=None, git=default_git, fetch=fetch_json, now=None): + env = os.environ if env is None else env + log = [] + try: + reuse, evidence, log = decide(env, git, fetch, now) + except Doubt as doubt: + reuse, evidence = False, "" + log.append("doubt ({0})".format(doubt)) + except Exception: + reuse, evidence = False, "" + log.append("doubt (error)") + for line in log: + print("tree-receipt verify: " + line) + print("tree-receipt verify: reuse={0}".format("true" if reuse else "false")) + write_output(env.get("GITHUB_OUTPUT"), reuse, evidence) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validate.sh b/scripts/validate.sh index 85ae8bf..bef5609 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -21,6 +21,7 @@ python3 .github/tests/starchart_refresh_contract_test.py python3 .github/tests/main_is_released_contract_test.py python3 .github/tests/tracked_validation_test.py python3 .github/tests/changes_gate_contract_test.py +python3 .github/tests/tree_receipt_contract_test.py python3 .github/tests/test_wiring_contract_test.py echo "==> compile python" From f9729f520e37fd0bcba28a8e22f8d6c491f4f7ba Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:23:32 -0500 Subject: [PATCH 40/44] fix(changes-gate): fail open on gate failure, harden matching and fetches (#74) * fix(changes-gate): harden matching, redirects and head binding Match globs per path segment with a bounded wildcard matcher instead of backtracking regexes, keep excludes case-sensitive, fail open on braces, leading slash and POSIX classes, refuse redirects so credentials stay on the API host, bind the listing to the event head SHA, and run python -I. * docs(changes-gate): fail closed caller condition and grammar notes * test(changes-gate): cover pagination bounds, wiring and event validation * fix(changes-gate): fold class members symmetrically and recheck head after listing Drop multi-character case expansions from class comparisons, compare single class members by shared case variants, and re-read the pull request after the file listing so a head that moved mid-listing resolves to run=true. * fix(changes-gate): close case variants so ranges fold the Kelvin sign --- .github/tests/changes_gate_contract_test.py | 315 +++++++++++++++++++- actions/changes-gate/README.md | 29 +- actions/changes-gate/action.yml | 2 +- actions/changes-gate/changes_gate.py | 210 ++++++++++--- 4 files changed, 503 insertions(+), 53 deletions(-) diff --git a/.github/tests/changes_gate_contract_test.py b/.github/tests/changes_gate_contract_test.py index 3e42838..da6f8b2 100644 --- a/.github/tests/changes_gate_contract_test.py +++ b/.github/tests/changes_gate_contract_test.py @@ -9,7 +9,9 @@ import sys import tempfile import threading +import time import unittest +import urllib.request ROOT = Path(__file__).resolve().parents[2] @@ -30,15 +32,16 @@ def entry(name, previous=None): API = "https://api.github.com" +HEAD = "a" * 40 -def pager(files, changed=None): +def pager(files, changed=None, head=HEAD): """Mock HTTP layer: the PR read plus the files listing in pages of 100.""" total = len(files) if changed is None else changed def fetch(url, auth): if url.endswith("/pulls/7"): - return {"changed_files": total}, None + return {"changed_files": total, "head": {"sha": head}}, None page = 1 if "&page=" in url: page = int(url.rsplit("&page=", 1)[1]) @@ -51,10 +54,14 @@ def fetch(url, auth): return fetch -def run_gate(event, files=None, patterns=PATTERNS, fetch=None, number=7, changed=None): +def run_gate(event, files=None, patterns=PATTERNS, fetch=None, number=7, changed=None, + head=HEAD, payload=None, write_event=True): with tempfile.TemporaryDirectory() as tmp: event_path = Path(tmp) / "event.json" - event_path.write_text(json.dumps({"pull_request": {"number": number}})) + if payload is None: + payload = {"pull_request": {"number": number, "head": {"sha": head}}} + if write_event: + event_path.write_text(json.dumps(payload)) out_path = Path(tmp) / "output" env = { "CHANGES_GATE_EVENT_NAME": event, @@ -189,8 +196,124 @@ def test_exclude_overrides_include(self): out, _ = run_gate("pull_request", [entry("Sources/Generated/A.swift")], patterns=patterns) self.assertRun("false", out) out, _ = run_gate("pull_request", [entry("sources/generated/A.swift")], patterns=patterns) + self.assertRun("true", out) + + def test_excludes_are_case_sensitive(self): + out, _ = run_gate("pull_request", [entry("Sources/App/generated/Evil.swift")], + patterns="Sources/**\n!Sources/App/Generated/**") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("Sources/App/Generated/Ok.swift")], + patterns="Sources/**\n!Sources/App/Generated/**") + self.assertRun("false", out) + + def test_excludes_have_no_unicode_folding(self): + out, _ = run_gate("pull_request", [entry("doc\u017f/x")], patterns="**\n!docs/**") + self.assertRun("true", out) + + def test_includes_stay_case_insensitive(self): + out, _ = run_gate("pull_request", [entry("SRC/a.js")], patterns="src/**") + self.assertRun("true", out) + + def test_unsupported_glob_syntax_runs(self): + for pattern in ("Sources/{a,b}/**", "Sources/a}", "{a", "/Sources/**", + "Sources/[[:alpha:]].swift", "!{a,b}", "!/docs/**", "Sources/**.swift/**x"): + with self.subTest(pattern=pattern): + out, _ = run_gate("pull_request", [entry("docs/a.md")], + patterns="Sources/**\n" + pattern) + self.assertRun("true", out) + + def test_pathological_pattern_is_bounded(self): + pattern = "a/**/**/**/**/b*c*d*e*f*g" + name = "a/" + "x" * 5000 + "/" + "bcdef" * 1000 + started = time.monotonic() + out, _ = run_gate("pull_request", [entry(name)], patterns=pattern) + elapsed = time.monotonic() - started + self.assertRun("false", out) + self.assertLess(elapsed, 1.0) + print("redos elapsed {0:.4f}s".format(elapsed), file=sys.stderr) + deep = "a/" + "/".join("s" * 20 for _ in range(300)) + "/z" + started = time.monotonic() + out, _ = run_gate("pull_request", [entry(deep)], patterns="a/**/*s/**/*s/**/q") + self.assertRun("false", out) + self.assertLess(time.monotonic() - started, 1.0) + + def test_redirect_is_never_followed(self): + seen = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + seen.append((self.path, self.headers.get("Authorization"))) + self.send_response(302) + self.send_header("Location", "/elsewhere") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + old = {k: os.environ.get(k) for k in ("NO_PROXY", "no_proxy")} + os.environ["NO_PROXY"] = os.environ["no_proxy"] = "127.0.0.1" + try: + with tempfile.TemporaryDirectory() as tmp: + event = Path(tmp) / "event.json" + event.write_text(json.dumps({"pull_request": {"number": 7, "head": {"sha": HEAD}}})) + out = Path(tmp) / "output" + env = { + "CHANGES_GATE_EVENT_NAME": "pull_request", + "CHANGES_GATE_PATTERNS": PATTERNS, + "CHANGES_GATE_AUTH": "secret-value", + "GITHUB_REPOSITORY": "CodesWhat/example", + "GITHUB_API_URL": "http://127.0.0.1:{0}".format(server.server_address[1]), + "GITHUB_EVENT_PATH": str(event), + "GITHUB_OUTPUT": str(out), + } + with contextlib.redirect_stdout(io.StringIO()): + gate.main(env) + self.assertRun("true", out.read_text()) + finally: + server.shutdown() + server.server_close() + for key, value in old.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + self.assertEqual([("/repos/CodesWhat/example/pulls/7", "Bearer secret-value")], seen) + + def test_opener_refuses_redirects(self): + handler = gate.NoRedirect() + request = urllib.request.Request("https://api.github.com/x") + self.assertIsNone(handler.redirect_request( + request, None, 302, "Found", {}, "https://evil.example/y")) + self.assertTrue(any(isinstance(h, gate.NoRedirect) for h in gate.OPENER.handlers)) + self.assertFalse(any(type(h) is urllib.request.HTTPRedirectHandler + for h in gate.OPENER.handlers)) + + def test_head_sha_mismatch_runs(self): + out, _ = run_gate("pull_request", fetch=pager([entry("docs/a.md")], head="b" * 40)) + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("docs/a.md")]) self.assertRun("false", out) + def test_bad_event_head_sha_runs(self): + for sha in (None, "", "abc", "g" * 40, 5, "a" * 41): + with self.subTest(sha=sha): + out, _ = run_gate("pull_request", [entry("docs/a.md")], head=sha) + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("docs/a.md")], + payload={"pull_request": {"number": 7}}) + self.assertRun("true", out) + def no_head(url, auth): + data, link = pager([entry("docs/a.md")])(url, auth) + if url.endswith("/pulls/7"): + data = {"changed_files": 1} + return data, link + out, _ = run_gate("pull_request", fetch=no_head) + self.assertRun("true", out) + def test_regex_metacharacters_are_literal(self): cases = ( ("a+b.txt", "a+b.txt", "true"), ("a+b.txt", "aab.txt", "false"), @@ -214,7 +337,7 @@ def fetch(url, auth): return [], None with tempfile.TemporaryDirectory() as tmp: event = Path(tmp) / "event.json" - event.write_text(json.dumps({"pull_request": {"number": 7}})) + event.write_text(json.dumps({"pull_request": {"number": 7, "head": {"sha": HEAD}}})) out_path = Path(tmp) / "output" env = { "CHANGES_GATE_EVENT_NAME": "pull_request", @@ -365,7 +488,7 @@ def log_message(self, *args): for pattern, expected in (("Sources/**", "false"), ("docs/119.md", "true")): with self.subTest(pattern=pattern), tempfile.TemporaryDirectory() as tmp: event = Path(tmp) / "event.json" - event.write_text(json.dumps({"pull_request": {"number": 7}})) + event.write_text(json.dumps({"pull_request": {"number": 7, "head": {"sha": HEAD}}})) out = Path(tmp) / "output" env = { "PATH": os.environ.get("PATH", ""), @@ -389,11 +512,189 @@ def log_message(self, *args): server.shutdown() server.server_close() + def test_readme_caller_condition_fails_open_on_gate_failure(self): + readme = (ACTION_DIR / "README.md").read_text(encoding="utf-8") + flat = " ".join(readme.split()) + self.assertIn("needs.changes.result != 'success'", flat) + self.assertIn("!cancelled()", flat) + self.assertIn("needs.changes.outputs.run != 'false'", flat) + self.assertNotIn("if: needs.changes.outputs.run == 'true'", readme) + + def test_off_host_next_link_is_never_fetched(self): + files = [entry("docs/{0}.md".format(i)) for i in range(150)] + calls = [] + + def fetch(url, auth): + calls.append((url, auth)) + if url.endswith("/pulls/7"): + return {"changed_files": 150, "head": {"sha": HEAD}}, None + if url.startswith("https://evil.example/"): + return files[100:], None + return files[:100], '; rel="next"' + out, _ = run_gate("pull_request", fetch=fetch) + self.assertRun("true", out) + self.assertEqual( + [API + "/repos/CodesWhat/example/pulls/7", + API + "/repos/CodesWhat/example/pulls/7/files?per_page=100"], + [url for url, _ in calls]) + self.assertTrue(all(auth == "secret-value" for _, auth in calls)) + + def test_action_output_and_env_wiring(self): + lines = (ACTION_DIR / "action.yml").read_text(encoding="utf-8").splitlines() + self.assertIn(" value: ${{ steps.gate.outputs.run }}", lines) + self.assertIn(" - id: gate", lines) + for expected in ( + " CHANGES_GATE_PATTERNS: ${{ inputs.patterns }}", + " CHANGES_GATE_AUTH: ${{ inputs.github-token }}", + " CHANGES_GATE_EVENT_NAME: ${{ github.event_name }}"): + self.assertIn(expected, lines) + step = lines.index(" - id: gate") + env = lines.index(" env:", step) + run = next(i for i, l in enumerate(lines) if l.strip().startswith("run: python3")) + self.assertTrue(step < env < run) + for expected in ("CHANGES_GATE_PATTERNS", "CHANGES_GATE_AUTH", "CHANGES_GATE_EVENT_NAME"): + self.assertTrue(any(expected in l for l in lines[env:run])) + + def test_invalid_pull_numbers_rejected_before_fetch(self): + for number in (True, False, 0, -1): + with self.subTest(number=number): + calls = [] + + def fetch(url, auth): + calls.append(url) + return {}, None + out, _ = run_gate("pull_request", fetch=fetch, number=number) + self.assertRun("true", out) + self.assertEqual([], calls) + + def test_missing_event_file_runs(self): + calls = [] + + def fetch(url, auth): + calls.append(url) + return {}, None + out, _ = run_gate("pull_request", fetch=fetch, write_event=False) + self.assertRun("true", out) + self.assertEqual([], calls) + + def test_missing_pull_request_key_runs(self): + for payload in ({}, {"pull_request": {}}, {"pull_request": {"head": {"sha": HEAD}}}, + {"pull_request": None}, []): + with self.subTest(payload=payload): + calls = [] + + def fetch(url, auth): + calls.append(url) + return {}, None + out, _ = run_gate("pull_request", fetch=fetch, payload=payload) + self.assertRun("true", out) + self.assertEqual([], calls) + + def test_listing_cap_with_underreported_count(self): + files = [entry("docs/{0}.md".format(i)) for i in range(3000)] + pages = [] + base = pager(files) + + def fetch(url, auth): + if "/files" in url: + pages.append(url) + return base(url, auth) + fetch_pr = lambda url, auth: ({"changed_files": 2999, "head": {"sha": HEAD}}, None) \ + if url.endswith("/pulls/7") else fetch(url, auth) + with self.assertRaises(gate.Doubt) as caught: + gate.list_names(API, "CodesWhat/example", 7, "secret-value", fetch_pr, HEAD) + self.assertEqual("cap", str(caught.exception)) + self.assertEqual(30, len(pages)) + + def test_pagination_loop_bound(self): + old = gate.FILE_CAP + gate.FILE_CAP = 4000 + self.addCleanup(setattr, gate, "FILE_CAP", old) + files = [entry("docs/{0}.md".format(i)) for i in range(4000)] + base = pager(files) + pages = [] + + def fetch(url, auth): + if url.endswith("/pulls/7"): + return {"changed_files": 3999, "head": {"sha": HEAD}}, None + pages.append(url) + if len(pages) > gate.MAX_PAGES + 1: + self.fail("fetched past the page bound") + return base(url, auth) + with self.assertRaises(gate.Doubt) as caught: + gate.list_names(API, "CodesWhat/example", 7, "secret-value", fetch, HEAD) + self.assertEqual("cap", str(caught.exception)) + self.assertEqual(gate.MAX_PAGES + 1, len(pages)) + + def test_range_includes_fold_kelvin_sign(self): + out, _ = run_gate("pull_request", [entry("\u212a.txt")], patterns="[A-Z].txt") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("\u212a.txt")], patterns="**\n![A-Z].txt") + self.assertRun("true", out) + + def test_class_includes_fold_symmetrically(self): + out, _ = run_gate("pull_request", [entry("\u212a.txt")], patterns="[K].txt") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("K.txt")], patterns="[\u212a].txt") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("docs.txt")], patterns="[K].txt") + self.assertRun("false", out) + + def test_class_ignores_multi_character_folds(self): + out, _ = run_gate("pull_request", [entry("\u00df.txt")], patterns="[!a-z].txt") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("\u00df.txt")], patterns="[a-z].txt") + self.assertRun("false", out) + + def test_class_excludes_stay_exact(self): + out, _ = run_gate("pull_request", [entry("\u212a.txt")], patterns="**\n![K].txt") + self.assertRun("true", out) + out, _ = run_gate("pull_request", [entry("K.txt")], patterns="**\n![K].txt") + self.assertRun("false", out) + + def test_head_moving_during_listing_runs(self): + base = pager([entry("docs/a.md")]) + reads = [] + + def fetch(url, auth): + if url.endswith("/pulls/7"): + reads.append(url) + head = HEAD if len(reads) == 1 else "b" * 40 + return {"changed_files": 1, "head": {"sha": head}}, None + return base(url, auth) + out, _ = run_gate("pull_request", fetch=fetch) + self.assertRun("true", out) + self.assertEqual(2, len(reads)) + + def test_changed_files_moving_during_listing_runs(self): + base = pager([entry("docs/a.md")]) + reads = [] + + def fetch(url, auth): + if url.endswith("/pulls/7"): + reads.append(url) + return {"changed_files": len(reads), "head": {"sha": HEAD}}, None + return base(url, auth) + out, _ = run_gate("pull_request", fetch=fetch) + self.assertRun("true", out) + + def test_stable_head_rechecked_and_skips(self): + reads = [] + base = pager([entry("docs/a.md")]) + + def fetch(url, auth): + if url.endswith("/pulls/7"): + reads.append(url) + return base(url, auth) + out, _ = run_gate("pull_request", fetch=fetch) + self.assertRun("false", out) + self.assertEqual(2, len(reads)) + def test_action_shape(self): action = (ACTION_DIR / "action.yml").read_text(encoding="utf-8") for expected in ("using: composite", "required: true", "default: ${{ github.token }}", - 'run: python3 "$GITHUB_ACTION_PATH/changes_gate.py"'): + 'run: python3 -I "$GITHUB_ACTION_PATH/changes_gate.py"'): self.assertIn(expected, action) # Expressions are only ever passed through env, never interpolated into run. run_lines = [l for l in action.splitlines() if l.strip().startswith("run:")] diff --git a/actions/changes-gate/README.md b/actions/changes-gate/README.md index 611bb5e..748a714 100644 --- a/actions/changes-gate/README.md +++ b/actions/changes-gate/README.md @@ -26,7 +26,10 @@ jobs: macos-build: needs: changes - if: needs.changes.outputs.run == 'true' + if: >- + ${{ !cancelled() && + (needs.changes.result != 'success' || + needs.changes.outputs.run != 'false') }} runs-on: macos-26 steps: - run: echo "expensive work" @@ -34,15 +37,29 @@ jobs: Pin the action to a full commit SHA. No checkout is needed. +Don't write the caller's `if:` as `needs.changes.outputs.run == 'true'`. A +bare condition carries an implicit `success()`, so if the gate job fails or +times out the gated job is skipped and a required check passes. The +expression above runs the job unless the gate succeeded and said `false`, so a +gate failure means run. + +On a fork `pull_request` the gate isn't a security boundary, because the PR +author controls the workflow file and can change or drop the gate. It matters +as a boundary under `pull_request_target`, and elsewhere it only makes honest +skip decisions. + ## Contract - `patterns` (required): newline-separated globs. `**` matches across - directories. `*`, `?` and `[abc]`, `[a-z]`, `[!x]` classes stay inside one - path segment. + directories and must be a whole path segment (`a/**/b`, not `a**b`). + `*`, `?` and `[abc]`, `[a-z]`, `[!x]` classes stay inside one path + segment. A leading `./` is ignored and a trailing `/` means `/**`. An unparseable - glob (an unclosed `[`) makes the result `true`. `#` comments and - blank lines are ignored. A leading `!` excludes. Matching is - case-insensitive. + glob makes the result `true`: an unclosed `[`, a bad range, `**` inside a + segment, braces (`{` or `}`), a leading `/`, or a POSIX class (`[[:`). + `#` comments and blank lines are ignored. A leading `!` excludes. Include + patterns match case-insensitively, since over-triggering is safe. Exclude + patterns are case-sensitive, so `!docs/**` never hides `Docs/x`. - `github-token`: defaults to `github.token`. - Output `run` is exactly `true` or `false`. diff --git a/actions/changes-gate/action.yml b/actions/changes-gate/action.yml index 5d56137..5b14fdc 100644 --- a/actions/changes-gate/action.yml +++ b/actions/changes-gate/action.yml @@ -28,4 +28,4 @@ runs: CHANGES_GATE_PATTERNS: ${{ inputs.patterns }} CHANGES_GATE_AUTH: ${{ inputs.github-token }} CHANGES_GATE_EVENT_NAME: ${{ github.event_name }} - run: python3 "$GITHUB_ACTION_PATH/changes_gate.py" + run: python3 -I "$GITHUB_ACTION_PATH/changes_gate.py" diff --git a/actions/changes-gate/changes_gate.py b/actions/changes-gate/changes_gate.py index 9a917f4..a69e5b0 100644 --- a/actions/changes-gate/changes_gate.py +++ b/actions/changes-gate/changes_gate.py @@ -23,6 +23,25 @@ class Doubt(Exception): """Raised for anything that should resolve to run=true.""" +STAR = ("*",) +ANY = ("?",) + + +def variants(ch): + """Single-character case variants of ch, closed under lower/upper/casefold + so the Kelvin sign also reaches ASCII K. Multi-character expansions + (e.g. the casefold of the German sharp s) are dropped.""" + seen = {ch} + pending = [ch] + while pending: + current = pending.pop() + for v in (current.lower(), current.upper(), current.casefold()): + if len(v) == 1 and v not in seen: + seen.add(v) + pending.append(v) + return seen + + def normalize(line): while line.startswith("./"): line = line[2:] @@ -32,31 +51,35 @@ def normalize(line): def parse_patterns(text): - """Return (includes, excludes). Raises ValueError on an unparseable glob.""" + """Return (includes, excludes). Raises ValueError on an unparseable glob. + + Includes match case-insensitively (over-triggering is safe). Excludes are + exact: a case-folded exclude could hide a file the author never meant. + """ includes, excludes = [], [] for raw in (text or "").splitlines(): line = raw.strip() if not line or line.startswith("#"): continue - target = includes + target, fold = includes, True if line.startswith("!"): line = line[1:].strip() - target = excludes + target, fold = excludes, False line = normalize(line) if line: - target.append(glob_to_regex(line)) + target.append(Glob(line, fold)) return includes, excludes def char_class(pattern, start): - """Parse a [...] class opening at start. Return (regex, next index).""" + """Parse a [...] class opening at start. Return (token, next index).""" n = len(pattern) i = start + 1 negate = False if i < n and pattern[i] in "!^": negate = True i += 1 - items = [] + ranges = [] first = True while True: if i >= n: @@ -70,43 +93,124 @@ def char_class(pattern, start): lo, hi = c, pattern[i + 2] if lo > hi: raise ValueError("bad range") - items.append(re.escape(lo) + "-" + re.escape(hi)) + ranges.append((lo, hi)) i += 3 else: - items.append(re.escape(c)) + ranges.append((c, c)) i += 1 - body = "".join(items) - if negate: - return "[^/" + body + "]", i - return "(?!/)[" + body + "]", i + return ("[", negate, tuple(ranges)), i -def glob_to_regex(pattern): - out = [] +def parse_segment(segment): + """Turn one path segment of a glob into tokens.""" + tokens = [] i = 0 - n = len(pattern) + n = len(segment) while i < n: - c = pattern[i] + c = segment[i] if c == "*": - if pattern.startswith("**", i): - i += 2 - if i < n and pattern[i] == "/": - i += 1 - out.append("(?:.*/)?") - else: - out.append(".*") - continue - out.append("[^/]*") + if not tokens or tokens[-1] != STAR: + tokens.append(STAR) elif c == "?": - out.append("[^/]") + tokens.append(ANY) elif c == "[": - piece, i = char_class(pattern, i) - out.append(piece) + token, i = char_class(segment, i) + tokens.append(token) continue else: - out.append(re.escape(c)) + tokens.append(("c", c, frozenset(variants(c)))) i += 1 - return re.compile("".join(out), re.IGNORECASE | re.DOTALL) + return tokens + + +def token_matches(token, ch, fold): + kind = token[0] + if kind == "?": + return True + if kind == "c": + return ch == token[1] or (fold and not variants(ch).isdisjoint(token[2])) + seen = variants(ch) if fold else {ch} + hit = False + for lo, hi in token[2]: + if fold and lo == hi: + hit = not seen.isdisjoint(variants(lo)) + else: + hit = any(lo <= v <= hi for v in seen) + if hit: + break + return hit != token[1] + + +def match_segment(tokens, text, fold): + """Wildcard match of one segment. Worst case O(len(text) * len(tokens)).""" + ti = si = 0 + star = -1 + mark = 0 + count = len(tokens) + while si < len(text): + if ti < count and tokens[ti] == STAR: + star = ti + mark = si + ti += 1 + elif ti < count and tokens[ti] != STAR and token_matches(tokens[ti], text[si], fold): + ti += 1 + si += 1 + elif star >= 0: + ti = star + 1 + mark += 1 + si = mark + else: + return False + while ti < count and tokens[ti] == STAR: + ti += 1 + return ti == count + + +class Glob: + """A compiled glob. ** is a whole segment matching one or more (trailing) + or zero or more (elsewhere) path segments.""" + + def __init__(self, pattern, fold): + if "{" in pattern or "}" in pattern or pattern.startswith("/") or "[[:" in pattern: + raise ValueError("unsupported glob syntax") + self.fold = fold + segments = [] + for part in pattern.split("/"): + if part == "**": + if not segments or segments[-1] is not None: + segments.append(None) + elif "**" in part: + raise ValueError("embedded globstar") + else: + segments.append(parse_segment(part)) + if segments[-1] is None: + segments.append([STAR]) + self.segments = segments + + def fullmatch(self, name): + segs = self.segments + parts = name.split("/") + + def close(states): + for i in sorted(states): + if i < len(segs) and segs[i] is None: + states.add(i + 1) + return states + + states = close({0}) + for part in parts: + nxt = set() + for i in states: + if i >= len(segs): + continue + if segs[i] is None: + nxt.add(i) + elif match_segment(segs[i], part, self.fold): + nxt.add(i + 1) + if not nxt: + return False + states = close(nxt) + return len(segs) in states def matches(name, includes, excludes): @@ -115,6 +219,16 @@ def matches(name, includes, excludes): return not any(r.fullmatch(name) for r in excludes) +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Never follow a redirect: the Authorization header must not leave the API.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +OPENER = urllib.request.build_opener(NoRedirect()) + + def fetch_page(url, auth): """GET url and return (parsed JSON, Link header or None).""" request = urllib.request.Request( @@ -126,7 +240,7 @@ def fetch_page(url, auth): "User-Agent": "codeswhat-changes-gate", }, ) - with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: + with OPENER.open(request, timeout=REQUEST_TIMEOUT) as response: if response.status != 200: raise Doubt("status") return json.loads(response.read().decode("utf-8")), response.headers.get("Link") @@ -157,8 +271,12 @@ def next_link(header): return found -def expected_count(api, repo, number, auth, fetch): +def expected_count(api, repo, number, auth, fetch, head_sha): data, _ = fetch("{0}/repos/{1}/pulls/{2}".format(api, repo, number), auth) + head = data.get("head") if isinstance(data, dict) else None + current = head.get("sha") if isinstance(head, dict) else None + if not isinstance(current, str) or current.lower() != head_sha: + raise Doubt("head") count = data.get("changed_files") if isinstance(data, dict) else None if isinstance(count, bool) or not isinstance(count, int) or count < 0: raise Doubt("count") @@ -167,8 +285,17 @@ def expected_count(api, repo, number, auth, fetch): return count -def list_names(api, repo, number, auth, fetch): - expected = expected_count(api, repo, number, auth, fetch) +def list_names(api, repo, number, auth, fetch, head_sha): + expected = expected_count(api, repo, number, auth, fetch, head_sha) + names = list_pages(api, repo, number, auth, fetch, expected) + # A force-push between the metadata read and the listing can swap the + # head under us, so the metadata has to be unchanged afterwards. + if expected_count(api, repo, number, auth, fetch, head_sha) != expected: + raise Doubt("moved") + return names + + +def list_pages(api, repo, number, auth, fetch, expected): names = [] files = 0 started = time.monotonic() @@ -201,15 +328,20 @@ def list_names(api, repo, number, auth, fetch): raise Doubt("cap") -def pull_number(env): +def pull_request(env): + """Return (number, head sha) from the event payload.""" try: with open(env["GITHUB_EVENT_PATH"], encoding="utf-8") as handle: - number = json.load(handle)["pull_request"]["number"] + pull = json.load(handle)["pull_request"] + number = pull["number"] + sha = pull["head"]["sha"] except (KeyError, OSError, ValueError, TypeError): raise Doubt("event") if isinstance(number, bool) or not isinstance(number, int) or number <= 0: raise Doubt("event") - return number + if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-fA-F]{40}", sha): + raise Doubt("event") + return number, sha.lower() def decide(env, fetch=fetch_page): @@ -231,8 +363,8 @@ def decide(env, fetch=fetch_page): if not auth: return True, 0, 0 try: - number = pull_number(env) - names = list_names(api, repo, number, auth, fetch) + number, head_sha = pull_request(env) + names = list_names(api, repo, number, auth, fetch, head_sha) except Exception: return True, 0, 0 matched = sum(1 for name in names if matches(name, includes, excludes)) From 84880e6e33f2d103e7ef3c6a67361f2d54d5b6ea Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:08:50 -0500 Subject: [PATCH 41/44] fix(tree-receipt): bind receipts to verified push-run evidence (#75) * fix(actions): bind tree receipts to push-run evidence Statuses are lookup hints only. verify now accepts a cited run only when it is a push run whose commit tree (via the API) matches the checkout tree, whose workflow blob matches the default branch head, and whose jobs all succeeded. record writes only on push, from the GITHUB_SHA commit tree, and the tested-tree override is gone. Redirects are refused so the auth header never follows one, both scripts run under python -I, and the README wiring now runs the expensive job when verify fails. * docs(actions): wrap tree-receipt README gate condition for markdownlint * fix(actions): enforce tree-receipt verify deadline across requests Pass the remaining budget into each request as its timeout, refuse to issue a request once the budget is spent, and re-check the deadline before accepting run evidence. * test(actions): cover the exact tree-receipt budget boundary --- .github/tests/tree_receipt_contract_test.py | 510 +++++++++++++++++--- actions/tree-receipt/README.md | 110 +++-- actions/tree-receipt/record/action.yml | 15 +- actions/tree-receipt/record/record.py | 56 +-- actions/tree-receipt/verify/action.yml | 2 +- actions/tree-receipt/verify/verify.py | 108 ++++- 6 files changed, 642 insertions(+), 159 deletions(-) diff --git a/.github/tests/tree_receipt_contract_test.py b/.github/tests/tree_receipt_contract_test.py index 2b362d0..8446376 100644 --- a/.github/tests/tree_receipt_contract_test.py +++ b/.github/tests/tree_receipt_contract_test.py @@ -12,6 +12,7 @@ import tempfile import threading import unittest +import unittest.mock import urllib.error @@ -36,6 +37,9 @@ def load(name, path): WF_REF = "{0}/{1}@refs/pull/7/merge".format(REPO, WF) TREE = "a" * 40 OTHER_TREE = "b" * 40 +BLOB = "c" * 40 +OTHER_BLOB = "d" * 40 +MAIN = "e" * 40 HEAD = "1" * 40 PARENT_A = "2" * 40 PARENT_B = "3" * 40 @@ -60,7 +64,7 @@ def status(tree=TREE, context="tree-receipt/" + WF, state="success", def run_obj(sha, **over): data = { "repository": {"full_name": REPO}, "path": WF + "@refs/pull/7/merge", - "conclusion": "success", "status": "completed", "head_sha": sha, + "event": "push", "conclusion": "success", "status": "completed", "head_sha": sha, "created_at": FRESH, } data.update(over) @@ -80,12 +84,22 @@ def __init__(self, *pages): class Api: """Mock fetch: routes keyed by path, optionally paged.""" - def __init__(self, routes): + def __init__(self, routes, after=None): self.routes = routes + self.after = after or {} self.calls = [] + self.timeouts = [] - def __call__(self, url, auth): + def __call__(self, url, auth, timeout=None): + self.timeouts.append(timeout) self.calls.append(url) + value = self.lookup(url) + hook = self.after.get(url[len(API):].partition("?")[0]) + if hook: + hook() + return value + + def lookup(self, url): assert url.startswith(API), url rest = url[len(API):] path, _, query = rest.partition("?") @@ -93,9 +107,10 @@ def __call__(self, url, auth): match = re.search(r"(?:^|&)page=([0-9]+)", query) if match: page = int(match.group(1)) - if path not in self.routes: + key = rest if rest in self.routes else path + if key not in self.routes: raise urllib.error.HTTPError(url, 404, "nf", {}, None) - value = self.routes[path] + value = self.routes[key] if isinstance(value, Exception): raise value if isinstance(value, Pages): @@ -103,10 +118,12 @@ def __call__(self, url, auth): return value -def git_stub(tree=TREE, head=HEAD, parents=(PARENT_A,)): +def git_stub(tree=TREE, head=HEAD, parents=(PARENT_A,), shallow="false"): def git(args): - if args == ["rev-parse", "HEAD^{tree}"]: + if len(args) == 2 and args[0] == "rev-parse" and args[1].endswith("^{tree}"): return tree + if args == ["rev-parse", "--is-shallow-repository"]: + return shallow if args == ["rev-parse", "HEAD"]: return head if args == ["rev-parse", "HEAD^@"]: @@ -123,12 +140,29 @@ def run_path(run_id=500): return "/repos/{0}/actions/runs/{1}".format(REPO, run_id) +def commit_path(sha): + return "/repos/{0}/git/commits/{1}".format(REPO, sha) + + +def contents_path(ref): + return "/repos/{0}/contents/{1}?ref={2}".format(REPO, WF, ref) + + +REPO_PATH = "/repos/" + REPO +BRANCH_PATH = "/repos/{0}/branches/main".format(REPO) + + def good_routes(sha=PARENT_A, run_id=500): return { "/repos/{0}/commits/{1}/pulls".format(REPO, HEAD): [], stat_path(sha): [status(target=run_url(run_id))], run_path(run_id): run_obj(sha), - run_path(run_id) + "/jobs": jobs("success", "skipped"), + run_path(run_id) + "/jobs": jobs("success", "success"), + commit_path(sha): {"tree": {"sha": TREE}}, + REPO_PATH: {"default_branch": "main"}, + BRANCH_PATH: {"commit": {"sha": MAIN}}, + contents_path(MAIN): {"type": "file", "sha": BLOB}, + contents_path(sha): {"type": "file", "sha": BLOB}, } @@ -152,10 +186,11 @@ def base_env(tmp, event="push", pr_head=None, **extra): return env -def run_verify(routes, event="push", git=None, pr_head=None, now=NOW, **extra): +def run_verify(routes, event="push", git=None, pr_head=None, now=NOW, after=None, + **extra): with tempfile.TemporaryDirectory() as tmp: env = base_env(tmp, event, pr_head, **extra) - api = Api(routes) + api = Api(routes, after) buf = io.StringIO() with contextlib.redirect_stdout(buf): verify.main(env, git or git_stub(), api, now) @@ -172,8 +207,9 @@ def assertReuse(self, expected, out): self.assertEqual(expected, reuse_of(out), out) def test_valid_receipt_on_parent_reuses(self): - out, log, _ = run_verify(good_routes()) + out, log, api = run_verify(good_routes()) self.assertReuse("true", out) + self.assertIn(contents_path(MAIN), [c[len(API):] for c in api.calls]) self.assertIn("evidence-run=" + run_url() + "\n", out) self.assertIn("candidate=" + PARENT_A, log) self.assertIn("created_at=" + FRESH, log) @@ -234,6 +270,7 @@ def test_run_failures(self): "conclusion": run_obj(PARENT_A, conclusion="failure"), "status": run_obj(PARENT_A, status="in_progress"), "head_sha": run_obj(PARENT_A, head_sha=PARENT_B), + "no-event": run_obj(PARENT_A, event=None), "repo": run_obj(PARENT_A, repository={"full_name": "CodesWhat/other"}), "old": run_obj(PARENT_A, created_at=OLD), "future": run_obj(PARENT_A, created_at="2026-11-23T12:00:00Z"), @@ -256,7 +293,7 @@ def test_max_age_input(self): def test_bad_jobs(self): for conclusion in ("failure", "cancelled", "timed_out", "action_required", - "startup_failure", None): + "startup_failure", "skipped", "neutral", "stale", None, ""): with self.subTest(conclusion=conclusion): routes = good_routes() routes[run_path(500) + "/jobs"] = jobs("success", conclusion) @@ -277,7 +314,9 @@ def test_bad_job_on_second_page(self): self.assertReuse("false", run_verify(routes)[0]) def test_api_error_at_each_step(self): - for key in (stat_path(PARENT_A), run_path(500), run_path(500) + "/jobs"): + for key in (stat_path(PARENT_A), run_path(500), run_path(500) + "/jobs", + commit_path(PARENT_A), REPO_PATH, BRANCH_PATH, + contents_path(MAIN), contents_path(PARENT_A)): with self.subTest(step=key): routes = good_routes() routes[key] = OSError("boom") @@ -414,6 +453,10 @@ def git(*args): stat_path(feature): [status(tree=tree)], run_path(500): run_obj(feature, created_at=created), run_path(500) + "/jobs": jobs("success"), + commit_path(feature): {"tree": {"sha": tree}}, + REPO_PATH: {"default_branch": "main"}, + BRANCH_PATH: {"commit": {"sha": MAIN}}, + "/repos/{0}/contents/{1}".format(REPO, WF): {"type": "file", "sha": BLOB}, } class Handler(http.server.BaseHTTPRequestHandler): @@ -474,13 +517,300 @@ def log_message(self, *args): server.shutdown() server.server_close() + def test_forged_description_with_other_tree_commit(self): + # Green push run, receipt claims TREE, but the run's commit has another tree. + routes = good_routes() + routes[commit_path(PARENT_A)] = {"tree": {"sha": OTHER_TREE}} + self.assertReuse("false", run_verify(routes)[0]) + routes = good_routes(PARENT_B) + routes[commit_path(PARENT_B)] = {"tree": {"sha": OTHER_TREE}} + out, _, _ = run_verify(routes, event="pull_request", pr_head=PARENT_B) + self.assertReuse("false", out) + + def test_positive_controls(self): + pr_head = "4" * 40 + routes = good_routes(pr_head) + routes[stat_path(PARENT_A)] = [] + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = [{"head": {"sha": pr_head}}] + self.assertReuse("true", run_verify(routes)[0]) + # Promotion-style push: merge commit with main and dev parents. + routes = good_routes(PARENT_B) + routes[stat_path(PARENT_A)] = [] + out, log, _ = run_verify(routes, git=git_stub(parents=(PARENT_A, PARENT_B))) + self.assertReuse("true", out) + self.assertIn("candidate=" + PARENT_B, log) + # Pull request caller citing a push run on the PR head. + out, _, _ = run_verify(good_routes(PARENT_B), event="pull_request", pr_head=PARENT_B) + self.assertReuse("true", out) + + def test_workflow_blob_differs_from_default_branch(self): + routes = good_routes() + routes[contents_path(PARENT_A)] = {"type": "file", "sha": OTHER_BLOB} + self.assertReuse("false", run_verify(routes)[0]) + + def test_default_branch_compared_by_head_sha_not_name(self): + routes = good_routes() + del routes[contents_path(MAIN)] + routes["/repos/{0}/contents/{1}?ref=main".format(REPO, WF)] = {"sha": BLOB} + self.assertReuse("false", run_verify(routes)[0]) + + def test_malformed_lookups(self): + bad_values = ({}, [], None, {"sha": "xyz"}, {"sha": 5}, {"tree": {}}, + {"tree": {"sha": "short"}}, {"default_branch": ""}, + {"commit": {"sha": "short"}}, "text") + for key in (commit_path(PARENT_A), REPO_PATH, BRANCH_PATH, + contents_path(MAIN), contents_path(PARENT_A)): + for bad in bad_values: + with self.subTest(key=key, bad=bad): + routes = good_routes() + routes[key] = bad + self.assertReuse("false", run_verify(routes)[0]) + + def test_non_push_source_runs_rejected(self): + for event in ("pull_request", "pull_request_target", "schedule", + "workflow_dispatch", "merge_group", "workflow_call", 5): + with self.subTest(event=event): + routes = good_routes() + routes[run_path(500)] = run_obj(PARENT_A, event=event) + out, _, api = run_verify(routes) + self.assertReuse("false", out) + self.assertFalse(any("/jobs" in c or "/git/commits" in c for c in api.calls)) + + def test_skipped_job_rejected_all_success_accepted(self): + routes = good_routes() + routes[run_path(500) + "/jobs"] = jobs("success", "skipped") + self.assertReuse("false", run_verify(routes)[0]) + routes[run_path(500) + "/jobs"] = jobs("success", "success", "success") + self.assertReuse("true", run_verify(routes)[0]) + + def test_run_checks_capped_at_five(self): + def routes_for(valid): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(target=run_url(500 + i)) for i in range(6)] + for i in range(6): + routes[run_path(500 + i)] = run_obj(PARENT_A, conclusion="failure") + routes[run_path(500 + i) + "/jobs"] = jobs("success") + routes[run_path(500 + valid)] = run_obj(PARENT_A) + return routes + out, log, api = run_verify(routes_for(5)) + self.assertReuse("false", out) + self.assertIn("run check limit reached", log) + self.assertNotIn(run_path(505), [c[len(API):] for c in api.calls]) + out, _, _ = run_verify(routes_for(4)) + self.assertReuse("true", out) + + def test_duplicate_runs_checked_once(self): + routes = good_routes() + routes[stat_path(PARENT_A)] = [status(), status(), status()] + routes[run_path(500)] = run_obj(PARENT_A, conclusion="failure") + out, _, api = run_verify(routes) + self.assertReuse("false", out) + self.assertEqual(1, sum(1 for c in api.calls if c.endswith("/actions/runs/500"))) + + def test_verify_deadline(self): + # Evidence finishing inside the budget is accepted, past it is not. + for finish, expected in ((119, "true"), (120, "true"), (121, "false")): + with self.subTest(finish=finish): + clock = {"t": 0} + first = [] + + def mono(): + if not first: + first.append(1) + return 0 + return clock["t"] + clock["t"] = 119 + after = {run_path(500) + "/jobs": lambda f=finish: clock.update(t=f)} + with unittest.mock.patch.object(verify.time, "monotonic", mono): + out, log, _ = run_verify(good_routes(), after=after) + self.assertReuse(expected, out) + if expected == "false": + self.assertIn("deadline", log) + + def test_no_request_issued_once_budget_is_spent(self): + # 120 is exactly the budget: no time remains, so no request may start. + for now in (120, 121): + with self.subTest(now=now): + clock = iter([0] + [now] * 50) + with unittest.mock.patch.object(verify.time, "monotonic", lambda: next(clock)): + out, log, api = run_verify(good_routes()) + self.assertReuse("false", out) + self.assertIn("deadline", log) + self.assertEqual([], api.calls) + + def test_request_timeout_is_capped_by_remaining_budget(self): + routes = good_routes() + times = iter([0] + [110] * 200) + with unittest.mock.patch.object(verify.time, "monotonic", lambda: next(times)): + _, _, api = run_verify(routes) + self.assertTrue(api.timeouts) + self.assertTrue(all(0 < t <= 10 for t in api.timeouts), api.timeouts) + _, _, api = run_verify(routes) + self.assertTrue(all(t == verify.REQUEST_TIMEOUT for t in api.timeouts)) + + def test_fetch_json_passes_timeout_to_opener(self): + seen = [] + + class Response: + status = 200 + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def read(self): + return b"{}" + + class Opener: + def open(self, request, timeout=None): + seen.append(timeout) + return Response() + with unittest.mock.patch.object(verify, "OPENER", Opener()): + verify.fetch_json(API + "/x", "a", timeout=7.5) + verify.fetch_json(API + "/x", "a") + self.assertEqual([7.5, verify.REQUEST_TIMEOUT], seen) + + def test_malformed_pulls_response(self): + for bad in ({"x": 1}, "text", [{"head": {}}], [{}], [None], [{"head": {"sha": 5}}]): + with self.subTest(bad=bad): + routes = good_routes() + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = bad + self.assertReuse("false", run_verify(routes)[0]) + + def test_invalid_candidate_sha_rejected_before_status_lookup(self): + for bad in ("abc", "g" * 40, "A" * 40, "1" * 39, "1" * 41, 12, None): + with self.subTest(bad=bad, source="parent"): + git = git_stub(parents=(bad,)) if isinstance(bad, str) else None + if git is None: + continue + out, _, api = run_verify(good_routes(), git=git) + self.assertReuse("false", out) + self.assertFalse(any("/statuses" in c for c in api.calls)) + with self.subTest(bad=bad, source="pull"): + routes = good_routes() + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = [ + {"head": {"sha": bad}}] + out, _, api = run_verify(routes) + self.assertReuse("false", out) + self.assertFalse(any("/statuses" in c for c in api.calls)) + with self.subTest(bad=bad, source="pr-event"): + with tempfile.TemporaryDirectory() as tmp: + env = base_env(tmp, "pull_request") + Path(env["GITHUB_EVENT_PATH"]).write_text(json.dumps( + {"pull_request": {"head": {"sha": bad}}})) + api = Api(good_routes()) + with contextlib.redirect_stdout(io.StringIO()): + verify.main(env, git_stub(), api, NOW) + self.assertReuse("false", Path(env["GITHUB_OUTPUT"]).read_text()) + self.assertFalse(any("/statuses" in c for c in api.calls)) + + def test_bad_created_at_rejected_without_jobs_fetch(self): + for bad in (None, "", "yesterday", 5, "2026-11-21", "2026-11-21T12:00:00+00:00"): + with self.subTest(bad=bad): + routes = good_routes() + routes[run_path(500)] = run_obj(PARENT_A, created_at=bad) + out, _, api = run_verify(routes) + self.assertReuse("false", out) + self.assertFalse(any("/jobs" in c for c in api.calls)) + routes = good_routes() + run = run_obj(PARENT_A) + del run["created_at"] + routes[run_path(500)] = run + out, _, api = run_verify(routes) + self.assertReuse("false", out) + self.assertFalse(any("/jobs" in c for c in api.calls)) + + def test_malformed_pull_request_event_makes_no_api_calls(self): + for content in ("not json", "[]", "{}", json.dumps({"pull_request": []}), + json.dumps({"pull_request": {"head": {}}}), None): + with self.subTest(content=content): + with tempfile.TemporaryDirectory() as tmp: + env = base_env(tmp, "pull_request") + if content is None: + os.unlink(env["GITHUB_EVENT_PATH"]) + else: + Path(env["GITHUB_EVENT_PATH"]).write_text(content) + api = Api(good_routes()) + with contextlib.redirect_stdout(io.StringIO()): + verify.main(env, git_stub(), api, NOW) + self.assertReuse("false", Path(env["GITHUB_OUTPUT"]).read_text()) + self.assertEqual([], api.calls) + + def test_job_pagination_limit(self): + def page(total): + return {"total_count": total, "jobs": [{"conclusion": "success"}] * 100} + routes = good_routes() + routes[run_path(500) + "/jobs"] = Pages(*[page(501)] * 6) + out, _, api = run_verify(routes) + self.assertReuse("false", out) + self.assertEqual(5, sum(1 for c in api.calls if "/jobs" in c)) + routes[run_path(500) + "/jobs"] = Pages(*[page(500)] * 6) + out, _, api = run_verify(routes) + self.assertReuse("true", out) + self.assertEqual(5, sum(1 for c in api.calls if "/jobs" in c)) + + def test_shallow_clone_logs_and_keeps_pr_head_candidates(self): + pr_head = "4" * 40 + routes = good_routes(pr_head) + routes["/repos/{0}/commits/{1}/pulls".format(REPO, HEAD)] = [{"head": {"sha": pr_head}}] + out, log, _ = run_verify(routes, git=git_stub(parents=(), shallow="true")) + self.assertReuse("true", out) + self.assertIn("shallow checkout, parents unavailable", log) + out, log, _ = run_verify(routes, git=git_stub(parents=(), shallow="false")) + self.assertNotIn("shallow checkout", log) + + def test_redirect_is_refused_without_following(self): + seen = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + seen.append((self.path, self.headers.get("Authorization"))) + self.send_response(302) + self.send_header("Location", "/elsewhere") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with tempfile.TemporaryDirectory() as tmp: + env = base_env(tmp, "push", NO_PROXY="127.0.0.1", no_proxy="127.0.0.1", + GITHUB_API_URL="http://127.0.0.1:{0}".format( + server.server_address[1])) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + verify.main(env, git_stub(), verify.fetch_json, NOW) + out = Path(env["GITHUB_OUTPUT"]).read_text() + self.assertReuse("false", out) + self.assertIn("redirect", buf.getvalue()) + self.assertEqual(1, len(seen), seen) + finally: + server.shutdown() + server.server_close() + + def test_readme_wiring_guards_verify_failure(self): + readme = (BASE / "README.md").read_text(encoding="utf-8") + self.assertIn("needs.verify.result != 'success'", readme) + self.assertIn("!cancelled()", readme) + self.assertIn("needs.verify.outputs.reuse != 'true'", readme) + self.assertIn("fetch-depth: 2", readme) + self.assertNotIn("tested-tree", readme.replace("`tested-tree` input", "")) + def test_action_shape(self): action = (BASE / "verify" / "action.yml").read_text(encoding="utf-8") for expected in ("using: composite", 'default: "168"', "default: ${{ github.token }}", "value: ${{ steps.verify.outputs.reuse }}", "value: ${{ steps.verify.outputs.evidence-run }}", - 'run: python3 "$GITHUB_ACTION_PATH/verify.py"'): + "TREE_RECEIPT_MAX_AGE_HOURS: ${{ inputs.max-age-hours }}", + "TREE_RECEIPT_AUTH: ${{ inputs.github-token }}", + "TREE_RECEIPT_EVENT_NAME: ${{ github.event_name }}", + 'run: python3 -I "$GITHUB_ACTION_PATH/verify.py"'): self.assertIn(expected, action) for line in action.splitlines(): if line.strip().startswith("run:"): @@ -499,10 +829,10 @@ def __call__(self, url, auth, payload): raise OSError("boom") -def run_record(event="push", tree=TREE, git=None, recorder=None, event_data=None, **extra): +def run_record(event="push", git=None, recorder=None, event_data=None, **extra): recorder = recorder or Recorder() with tempfile.TemporaryDirectory() as tmp: - env = base_env(tmp, event, TREE_RECEIPT_TESTED_TREE=tree, **extra) + env = base_env(tmp, event, **extra) if event_data is not None: Path(env["GITHUB_EVENT_PATH"]).write_text(json.dumps(event_data)) buf = io.StringIO() @@ -524,51 +854,57 @@ def test_push_writes_receipt_on_github_sha(self): }, payload) self.assertNotIn("secret-value", log) - def test_pull_request_writes_on_head_sha(self): - head = "5" * 40 - _, _, rec = run_record(event="pull_request", event_data={"pull_request": { - "head": {"sha": head, "repo": {"full_name": REPO}}, - "base": {"repo": {"full_name": REPO}}}}) - self.assertTrue(rec.calls[0][0].endswith("/statuses/" + head)) + def test_tree_comes_from_github_sha_commit(self): + asked = [] + def git(args): + asked.append(args) + return OTHER_TREE + _, _, rec = run_record(git=git) + self.assertEqual([["rev-parse", HEAD + "^{tree}"]], asked) + self.assertEqual("tree=" + OTHER_TREE, rec.calls[0][2]["description"]) + + def test_tested_tree_override_is_ignored(self): + _, _, rec = run_record(TREE_RECEIPT_TESTED_TREE=OTHER_TREE, git=git_stub(tree=TREE)) + self.assertEqual("tree=" + TREE, rec.calls[0][2]["description"]) - def test_fork_pull_request_skipped(self): - for event in ("pull_request", "pull_request_target"): + def test_non_push_events_write_nothing(self): + pr = {"pull_request": {"head": {"sha": HEAD, "repo": {"full_name": REPO}}, + "base": {"repo": {"full_name": REPO}}}} + for event in ("pull_request", "pull_request_target", "schedule", + "workflow_dispatch", "merge_group", "workflow_call", ""): with self.subTest(event=event): - code, log, rec = run_record(event=event, event_data={"pull_request": { - "head": {"sha": HEAD, "repo": {"full_name": "someone/example"}}, - "base": {"repo": {"full_name": REPO}}}}) + code, log, rec = run_record(event=event, event_data=pr) self.assertEqual(0, code) self.assertEqual([], rec.calls) - self.assertIn("skipped (fork)", log) - - def test_malformed_pull_request_event_skipped(self): - code, _, rec = run_record(event="pull_request", event_data={"pull_request": {}}) - self.assertEqual(0, code) - self.assertEqual([], rec.calls) + self.assertIn("skipped (event", log) def test_write_failure_exits_zero(self): code, log, _ = run_record(recorder=Recorder(fail=True)) self.assertEqual(0, code) self.assertIn("write failed", log) - def test_invalid_tested_tree_rejected(self): - for bad in ("abc", "A" * 40, "g" * 40, "a" * 41, "a" * 40 + "\n--", TREE[:-1]): + def test_invalid_tree_from_git_rejected(self): + for bad in ("abc", "A" * 40, "g" * 40, "a" * 41, "a" * 40 + "\n--", TREE[:-1], ""): with self.subTest(tree=bad): - code, log, rec = run_record(tree=bad) + code, log, rec = run_record(git=git_stub(tree=bad)) self.assertEqual(0, code) self.assertEqual([], rec.calls) self.assertIn("invalid-tree", log) - def test_default_tree_from_git(self): - _, _, rec = run_record(tree="", git=git_stub(tree=OTHER_TREE)) - self.assertEqual("tree=" + OTHER_TREE, rec.calls[0][2]["description"]) + def test_invalid_github_sha_skips(self): + for bad in ("abc", "G" * 40, HEAD + "0", ""): + with self.subTest(sha=bad): + _, log, rec = run_record(GITHUB_SHA=bad) + self.assertEqual([], rec.calls) + self.assertIn("skipped (sha)", log) - def test_default_tree_git_failure_skips(self): + def test_git_failure_skips(self): def git(args): raise subprocess.CalledProcessError(128, "git") - code, _, rec = run_record(tree="", git=git) + code, log, rec = run_record(git=git) self.assertEqual(0, code) self.assertEqual([], rec.calls) + self.assertIn("no-tree", log) def test_bad_workflow_ref_or_run_id_skips(self): for extra in ({"GITHUB_WORKFLOW_REF": "junk"}, {"GITHUB_RUN_ID": "abc"}, @@ -598,32 +934,81 @@ def log_message(self, *args): threading.Thread(target=server.serve_forever, daemon=True).start() try: with tempfile.TemporaryDirectory() as tmp: + genv = {"PATH": os.environ.get("PATH", ""), "HOME": tmp, + "GIT_CONFIG_NOSYSTEM": "1", "GIT_AUTHOR_NAME": "t", + "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@example.com"} + work = Path(tmp) / "work" + work.mkdir() + + def git(*args): + return subprocess.run(["git"] + list(args), cwd=work, env=genv, + capture_output=True, text=True, + check=True).stdout.strip() + git("init", "-q", "-b", "main") + (work / "a.txt").write_text("a") + git("add", "a.txt") + git("commit", "-q", "-m", "a") + sha = git("rev-parse", "HEAD") + tree = git("rev-parse", "HEAD^{tree}") env = { - "PATH": os.environ.get("PATH", ""), + "PATH": os.environ.get("PATH", ""), "HOME": tmp, "NO_PROXY": "127.0.0.1", "no_proxy": "127.0.0.1", "TREE_RECEIPT_EVENT_NAME": "push", "TREE_RECEIPT_AUTH": "secret-value", - "TREE_RECEIPT_TESTED_TREE": TREE, "GITHUB_REPOSITORY": REPO, "GITHUB_WORKFLOW_REF": WF_REF, - "GITHUB_SERVER_URL": SERVER, "GITHUB_RUN_ID": "900", "GITHUB_SHA": HEAD, + "GITHUB_SERVER_URL": SERVER, "GITHUB_RUN_ID": "900", "GITHUB_SHA": sha, "GITHUB_API_URL": "http://127.0.0.1:{0}".format(server.server_address[1]), } proc = subprocess.run( [sys.executable, "-I", str(BASE / "record" / "record.py")], - cwd=tmp, env=env, capture_output=True, text=True, timeout=60) - self.assertEqual(0, proc.returncode, proc.stderr) - (path, auth, payload), = seen - self.assertEqual("/repos/{0}/statuses/{1}".format(REPO, HEAD), path) - self.assertEqual("Bearer secret-value", auth) - self.assertEqual("tree=" + TREE, payload["description"]) - self.assertEqual("tree-receipt/" + WF, payload["context"]) - self.assertNotIn("secret-value", proc.stdout + proc.stderr) - # An unreachable server must still exit 0. - env["GITHUB_API_URL"] = "http://127.0.0.1:1" - proc = subprocess.run( - [sys.executable, "-I", str(BASE / "record" / "record.py")], - cwd=tempfile.gettempdir(), env=env, capture_output=True, text=True, timeout=60) - self.assertEqual(0, proc.returncode, proc.stderr) - self.assertIn("write failed", proc.stdout) + cwd=work, env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(0, proc.returncode, proc.stderr) + (path, auth, payload), = seen + self.assertEqual("/repos/{0}/statuses/{1}".format(REPO, sha), path) + self.assertEqual("Bearer secret-value", auth) + self.assertEqual("tree=" + tree, payload["description"]) + self.assertEqual("tree-receipt/" + WF, payload["context"]) + self.assertNotIn("secret-value", proc.stdout + proc.stderr) + # An unreachable server must still exit 0. + env["GITHUB_API_URL"] = "http://127.0.0.1:1" + proc = subprocess.run( + [sys.executable, "-I", str(BASE / "record" / "record.py")], + cwd=work, env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(0, proc.returncode, proc.stderr) + self.assertIn("write failed", proc.stdout) + finally: + server.shutdown() + server.server_close() + + def test_redirect_is_refused_without_following(self): + seen = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + self.rfile.read(length) + seen.append(self.path) + self.send_response(307) + self.send_header("Location", "/elsewhere") + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, *args): + pass + + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with tempfile.TemporaryDirectory() as tmp: + env = base_env(tmp, "push", NO_PROXY="127.0.0.1", no_proxy="127.0.0.1", + GITHUB_API_URL="http://127.0.0.1:{0}".format( + server.server_address[1])) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = record.main(env, git_stub()) + self.assertEqual(0, code) + self.assertIn("write failed", buf.getvalue()) + self.assertEqual(1, len(seen), seen) finally: server.shutdown() server.server_close() @@ -631,9 +1016,12 @@ def log_message(self, *args): def test_action_shape(self): action = (BASE / "record" / "action.yml").read_text(encoding="utf-8") for expected in ("using: composite", "default: ${{ github.token }}", - "TREE_RECEIPT_TESTED_TREE: ${{ inputs.tested-tree }}", - 'run: python3 "$GITHUB_ACTION_PATH/record.py"'): + "TREE_RECEIPT_AUTH: ${{ inputs.github-token }}", + "TREE_RECEIPT_EVENT_NAME: ${{ github.event_name }}", + 'run: python3 -I "$GITHUB_ACTION_PATH/record.py"'): self.assertIn(expected, action) + self.assertNotIn("tested-tree", action) + self.assertNotIn("TESTED_TREE", action) for line in action.splitlines(): if line.strip().startswith("run:"): self.assertNotIn("${{", line) diff --git a/actions/tree-receipt/README.md b/actions/tree-receipt/README.md index b390dea..df82a92 100644 --- a/actions/tree-receipt/README.md +++ b/actions/tree-receipt/README.md @@ -6,9 +6,9 @@ push to main). These two composite actions let later events reuse the first run's result and fall back to a full run on any doubt. - `verify` runs first. It outputs `reuse=true` only when a trusted earlier - run verified exactly this tree. -- `record` runs last, in a final gate job, and writes the receipt that a later - `verify` looks for. + push run verified exactly this tree. +- `record` runs last, in a final gate job on push events, and writes the + receipt that a later `verify` looks for. Required check names keep reporting. Callers skip the expensive jobs with a job-level `if`, and a skipped job reports success to branch protection. @@ -31,13 +31,17 @@ jobs: steps: - uses: actions/checkout@ with: + fetch-depth: 2 persist-credentials: false - id: receipt uses: CodesWhat/.github/actions/tree-receipt/verify@ build-and-test: needs: verify - if: needs.verify.outputs.reuse != 'true' + if: >- + ${{ !cancelled() && + (needs.verify.result != 'success' || + needs.verify.outputs.reuse != 'true') }} runs-on: macos-26 steps: - uses: actions/checkout@ @@ -56,7 +60,14 @@ jobs: - name: Fail on any failed or cancelled job env: RESULTS: ${{ join(needs.*.result, ' ') }} + VERIFY_RESULT: ${{ needs.verify.result }} + REUSE: ${{ needs.verify.outputs.reuse }} + BUILD_RESULT: ${{ needs.build-and-test.result }} run: | + if [ "$BUILD_RESULT" = skipped ] \ + && { [ "$VERIFY_RESULT" != success ] || [ "$REUSE" != true ]; }; then + echo "expensive job skipped without a verified reuse"; exit 1 + fi for result in $RESULTS; do case "$result" in success|skipped) ;; @@ -71,30 +82,55 @@ jobs: if: needs.build-and-test.result == 'success' ``` -The gate accepts `success` or `skipped` (skipped because the tree was reused) -and fails on anything else. It records only when the expensive jobs actually -ran and passed, so reused evidence is never re-recorded and its age is never -refreshed. If `verify` itself fails, `reuse` is empty, the expensive jobs run, -and the gate fails on the failed `verify` job. - -Pin both actions to a full commit SHA. Both need a checkout, and for -`pull_request` runs that checkout is the synthetic merge commit. That commit's -tree is the one tested, so that is the tree recorded and compared. Pass -`tested-tree` to `record` if the tested tree is not `HEAD` in the gate job's -workspace. - -## Contract +The gate accepts `success` or `skipped`, but a skipped expensive job only +passes when `verify` succeeded with `reuse=true`. It records only when the +expensive jobs actually ran and passed, so reused evidence is never +re-recorded and its age is never refreshed. + +A plain `if: needs.verify.outputs.reuse != 'true'` carries an implicit +`success()`. If `verify` fails, the expensive job would be skipped and the +gate would see only skipped jobs, so the job-level `if` above must run the +expensive job whenever `verify` did not succeed. + +Pin both actions to a full commit SHA. Both need a checkout. For `push` runs +`verify` also looks at the pushed commit's parents, so check out with +`fetch-depth: 2`. On a shallow clone with no parents it logs `shallow checkout, +parents unavailable` and still uses the associated PR heads. + +## Trust boundary + +Commit statuses are lookup hints only. Any workflow in the repository with +`statuses: write` can post a status that names any tree and cites any run, so +a status never proves anything by itself. `verify` accepts a cited run only +when all of these hold: + +- the run was a `push` run, in this repository, of this workflow file, with + conclusion `success`, younger than `max-age-hours`, and `head_sha` equal to + the candidate commit; +- the commit API reports that run commit's tree as exactly the tree checked + out now, which is also the tree the receipt claims; +- the workflow file's blob at the run's commit equals its blob at the default + branch's current head (compared by immutable commit sha, not branch name); +- every job in the run concluded `success`. Skipped, neutral, cancelled and + similar jobs reject the run. + +Pull request runs are never evidence, because their synthetic merge commit +can't be authenticated against a tree the API reports. `schedule`, +`workflow_dispatch`, `pull_request_target` and other source events are rejected +for the same reason. Any API error, malformed data, redirect or ambiguity +outputs `false`. `verify` inputs: `max-age-hours` (default `168`) and `github-token`. Outputs: `reuse` (exactly `true` or `false`) and `evidence-run` (the run URL, or empty). -`verify` looks only at narrow candidates. For `pull_request` that is the PR -head SHA. For `push` it is the pushed commit's parents (so a merge commit finds -the dev head) plus the head SHAs of PRs associated with the pushed commit, up -to 10 commits. Other events (`schedule`, `workflow_dispatch`, `merge_group`, -`workflow_call`) always output `false`. +Supported callers are `pull_request` and `push`; other events (`schedule`, +`workflow_dispatch`, `merge_group`, `workflow_call`) always output `false`. +Candidates are narrow. For `pull_request` that is the PR head SHA, compared +against the caller's checkout tree. For `push` it is the pushed commit's parents +(so a merge commit finds the dev head) plus the head SHAs of PRs associated +with the pushed commit, up to 10 commits. -A candidate's commit status is accepted only when all of these hold: +A candidate's commit status is considered only when all of these hold: - the context is `tree-receipt/`, so receipts never cross workflows; @@ -102,21 +138,19 @@ A candidate's commit status is accepted only when all of these hold: - the description is exactly `tree=`; - the target URL is a run URL for this repository. -The run is then checked through the API. It must belong to this repository, -have the same workflow path, be completed with conclusion `success`, have -`head_sha` equal to the candidate, and be younger than `max-age-hours`. No job -in it may be failed, cancelled, timed out, action-required or startup-failed. -The age is the original run's age. Reuse never refreshes it. - -Any API error, malformed data or ambiguity outputs `false`. The log carries -only SHAs, counts, run ids and the decision. - -`record` writes a `success` commit status on the commit the workflow ran for -(the PR head for `pull_request`, else `github.sha`). Context is -`tree-receipt/`, description is `tree=<40-hex tree>`, and the -target URL is this run. It needs `statuses: write`. If the write fails it logs -and exits 0, because a missing receipt only costs a full run later. Fork PRs -never produce receipts, so they always run in full. +At most five distinct runs are checked, and the age is the original run's age. +Reuse never refreshes it. The log carries only SHAs, counts, run ids and the +decision. + +`record` writes a `success` commit status on `github.sha`, and only for `push` +events. The tree is that commit's tree (`git rev-parse "$GITHUB_SHA^{tree}"`). +Context is `tree-receipt/`, description is `tree=<40-hex tree>`, +and the target URL is this run. It needs `statuses: write` and a checkout that +contains the pushed commit. `pull_request`, `pull_request_target` and every +other event write no receipt and log why. The old `tested-tree` input and +`TREE_RECEIPT_TESTED_TREE` override are removed, so the tree can't be chosen by +the caller. If the write fails or is redirected it logs and exits 0, because a +missing receipt only costs a full run later. ## What must not be gated by reuse diff --git a/actions/tree-receipt/record/action.yml b/actions/tree-receipt/record/action.yml index 0db0d6e..472f94d 100644 --- a/actions/tree-receipt/record/action.yml +++ b/actions/tree-receipt/record/action.yml @@ -1,16 +1,10 @@ name: Tree receipt record description: >- - Write a verification receipt for the tree this workflow run just tested. - Run it as the last step of a final gate job, only when every verified job - succeeded. Never fails the job. + Write a verification receipt for the tree this push run just tested. Run it + as the last step of a final gate job, only when every verified job + succeeded. Writes nothing on other events. Never fails the job. inputs: - tested-tree: - description: >- - 40-hex tree of the commit that was checked out and tested. Defaults to - the tree of HEAD in the workspace. - required: false - default: "" github-token: description: Token used to write the commit status. Needs statuses write. required: false @@ -22,7 +16,6 @@ runs: - id: record shell: bash env: - TREE_RECEIPT_TESTED_TREE: ${{ inputs.tested-tree }} TREE_RECEIPT_AUTH: ${{ inputs.github-token }} TREE_RECEIPT_EVENT_NAME: ${{ github.event_name }} - run: python3 "$GITHUB_ACTION_PATH/record.py" + run: python3 -I "$GITHUB_ACTION_PATH/record.py" diff --git a/actions/tree-receipt/record/record.py b/actions/tree-receipt/record/record.py index 28d5772..4bc02a1 100644 --- a/actions/tree-receipt/record/record.py +++ b/actions/tree-receipt/record/record.py @@ -9,6 +9,7 @@ import re import subprocess import sys +import urllib.error import urllib.request REQUEST_TIMEOUT = 20 @@ -22,6 +23,16 @@ class Skip(Exception): """Raised for anything that means no receipt is written.""" +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse every redirect so the Authorization header never follows one.""" + + def redirect_request(self, *args, **kwargs): + return None + + +OPENER = urllib.request.build_opener(NoRedirect) + + def workflow_path(ref): match = WORKFLOW_REF.fullmatch(ref or "") if not match: @@ -29,33 +40,12 @@ def workflow_path(ref): return match.group(1) -def read_event(env): - try: - with open(env["GITHUB_EVENT_PATH"], encoding="utf-8") as handle: - data = json.load(handle) - except (KeyError, OSError, ValueError): - return {} - return data if isinstance(data, dict) else {} - - def target_sha(env): - """Return the commit the workflow ran for, or raise Skip for fork PRs.""" + """Return the pushed commit. Receipts exist only for push events.""" name = env.get("TREE_RECEIPT_EVENT_NAME", "") - if name in ("pull_request", "pull_request_target"): - pr = read_event(env).get("pull_request") - if not isinstance(pr, dict): - raise Skip("event") - head, base = pr.get("head"), pr.get("base") - try: - head_repo = head["repo"]["full_name"] - base_repo = base["repo"]["full_name"] - sha = head["sha"] - except (KeyError, TypeError): - raise Skip("event") - if head_repo != base_repo: - raise Skip("fork") - else: - sha = env.get("GITHUB_SHA", "") + if name != "push": + raise Skip("event {0}".format(name if re.fullmatch(r"[a-z_]{1,40}", name) else "?")) + sha = env.get("GITHUB_SHA", "") if not isinstance(sha, str) or not TREE.fullmatch(sha): raise Skip("sha") return sha @@ -66,13 +56,11 @@ def default_git(args): timeout=30, check=True).stdout.strip() -def tested_tree(env, git): - tree = (env.get("TREE_RECEIPT_TESTED_TREE") or "").strip() - if not tree: - try: - tree = git(["rev-parse", "HEAD^{tree}"]) - except Exception: - raise Skip("no-tree") +def tested_tree(sha, git): + try: + tree = git(["rev-parse", sha + "^{tree}"]) + except Exception: + raise Skip("no-tree") if not TREE.fullmatch(tree): raise Skip("invalid-tree") return tree @@ -91,7 +79,7 @@ def post_status(url, auth, payload): "User-Agent": "codeswhat-tree-receipt", }, ) - with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: + with OPENER.open(request, timeout=REQUEST_TIMEOUT) as response: if response.status != 201: raise OSError("status") @@ -106,7 +94,7 @@ def record(env, git=default_git, post=post_status): raise Skip("no-auth") path = workflow_path(env.get("GITHUB_WORKFLOW_REF")) sha = target_sha(env) - tree = tested_tree(env, git) + tree = tested_tree(sha, git) run_id = env.get("GITHUB_RUN_ID", "") if not re.fullmatch(r"[0-9]+", run_id): raise Skip("run-id") diff --git a/actions/tree-receipt/verify/action.yml b/actions/tree-receipt/verify/action.yml index 42e392e..d40c69f 100644 --- a/actions/tree-receipt/verify/action.yml +++ b/actions/tree-receipt/verify/action.yml @@ -30,4 +30,4 @@ runs: TREE_RECEIPT_MAX_AGE_HOURS: ${{ inputs.max-age-hours }} TREE_RECEIPT_AUTH: ${{ inputs.github-token }} TREE_RECEIPT_EVENT_NAME: ${{ github.event_name }} - run: python3 "$GITHUB_ACTION_PATH/verify.py" + run: python3 -I "$GITHUB_ACTION_PATH/verify.py" diff --git a/actions/tree-receipt/verify/verify.py b/actions/tree-receipt/verify/verify.py index a40fd33..8421ab8 100644 --- a/actions/tree-receipt/verify/verify.py +++ b/actions/tree-receipt/verify/verify.py @@ -3,7 +3,9 @@ Everything comes from environment variables. The log carries only SHAs, counts, run ids and the decision, and GITHUB_OUTPUT gets reuse=true or reuse=false. -Any doubt resolves to false. +Any doubt resolves to false. Statuses are lookup hints only: a cited run counts +when it is a push run whose commit tree and workflow blob are independently +confirmed and whose jobs all succeeded. """ import datetime import json @@ -12,6 +14,7 @@ import subprocess import sys import time +import urllib.error import urllib.parse import urllib.request @@ -27,13 +30,22 @@ REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") WORKFLOW_REF = re.compile( r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/(\.github/workflows/[A-Za-z0-9_./-]+)@\S+") -BAD_JOB = {"failure", "cancelled", "timed_out", "action_required", "startup_failure"} class Doubt(Exception): """Raised for anything that should resolve to reuse=false.""" +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse every redirect so the Authorization header never follows one.""" + + def redirect_request(self, *args, **kwargs): + return None + + +OPENER = urllib.request.build_opener(NoRedirect) + + def workflow_path(ref): match = WORKFLOW_REF.fullmatch(ref or "") if not match: @@ -46,7 +58,7 @@ def default_git(args): timeout=30, check=True).stdout.strip() -def fetch_json(url, auth): +def fetch_json(url, auth, timeout=REQUEST_TIMEOUT): request = urllib.request.Request( url, headers={ @@ -56,10 +68,15 @@ def fetch_json(url, auth): "User-Agent": "codeswhat-tree-receipt", }, ) - with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: - if response.status != 200: - raise Doubt("status") - return json.loads(response.read().decode("utf-8")) + try: + with OPENER.open(request, timeout=timeout) as response: + if response.status != 200: + raise Doubt("status") + return json.loads(response.read().decode("utf-8")) + except urllib.error.HTTPError as error: + if 300 <= error.code < 400: + raise Doubt("redirect") + raise def read_event(env): @@ -83,7 +100,7 @@ def current_tree(git): return tree -def candidates(env, git, api, repo, auth, fetch): +def candidates(env, git, api, repo, auth, fetch, log): name = env.get("TREE_RECEIPT_EVENT_NAME", "") found = [] if name == "pull_request": @@ -99,6 +116,13 @@ def candidates(env, git, api, repo, auth, fetch): raise Doubt("no-git") if not HEX40.fullmatch(head): raise Doubt("head") + if not parents: + try: + shallow = git(["rev-parse", "--is-shallow-repository"]) == "true" + except Exception: + shallow = False + if shallow: + log.append("shallow checkout, parents unavailable") found.extend(parents) pulls = fetch("{0}/repos/{1}/commits/{2}/pulls?per_page={3}".format( api, repo, head, PER_PAGE), auth) @@ -143,7 +167,41 @@ def parse_time(text): return parsed.replace(tzinfo=datetime.timezone.utc) -def validate_run(api, repo, run_id, sha, path, max_age, now, auth, fetch): +def commit_tree(api, repo, sha, auth, fetch): + data = fetch("{0}/repos/{1}/git/commits/{2}".format(api, repo, sha), auth) + tree = data.get("tree") if isinstance(data, dict) else None + value = tree.get("sha") if isinstance(tree, dict) else None + if not isinstance(value, str) or not HEX40.fullmatch(value): + raise Doubt("shape") + return value + + +def file_blob(api, repo, path, ref, auth, fetch): + data = fetch("{0}/repos/{1}/contents/{2}?ref={3}".format( + api, repo, urllib.parse.quote(path, safe="/"), ref), auth) + blob = data.get("sha") if isinstance(data, dict) else None + if not isinstance(blob, str) or not HEX40.fullmatch(blob): + raise Doubt("shape") + return blob + + +def default_branch_blob(api, repo, path, auth, fetch): + """Blob of the workflow file at the default branch's current head sha.""" + info = fetch("{0}/repos/{1}".format(api, repo), auth) + branch = info.get("default_branch") if isinstance(info, dict) else None + if not isinstance(branch, str) or not branch: + raise Doubt("shape") + head = fetch("{0}/repos/{1}/branches/{2}".format( + api, repo, urllib.parse.quote(branch, safe="")), auth) + commit = head.get("commit") if isinstance(head, dict) else None + sha = commit.get("sha") if isinstance(commit, dict) else None + if not isinstance(sha, str) or not HEX40.fullmatch(sha): + raise Doubt("shape") + return file_blob(api, repo, path, sha, auth, fetch) + + +def validate_run(api, repo, run_id, sha, path, tree, claimed, trusted, max_age, now, + auth, fetch): """Return the run's created_at, or None when the run is not good evidence.""" run = fetch("{0}/repos/{1}/actions/runs/{2}".format(api, repo, run_id), auth) if not isinstance(run, dict): @@ -154,6 +212,7 @@ def validate_run(api, repo, run_id, sha, path, max_age, now, auth, fetch): if not isinstance(run_path, str): raise Doubt("shape") if (full != repo or run_path.split("@", 1)[0] != path + or run.get("event") != "push" or run.get("conclusion") != "success" or run.get("status") != "completed" or run.get("head_sha") != sha): return None @@ -161,6 +220,11 @@ def validate_run(api, repo, run_id, sha, path, max_age, now, auth, fetch): age = now - created if age < datetime.timedelta(0) or age > datetime.timedelta(hours=max_age): return None + run_tree = commit_tree(api, repo, sha, auth, fetch) + if run_tree != tree or run_tree != claimed: + return None + if file_blob(api, repo, path, sha, auth, fetch) != trusted(): + return None seen = 0 total = None for page in range(1, JOB_PAGES + 1): @@ -174,8 +238,7 @@ def validate_run(api, repo, run_id, sha, path, max_age, now, auth, fetch): for job in jobs: if not isinstance(job, dict): raise Doubt("shape") - conclusion = job.get("conclusion") - if conclusion is None or conclusion in BAD_JOB: + if job.get("conclusion") != "success": return None seen += len(jobs) if seen >= total or len(jobs) < PER_PAGE: @@ -206,7 +269,21 @@ def decide(env, git=default_git, fetch=fetch_json, now=None): now = now or datetime.datetime.now(datetime.timezone.utc) started = time.monotonic() tree = current_tree(git) - cands = candidates(env, git, api, repo, auth, fetch) + + def budgeted(url, token): + remaining = DEADLINE_SECONDS - (time.monotonic() - started) + if remaining <= 0: + raise Doubt("deadline") + return fetch(url, token, timeout=min(REQUEST_TIMEOUT, remaining)) + + cands = candidates(env, git, api, repo, auth, budgeted, log) + cache = [] + + def trusted(): + if not cache: + cache.append(default_branch_blob(api, repo, path, auth, budgeted)) + return cache[0] + log.append("tree={0} candidates={1}".format(tree, len(cands))) context = "tree-receipt/" + path description = "tree=" + tree @@ -216,7 +293,7 @@ def decide(env, git=default_git, fetch=fetch_json, now=None): for sha in cands: if time.monotonic() - started > DEADLINE_SECONDS: raise Doubt("deadline") - for status in statuses(api, repo, sha, auth, fetch): + for status in statuses(api, repo, sha, auth, budgeted): if not isinstance(status, dict): raise Doubt("shape") creator = status.get("creator") @@ -234,10 +311,13 @@ def decide(env, git=default_git, fetch=fetch_json, now=None): log.append("run check limit reached") return False, "", log checked.add(run_id) - created = validate_run(api, repo, run_id, sha, path, max_age, now, auth, fetch) + created = validate_run(api, repo, run_id, sha, path, tree, tree, trusted, + max_age, now, auth, budgeted) if created is None: log.append("rejected candidate={0} run={1}".format(sha, run_id)) continue + if time.monotonic() - started > DEADLINE_SECONDS: + raise Doubt("deadline") evidence = target log.append("evidence candidate={0} run={1} created_at={2}".format( sha, evidence, created.strftime("%Y-%m-%dT%H:%M:%SZ"))) From fbeed2e3aaf5783bec84e1f97420d1e1b06dda56 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:09:38 -0500 Subject: [PATCH 42/44] chore(quality): add local qlty config and pre-push check (#77) --- .github/tests/changes_gate_contract_test.py | 12 ++++--- .qlty/.gitignore | 7 ++++ .qlty/qlty.toml | 39 +++++++++++++++++++++ lefthook.yml | 7 ++++ 4 files changed, 60 insertions(+), 5 deletions(-) create mode 100644 .qlty/.gitignore create mode 100644 .qlty/qlty.toml diff --git a/.github/tests/changes_gate_contract_test.py b/.github/tests/changes_gate_contract_test.py index da6f8b2..f3710d5 100644 --- a/.github/tests/changes_gate_contract_test.py +++ b/.github/tests/changes_gate_contract_test.py @@ -550,10 +550,10 @@ def test_action_output_and_env_wiring(self): self.assertIn(expected, lines) step = lines.index(" - id: gate") env = lines.index(" env:", step) - run = next(i for i, l in enumerate(lines) if l.strip().startswith("run: python3")) + run = next(i for i, ln in enumerate(lines) if ln.strip().startswith("run: python3")) self.assertTrue(step < env < run) for expected in ("CHANGES_GATE_PATTERNS", "CHANGES_GATE_AUTH", "CHANGES_GATE_EVENT_NAME"): - self.assertTrue(any(expected in l for l in lines[env:run])) + self.assertTrue(any(expected in ln for ln in lines[env:run])) def test_invalid_pull_numbers_rejected_before_fetch(self): for number in (True, False, 0, -1): @@ -599,8 +599,10 @@ def fetch(url, auth): if "/files" in url: pages.append(url) return base(url, auth) - fetch_pr = lambda url, auth: ({"changed_files": 2999, "head": {"sha": HEAD}}, None) \ - if url.endswith("/pulls/7") else fetch(url, auth) + def fetch_pr(url, auth): + if url.endswith("/pulls/7"): + return {"changed_files": 2999, "head": {"sha": HEAD}}, None + return fetch(url, auth) with self.assertRaises(gate.Doubt) as caught: gate.list_names(API, "CodesWhat/example", 7, "secret-value", fetch_pr, HEAD) self.assertEqual("cap", str(caught.exception)) @@ -697,7 +699,7 @@ def test_action_shape(self): 'run: python3 -I "$GITHUB_ACTION_PATH/changes_gate.py"'): self.assertIn(expected, action) # Expressions are only ever passed through env, never interpolated into run. - run_lines = [l for l in action.splitlines() if l.strip().startswith("run:")] + run_lines = [ln for ln in action.splitlines() if ln.strip().startswith("run:")] for line in run_lines: self.assertNotIn("${{", line) self.assertNotIn("uses:", action) diff --git a/.qlty/.gitignore b/.qlty/.gitignore new file mode 100644 index 0000000..3036618 --- /dev/null +++ b/.qlty/.gitignore @@ -0,0 +1,7 @@ +* +!configs +!configs/** +!hooks +!hooks/** +!qlty.toml +!.gitignore diff --git a/.qlty/qlty.toml b/.qlty/qlty.toml new file mode 100644 index 0000000..62a7034 --- /dev/null +++ b/.qlty/qlty.toml @@ -0,0 +1,39 @@ +# Local-only config for the pre-push hook (lefthook.yml). No Qlty Cloud. +config_version = "0" + +exclude_patterns = [ + ".claude/**", + ".planning/**", + ".qlty/**", +] + +[smells] +mode = "comment" + +[[source]] +name = "default" +default = true + +[[plugin]] +name = "actionlint" + +[[plugin]] +name = "markdownlint" +mode = "comment" + +[[plugin]] +name = "ruff" +drivers = ["lint"] + +[[plugin]] +name = "shellcheck" + +[[plugin]] +name = "zizmor" + +# profile/README.md is the org profile landing page, built from inline HTML +# on purpose (centered banner and badges), so it has no top-level heading. +[[triage]] +match.rules = ["markdownlint:MD033", "markdownlint:MD041"] +match.file_patterns = ["profile/README.md"] +set.ignored = true diff --git a/lefthook.yml b/lefthook.yml index 3872369..10ba6c8 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -10,3 +10,10 @@ pre-push: commands: validate: run: bash scripts/validate.sh + qlty: + run: | + if ! command -v qlty >/dev/null 2>&1; then + echo "qlty not installed; skipping" + exit 0 + fi + qlty check --all --no-progress From 5a77e4ef79dbb9e67498c2ead05de81db5e0f8fa Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:12:09 -0500 Subject: [PATCH 43/44] chore(deps): update non-major (github-actions) (#72) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .github/workflows/go-ci.yml | 22 +++++++++---------- .github/workflows/greptile-summon.yml | 2 +- .github/workflows/main-is-released.yml | 2 +- .github/workflows/node-ci.yml | 6 ++--- .github/workflows/profile-assets.yml | 2 +- .../workflows/quality-report-aggregate.yml | 2 +- .github/workflows/release-gate.yml | 2 +- .github/workflows/standards-validation.yml | 8 +++---- .github/workflows/starchart-refresh.yml | 2 +- 9 files changed, 24 insertions(+), 24 deletions(-) diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index b993976..adb736a 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -186,7 +186,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.test-egress-policy }} allowed-endpoints: ${{ inputs.test-allowed-endpoints }} @@ -226,7 +226,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.lint-egress-policy }} allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} @@ -257,7 +257,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.govulncheck-egress-policy }} allowed-endpoints: ${{ inputs.govulncheck-allowed-endpoints }} @@ -289,7 +289,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.workflow-security-egress-policy }} allowed-endpoints: ${{ inputs.workflow-security-allowed-endpoints }} @@ -316,7 +316,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.commit-message-egress-policy }} allowed-endpoints: ${{ inputs.commit-message-allowed-endpoints }} @@ -343,7 +343,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.goreleaser-egress-policy }} allowed-endpoints: ${{ inputs.goreleaser-allowed-endpoints }} @@ -376,7 +376,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.codeql-egress-policy }} allowed-endpoints: ${{ inputs.codeql-allowed-endpoints }} @@ -387,7 +387,7 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: languages: actions, go queries: security-and-quality @@ -404,7 +404,7 @@ jobs: run: ./scripts/ci/go-codeql-build.sh - name: Analyze with CodeQL - uses: github/codeql-action/analyze@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 qlty: name: Qlty Check @@ -416,7 +416,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.qlty-egress-policy }} allowed-endpoints: ${{ inputs.qlty-allowed-endpoints }} @@ -448,7 +448,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.fuzz-egress-policy }} allowed-endpoints: ${{ inputs.fuzz-allowed-endpoints }} diff --git a/.github/workflows/greptile-summon.yml b/.github/workflows/greptile-summon.yml index 755aad6..7ecdc78 100644 --- a/.github/workflows/greptile-summon.yml +++ b/.github/workflows/greptile-summon.yml @@ -32,7 +32,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: block allowed-endpoints: > diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml index d83f8b8..9cfa0fe 100644 --- a/.github/workflows/main-is-released.yml +++ b/.github/workflows/main-is-released.yml @@ -46,7 +46,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: block allowed-endpoints: > diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml index 3496b49..2c7c4c7 100644 --- a/.github/workflows/node-ci.yml +++ b/.github/workflows/node-ci.yml @@ -98,7 +98,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.lint-egress-policy }} allowed-endpoints: ${{ inputs.lint-allowed-endpoints }} @@ -130,7 +130,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.test-egress-policy }} allowed-endpoints: ${{ inputs.test-allowed-endpoints }} @@ -171,7 +171,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: ${{ inputs.build-egress-policy }} allowed-endpoints: ${{ inputs.build-allowed-endpoints }} diff --git a/.github/workflows/profile-assets.yml b/.github/workflows/profile-assets.yml index 8b80126..2e3e080 100644 --- a/.github/workflows/profile-assets.yml +++ b/.github/workflows/profile-assets.yml @@ -38,7 +38,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: block allowed-endpoints: github.com:443 diff --git a/.github/workflows/quality-report-aggregate.yml b/.github/workflows/quality-report-aggregate.yml index efa6c67..6196156 100644 --- a/.github/workflows/quality-report-aggregate.yml +++ b/.github/workflows/quality-report-aggregate.yml @@ -79,7 +79,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index c4b591f..38be7ca 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -34,7 +34,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: block allowed-endpoints: api.github.com:443 diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 59004e6..349f846 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -23,7 +23,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit @@ -94,7 +94,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit @@ -104,11 +104,11 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: languages: python - name: Analyze - uses: github/codeql-action/analyze@1fc58d04a4d4374f921bdac573c3811c240f9c26 # v4.39.2 + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: category: /language:python diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index 997fae1..b1d3ca4 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -135,7 +135,7 @@ jobs: steps: - name: Harden runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: block allowed-endpoints: > From bf97f1af48e0e987cfbb1ad2ec66a9ecf2993e72 Mon Sep 17 00:00:00 2001 From: Scott Benson <80784472+scttbnsn@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:44:20 -0500 Subject: [PATCH 44/44] fix: land the 2026-11-26 audit fixes (#80) * test(main-is-released): run the assertion script against temp repos * fix(main-is-released): accept any release tag among several on HEAD * test(greptile-summon): execute github-script logic under node * test(hooks): cover the commit-msg hook accept and reject sets * test(quality-report): cover the fail_on_incomplete=false rejection * fix(quality-report): aggregate only results from the current attempt * docs(onboarding): fix the starchart caller trigger guidance * fix(starchart): retry transient API failures and rebase before pushing * fix(release-gate): page run lookups to the API 1,000-run ceiling * test(main-is-released): strip GIT_* env so hook runs cannot touch the real repo * fix: expand artifact pattern braces and normalize the starchart retry branch * fix(quality-report): reject extglob artifact patterns explicitly * fix(ci): add retry and timeouts to the actionlint download --- .../tests/commit_msg_hook_contract_test.py | 63 ++++++ .../tests/community_health_contract_test.py | 18 ++ .../tests/greptile_summon_contract_test.py | 97 +++++++++ .../tests/main_is_released_contract_test.py | 203 +++++++++++++++++- .github/tests/quality_report_contract_test.py | 172 ++++++++++++++- .github/tests/reusable_ci_contract_test.py | 45 +++- .../tests/starchart_refresh_contract_test.py | 191 ++++++++++++++++ .github/workflows/main-is-released.yml | 54 +++-- .../workflows/quality-report-aggregate.yml | 22 +- .github/workflows/release-gate.yml | 4 +- .github/workflows/standards-validation.yml | 3 +- .github/workflows/starchart-refresh.yml | 91 +++++++- REPOSITORY_ONBOARDING.md | 16 +- decisions/quality-reporting.md | 7 + quality-report/v1/select_artifacts.py | 163 ++++++++++++++ scripts/validate.sh | 1 + 16 files changed, 1096 insertions(+), 54 deletions(-) create mode 100644 .github/tests/commit_msg_hook_contract_test.py create mode 100644 quality-report/v1/select_artifacts.py diff --git a/.github/tests/commit_msg_hook_contract_test.py b/.github/tests/commit_msg_hook_contract_test.py new file mode 100644 index 0000000..bdee3b2 --- /dev/null +++ b/.github/tests/commit_msg_hook_contract_test.py @@ -0,0 +1,63 @@ +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +HOOK = ROOT / "scripts" / "check-commit-msg.sh" + +ACCEPTED = [ + "feat(scope): x", + "fix!: x", + "revert: x", + "chore(deps/a.b-c): x", + "Merge branch 'x'", + "Merge pull request #1 from a/b", + "Merge remote-tracking branch 'o/x'", + "fixup! feat: x", + "squash! feat: x", + 'Revert "feat: x"', +] + +REJECTED = [ + "feat: ", + "Feat: x", + "wip: x", + "feat(Bad Scope): x", + "feat x", + "feat:x", +] + + +def run_hook(message): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "COMMIT_EDITMSG" + path.write_text(message, encoding="utf-8") + return subprocess.run( + ["bash", str(HOOK), str(path)], capture_output=True, text=True + ) + + +class CommitMsgHookContractTest(unittest.TestCase): + def test_accepts_valid_subjects(self): + for subject in ACCEPTED: + with self.subTest(subject=subject): + result = run_hook(subject + "\n") + self.assertEqual(0, result.returncode, result.stderr) + + def test_rejects_invalid_subjects(self): + for subject in REJECTED: + with self.subTest(subject=subject): + result = run_hook(subject + "\n") + self.assertEqual(1, result.returncode) + self.assertIn(subject, result.stderr) + self.assertIn("plain Conventional Commits", result.stderr) + + def test_only_first_line_is_checked(self): + result = run_hook("feat: x\n\nthis body is not a conventional subject\nwip: junk\n") + self.assertEqual(0, result.returncode, result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/tests/community_health_contract_test.py b/.github/tests/community_health_contract_test.py index 8596696..77cb67a 100644 --- a/.github/tests/community_health_contract_test.py +++ b/.github/tests/community_health_contract_test.py @@ -202,6 +202,24 @@ def test_zizmor_action_owns_its_supported_cli_version(self): self.assertNotIn("\n version:", zizmor_step) + def test_actionlint_download_retries_and_is_bounded(self): + workflow = self.read_text(".github/workflows/standards-validation.yml") + curl_line = next( + line for line in workflow.splitlines() + if "curl" in line and "actionlint_1.7.12" in line + ) + + for flag in ( + "--proto =https", + "--tlsv1.2", + "--retry 3", + "--retry-all-errors", + "--connect-timeout 10", + "--max-time 120", + ): + self.assertIn(flag, curl_line) + self.assertIn("sha256", workflow) + def test_linter_configs_do_not_suppress_workflow_findings(self): markdown_config = self.read_text(".github/markdownlint-profile.yaml") diff --git a/.github/tests/greptile_summon_contract_test.py b/.github/tests/greptile_summon_contract_test.py index 0cc964d..1fa7222 100644 --- a/.github/tests/greptile_summon_contract_test.py +++ b/.github/tests/greptile_summon_contract_test.py @@ -1,5 +1,11 @@ from pathlib import Path +import json +import os import re +import shutil +import subprocess +import tempfile +import textwrap import unittest @@ -83,6 +89,97 @@ def test_workflow_pins_actions_and_is_run_by_standards_validation(self): ).read_text() self.assertIn("greptile_summon_contract_test.py", validation) + def test_summon_script_behavior(self): + node = shutil.which("node") + if node is None: + self.skipTest("node is not available") + + sha = "a" * 40 + other = "b" * 40 + marker = f"" + + def pull(head, state="open"): + return {"data": {"state": state, "head": {"sha": head}}} + + bot_comment = {"user": {"login": "github-actions[bot]"}, "body": marker} + cases = ( + ("abc", [], [], 1, 0, 0), + ("1x", [], [], 1, 0, 0), + ("7", [pull(sha, "closed")], [], 1, 0, 0), + ("7", [pull(other)], [], 1, 0, 0), + ("7", [pull(sha)], [bot_comment], 0, 0, 1), + ("7", [pull(sha), pull(other)], [], 1, 0, 0), + ("7", [pull(sha), pull(sha)], [], 0, 1, 0), + ) + + body = self.script_body(self.read_workflow()) + harness = textwrap.dedent( + """\ + const body = %s; + const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; + const run = new AsyncFunction("github", "core", "context", "process", body); + const scenario = JSON.parse(process.argv[2]); + const calls = { setFailed: [], notice: [], createComment: [] }; + const queue = [...scenario.pulls]; + const listComments = () => {}; + const github = { + rest: { + pulls: { get: async () => queue.shift() }, + issues: { + listComments, + createComment: async (args) => { calls.createComment.push(args); }, + }, + }, + paginate: async () => scenario.comments, + }; + const core = { + setFailed: (m) => calls.setFailed.push(m), + notice: (m) => calls.notice.push(m), + }; + const context = { repo: { owner: "o", repo: "r" } }; + run(github, core, context, process).then( + () => console.log(JSON.stringify(calls)), + (e) => { console.error(e); process.exit(1); }, + ); + """ + ) % json.dumps(body) + + with tempfile.TemporaryDirectory() as tmp: + harness_path = Path(tmp) / "harness.js" + harness_path.write_text(harness) + for pr_number, pulls, comments, failed, created, notices in cases: + with self.subTest(pr_number=pr_number, pulls=pulls): + env = { + **os.environ, + "PR_NUMBER": pr_number, + "HEAD_SHA": sha, + "REVIEW_FOCUS": "check the diff", + } + result = subprocess.run( + [node, str(harness_path), json.dumps({"pulls": pulls, "comments": comments})], + check=True, + capture_output=True, + text=True, + env=env, + ) + calls = json.loads(result.stdout) + self.assertEqual(len(calls["setFailed"]), failed, calls) + self.assertEqual(len(calls["createComment"]), created, calls) + self.assertEqual(len(calls["notice"]), notices, calls) + if created: + comment_body = calls["createComment"][0]["body"] + self.assertIn("@greptileai", comment_body) + self.assertIn(marker, comment_body) + + def script_body(self, workflow): + lines = workflow.split(" script: |\n", 1)[1].splitlines() + body = [] + for line in lines: + if line.strip() and not line.startswith(" " * 12): + break + body.append(line[12:]) + return "\n".join(body) + def read_workflow(self): self.assertTrue(WORKFLOW.is_file(), f"missing workflow: {WORKFLOW}") return WORKFLOW.read_text() diff --git a/.github/tests/main_is_released_contract_test.py b/.github/tests/main_is_released_contract_test.py index ff1a826..1a12a2f 100644 --- a/.github/tests/main_is_released_contract_test.py +++ b/.github/tests/main_is_released_contract_test.py @@ -1,12 +1,52 @@ from pathlib import Path +import os import re +import stat +import subprocess +import tempfile +import textwrap import unittest +import unittest.mock ROOT = Path(__file__).resolve().parents[2] WORKFLOW = ROOT / ".github/workflows/main-is-released.yml" +def isolated_env(**extra): + """os.environ minus GIT_* variables. Under a git hook, GIT_DIR and + GIT_INDEX_FILE point at the real repository, and a throwaway repo's git + calls would write there instead.""" + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env.update(extra) + return env + + +def extract_script(): + """Return the `run: |` body of the assertion step, de-indented.""" + lines = WORKFLOW.read_text().splitlines() + start = next( + i for i, line in enumerate(lines) + if "- name: Assert main points at a release tag" in line + ) + run = next( + i for i in range(start, len(lines)) if lines[i].strip() == "run: |" + ) + body = [] + indent = None + for line in lines[run + 1:]: + if line.strip(): + width = len(line) - len(line.lstrip()) + if indent is None: + indent = width + elif width < indent: + break + body.append(line[indent:]) + else: + body.append("") + return "\n".join(body).rstrip() + "\n" + + class MainIsReleasedContractTest(unittest.TestCase): def test_reusable_workflow_shape_and_read_only_permissions(self): workflow = self.read_workflow() @@ -30,15 +70,24 @@ def test_reusable_workflow_shape_and_read_only_permissions(self): def test_the_invariant_is_an_exact_tag_match(self): workflow = self.read_workflow() - self.assertIn("git describe --exact-match --tags HEAD", workflow) + self.assertIn("git tag --points-at HEAD", workflow) + self.assertNotIn("--exact-match", workflow) # --abbrev=0 alone answers "what tag is nearest", which is true of a # drifted main too. It may only be used to report inside the failure # branch, never in the condition that decides pass or fail — so the - # decisive slice is the condition line, not the whole if-block. - decisive = workflow.split('if tag="$(', 1)[1].split("\n", 1)[0] - self.assertIn("--exact-match", decisive) + # decisive slice is the line reading the tags, not the whole block. + decisive = workflow.split('tags="$(', 2)[1].split("\n", 1)[0] + self.assertIn("--points-at HEAD", decisive) self.assertNotIn("--abbrev=0", decisive) + def test_every_tag_on_head_is_considered(self): + """Several tags can point at main. Judging only one (as describe does) + fails a correctly released main when a non-release tag wins.""" + workflow = self.read_workflow() + + self.assertIn('done <<< "$tags"', workflow) + self.assertIn("while IFS= read -r t", workflow) + def test_no_tags_is_reported_as_unevaluable_not_as_drift(self): """A repo with zero tags produces the same 'not tagged' as one that drifted. Those need different answers, so the measurement proves it @@ -48,7 +97,7 @@ def test_no_tags_is_reported_as_unevaluable_not_as_drift(self): self.assertIn('if [ -z "$(git tag)" ]; then', workflow) self.assertLess( workflow.index('if [ -z "$(git tag)" ]'), - workflow.index("git describe --exact-match"), + workflow.index("git tag --points-at HEAD"), ) def test_shallow_checkout_would_break_the_measurement(self): @@ -65,12 +114,13 @@ def test_an_exact_match_alone_is_not_the_invariant(self): workflow = self.read_workflow() self.assertIn("[0-9]+\\.[0-9]+\\.[0-9]+", workflow) - self.assertIn("not a release version tag", workflow) + self.assertIn("none of which is a release version tag", workflow) # Prerelease detection keys on the hyphen AFTER the version, not any # hyphen anywhere — the old `case $tag in *-*)` called `my-tag` a # prerelease and would have accepted it under allow-prerelease. self.assertNotIn('case "$tag" in', workflow) + self.assertIn("pre_re=", workflow) self.assertIn("^v?[0-9]+\\.[0-9]+\\.[0-9]+-", workflow) def test_the_merge_to_tag_window_is_retried_not_reported_as_drift(self): @@ -95,7 +145,7 @@ def test_a_prerelease_on_main_fails_by_default(self): workflow = self.read_workflow() self.assertIn(" default: false\n", workflow) - self.assertIn('if [ "$ALLOW_PRERELEASE" != "true" ]', workflow) + self.assertIn('[ "$ALLOW_PRERELEASE" != "true" ]', workflow) self.assertIn("ALLOW_PRERELEASE: ${{ inputs.allow-prerelease }}", workflow) def test_failures_say_what_to_do_next(self): @@ -116,6 +166,145 @@ def test_workflow_pins_actions_and_is_run_by_standards_validation(self): validation = (ROOT / ".github/workflows/standards-validation.yml").read_text() self.assertIn("main_is_released_contract_test.py", validation) + def test_isolated_env_drops_hook_git_variables(self): + """Pre-push runs these tests with GIT_DIR set to the real repo.""" + with unittest.mock.patch.dict(os.environ, {"GIT_DIR": "/real/.git", "GIT_INDEX_FILE": "/real/index"}): + env = isolated_env(EXTRA="1") + self.assertNotIn("GIT_DIR", env) + self.assertNotIn("GIT_INDEX_FILE", env) + self.assertEqual("1", env["EXTRA"]) + + def test_main_is_released_script_behavior(self): + """Run the extracted bash against throwaway repos so the pass/fail + decision is exercised, not just grepped for.""" + script_text = extract_script() + self.assertTrue(script_text.strip()) + self.assertIn("set -euo pipefail", script_text) + + def git(repo, *args): + subprocess.run( + ["git", *args], cwd=repo, check=True, env=isolated_env(), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + def commit(repo, name): + (Path(repo) / name).write_text(name) + git(repo, "add", name) + git(repo, "commit", "-q", "-m", name) + + def no_tags(repo): + pass + + def untagged_head(repo): + git(repo, "tag", "v1.0.0") + commit(repo, "second") + + def tag_head(name): + def setup(repo): + git(repo, "tag", name) + return setup + + def tag_old(repo): + git(repo, "tag", "v1.2.3") + commit(repo, "second") + + cases = ( + ("no tags", no_tags, "true", False, "stderr", "no tags"), + ("untagged head", untagged_head, "true", False, "stderr", "not a tagged release"), + ("moving tag", tag_head("snapshot"), "true", False, "stderr", "none of which is a release version tag"), + ("release tag", tag_head("v1.2.3"), "true", True, "stdout", "released at v1.2.3"), + ("prerelease denied", tag_head("v1.2.3-rc.1"), "false", False, None, None), + ("prerelease allowed", tag_head("v1.2.3-rc.1"), "true", True, None, None), + ("tag on older commit", tag_old, "true", False, None, None), + ) + + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) / "bin" + bin_dir.mkdir() + sleep = bin_dir / "sleep" + sleep.write_text("#!/bin/sh\nexit 0\n") + sleep.chmod(sleep.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + script = Path(tmp) / "assert.sh" + script.write_text(script_text) + env = isolated_env(PATH=f"{bin_dir}{os.pathsep}{os.environ['PATH']}") + + for label, setup, allow, ok, stream, needle in cases: + with self.subTest(label): + repo = Path(tmp) / label.replace(" ", "-") + repo.mkdir() + git(repo, "init", "-q") + git(repo, "config", "user.name", "test") + git(repo, "config", "user.email", "test@example.com") + git(repo, "config", "commit.gpgsign", "false") + git(repo, "config", "tag.gpgsign", "false") + commit(repo, "first") + setup(repo) + result = subprocess.run( + ["bash", str(script)], cwd=repo, env={**env, "ALLOW_PRERELEASE": allow}, + capture_output=True, text=True, + ) + if ok: + self.assertEqual(result.returncode, 0, result.stderr) + else: + self.assertNotEqual(result.returncode, 0, result.stdout) + if needle: + self.assertIn(needle, getattr(result, stream)) + + def run_check(self, setup, allow_prerelease="false"): + """Run the real step script against a throwaway repo.""" + workflow = self.read_workflow() + step = workflow.split("- name: Assert main points at a release tag", 1)[1] + body = step.split(" run: |\n", 1)[1] + script = textwrap.dedent(body) + with tempfile.TemporaryDirectory() as tmp: + env = isolated_env( + ALLOW_PRERELEASE=allow_prerelease, + GIT_CONFIG_GLOBAL=os.devnull, + GIT_CONFIG_SYSTEM=os.devnull, + ) + + def git(*args): + subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false", *args], + cwd=tmp, env=env, check=True, capture_output=True, + ) + + git("init", "-q") + git("commit", "-q", "--allow-empty", "-m", "release") + setup(git) + return subprocess.run( + ["bash", "-c", script], cwd=tmp, env=env, capture_output=True, text=True + ) + + def test_behavior_release_tag_among_non_release_tags_passes(self): + def setup(git): + git("tag", "v1.2.3") + git("tag", "-a", "v1", "-m", "moving") + git("tag", "-a", "latest", "-m", "moving") + + result = self.run_check(setup) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("main is released at v1.2.3", result.stdout) + + def test_behavior_final_release_beats_prerelease_when_prereleases_disallowed(self): + def setup(git): + git("tag", "-a", "v1.0.0-rc.1", "-m", "rc") + git("tag", "v1.0.0") + + result = self.run_check(setup) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("main is released at v1.0.0", result.stdout) + + def test_behavior_only_prerelease_fails_by_default(self): + result = self.run_check(lambda git: git("tag", "v1.0.0-rc.1")) + self.assertNotEqual(result.returncode, 0) + self.assertIn("prerelease v1.0.0-rc.1", result.stderr) + + def test_behavior_only_non_release_tag_fails(self): + result = self.run_check(lambda git: git("tag", "latest")) + self.assertNotEqual(result.returncode, 0) + self.assertIn("none of which is a release version tag", result.stderr) + def read_workflow(self): self.assertTrue(WORKFLOW.is_file(), f"missing workflow: {WORKFLOW}") return WORKFLOW.read_text() diff --git a/.github/tests/quality_report_contract_test.py b/.github/tests/quality_report_contract_test.py index a423769..dcbc7ea 100644 --- a/.github/tests/quality_report_contract_test.py +++ b/.github/tests/quality_report_contract_test.py @@ -18,7 +18,9 @@ WORKFLOW = ROOT / ".github" / "workflows" / "quality-report-aggregate.yml" DECISION = ROOT / "decisions" / "quality-reporting.md" SHA = "0123456789abcdef0123456789abcdef01234567" +SELECTOR = CONTRACT_ROOT / "select_artifacts.py" QUALITY_REPORT = runpy.run_path(str(SCRIPT)) +SELECTOR_MODULE = runpy.run_path(str(SELECTOR)) class QualityReportContractTest(unittest.TestCase): @@ -62,6 +64,25 @@ def test_complete_fuzz_fixture_emits_a_valid_report_and_summary(self): self.assertIn("complete 2/2", summary) self.assertEqual(0, self.validate_report(report).returncode) + def test_aggregate_rejects_fail_on_incomplete_false(self): + result, report, _summary = self.aggregate( + "complete", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + fail_on_incomplete="false", + ) + + self.assertEqual(1, result.returncode, result.stderr) + self.assertIn( + "fail_on_incomplete must be true for CodesWhat telemetry", + report["errors"], + ) + self.assertNotEqual("passed", report["outcome"]) + def test_incomplete_fixture_fails_closed_without_a_subset_score(self): result, report, summary = self.aggregate( "incomplete", @@ -82,6 +103,145 @@ def test_incomplete_fixture_fails_closed_without_a_subset_score(self): self.assertNotIn("Canonical score", summary) self.assertEqual(0, self.validate_report(report).returncode) + def test_partial_rerun_without_a_replacement_fails_closed(self): + def drop_stale_target(input_dir): + shutil.rmtree(input_dir / "quality-result-stats") + + result, report, summary = self.aggregate( + "complete", + track="fuzz", + tool="go-fuzz", + expected=[ + "internal/auth/FuzzVerifyRequest", + "internal/docker/FuzzDecodeStats", + ], + input_mutator=drop_stale_target, + ) + + self.assertNotEqual(0, result.returncode) + self.assertFalse(report["completeness"]["complete"]) + self.assertEqual("error", report["outcome"]) + self.assertIsNone(report["metrics"]) + self.assertNotIn("Canonical score", summary) + + def selector_fetch(self, artifacts, started_at="2026-08-13T12:00:00Z"): + calls = [] + + def fetch(path): + calls.append(path) + if "/attempts/" in path: + return {"run_started_at": started_at} + page = int(path.rsplit("page=", 1)[1]) + size = SELECTOR_MODULE["PAGE_SIZE"] + return { + "total_count": len(artifacts), + "artifacts": artifacts[(page - 1) * size : page * size], + } + + return fetch, calls + + def artifact(self, artifact_id, created_at, name="quality-result-a"): + return {"id": artifact_id, "name": name, "created_at": created_at} + + def select(self, artifacts, pattern="quality-result-*", **kwargs): + fetch, calls = self.selector_fetch(artifacts, **kwargs) + ids = SELECTOR_MODULE["select_artifacts"]( + "CodesWhat/example", "1", "2", pattern, fetch + ) + return ids, calls + + def test_selector_keeps_only_fresh_artifacts_matching_the_pattern(self): + ids, calls = self.select( + [ + self.artifact(1, "2026-08-13T11:59:59Z"), + self.artifact(2, "2026-08-13T12:00:01Z"), + self.artifact(3, "2026-08-13T12:05:00Z", name="other-result"), + self.artifact(4, "2026-08-13T12:10:00Z", name="quality-result-b"), + ] + ) + + self.assertEqual([2, 4], ids) + self.assertIn("/repos/CodesWhat/example/actions/runs/1/attempts/2", calls[0]) + + def test_selector_expands_brace_alternatives_like_download_artifact(self): + ids, _ = self.select( + [ + self.artifact(1, "2026-08-13T12:01:00Z", name="quality-result-auth"), + self.artifact(2, "2026-08-13T12:01:00Z", name="quality-result-stats"), + self.artifact(3, "2026-08-13T12:01:00Z", name="quality-result-other"), + self.artifact(4, "2026-08-13T11:00:00Z", name="quality-result-auth"), + ], + pattern="quality-result-{auth,stats}", + ) + + self.assertEqual([1, 2], ids) + + def test_selector_rejects_extglob_patterns(self): + with self.assertRaises(SELECTOR_MODULE["SelectionError"]) as caught: + self.select( + [self.artifact(1, "2026-08-13T12:01:00Z", name="quality-result-auth")], + pattern="quality-result-@(auth|stats)", + ) + self.assertIn("extglob", str(caught.exception)) + + def test_brace_expansion_handles_nesting_and_literals(self): + expand = SELECTOR_MODULE["expand_braces"] + self.assertEqual(["a-x-1", "a-x-2", "a-y"], expand("a-{x-{1,2},y}")) + self.assertEqual(["a-{x}"], expand("a-{x}")) + self.assertEqual(["a-{x,y"], expand("a-{x,y")) + self.assertEqual(["quality-result-*"], expand("quality-result-*")) + + def test_selector_rejects_an_artifact_created_at_the_attempt_start(self): + ids, _ = self.select([self.artifact(1, "2026-08-13T12:00:00Z")]) + + self.assertEqual([], ids) + + def test_selector_reads_every_artifact_page(self): + artifacts = [ + self.artifact(i, "2026-08-13T13:00:00Z", name="quality-result-{0}".format(i)) + for i in range(1, 251) + ] + ids, calls = self.select(artifacts) + + self.assertEqual(list(range(1, 251)), ids) + self.assertEqual(3, len([c for c in calls if "/artifacts?" in c])) + + def test_selector_rejects_missing_or_ambiguous_timestamps(self): + error = SELECTOR_MODULE["SelectionError"] + with self.assertRaises(error): + self.select([{"id": 1, "name": "quality-result-a"}]) + with self.assertRaises(error): + self.select([self.artifact(1, "2026-08-13T12:30:00")]) + with self.assertRaises(error): + self.select([self.artifact(1, "2026-08-13T12:30:00Z")], started_at=None) + + def test_empty_selection_exits_zero_and_never_downloads_everything(self): + fetch, _ = self.selector_fetch([self.artifact(1, "2026-08-13T11:00:00Z")]) + with tempfile.TemporaryDirectory() as temp_dir: + output = Path(temp_dir) / "github-output" + code = SELECTOR_MODULE["main"]( + [ + "--repository", + "CodesWhat/example", + "--run-id", + "1", + "--run-attempt", + "2", + "--pattern", + "quality-result-*", + "--github-output", + str(output), + ], + fetch, + ) + self.assertEqual(0, code) + self.assertEqual("artifact_ids=\n", output.read_text()) + + workflow = WORKFLOW.read_text() + self.assertIn("artifact-ids: ${{ steps.select.outputs.artifact_ids }}", workflow) + self.assertIn("steps.select.outputs.artifact_ids != ''", workflow) + self.assertNotIn("pattern: ${{ inputs.result_artifact_pattern }}", workflow) + def test_crash_fixture_fails_even_when_every_target_reports(self): result, report, summary = self.aggregate( "crash", @@ -718,7 +878,15 @@ def test_standards_validation_runs_this_contract(self): ) def aggregate( - self, fixture, *, track, tool, expected, input_mutator=None, env=None + self, + fixture, + *, + track, + tool, + expected, + input_mutator=None, + env=None, + fail_on_incomplete="true", ): self.assertTrue(SCRIPT.is_file(), f"missing aggregator: {SCRIPT}") with tempfile.TemporaryDirectory() as temp_dir: @@ -766,7 +934,7 @@ def aggregate( "--report-name", "Fixture quality report", "--fail-on-incomplete", - "true", + fail_on_incomplete, "--github-output", str(github_output), "--github-step-summary", diff --git a/.github/tests/reusable_ci_contract_test.py b/.github/tests/reusable_ci_contract_test.py index 22e18f9..3f6def3 100644 --- a/.github/tests/reusable_ci_contract_test.py +++ b/.github/tests/reusable_ci_contract_test.py @@ -297,7 +297,7 @@ def test_release_gate_checks_every_workflow_by_exact_sha_push_and_nonempty_branc def test_release_gate_keeps_authoritative_client_side_run_filtering(self): release = self.read_workflow(WORKFLOWS["release"]) - self.assertIn("for page in 1 2 3 4 5; do", release) + self.assertIn("for ((page=1; page<=10; page++)); do", release) self.assertIn("/runs?per_page=100&page=${page}\"", release) self.assertIn("-lt 100 ]; then", release) self.assertNotRegex(release, r"runs\?[^\"\n]*(?:event|head_sha)=") @@ -338,7 +338,44 @@ def test_release_gate_stops_paging_after_a_short_page(self): self.assertEqual(1, len(result.requests), result.requests) self.assertTrue(result.requests[0].endswith("/runs?per_page=100&page=1")) - def test_release_gate_caps_paging_at_five_pages(self): + def test_release_gate_finds_a_target_run_past_five_pages(self): + filler = { + "head_sha": "b" * 40, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + exact_success = {**filler, "head_sha": TARGET_SHA} + result = self.run_release_gate( + {"ci-verify.yml": [filler] * 100}, + extra_pages_by_workflow={ + "ci-verify.yml": [[filler] * 100] * 4 + [[exact_success]] + }, + ) + + self.assertEqual(0, result.returncode, result.stderr) + self.assertIn(f"Found successful CI Verify push run for {TARGET_SHA}.", result.stdout) + self.assertEqual(6, len(result.requests), result.requests) + + def test_release_gate_times_out_when_pages_are_exhausted_without_a_match(self): + filler = { + "head_sha": "b" * 40, + "event": "push", + "head_branch": "main", + "status": "completed", + "conclusion": "success", + } + result = self.run_release_gate( + {"ci-verify.yml": [filler] * 100}, + extra_pages_by_workflow={"ci-verify.yml": [[filler] * 100] * 4}, + ) + + self.assertNotEqual(0, result.returncode) + self.assertIn("Timed out waiting for successful CI Verify push run", result.stdout + result.stderr) + self.assertEqual(6, len(result.requests), result.requests) + + def test_release_gate_caps_paging_at_the_api_result_ceiling(self): filler = { "head_sha": "b" * 40, "event": "push", @@ -348,11 +385,11 @@ def test_release_gate_caps_paging_at_five_pages(self): } result = self.run_release_gate( {"ci-verify.yml": [filler] * 100}, - extra_pages_by_workflow={"ci-verify.yml": [[filler] * 100] * 5}, + extra_pages_by_workflow={"ci-verify.yml": [[filler] * 100] * 14}, ) self.assertNotEqual(0, result.returncode) - self.assertEqual(5, len(result.requests), result.requests) + self.assertEqual(10, len(result.requests), result.requests) def test_release_gate_uses_one_shared_poll_budget_for_every_workflow(self): in_progress = { diff --git a/.github/tests/starchart_refresh_contract_test.py b/.github/tests/starchart_refresh_contract_test.py index e611d67..c8baabf 100644 --- a/.github/tests/starchart_refresh_contract_test.py +++ b/.github/tests/starchart_refresh_contract_test.py @@ -1,4 +1,6 @@ from pathlib import Path +import json +import os import re import shutil import subprocess @@ -191,6 +193,24 @@ def test_the_documented_trigger_is_a_dispatch_not_a_cron_or_a_release(self): for dead in ("release:", "types: [published]", "cron", "schedule:"): self.assertNotIn(dead, example) + def test_onboarding_doc_recommends_dispatch_not_release_trigger(self): + doc = (ROOT / "REPOSITORY_ONBOARDING.md").read_text() + start = doc.index("A repository that still commits a first-party star-history") + item = " ".join(doc[start:].split("\n### ", 1)[0].split()) + + for expected in ( + "workflow_dispatch", + "integration branch", + "`actions: write`", + "`contents: write`", + "Do not trigger it with `release: [published]`", + ): + self.assertIn(expected, item) + + # Any mention of the release trigger must sit inside a prohibition. + for match in re.finditer(re.escape("`release: [published]`"), item): + self.assertRegex(item[: match.start()], r"Do not trigger it with $") + def test_the_suppression_trap_is_documented_not_just_avoided(self): """Removing the bad example only stops it being copied from here. The reason has to travel with it, or the next person reaches for the @@ -316,6 +336,177 @@ def test_embedded_generator_is_valid_javascript(self): ) self.assertEqual(result.returncode, 0, result.stderr) + def test_api_helper_retries_transient_failures_and_bounds_each_request(self): + workflow = self.read_workflow() + for expected in ( + "AbortSignal.timeout(REQUEST_TIMEOUT_MS)", + "const REQUEST_TIMEOUT_MS = 15000", + "const MAX_ATTEMPTS = 4", + "const FETCH_BUDGET_MS = 7 * 60 * 1000", + "const MAX_BACKOFF_MS = 30000", + ): + self.assertIn(expected, workflow) + + def test_generator_recovers_from_a_transient_5xx_or_429(self): + for status in (502, 429): + with self.subTest(status=status): + result = self.run_generator( + [self.repo_reply(2), {"status": status}, self.stars_reply()] + ) + self.assertEqual(result["code"], 0, result["stderr"]) + self.assertEqual(len(result["fetches"]), 3) + self.assertEqual(len(result["sleeps"]), 1) + self.assertTrue(result["svgs"]) + + def test_generator_waits_out_a_rate_limit(self): + reply = {"status": 403, "headers": {"retry-after": "7"}} + result = self.run_generator([self.repo_reply(2), reply, self.stars_reply()]) + self.assertEqual(result["code"], 0, result["stderr"]) + self.assertEqual(result["sleeps"], [7000]) + + reset = { + "status": 403, + "headers": {"x-ratelimit-remaining": "0", "x-ratelimit-reset": "__SOON__"}, + } + result = self.run_generator([self.repo_reply(2), reset, self.stars_reply()]) + self.assertEqual(result["code"], 0, result["stderr"]) + self.assertEqual(len(result["sleeps"]), 1) + self.assertGreater(result["sleeps"][0], 1000) + + def test_generator_backs_off_exponentially_between_attempts(self): + result = self.run_generator( + [self.repo_reply(2), {"status": 500}, {"status": 503}, self.stars_reply()] + ) + self.assertEqual(result["code"], 0, result["stderr"]) + self.assertEqual(result["sleeps"], [1000, 2000]) + + def test_generator_aborts_a_hung_request_on_the_deadline(self): + result = self.run_generator([self.repo_reply(2), {"hang": True}, self.stars_reply()]) + self.assertEqual(result["code"], 0, result["stderr"]) + self.assertEqual(result["timeouts"][0], 15000) + self.assertEqual(len(result["fetches"]), 3) + + def test_generator_exits_nonzero_when_retries_are_exhausted(self): + result = self.run_generator([self.repo_reply(2)] + [{"status": 502}] * 4) + self.assertNotEqual(result["code"], 0) + self.assertEqual(len(result["fetches"]), 5) + self.assertIn("stargazers?per_page=100&page=1", result["stderr"]) + self.assertIn("502", result["stderr"]) + self.assertEqual(result["svgs"], []) + + def test_generator_fails_at_once_on_a_permanent_client_error(self): + for status in (404, 401, 403): + with self.subTest(status=status): + result = self.run_generator([{"status": status}]) + self.assertNotEqual(result["code"], 0) + self.assertEqual(len(result["fetches"]), 1) + self.assertEqual(result["sleeps"], []) + self.assertIn(str(status), result["stderr"]) + self.assertIn("https://api.github.com/repos/o/r", result["stderr"]) + self.assertEqual(result["svgs"], []) + + def test_commit_step_rebases_and_retries_a_rejected_push(self): + step = self.read_workflow().split("Commit the chart only when it actually changed", 1)[1] + self.assertIn('git push origin "HEAD:$TARGET_BRANCH"', step) + self.assertRegex(step, r"for attempt in 1 2 3; do") + # inputs.branch may be fully qualified; the remote-tracking ref may not. + self.assertIn('short_branch="${TARGET_BRANCH#refs/heads/}"', step) + self.assertIn('git fetch --depth=50 origin "+refs/heads/$short_branch:refs/remotes/origin/$short_branch"', step) + self.assertIn('git rebase "origin/$short_branch"', step) + self.assertNotIn('origin/$TARGET_BRANCH', step) + self.assertLess(step.index("for attempt in"), step.index("git push origin")) + self.assertLess(step.index("git rebase"), step.index("could not push the chart")) + self.assertIn("exit 1", step.split("could not push the chart", 1)[1]) + + @staticmethod + def repo_reply(count): + return {"status": 200, "body": {"stargazers_count": count}} + + @staticmethod + def stars_reply(): + return { + "status": 200, + "body": [ + {"starred_at": "2024-01-01T00:00:00Z"}, + {"starred_at": "2024-06-01T00:00:00Z"}, + ], + } + + def run_generator(self, replies): + """Run the extracted generator under node with fetch, timers and the + abort deadline mocked, in a scratch workspace. Returns exit code, + stderr, and what the mocks saw.""" + node = shutil.which("node") + if node is None: + self.skipTest("node is not available") + + soon = str(int(__import__("time").time()) + 5) + for reply in replies: + for key, value in reply.get("headers", {}).items(): + if value == "__SOON__": + reply["headers"][key] = soon + + preamble = """ +const __replies = JSON.parse(process.env.MOCK_REPLIES) +const __log = { fetches: [], sleeps: [], timeouts: [] } +const __realTimeout = AbortSignal.timeout.bind(AbortSignal) +AbortSignal.timeout = (ms) => { __log.timeouts.push(ms); return __realTimeout(40) } +globalThis.setTimeout = (fn, ms) => { __log.sleeps.push(ms); queueMicrotask(fn); return 0 } +Math.random = () => 0 +globalThis.fetch = (url, init) => { + __log.fetches.push(String(url)) + const reply = __replies.shift() + if (!reply) return Promise.reject(new Error('unexpected extra fetch')) + if (reply.hang) { + // AbortSignal.timeout timers are unref'd, so hold the loop open until it fires. + const keepAlive = setInterval(() => {}, 1000) + return new Promise((_, reject) => + init.signal.addEventListener('abort', () => { + clearInterval(keepAlive) + reject(init.signal.reason) + })) + } + const headers = new Headers(reply.headers ?? {}) + return Promise.resolve({ + ok: reply.status >= 200 && reply.status < 300, + status: reply.status, + statusText: 'mock', + headers, + json: async () => reply.body, + }) +} +process.on('exit', () => process.stdout.write('__LOG__' + JSON.stringify(__log))) +""" + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) / "ws" + workspace.mkdir() + script = Path(tmp) / "generator.mjs" + script.write_text(preamble + self.read_generator()) + env = { + "PATH": os.environ.get("PATH", ""), + "TARGET_REPO": "o/r", + "OUTPUT_PATH": "out/chart.svg", + "ACCENT": "#aabbcc", + "MAX_PAGES": "100", + "GITHUB_API_TOKEN": "x", + "GITHUB_WORKSPACE": str(workspace), + "MOCK_REPLIES": json.dumps(replies), + } + proc = subprocess.run( + [node, str(script)], + capture_output=True, + text=True, + check=False, + env=env, + timeout=60, + ) + svgs = sorted(str(p.name) for p in workspace.rglob("*.svg")) + + self.assertIn("__LOG__", proc.stdout, proc.stderr) + log = json.loads(proc.stdout.rsplit("__LOG__", 1)[1]) + log.update(code=proc.returncode, stderr=proc.stderr, svgs=svgs) + return log + def test_workflow_pins_actions_and_is_run_by_standards_validation(self): workflow = self.read_workflow() actions = re.findall(r"^\s+uses: ([^\s#]+)", workflow, re.MULTILINE) diff --git a/.github/workflows/main-is-released.yml b/.github/workflows/main-is-released.yml index 9cfa0fe..0556590 100644 --- a/.github/workflows/main-is-released.yml +++ b/.github/workflows/main-is-released.yml @@ -80,12 +80,12 @@ jobs: # itself seconds later. Refetch and retry before believing it. This # cannot mask real drift: a genuinely untagged main is still # untagged on the last attempt. - tag="" + tags="" for attempt in 1 2 3; do - if tag="$(git describe --exact-match --tags HEAD 2>/dev/null)"; then + tags="$(git tag --points-at HEAD)" + if [ -n "$tags" ]; then break fi - tag="" [ "$attempt" -eq 3 ] && break echo "main is untagged on attempt ${attempt}; refetching tags in case a promotion is mid-cut" sleep 20 @@ -95,30 +95,46 @@ jobs: || echo "::warning::could not refetch tags on attempt ${attempt}; the verdict below uses the refs currently available on the runner" done - if [ -z "$tag" ]; then + if [ -z "$tags" ]; then latest="$(git describe --tags --abbrev=0 HEAD 2>/dev/null || echo '')" ahead="$(git rev-list --count "${latest}..HEAD" 2>/dev/null || echo '?')" echo "::error::main is not a tagged release. Newest reachable tag is ${latest}, and main is ${ahead} commit(s) past it. Either cut a release or move the unshipped work to a dev branch." >&2 exit 1 fi - # An exact match alone is not the invariant. Any tag satisfies it, - # including one literally named "snapshot" or "latest" parked on a - # drifted main — which reads as a pass and is the failure this - # workflow exists to catch. Require a release-shaped tag. - if ! printf '%s' "$tag" | grep -Eq '^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$'; then - echo "::error::main points at ${tag}, which is not a release version tag (expected vMAJOR.MINOR.PATCH). A moving or descriptive tag satisfies an exact-match check while main carries unshipped work." >&2 - exit 1 - fi - + # Any tag at HEAD satisfies "is tagged", including one literally + # named "snapshot" or "latest" parked on a drifted main, which reads + # as a pass and is the failure this workflow exists to catch. Several + # tags can point at one commit, so look at all of them and require + # at least one release-shaped tag. + release_re='^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$' # Prerelease is the part AFTER the version, so match on that rather # than on any hyphen anywhere in the tag. - if printf '%s' "$tag" | grep -Eq '^v?[0-9]+\.[0-9]+\.[0-9]+-'; then - if [ "$ALLOW_PRERELEASE" != "true" ]; then - echo "::error::main points at prerelease ${tag}. Prereleases belong on the dev branch; main carries what users actually run." >&2 - exit 1 + pre_re='^v?[0-9]+\.[0-9]+\.[0-9]+-' + ok="" + pre="" + while IFS= read -r t; do + [ -n "$t" ] || continue + printf '%s' "$t" | grep -Eq "$release_re" || continue + if printf '%s' "$t" | grep -Eq "$pre_re" && [ "$ALLOW_PRERELEASE" != "true" ]; then + pre="${pre:+${pre} }${t}" + continue + fi + ok="$t" + break + done <<< "$tags" + + if [ -z "$ok" ]; then + if [ -n "$pre" ]; then + echo "::error::main points at prerelease ${pre}. Prereleases belong on the dev branch; main carries what users actually run." >&2 + else + echo "::error::main points at ${tags//$'\n'/ }, none of which is a release version tag (expected vMAJOR.MINOR.PATCH). A moving or descriptive tag marks main as tagged while it carries unshipped work." >&2 fi - echo "::warning::main points at prerelease ${tag}, accepted because allow-prerelease is set" + exit 1 + fi + + if printf '%s' "$ok" | grep -Eq "$pre_re"; then + echo "::warning::main points at prerelease ${ok}, accepted because allow-prerelease is set" fi - echo "main is released at ${tag}" + echo "main is released at ${ok}" diff --git a/.github/workflows/quality-report-aggregate.yml b/.github/workflows/quality-report-aggregate.yml index 6196156..c8bd454 100644 --- a/.github/workflows/quality-report-aggregate.yml +++ b/.github/workflows/quality-report-aggregate.yml @@ -20,7 +20,7 @@ on: required: true type: string result_artifact_pattern: - description: Artifact-name pattern containing target-result.json files + description: Artifact-name glob (* ? [] and {a,b} alternatives; extglob is not supported) containing target-result.json files required: false type: string default: quality-result-* @@ -104,12 +104,28 @@ jobs: test -n "$started_at" echo "started_at=${started_at}" >> "$GITHUB_OUTPUT" + - name: Select target results from this attempt + id: select + if: always() + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + PATTERN: ${{ inputs.result_artifact_pattern }} + run: | + set -euo pipefail + python3 quality-report-contract/quality-report/v1/select_artifacts.py \ + --repository "$GITHUB_REPOSITORY" \ + --run-id "$GITHUB_RUN_ID" \ + --run-attempt "$GITHUB_RUN_ATTEMPT" \ + --pattern "$PATTERN" \ + --github-output "$GITHUB_OUTPUT" + - name: Download normalized target results id: download - if: always() + if: always() && steps.select.outputs.artifact_ids != '' uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - pattern: ${{ inputs.result_artifact_pattern }} + artifact-ids: ${{ steps.select.outputs.artifact_ids }} path: quality-result-artifacts - name: Validate and aggregate target results diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index 38be7ca..c279eb7 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -117,9 +117,9 @@ jobs: workflow_id="${workflow_ids[${index}]}" workflow_name="${workflow_names[${index}]}" # GitHub's `?head_sha=` and `?event=` query filters have been spuriously returning 0 results since 2026-04-27. - # Filter the latest runs client-side instead, paging up to 5 x 100 so an older target run is still found. + # Filter the latest runs client-side instead, paging until a short page or the API's 1,000-result ceiling (10 x 100). runs_pages=() - for page in 1 2 3 4 5; do + for ((page=1; page<=10; page++)); do runs_url="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/workflows/${workflow_id}/runs?per_page=100&page=${page}" page_json="$(curl --proto '=https' --tlsv1.2 --retry 3 --fail --silent --show-error \ -H "Authorization: Bearer ${GH_TOKEN}" \ diff --git a/.github/workflows/standards-validation.yml b/.github/workflows/standards-validation.yml index 349f846..8f07336 100644 --- a/.github/workflows/standards-validation.yml +++ b/.github/workflows/standards-validation.yml @@ -44,6 +44,7 @@ jobs: python3 .github/tests/tracked_validation_test.py python3 .github/tests/changes_gate_contract_test.py python3 .github/tests/tree_receipt_contract_test.py + python3 .github/tests/commit_msg_hook_contract_test.py python3 .github/tests/test_wiring_contract_test.py - name: Compile Python @@ -69,7 +70,7 @@ jobs: run: | set -euo pipefail archive="$RUNNER_TEMP/actionlint_1.7.12_linux_amd64.tar.gz" - curl -fsSL -o "$archive" https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz + curl -fsSL --proto =https --tlsv1.2 --retry 3 --retry-all-errors --connect-timeout 10 --max-time 120 -o "$archive" https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 $archive" | sha256sum -c - tar -xzf "$archive" -C "$RUNNER_TEMP" actionlint "$RUNNER_TEMP/actionlint" -color diff --git a/.github/workflows/starchart-refresh.yml b/.github/workflows/starchart-refresh.yml index b1d3ca4..f0a5cb2 100644 --- a/.github/workflows/starchart-refresh.yml +++ b/.github/workflows/starchart-refresh.yml @@ -208,17 +208,75 @@ jobs: throw new Error(`max-pages must be a positive integer, got: ${process.env.MAX_PAGES}`) } + // One flaky response on page 60 of 100 shouldn't cost the whole run, + // and a hung socket shouldn't eat the job timeout. Each attempt has a + // 15 s deadline covering the body as well as the headers. Transient + // failures (network, timeout, 5xx, 429, and a 403 that is clearly a + // rate limit) retry up to 4 attempts inside one 7 minute budget. + // Anything else fails at once, so a bad credential or a missing repo + // isn't hammered. + const REQUEST_TIMEOUT_MS = 15000 + const MAX_ATTEMPTS = 4 + const FETCH_BUDGET_MS = 7 * 60 * 1000 + const MAX_BACKOFF_MS = 30000 + const fetchStarted = Date.now() + const sleep = (ms) => new Promise((done) => setTimeout(done, ms)) + + // Retry-After (seconds or a date) wins, then x-ratelimit-reset + // (epoch seconds), then exponential backoff with jitter. + const retryDelayMs = (res, attempt) => { + const retryAfter = res?.headers.get('retry-after') + if (retryAfter) { + const seconds = Number(retryAfter) + const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(retryAfter) - Date.now() + if (Number.isFinite(ms)) return Math.max(0, ms) + } + const reset = Number(res?.headers.get('x-ratelimit-reset')) + if (res?.headers.get('x-ratelimit-remaining') === '0' && Number.isFinite(reset) && reset > 0) { + return Math.max(0, reset * 1000 - Date.now()) + 1000 + } + return Math.min(MAX_BACKOFF_MS, 1000 * 2 ** (attempt - 1) + Math.random() * 500) + } + const api = async (path, accept) => { - const res = await fetch(`https://api.github.com/${path}`, { - headers: { - accept, - authorization: `Bearer ${auth}`, - 'user-agent': 'codeswhat-starchart', - 'x-github-api-version': '2022-11-28', - }, - }) - if (!res.ok) throw new Error(`GET ${path} -> ${res.status} ${res.statusText}`) - return res.json() + const url = `https://api.github.com/${path}` + for (let attempt = 1; ; attempt++) { + let res + let failure + try { + res = await fetch(url, { + headers: { + accept, + authorization: `Bearer ${auth}`, + 'user-agent': 'codeswhat-starchart', + 'x-github-api-version': '2022-11-28', + }, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }) + if (res.ok) return await res.json() + failure = `${res.status} ${res.statusText}` + } catch (err) { + // Network error, deadline abort, or a body that died mid-read. + res = undefined + failure = err?.name === 'TimeoutError' || err?.name === 'AbortError' + ? `timed out after ${REQUEST_TIMEOUT_MS} ms` + : `network error: ${err?.message ?? err}` + } + + const rateLimited = + res?.status === 429 || + (res?.status === 403 && + (res.headers.get('x-ratelimit-remaining') === '0' || res.headers.has('retry-after'))) + const retryable = !res || res.status >= 500 || rateLimited + if (!retryable) throw new Error(`GET ${url} -> ${failure}`) + + const delay = retryDelayMs(res, attempt) + if (attempt >= MAX_ATTEMPTS || Date.now() - fetchStarted + delay > FETCH_BUDGET_MS) { + throw new Error(`GET ${url} -> ${failure} (gave up after ${attempt} attempt(s))`) + } + console.log(`::warning::GET ${url} -> ${failure}; retrying in ${Math.round(delay)} ms (attempt ${attempt} of ${MAX_ATTEMPTS})`) + await sleep(delay) + } } const total = (await api(`repos/${repo}`, 'application/vnd.github+json')).stargazers_count @@ -558,4 +616,15 @@ jobs: git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git add -- "$OUTPUT_PATH" "$DARK_PATH" git commit -m "chore(docs): refresh the star-history chart" - git push origin "HEAD:$TARGET_BRANCH" + # Another run or a human can land on the branch between checkout and + # here. The commit touches only the two SVGs, so rebasing onto + # whatever arrived is safe. Bounded, so a real rejection still fails. + short_branch="${TARGET_BRANCH#refs/heads/}" + for attempt in 1 2 3; do + if git push origin "HEAD:$TARGET_BRANCH"; then exit 0; fi + echo "::warning::push rejected (attempt $attempt); rebasing onto origin/$short_branch" + git fetch --depth=50 origin "+refs/heads/$short_branch:refs/remotes/origin/$short_branch" + git rebase "origin/$short_branch" + done + echo "::error::could not push the chart after 3 attempts" >&2 + exit 1 diff --git a/REPOSITORY_ONBOARDING.md b/REPOSITORY_ONBOARDING.md index a95300b..9d08a41 100644 --- a/REPOSITORY_ONBOARDING.md +++ b/REPOSITORY_ONBOARDING.md @@ -346,11 +346,17 @@ Add these only when the behavior exists: credential into the README. A hosted chart is live presentation rather than a release artifact, so it needs no refresh workflow. - [ ] A repository that still commits a first-party star-history SVG pair keeps - its pinned `starchart-refresh.yml` caller, on `release: [published]` plus - `workflow_dispatch` with the job granted `contents: write`, until it moves to - Star History through its own reviewed change. Trace other consumers of the - committed SVGs, such as a website, before removing them or the caller. The - reusable workflow keeps its interface for existing pins. + its pinned `starchart-refresh.yml` caller, on `workflow_dispatch` (and + `repository_dispatch` if used) with the job granted `contents: write`, until + it moves to Star History through its own reviewed change. Do not trigger it + with `release: [published]`. Releases published with GITHUB_TOKEN create no + downstream run, so the refresh silently never happens. The release-cut + workflow dispatches it instead, running `gh workflow run .yml --ref + "$BRANCH"` against the active integration branch, with `actions: write` on + the dispatching job. See the header of `.github/workflows/starchart-refresh.yml`. + Trace other consumers of the committed SVGs, such as a website, before + removing them or the caller. The reusable workflow keeps its interface for + existing pins. ### Qlty diff --git a/decisions/quality-reporting.md b/decisions/quality-reporting.md index b826c22..9aed1d1 100644 --- a/decisions/quality-reporting.md +++ b/decisions/quality-reporting.md @@ -114,6 +114,13 @@ The aggregate artifact is named `quality-report---` and contains `report.json` plus `summary.md`. Native reports and crash corpora remain separate artifacts. Target result JSON is always uploaded; crash forensics remain failure-only. +Completeness requires fresh results for every expected target. The aggregate +job downloads only artifacts matching `result_artifact_pattern` that were +created strictly after the current attempt started, selected by explicit +artifact ID. Results retained from an earlier attempt never count, and a +partial rerun that lacks replacements fails closed: `complete=false`, +`outcome=error`, no aggregate score, and a nonzero exit. An empty selection +downloads nothing instead of falling back to every artifact. Normalized aggregate artifacts use at least 90 days of retention. The reusable workflow checks out its own contract at the exact called-workflow diff --git a/quality-report/v1/select_artifacts.py b/quality-report/v1/select_artifacts.py new file mode 100644 index 0000000..de96d6e --- /dev/null +++ b/quality-report/v1/select_artifacts.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Select the target-result artifacts produced by the current workflow attempt.""" + +import argparse +from datetime import datetime, timezone +import fnmatch +import json +import re +import subprocess +import sys + +PAGE_SIZE = 100 +TIMESTAMP = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$") + + +EXTGLOB = re.compile(r"[@+!?*]\(") + + +class SelectionError(Exception): + pass + + +def expand_braces(pattern): + """Expand {a,b} alternatives the way minimatch does for download-artifact. + + Nested groups expand recursively. A group with no top-level comma, or an + unbalanced brace, stays literal, which also matches minimatch. + """ + depth = 0 + start = None + for index, char in enumerate(pattern): + if char == "{": + if depth == 0: + start = index + depth += 1 + elif char == "}" and depth: + depth -= 1 + if depth == 0: + body = pattern[start + 1:index] + options, level, last = [], 0, 0 + for position, inner in enumerate(body): + if inner == "{": + level += 1 + elif inner == "}": + level -= 1 + elif inner == "," and level == 0: + options.append(body[last:position]) + last = position + 1 + if not options: + head, tail = pattern[:index + 1], pattern[index + 1:] + return [head + rest for rest in expand_braces(tail)] + options.append(body[last:]) + prefix, suffix = pattern[:start], pattern[index + 1:] + expanded = [] + for option in options: + for item in expand_braces(prefix + option + suffix): + if item not in expanded: + expanded.append(item) + return expanded + return [pattern] + + +def matches(name, pattern): + return any(fnmatch.fnmatchcase(name, item) for item in expand_braces(pattern)) + + +def gh_api(path): + result = subprocess.run( + ["gh", "api", path], capture_output=True, text=True, check=False, timeout=60 + ) + if result.returncode != 0: + raise SelectionError("gh api {0} failed: {1}".format(path, result.stderr.strip())) + try: + return json.loads(result.stdout) + except ValueError as error: + raise SelectionError("gh api {0} returned invalid JSON".format(path)) from error + + +def parse_timestamp(value, label): + if not isinstance(value, str) or not TIMESTAMP.match(value): + raise SelectionError("{0}: missing or ambiguous timestamp: {1!r}".format(label, value)) + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + return parsed.astimezone(timezone.utc) + + +def list_artifacts(repository, run_id, fetch): + artifacts = [] + page = 1 + while True: + document = fetch( + "/repos/{0}/actions/runs/{1}/artifacts?per_page={2}&page={3}".format( + repository, run_id, PAGE_SIZE, page + ) + ) + batch = document.get("artifacts") if isinstance(document, dict) else None + if not isinstance(batch, list): + raise SelectionError("artifact listing page {0} is malformed".format(page)) + artifacts.extend(batch) + total = document.get("total_count") + if len(batch) < PAGE_SIZE or (isinstance(total, int) and len(artifacts) >= total): + return artifacts + page += 1 + + +def select_artifacts(repository, run_id, attempt, pattern, fetch=gh_api): + if EXTGLOB.search(pattern): + raise SelectionError( + "unsupported extglob in artifact pattern: {0}".format(pattern) + ) + attempt_run = fetch( + "/repos/{0}/actions/runs/{1}/attempts/{2}".format(repository, run_id, attempt) + ) + started_at = parse_timestamp( + attempt_run.get("run_started_at") if isinstance(attempt_run, dict) else None, + "attempt run_started_at", + ) + selected = [] + for artifact in list_artifacts(repository, run_id, fetch): + name = artifact.get("name") + if not isinstance(name, str) or not matches(name, pattern): + continue + if artifact.get("expired") is True: + continue + created_at = parse_timestamp( + artifact.get("created_at"), "artifact {0} created_at".format(name) + ) + if created_at > started_at: + artifact_id = artifact.get("id") + if not isinstance(artifact_id, int) or isinstance(artifact_id, bool): + raise SelectionError("artifact {0} has no integer id".format(name)) + selected.append(artifact_id) + return sorted(set(selected)) + + +def write_output(path, ids): + if path is not None: + with open(path, "a") as handle: + handle.write("artifact_ids={0}\n".format(",".join(str(i) for i in ids))) + + +def main(argv=None, fetch=gh_api): + parser = argparse.ArgumentParser() + parser.add_argument("--repository", required=True) + parser.add_argument("--run-id", required=True) + parser.add_argument("--run-attempt", required=True) + parser.add_argument("--pattern", required=True) + parser.add_argument("--github-output") + args = parser.parse_args(argv) + try: + ids = select_artifacts( + args.repository, args.run_id, args.run_attempt, args.pattern, fetch + ) + except SelectionError as error: + write_output(args.github_output, []) + print("error: {0}".format(error), file=sys.stderr) + return 1 + write_output(args.github_output, ids) + print("selected {0} artifact(s) from attempt {1}".format(len(ids), args.run_attempt)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validate.sh b/scripts/validate.sh index bef5609..ed99360 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -22,6 +22,7 @@ python3 .github/tests/main_is_released_contract_test.py python3 .github/tests/tracked_validation_test.py python3 .github/tests/changes_gate_contract_test.py python3 .github/tests/tree_receipt_contract_test.py +python3 .github/tests/commit_msg_hook_contract_test.py python3 .github/tests/test_wiring_contract_test.py echo "==> compile python"