diff --git a/.github/workflows/__checks.yml b/.github/workflows/__checks.yml index eece5a77..1f8743b4 100644 --- a/.github/workflows/__checks.yml +++ b/.github/workflows/__checks.yml @@ -7,30 +7,39 @@ on: value: ${{ toJSON(jobs) }} permissions: {} jobs: - security: - name: Security checks - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 + continuous-integration: + name: CI (${{ matrix.directory }}) + strategy: + fail-fast: false + matrix: + directory: + - actions/action-distributions + - actions/create-and-merge-pull-request + - actions/download-artifact + - actions/need-fix-to-issue + - actions/quality/discard-report-fixtures + - actions/quality/lint-pull-request-title + - actions/quality/prepare-ci-reports + - actions/quality/publish-ci-reports + - actions/quality/test-action-distribution + uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@ec682a1547aa7f917034bd62a833aac7e09709d1 # PR #624 (unreleased) permissions: &nodejs-ci-permissions actions: read contents: read - id-token: write packages: read - pull-requests: write + pull-requests: read security-events: write with: - build: "" - lint: "" - test: "" - code-ql: '{"languages":"javascript-typescript","config-file":".github/codeql/config.yml"}' - test-bundled-actions: - permissions: - actions: read - contents: read - uses: $/.github/workflows/test-action-distributions.yml - test-action-distributions: + working-directory: ${{ matrix.directory }} + code-ql: ${{ strategy.job-index == 0 && '{"languages":"javascript-typescript","config-file":".github/codeql/config.yml"}' || '' }} + dependency-review: ${{ strategy.job-index == 0 }} + + test-action-distribution-maintenance: + name: Test distribution maintenance permissions: *nodejs-ci-permissions uses: $/.github/workflows/__test-action-distributions.yml - test-action-test-action-distribution: + test-action-distribution-isolation: + name: Test distribution isolation permissions: *nodejs-ci-permissions uses: $/.github/workflows/__test-action-test-action-distribution.yml lint: @@ -49,9 +58,6 @@ jobs: actions: read contents: read uses: $/.github/workflows/__test-action-matrix-outputs.yml - test-action-create-and-merge-pull-request: - permissions: *nodejs-ci-permissions - uses: $/.github/workflows/__test-action-create-and-merge-pull-request.yml test-action-lint-pull-request-title: permissions: *nodejs-ci-permissions uses: $/.github/workflows/__test-action-lint-pull-request-title.yml @@ -76,9 +82,6 @@ jobs: actions: read contents: read uses: $/.github/workflows/__test-action-get-issue-number.yml - test-action-need-fix-to-issue: - permissions: *nodejs-ci-permissions - uses: $/.github/workflows/__test-action-need-fix-to-issue.yml test-action-repository-owner-is-organization: permissions: actions: read @@ -97,16 +100,7 @@ jobs: actions: read contents: read uses: $/.github/workflows/__test-action-working-directory.yml - test-action-publish-ci-reports: - uses: $/.github/workflows/__test-action-publish-ci-reports.yml - permissions: *nodejs-ci-permissions - test-action-discard-report-fixtures: - uses: $/.github/workflows/__test-action-discard-report-fixtures.yml - permissions: *nodejs-ci-permissions test-workflow-check-jobs: uses: $/.github/workflows/__test-workflow-check-jobs.yml permissions: contents: read - test-action-prepare-ci-reports: - uses: $/.github/workflows/__test-action-prepare-ci-reports.yml - permissions: *nodejs-ci-permissions diff --git a/.github/workflows/__commit-action-distributions.yml b/.github/workflows/__commit-action-distributions.yml index 1dc2ac32..a15c29c0 100644 --- a/.github/workflows/__commit-action-distributions.yml +++ b/.github/workflows/__commit-action-distributions.yml @@ -2,7 +2,7 @@ name: Internal - Commit action distributions on: # zizmor: ignore[dangerous-triggers] Trusted writer validates origin, actor, PR head and paths; it never executes PR code. workflow_run: - workflows: [Internal - Rebuild action distributions] + workflows: [Internal - Pull request - Continuous Integration] types: [completed] permissions: {} @@ -16,7 +16,7 @@ jobs: pull-requests: read with: pull-request-authors: | - ["dependabot", "renovate", {"login":"hoverkraft-bot[bot]","id":128996893,"branch-prefix":"renovate/"}] + ["dependabot", "renovate", "hoverkraft"] github-app-client-id: ${{ vars.CI_BOT_APP_CLIENT_ID }} secrets: github-app-key: ${{ secrets.CI_BOT_APP_PRIVATE_KEY }} diff --git a/.github/workflows/__pull-request-ci.yml b/.github/workflows/__pull-request-ci.yml index 84cc7ef2..dde94c1e 100644 --- a/.github/workflows/__pull-request-ci.yml +++ b/.github/workflows/__pull-request-ci.yml @@ -3,7 +3,6 @@ name: Internal - Pull request - Continuous Integration on: merge_group: pull_request: - branches: [main] concurrency: group: ${{ github.workflow }}-${{ github.ref }} diff --git a/.github/workflows/__rebuild-action-distributions.yml b/.github/workflows/__rebuild-action-distributions.yml deleted file mode 100644 index cf5ff291..00000000 --- a/.github/workflows/__rebuild-action-distributions.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Internal - Rebuild action distributions - -on: - pull_request: - branches: [main] - -permissions: {} - -jobs: - distributions: - uses: $/.github/workflows/action-distributions.yml - permissions: - actions: read - contents: read - pull-requests: read - with: - pull-request-authors: | - ["dependabot", "renovate", {"login":"hoverkraft-bot[bot]","id":128996893,"branch-prefix":"renovate/"}] diff --git a/.github/workflows/__shared-ci.yml b/.github/workflows/__shared-ci.yml index 28b9e669..ffa2ca2f 100644 --- a/.github/workflows/__shared-ci.yml +++ b/.github/workflows/__shared-ci.yml @@ -8,90 +8,14 @@ jobs: permissions: actions: read contents: read - id-token: write packages: read pull-requests: write security-events: write issues: write statuses: write - # FIXME: Remove this bridge when the action tests use the released Node.js #624 API. - # Released Node.js CI still emits native reports; Common must remain releasable first. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - prepare-nodejs-reports: - name: Normalize reports from released Node.js CI (${{ matrix.project }}) - needs: checks - if: ${{ !cancelled() }} - runs-on: ubuntu-latest - timeout-minutes: 10 - permissions: - actions: read - contents: read - strategy: - fail-fast: false - matrix: - include: - - job: test-action-create-and-merge-pull-request - project: actions/create-and-merge-pull-request - - job: test-action-discard-report-fixtures - project: actions/quality/discard-report-fixtures - - job: test-action-distributions - project: actions/action-distributions - - job: test-action-download-artifact - project: actions/download-artifact - - job: test-action-lint-pull-request-title - project: actions/quality/lint-pull-request-title - - job: test-action-need-fix-to-issue - project: actions/need-fix-to-issue - - job: test-action-prepare-ci-reports - project: actions/quality/prepare-ci-reports - - job: test-action-publish-ci-reports - project: actions/quality/publish-ci-reports - - job: test-action-test-action-distribution - project: actions/quality/test-action-distribution - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - ref: ${{ github.event.pull_request.head.sha || github.sha }} - - name: Describe the native reports - id: native - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - PROJECT: ${{ matrix.project }} - OUTCOME: ${{ fromJSON(needs.checks.outputs.job-results || '{}')[matrix.job].result || 'failure' }} - with: - script: |- - const fs = require('node:fs'); - const path = require('node:path'); - const project = process.env.PROJECT; - const reports = [{kind: 'test'}, {kind: 'coverage', language: 'JavaScript'}]; - core.setOutput('directory', fs.mkdtempSync(path.join(process.env.RUNNER_TEMP, 'nodejs-reports-'))); - core.setOutput('pattern', `ci-reports-${process.env.GITHUB_RUN_ATTEMPT}-*-${project.replaceAll('/', '-')}-*`); - core.setOutput('definition', {name: 'Node.js action checks', project, reports}); - core.setOutput('outcome', process.env.OUTCOME); - - name: Download the reports produced by Node.js CI - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - pattern: ${{ steps.native.outputs.pattern }} - path: ${{ steps.native.outputs.directory }} - merge-multiple: true - - name: Normalize and retain native reports - uses: $/actions/quality/prepare-ci-reports - with: - directory: ${{ steps.native.outputs.directory }} - definition: ${{ steps.native.outputs.definition }} - outcome: ${{ steps.native.outputs.outcome }} - - name: Clean downloaded native reports - if: ${{ always() && steps.native.outputs.directory != '' }} - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - DIRECTORY: ${{ steps.native.outputs.directory }} - with: - script: await io.rmRF(process.env.DIRECTORY); reports: needs: - checks - - prepare-nodejs-reports if: always() uses: $/.github/workflows/publish-ci-reports.yml permissions: @@ -120,7 +44,6 @@ jobs: if: always() needs: - checks - - prepare-nodejs-reports - reports - test-workflow-publish-ci-reports uses: $/.github/workflows/check-jobs.yml diff --git a/.github/workflows/__test-action-create-and-merge-pull-request.yml b/.github/workflows/__test-action-create-and-merge-pull-request.yml deleted file mode 100644 index 059464a8..00000000 --- a/.github/workflows/__test-action-create-and-merge-pull-request.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: Internal - Tests for create-and-merge-pull-request action -on: - workflow_call: -permissions: {} -jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test create-and-merge-pull-request - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/create-and-merge-pull-request - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' diff --git a/.github/workflows/__test-action-discard-report-fixtures.yml b/.github/workflows/__test-action-discard-report-fixtures.yml deleted file mode 100644 index a2ca2446..00000000 --- a/.github/workflows/__test-action-discard-report-fixtures.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: Internal - Tests for discard-report-fixtures action -on: - workflow_call: -permissions: {} -jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test discard-report-fixtures - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/quality/discard-report-fixtures - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' diff --git a/.github/workflows/__test-action-distributions.yml b/.github/workflows/__test-action-distributions.yml index 4cff36a6..1833283a 100644 --- a/.github/workflows/__test-action-distributions.yml +++ b/.github/workflows/__test-action-distributions.yml @@ -5,24 +5,6 @@ permissions: contents: read pull-requests: read jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test action-distributions - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/action-distributions - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' integration-tests: runs-on: ubuntu-latest timeout-minutes: 5 @@ -32,12 +14,6 @@ jobs: with: persist-credentials: false ref: ${{ github.event.pull_request.head.sha || github.sha }} - - name: Exercise public action on an unrelated package - id: prepare-build - uses: $/actions/action-distributions - with: - operation: prepare-build - working-directories: fixtures/unrelated-action - name: Exercise public writer action outside workflow_run if: github.event_name != 'workflow_run' id: prepare-commit @@ -47,10 +23,8 @@ jobs: - name: Check public no-op outputs uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - HEAD_SHA: ${{ steps.prepare-build.outputs.head-sha }} - ARTIFACT_ID: ${{ steps.prepare-commit.outputs.artifact-id }} + ARTIFACT_IDS: ${{ steps.prepare-commit.outputs.artifact-ids }} with: script: | const assert = require('node:assert/strict'); - assert.equal(process.env.HEAD_SHA, ''); - assert.equal(process.env.ARTIFACT_ID, ''); + assert.equal(process.env.ARTIFACT_IDS, ''); diff --git a/.github/workflows/__test-action-download-artifact.yml b/.github/workflows/__test-action-download-artifact.yml index d9d42745..b687e6e6 100644 --- a/.github/workflows/__test-action-download-artifact.yml +++ b/.github/workflows/__test-action-download-artifact.yml @@ -3,24 +3,6 @@ on: workflow_call: permissions: {} jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test download-artifact - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/download-artifact - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' integration-tests: name: Download a new artifact and verify its contents runs-on: ubuntu-latest diff --git a/.github/workflows/__test-action-lint-pull-request-title.yml b/.github/workflows/__test-action-lint-pull-request-title.yml index 20beac7a..0262f8c3 100644 --- a/.github/workflows/__test-action-lint-pull-request-title.yml +++ b/.github/workflows/__test-action-lint-pull-request-title.yml @@ -3,24 +3,6 @@ on: workflow_call: permissions: {} jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test lint-pull-request-title - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/quality/lint-pull-request-title - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' integration-tests: name: Validate event title with repository configuration if: ${{ github.event.pull_request }} diff --git a/.github/workflows/__test-action-need-fix-to-issue.yml b/.github/workflows/__test-action-need-fix-to-issue.yml deleted file mode 100644 index 346793a7..00000000 --- a/.github/workflows/__test-action-need-fix-to-issue.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: Internal - Tests for need-fix-to-issue action -on: - workflow_call: -permissions: - contents: read -jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test need-fix-to-issue - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/need-fix-to-issue - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' diff --git a/.github/workflows/__test-action-prepare-ci-reports.yml b/.github/workflows/__test-action-prepare-ci-reports.yml deleted file mode 100644 index 755536d4..00000000 --- a/.github/workflows/__test-action-prepare-ci-reports.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: Internal - Tests for prepare-ci-reports action -on: - workflow_call: -permissions: {} -jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test prepare-ci-reports - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/quality/prepare-ci-reports - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' diff --git a/.github/workflows/__test-action-publish-ci-reports.yml b/.github/workflows/__test-action-publish-ci-reports.yml deleted file mode 100644 index 864e20d8..00000000 --- a/.github/workflows/__test-action-publish-ci-reports.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: Internal - Tests for publish-ci-reports action -on: - workflow_call: -permissions: {} -jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test publish-ci-reports - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/quality/publish-ci-reports - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' diff --git a/.github/workflows/__test-action-test-action-distribution.yml b/.github/workflows/__test-action-test-action-distribution.yml index 4788d1b3..ffd2c2c1 100644 --- a/.github/workflows/__test-action-test-action-distribution.yml +++ b/.github/workflows/__test-action-test-action-distribution.yml @@ -3,24 +3,6 @@ on: workflow_call: permissions: {} jobs: - continuous-integration: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@64632ba90b771d20337b737d8b0ccee0cb7bae58 # 3.1.2 - name: Test test-action-distribution - permissions: - contents: read - id-token: write - packages: read - pull-requests: write - security-events: write - with: - working-directory: actions/quality/test-action-distribution - build: "" - lint: "" - code-ql: "" - dependency-review: false - # FIXME: Remove legacy publication options after Node.js #624 is released. - # https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624 - test: '{"command":"test:ci","coverage":"github","comment":false,"report-file":".reports/junit.xml,.reports/lcov.info"}' integration-tests: name: Execute package distribution contracts (${{ matrix.environment }}) runs-on: ubuntu-latest @@ -43,7 +25,7 @@ jobs: const path = require('node:path'); const directory = process.env.FIXTURE_PATH; await io.mkdirP(path.join(directory, 'dist')); - fs.writeFileSync(path.join(directory, 'package.json'), JSON.stringify({ scripts: { 'test:distribution': 'node contract.cjs' } })); + fs.writeFileSync(path.join(directory, 'package.json'), JSON.stringify({ scripts: { test: 'node contract.cjs' } })); fs.writeFileSync(path.join(directory, 'dist/index.js'), 'exports.value = 42;'); fs.writeFileSync(path.join(directory, 'contract.cjs'), 'require("node:assert/strict").equal(require(process.env.ACTION_ENTRYPOINT).value, 42);'); - name: Act and assert - Run package-owned contract tests diff --git a/.github/workflows/__test-workflow-publish-ci-reports.yml b/.github/workflows/__test-workflow-publish-ci-reports.yml index 753da7c8..103acbbc 100644 --- a/.github/workflows/__test-workflow-publish-ci-reports.yml +++ b/.github/workflows/__test-workflow-publish-ci-reports.yml @@ -35,7 +35,7 @@ jobs: try { const body = fs.readFileSync(directory + '/summary.md', 'utf8'); assert.equal(body, process.env.MARKDOWN); - assert.match(body, /Node.js action checks/); + assert.match(body, /Node.js tests/); assert.match(body, /^## CI report\n/); for (const section of ['Tests', 'Lint', 'Test coverage']) assert.ok(body.includes(`### ${section}\n`)); assert.match(body, /Workflow jobs<\/summary>/); diff --git a/.github/workflows/action-distributions.md b/.github/workflows/action-distributions.md index 59cac917..777a606e 100644 --- a/.github/workflows/action-distributions.md +++ b/.github/workflows/action-distributions.md @@ -22,150 +22,80 @@ ## Overview -Rebuild committed Node.js bundles in the same dependency PR through one reusable -workflow with separate build and writer event callers. Configure workflow inputs; -no repository configuration file is needed. The dedicated -[action](../../actions/action-distributions/README.md) owns the implementation and -tests. Existing CI must check bundle consistency before merging. - -### Configure a repository - -1. Each package needs a lockfile and build and check:dist scripts. Defaults use Node.js 24, - `npm ci --ignore-scripts`, `npm run build`, and `dist/index.js` plus `dist/licenses.txt`. - For pnpm workspaces, select the root working directory, commit pnpm-lock.yaml - and pin packageManager in the root package.json. Shared ci-github-nodejs actions - detect and configure the package manager from the first affected package. Installation - uses `pnpm install --frozen-lockfile`. Set ignore-scripts to false when approved - hooks are required; pnpm's allowBuilds policy still applies. Only the read-only - builder installs dependencies or executes repository scripts. All selected packages - must use the same package manager. The shared setup configures tooling only; - the builder installs once per affected package using the shared detected command. - The node-version input is applied after setup to preserve the requested runtime. -2. Copy the [build caller](https://github.com/hoverkraft-tech/ci-github-common/blob/main/.github/workflows/__rebuild-action-distributions.yml) and - [writer caller](https://github.com/hoverkraft-tech/ci-github-common/blob/main/.github/workflows/__commit-action-distributions.yml). Both call - `hoverkraft-tech/ci-github-common/.github/workflows/action-distributions.yml` - pinned to the same reviewed commit. Configure author rules in both callers; package directories are discovered - automatically. Repeat other shared settings when overriding defaults. -3. Set `workflow_run.workflows` to the build caller's unique, exact `name` - and `pull_request.branches` to the default branch. GitHub rejects a workflow - listening to its own completion, so the two small event callers are required - even though they share one reusable workflow. -4. Provide `CI_BOT_APP_CLIENT_ID` as a repository variable and - `CI_BOT_APP_PRIVATE_KEY` as an Actions secret. Install the App with contents - write, actions read and pull requests read on the consumer repository. Only - the writer caller passes the App key; the build caller passes no secrets. -5. Merge the callers into the default branch. Trigger a fresh dependency update - to verify regeneration, CI on the generated commit and bot rebasing. - GitHub.com is required for self-repository action references. - -The generated Usage block lists inputs. Actual execution requires both events in -the linked callers; a push-only caller does not run either job. To customize the -build, set `build-script` to a package script name and choose `node-version`. Override -`output-directory`, `required-files`, `artifact-name`, `retention-days` or -`commit-message` when needed. A workspace build can emit several bundles: supply -newline-separated output-directory paths or patterns such as `actions/**/dist` -relative to the workspace root. Patterns support `*`, `**` and `?`. Both jobs -resolve them against committed directories in the trusted PR base revision, -never the PR checkout or artifact. New matching directories become eligible -after reaching the default branch. Hidden and node_modules directories are excluded. -Every pattern must match; duplicate or overlapping resolved directories fail. -Required files must exist in every resolved output directory. Keep the patterns -and max-artifact-size limit identical in both callers. - -By default, discover root and `actions/**` packages declaring the selected build -script and check:dist. Override working-directories with newline-separated -literal directories or glob patterns (`*`, `**`, `?`). Literal directories explicitly -define the allowlist; glob matches must declare both scripts. No matches is a -successful no-op. Dependency, generated and hidden directories are excluded. -Selected directories must not overlap or contain traversal components. - -Build and writer discovery read manifests from the PR's default-branch base -revision through GitHub's API. No repository code is executed during discovery. -A newly introduced package must reach the default branch before automated -rebuilds can write its output; normal distribution CI tests it on the PR. -An empty required-files accepts any nonempty output for each affected package. -The writer uses its own default-branch inputs and manifests as the allowlist. -A PR cannot expand its write scope by editing inputs or package manifests. - -### Choose allowed PR authors - -`pull-request-authors` is a JSON array. It defaults to `["dependabot","renovate"]`, -which selects GitHub Dependabot and the hosted Renovate App. Both presets check -the PR creator and event actor by login and numeric account ID, with the respective -`dependabot/` and `renovate/` branch prefixes. Other PRs are skipped before any -package code executes. - -For self-hosted Renovate or another automation account, pass an explicit rule in -both callers. For example, the Hoverkraft callers add their own App: - -```yaml -pull-request-authors: | - ["dependabot", "renovate", {"login":"hoverkraft-bot[bot]","id":128996893,"branch-prefix":"renovate/"}] -``` - -Verify an account's ID with `gh api 'users/ACCOUNT_LOGIN' --jq .id`. Custom rules -require `login` and numeric `id`; `branch-prefix` and `commit-message-suffix` are -optional. Authorizing a branch prefix alone is insufficient. Inputs do not enable -or extend a dependency updater's package-manager coverage. - -Dependabot's preset adds `[dependabot skip]` to generated commits so it can rebase -over them. For Renovate, add the writer's actual commit author email to -[gitIgnoredAuthors](https://docs.renovatebot.com/configuration-options/#gitignoredauthors) -in its existing configuration; otherwise Renovate can treat the generated commit -as a manual modification and stop updating that PR. The common and container -repositories configure `128996893+hoverkraft-bot[bot]@users.noreply.github.com`. -Other installations must use their own writer's email. - -Every generated commit includes a fixed body trailer. The helper skips that head -on subsequent events, including when Renovate and the writer use the same App. -Normal CI still runs; no CI skip marker or automatic merge is configured. - -### Build and publication behavior - -The builder checks out the exact PR head and rebuilds affected configured packages, -including grouped updates and lockfile-only changes. Generated files and licenses -are uploaded together. Updated dependencies execute only in this read-only job. - -The writer checks the originating run and current PR through GitHub's API. It -accepts only the current successful attempt, the resolved builder and configured author, -a same-repository branch, and an unchanged open PR targeting the default branch. -It treats the artifact as bytes, validates every path, and commits only changes -inside the selected output directories. Deleted chunks are removed; unrelated -files remain untouched. It never checks out or executes PR code. These origin and -head checks cannot be disabled through inputs. - -The writer resolves its caller file through GitHub, then reads the workflow -definitions at its default-branch revision. Its workflow_run.workflows filter -must contain one exact name matching one pull_request workflow in that snapshot. -Missing or duplicate names, multiple names and wildcard filters fail publication. -The originating run must belong to that workflow path; a name supplied by a PR -or the run is never used to authorize publication. No builder-path input is needed. - -One generated commit covers all affected packages. The App token triggers normal -CI. Identical output and superseded runs produce no commit. Publication is -serialized per branch and checks the expected head atomically. A concurrent update -fails publication without a force push. - -### Troubleshooting - -- A failed build leaves the PR unchanged. Fix its package build; existing - distribution checks continue to prevent stale merges. -- Missing or expired artifacts fail publication. Retention defaults to one day; - rerun the builder to produce a new attempt, then inspect the writer run. -- A moved or closed PR is skipped. A new bot update rebuilds the latest head; a - failed atomic write never replaces newer commits. -- Token creation or commit failures require checking the App installation, - permissions, repository rules and Actions secret. No PAT fallback is used. -- Artifacts default to a 20 MiB JSON limit; max-artifact-size can raise it to 128 MiB. - Keep output below 1,000 regular files and each file below 50 MiB. Symbolic links, - executable distribution files and truncated GitHub tree/file listings are rejected. -- Changes above 20 MiB use individual Git blob uploads and one Git commit, followed - by a non-forced atomic update guarded by the expected head. Unlike the small-change - commit API, this path does not automatically sign the commit. Repositories requiring - signed bot commits must account for this before enabling large artifacts. - -See [ADR 0002](../../docs/adr/0002-audit-action-dependency-distributions.md) for the design, -alternatives and rollout constraints. +Commit action distributions produced by normal CI for authorized automation PRs. +This trusted workflow_run writer never checks out or executes PR code. + +### Repository setup + +Run each action package through ci-github-nodejs/continuous-integration.yml. +Its build job uploads generated dist/ before checking committed output. No +dedicated rebuild workflow or package-manager configuration is needed here. +Other CI can call actions/action-distributions with operation: collect and one +literal working-directories value after a successful build of the exact PR head. +Keep that step under the default success condition, before any stale-output check. + +Copy the [writer caller](https://github.com/hoverkraft-tech/ci-github-common/blob/main/.github/workflows/__commit-action-distributions.yml). +Set workflow_run.workflows to the unique, exact name of the normal pull_request +CI workflow. Merge the caller into the default branch before testing publication. +Provide CI_BOT_APP_CLIENT_ID and CI_BOT_APP_PRIVATE_KEY for an App installed with +contents write, actions read and pull requests read on the consumer repository. +The read-only CI jobs receive no App key. GitHub.com is required for self-references. + +### Package and author policy + +Defaults discover root and actions/**packages with an action manifest and a build +script, and allow changes only under their dist/ directories. Each output must +include index.js; license files and chunks are included when generated. Override +working-directories with newline-separated literal directories or glob patterns. +Output-directory supports multiple directories and patterns relative to each +package, for example actions/**/dist for a workspace root. Patterns resolve only +against committed directories at the trusted PR base. Selected paths must not +overlap. New packages become eligible after reaching the default branch. + +Match collection and writer settings when overriding output-directory, +required-files, artifact-name or max-artifact-size. An empty required-files input +accepts any nonempty output. The writer always enforces its own trusted policy; +PR manifests or artifacts cannot expand the write scope. + +Pull-request-authors defaults to ["dependabot","renovate"]. Presets validate the +creator and originating actor by login and immutable numeric ID, plus branch +prefix. Hoverkraft uses ["dependabot","renovate","hoverkraft"]. Custom rules +require login and ID, with optional branch-prefix and commit-message-suffix. +Verify IDs using gh API 'users/ACCOUNT_LOGIN' --jq .id. + +Dependabot commits include [dependabot skip] so it can rebase. For Renovate, add +the writer's actual author email to [gitIgnoredAuthors](https://docs.renovatebot.com/configuration-options/#gitignoredauthors). +Hoverkraft uses 128996893+hoverkraft-bot[bot]@users.noreply.github.com. +A generated-commit trailer prevents loops even when Renovate and the writer share +an App. The new commit triggers normal CI; no CI skip or automatic merge is used. + +### Publication and recovery + +The writer accepts a completed CI attempt with success or failure: a successful +build can produce valid output while the stale-distribution check fails. Failed +builds never reach collection. Missing output for any affected package blocks +the entire commit. Cancelled, superseded and stale-head runs cannot publish. + +Workflow identity comes from the writer caller at its default-branch revision. +Its workflow_run filter must resolve to one exact pull_request workflow path. +Author, same-repository branch, default target branch, open PR and current head +are rechecked before committing. Artifacts are treated as bytes, never executed. +Every path and package payload is validated; stale chunks are deleted only +within the trusted allowlist. One atomic commit covers all affected packages. + +Partial reruns cannot reuse earlier-attempt artifacts. If output is missing or +expired, rerun all CI jobs. Collection retains artifacts for one day by default. +A closed or updated PR is skipped. Conflicting writes fail without force-pushing. +For token or commit failures, check App installation, permissions and repository +rules. No PAT fallback is used. + +The combined JSON payload defaults to 20 MiB (configurable up to 128 MiB), with +at most 1,000 regular files and 50 MiB per file. Symlinks, executable distribution +files and truncated API listings are rejected. Changes above 20 MiB use Git blob +uploads and a guarded non-forced branch update; that API does not automatically +sign commits. Account for signature rules before enabling large artifacts. + +See [ADR 0002](../../docs/adr/0002-audit-action-dependency-distributions.md). ### Permissions @@ -196,7 +126,7 @@ jobs: # GitHub App private key, passed only by the trusted workflow_run caller. github-app-key: "" with: - # Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages declaring build and check:dist scripts. + # Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages with an action manifest and a build script. working-directories: "" # Newline-separated generated directories or glob patterns (`*`, `**`, `?`) relative to each package. Patterns select committed directories from the trusted base revision; matches must be non-overlapping. @@ -204,41 +134,25 @@ jobs: output-directory: dist # Newline-separated files required in every generated directory. Empty accepts any nonempty output. - # Default: `index.js - # licenses.txt - # ` - required-files: | - index.js - licenses.txt - - # JSON array of dependabot or renovate presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. + # Default: `index.js` + required-files: index.js + + # JSON array of dependabot, renovate or hoverkraft presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. # Default: `["dependabot","renovate"]` pull-request-authors: '["dependabot","renovate"]' - # Artifact name prefix shared by build and commit. The run attempt is appended automatically. + # Artifact name prefix shared with CI collection. Run attempt and package identity are appended automatically. # Default: `action-distributions` artifact-name: action-distributions - # Node.js version used for dependency installation and the build script. - # Default: `24` - node-version: "24" - - # Package script name to run after a locked dependency installation. + # Build script name used to discover eligible packages; this workflow never runs it. # Default: `build` build-script: build - # Disable install lifecycle scripts. Set false only when the read-only builder needs approved hooks. - # Default: `true` - ignore-scripts: true - - # Maximum serialized artifact size in MiB (integer from 1 to 128). Use the same limit for build and writer. + # Maximum serialized artifact size in MiB (integer from 1 to 128). Applied to all affected packages together. # Default: `20` max-artifact-size: 20 - # Artifact retention in days, within the repository's artifact policy. - # Default: `1` - retention-days: 1 - # Single-line commit headline. Per-author suffixes and a loop-prevention body trailer are appended. # Default: `build: regenerate action distributions` commit-message: "build: regenerate action distributions" @@ -254,20 +168,17 @@ jobs: ### Workflow Call Inputs -| **Input** | **Description** | **Required** | **Type** | **Default** | -| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ----------- | ------------------------------------------------------------------------------------------------- | -| **`working-directories`** | Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages declaring build and check:dist scripts. | **false** | **string** | - | -| **`output-directory`** | Newline-separated generated directories or glob patterns (`*`, `**`, `?`) relative to each package. Patterns select committed directories from the trusted base revision; matches must be non-overlapping. | **false** | **string** | `dist` | -| **`required-files`** | Newline-separated files required in every generated directory. Empty accepts any nonempty output. | **false** | **string** |
index.js
licenses.txt
| -| **`pull-request-authors`** | JSON array of dependabot or renovate presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. | **false** | **string** | `["dependabot","renovate"]` | -| **`artifact-name`** | Artifact name prefix shared by build and commit. The run attempt is appended automatically. | **false** | **string** | `action-distributions` | -| **`node-version`** | Node.js version used for dependency installation and the build script. | **false** | **string** | `24` | -| **`build-script`** | Package script name to run after a locked dependency installation. | **false** | **string** | `build` | -| **`ignore-scripts`** | Disable install lifecycle scripts. Set false only when the read-only builder needs approved hooks. | **false** | **boolean** | `true` | -| **`max-artifact-size`** | Maximum serialized artifact size in MiB (integer from 1 to 128). Use the same limit for build and writer. | **false** | **number** | `20` | -| **`retention-days`** | Artifact retention in days, within the repository's artifact policy. | **false** | **number** | `1` | -| **`commit-message`** | Single-line commit headline. Per-author suffixes and a loop-prevention body trailer are appended. | **false** | **string** | `build: regenerate action distributions` | -| **`github-app-client-id`** | Client ID of the GitHub App installed on the caller repository with contents write and actions and pull requests read access. | **false** | **string** | - | +| **Input** | **Description** | **Required** | **Type** | **Default** | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------- | ---------------------------------------- | +| **`working-directories`** | Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages with an action manifest and a build script. | **false** | **string** | - | +| **`output-directory`** | Newline-separated generated directories or glob patterns (`*`, `**`, `?`) relative to each package. Patterns select committed directories from the trusted base revision; matches must be non-overlapping. | **false** | **string** | `dist` | +| **`required-files`** | Newline-separated files required in every generated directory. Empty accepts any nonempty output. | **false** | **string** | `index.js` | +| **`pull-request-authors`** | JSON array of dependabot, renovate or hoverkraft presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. | **false** | **string** | `["dependabot","renovate"]` | +| **`artifact-name`** | Artifact name prefix shared with CI collection. Run attempt and package identity are appended automatically. | **false** | **string** | `action-distributions` | +| **`build-script`** | Build script name used to discover eligible packages; this workflow never runs it. | **false** | **string** | `build` | +| **`max-artifact-size`** | Maximum serialized artifact size in MiB (integer from 1 to 128). Applied to all affected packages together. | **false** | **number** | `20` | +| **`commit-message`** | Single-line commit headline. Per-author suffixes and a loop-prevention body trailer are appended. | **false** | **string** | `build: regenerate action distributions` | +| **`github-app-client-id`** | Client ID of the GitHub App installed on the caller repository with contents write and actions and pull requests read access. | **false** | **string** | - | diff --git a/.github/workflows/action-distributions.yml b/.github/workflows/action-distributions.yml index 2c533393..46b53bb1 100644 --- a/.github/workflows/action-distributions.yml +++ b/.github/workflows/action-distributions.yml @@ -1,154 +1,84 @@ -# Rebuild committed Node.js bundles in the same dependency PR through one reusable -# workflow with separate build and writer event callers. Configure workflow inputs; -# no repository configuration file is needed. The dedicated -# [action](../../actions/action-distributions/README.md) owns the implementation and -# tests. Existing CI must check bundle consistency before merging. -# -# ### Configure a repository -# -# 1. Each package needs a lockfile and build and check:dist scripts. Defaults use Node.js 24, -# `npm ci --ignore-scripts`, `npm run build`, and `dist/index.js` plus `dist/licenses.txt`. -# For pnpm workspaces, select the root working directory, commit pnpm-lock.yaml -# and pin packageManager in the root package.json. Shared ci-github-nodejs actions -# detect and configure the package manager from the first affected package. Installation -# uses `pnpm install --frozen-lockfile`. Set ignore-scripts to false when approved -# hooks are required; pnpm's allowBuilds policy still applies. Only the read-only -# builder installs dependencies or executes repository scripts. All selected packages -# must use the same package manager. The shared setup configures tooling only; -# the builder installs once per affected package using the shared detected command. -# The node-version input is applied after setup to preserve the requested runtime. -# 2. Copy the [build caller](https://github.com/hoverkraft-tech/ci-github-common/blob/main/.github/workflows/__rebuild-action-distributions.yml) and -# [writer caller](https://github.com/hoverkraft-tech/ci-github-common/blob/main/.github/workflows/__commit-action-distributions.yml). Both call -# `hoverkraft-tech/ci-github-common/.github/workflows/action-distributions.yml` -# pinned to the same reviewed commit. Configure author rules in both callers; package directories are discovered -# automatically. Repeat other shared settings when overriding defaults. -# 3. Set `workflow_run.workflows` to the build caller's unique, exact `name` -# and `pull_request.branches` to the default branch. GitHub rejects a workflow -# listening to its own completion, so the two small event callers are required -# even though they share one reusable workflow. -# 4. Provide `CI_BOT_APP_CLIENT_ID` as a repository variable and -# `CI_BOT_APP_PRIVATE_KEY` as an Actions secret. Install the App with contents -# write, actions read and pull requests read on the consumer repository. Only -# the writer caller passes the App key; the build caller passes no secrets. -# 5. Merge the callers into the default branch. Trigger a fresh dependency update -# to verify regeneration, CI on the generated commit and bot rebasing. -# GitHub.com is required for self-repository action references. -# -# The generated Usage block lists inputs. Actual execution requires both events in -# the linked callers; a push-only caller does not run either job. To customize the -# build, set `build-script` to a package script name and choose `node-version`. Override -# `output-directory`, `required-files`, `artifact-name`, `retention-days` or -# `commit-message` when needed. A workspace build can emit several bundles: supply -# newline-separated output-directory paths or patterns such as `actions/**/dist` -# relative to the workspace root. Patterns support `*`, `**` and `?`. Both jobs -# resolve them against committed directories in the trusted PR base revision, -# never the PR checkout or artifact. New matching directories become eligible -# after reaching the default branch. Hidden and node_modules directories are excluded. -# Every pattern must match; duplicate or overlapping resolved directories fail. -# Required files must exist in every resolved output directory. Keep the patterns -# and max-artifact-size limit identical in both callers. -# -# By default, discover root and `actions/**` packages declaring the selected build -# script and check:dist. Override working-directories with newline-separated -# literal directories or glob patterns (`*`, `**`, `?`). Literal directories explicitly -# define the allowlist; glob matches must declare both scripts. No matches is a -# successful no-op. Dependency, generated and hidden directories are excluded. -# Selected directories must not overlap or contain traversal components. -# -# Build and writer discovery read manifests from the PR's default-branch base -# revision through GitHub's API. No repository code is executed during discovery. -# A newly introduced package must reach the default branch before automated -# rebuilds can write its output; normal distribution CI tests it on the PR. -# An empty required-files accepts any nonempty output for each affected package. -# The writer uses its own default-branch inputs and manifests as the allowlist. -# A PR cannot expand its write scope by editing inputs or package manifests. -# -# ### Choose allowed PR authors -# -# `pull-request-authors` is a JSON array. It defaults to `["dependabot","renovate"]`, -# which selects GitHub Dependabot and the hosted Renovate App. Both presets check -# the PR creator and event actor by login and numeric account ID, with the respective -# `dependabot/` and `renovate/` branch prefixes. Other PRs are skipped before any -# package code executes. -# -# For self-hosted Renovate or another automation account, pass an explicit rule in -# both callers. For example, the Hoverkraft callers add their own App: -# -# ```yaml -# pull-request-authors: | -# ["dependabot", "renovate", {"login":"hoverkraft-bot[bot]","id":128996893,"branch-prefix":"renovate/"}] -# ``` -# -# Verify an account's ID with `gh api 'users/ACCOUNT_LOGIN' --jq .id`. Custom rules -# require `login` and numeric `id`; `branch-prefix` and `commit-message-suffix` are -# optional. Authorizing a branch prefix alone is insufficient. Inputs do not enable -# or extend a dependency updater's package-manager coverage. -# -# Dependabot's preset adds `[dependabot skip]` to generated commits so it can rebase -# over them. For Renovate, add the writer's actual commit author email to -# [gitIgnoredAuthors](https://docs.renovatebot.com/configuration-options/#gitignoredauthors) -# in its existing configuration; otherwise Renovate can treat the generated commit -# as a manual modification and stop updating that PR. The common and container -# repositories configure `128996893+hoverkraft-bot[bot]@users.noreply.github.com`. -# Other installations must use their own writer's email. -# -# Every generated commit includes a fixed body trailer. The helper skips that head -# on subsequent events, including when Renovate and the writer use the same App. -# Normal CI still runs; no CI skip marker or automatic merge is configured. -# -# ### Build and publication behavior -# -# The builder checks out the exact PR head and rebuilds affected configured packages, -# including grouped updates and lockfile-only changes. Generated files and licenses -# are uploaded together. Updated dependencies execute only in this read-only job. -# -# The writer checks the originating run and current PR through GitHub's API. It -# accepts only the current successful attempt, the resolved builder and configured author, -# a same-repository branch, and an unchanged open PR targeting the default branch. -# It treats the artifact as bytes, validates every path, and commits only changes -# inside the selected output directories. Deleted chunks are removed; unrelated -# files remain untouched. It never checks out or executes PR code. These origin and -# head checks cannot be disabled through inputs. -# -# The writer resolves its caller file through GitHub, then reads the workflow -# definitions at its default-branch revision. Its workflow_run.workflows filter -# must contain one exact name matching one pull_request workflow in that snapshot. -# Missing or duplicate names, multiple names and wildcard filters fail publication. -# The originating run must belong to that workflow path; a name supplied by a PR -# or the run is never used to authorize publication. No builder-path input is needed. -# -# One generated commit covers all affected packages. The App token triggers normal -# CI. Identical output and superseded runs produce no commit. Publication is -# serialized per branch and checks the expected head atomically. A concurrent update -# fails publication without a force push. -# -# ### Troubleshooting -# -# - A failed build leaves the PR unchanged. Fix its package build; existing -# distribution checks continue to prevent stale merges. -# - Missing or expired artifacts fail publication. Retention defaults to one day; -# rerun the builder to produce a new attempt, then inspect the writer run. -# - A moved or closed PR is skipped. A new bot update rebuilds the latest head; a -# failed atomic write never replaces newer commits. -# - Token creation or commit failures require checking the App installation, -# permissions, repository rules and Actions secret. No PAT fallback is used. -# - Artifacts default to a 20 MiB JSON limit; max-artifact-size can raise it to 128 MiB. -# Keep output below 1,000 regular files and each file below 50 MiB. Symbolic links, -# executable distribution files and truncated GitHub tree/file listings are rejected. -# - Changes above 20 MiB use individual Git blob uploads and one Git commit, followed -# by a non-forced atomic update guarded by the expected head. Unlike the small-change -# commit API, this path does not automatically sign the commit. Repositories requiring -# signed bot commits must account for this before enabling large artifacts. -# -# See [ADR 0002](../../docs/adr/0002-audit-action-dependency-distributions.md) for the design, -# alternatives and rollout constraints. +# Commit action distributions produced by normal CI for authorized automation PRs. +# This trusted workflow_run writer never checks out or executes PR code. +# +# ### Repository setup +# +# Run each action package through ci-github-nodejs/continuous-integration.yml. +# Its build job uploads generated dist/ before checking committed output. No +# dedicated rebuild workflow or package-manager configuration is needed here. +# Other CI can call actions/action-distributions with operation: collect and one +# literal working-directories value after a successful build of the exact PR head. +# Keep that step under the default success condition, before any stale-output check. +# +# Copy the [writer caller](https://github.com/hoverkraft-tech/ci-github-common/blob/main/.github/workflows/__commit-action-distributions.yml). +# Set workflow_run.workflows to the unique, exact name of the normal pull_request +# CI workflow. Merge the caller into the default branch before testing publication. +# Provide CI_BOT_APP_CLIENT_ID and CI_BOT_APP_PRIVATE_KEY for an App installed with +# contents write, actions read and pull requests read on the consumer repository. +# The read-only CI jobs receive no App key. GitHub.com is required for self-references. +# +# ### Package and author policy +# +# Defaults discover root and actions/** packages with an action manifest and a build +# script, and allow changes only under their dist/ directories. Each output must +# include index.js; license files and chunks are included when generated. Override +# working-directories with newline-separated literal directories or glob patterns. +# Output-directory supports multiple directories and patterns relative to each +# package, for example actions/**/dist for a workspace root. Patterns resolve only +# against committed directories at the trusted PR base. Selected paths must not +# overlap. New packages become eligible after reaching the default branch. +# +# Match collection and writer settings when overriding output-directory, +# required-files, artifact-name or max-artifact-size. An empty required-files input +# accepts any nonempty output. The writer always enforces its own trusted policy; +# PR manifests or artifacts cannot expand the write scope. +# +# Pull-request-authors defaults to ["dependabot","renovate"]. Presets validate the +# creator and originating actor by login and immutable numeric ID, plus branch +# prefix. Hoverkraft uses ["dependabot","renovate","hoverkraft"]. Custom rules +# require login and id, with optional branch-prefix and commit-message-suffix. +# Verify IDs using gh api 'users/ACCOUNT_LOGIN' --jq .id. +# +# Dependabot commits include [dependabot skip] so it can rebase. For Renovate, add +# the writer's actual author email to [gitIgnoredAuthors](https://docs.renovatebot.com/configuration-options/#gitignoredauthors). +# Hoverkraft uses 128996893+hoverkraft-bot[bot]@users.noreply.github.com. +# A generated-commit trailer prevents loops even when Renovate and the writer share +# an App. The new commit triggers normal CI; no CI skip or automatic merge is used. +# +# ### Publication and recovery +# +# The writer accepts a completed CI attempt with success or failure: a successful +# build can produce valid output while the stale-distribution check fails. Failed +# builds never reach collection. Missing output for any affected package blocks +# the entire commit. Cancelled, superseded and stale-head runs cannot publish. +# +# Workflow identity comes from the writer caller at its default-branch revision. +# Its workflow_run filter must resolve to one exact pull_request workflow path. +# Author, same-repository branch, default target branch, open PR and current head +# are rechecked before committing. Artifacts are treated as bytes, never executed. +# Every path and package payload is validated; stale chunks are deleted only +# within the trusted allowlist. One atomic commit covers all affected packages. +# +# Partial reruns cannot reuse earlier-attempt artifacts. If output is missing or +# expired, rerun all CI jobs. Collection retains artifacts for one day by default. +# A closed or updated PR is skipped. Conflicting writes fail without force-pushing. +# For token or commit failures, check App installation, permissions and repository +# rules. No PAT fallback is used. +# +# The combined JSON payload defaults to 20 MiB (configurable up to 128 MiB), with +# at most 1,000 regular files and 50 MiB per file. Symlinks, executable distribution +# files and truncated API listings are rejected. Changes above 20 MiB use Git blob +# uploads and a guarded non-forced branch update; that API does not automatically +# sign commits. Account for signature rules before enabling large artifacts. +# +# See [ADR 0002](../../docs/adr/0002-audit-action-dependency-distributions.md). name: Action distributions on: workflow_call: inputs: working-directories: - description: Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages declaring build and check:dist scripts. + description: Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages with an action manifest and a build script. type: string default: "" output-directory: @@ -158,37 +88,23 @@ on: required-files: description: Newline-separated files required in every generated directory. Empty accepts any nonempty output. type: string - default: | - index.js - licenses.txt + default: index.js pull-request-authors: - description: JSON array of dependabot or renovate presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. + description: JSON array of dependabot, renovate or hoverkraft presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. type: string default: '["dependabot","renovate"]' artifact-name: - description: Artifact name prefix shared by build and commit. The run attempt is appended automatically. + description: Artifact name prefix shared with CI collection. Run attempt and package identity are appended automatically. type: string default: action-distributions - node-version: - description: Node.js version used for dependency installation and the build script. - type: string - default: "24" build-script: - description: Package script name to run after a locked dependency installation. + description: Build script name used to discover eligible packages; this workflow never runs it. type: string default: build - ignore-scripts: - description: Disable install lifecycle scripts. Set false only when the read-only builder needs approved hooks. - type: boolean - default: true max-artifact-size: - description: Maximum serialized artifact size in MiB (integer from 1 to 128). Use the same limit for build and writer. + description: Maximum serialized artifact size in MiB (integer from 1 to 128). Applied to all affected packages together. type: number default: 20 - retention-days: - description: Artifact retention in days, within the repository's artifact policy. - type: number - default: 1 commit-message: description: Single-line commit headline. Per-author suffixes and a loop-prevention body trailer are appended. type: string @@ -205,86 +121,10 @@ on: permissions: {} jobs: - rebuild: - if: >- - github.event_name == 'pull_request' && - github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-latest - timeout-minutes: 15 - concurrency: - group: action-distributions-build-${{ github.event.pull_request.number }} - cancel-in-progress: true - permissions: - contents: read - pull-requests: read - steps: - - name: Select eligible PR and affected packages - id: prepare - uses: $/actions/action-distributions - with: - operation: prepare-build - build-script: ${{ inputs.build-script }} - working-directories: ${{ inputs.working-directories }} - output-directory: ${{ inputs.output-directory }} - max-artifact-size: ${{ inputs.max-artifact-size }} - required-files: ${{ inputs.required-files }} - pull-request-authors: ${{ inputs.pull-request-authors }} - artifact-name: ${{ inputs.artifact-name }} - - name: Checkout exact PR head - if: steps.prepare.outputs.head-sha - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ steps.prepare.outputs.head-sha }} - path: source - persist-credentials: false - - name: Configure the detected package manager - if: steps.prepare.outputs.head-sha - uses: hoverkraft-tech/ci-github-nodejs/actions/setup-node@191d7230d57982bfc11d57f68b005f386a6d7fbf # 3.1.1 - with: - working-directory: source/${{ fromJSON(steps.prepare.outputs.working-directories)[0] }} - install-dependencies: "false" - - name: Select the requested build runtime - if: steps.prepare.outputs.head-sha - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: ${{ inputs.node-version }} - package-manager-cache: false - - name: Resolve locked installation and script commands - if: steps.prepare.outputs.head-sha - id: package-manager - uses: hoverkraft-tech/ci-github-nodejs/actions/get-package-manager@191d7230d57982bfc11d57f68b005f386a6d7fbf # 3.1.1 - with: - working-directory: source/${{ fromJSON(steps.prepare.outputs.working-directories)[0] }} - - name: Rebuild affected distributions - if: steps.prepare.outputs.head-sha - id: build - uses: $/actions/action-distributions - with: - operation: build - working-directories: ${{ inputs.working-directories }} - output-directory: ${{ inputs.output-directory }} - max-artifact-size: ${{ inputs.max-artifact-size }} - required-files: ${{ inputs.required-files }} - pull-request-authors: ${{ inputs.pull-request-authors }} - artifact-name: ${{ inputs.artifact-name }} - build-script: ${{ inputs.build-script }} - install-command: ${{ steps.package-manager.outputs.install-command }} - run-script-command: ${{ steps.package-manager.outputs.run-script-command }} - ignore-scripts: ${{ inputs.ignore-scripts }} - workspace: ${{ github.workspace }}/source - - name: Upload generated bytes - if: steps.build.outputs.built == 'true' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: ${{ inputs.artifact-name }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/action-distributions/distributions.json - if-no-files-found: error - retention-days: ${{ inputs.retention-days }} - commit: if: >- github.event_name == 'workflow_run' && - github.event.workflow_run.conclusion == 'success' && + contains(fromJSON('["success", "failure"]'), github.event.workflow_run.conclusion) && github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.head_repository.full_name == github.repository runs-on: ubuntu-latest @@ -310,16 +150,16 @@ jobs: pull-request-authors: ${{ inputs.pull-request-authors }} artifact-name: ${{ inputs.artifact-name }} - name: Download this attempt's generated bytes - if: steps.prepare.outputs.artifact-id + if: steps.prepare.outputs.artifact-ids uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - artifact-ids: ${{ steps.prepare.outputs.artifact-id }} + artifact-ids: ${{ steps.prepare.outputs.artifact-ids }} merge-multiple: true run-id: ${{ github.event.workflow_run.id }} github-token: ${{ github.token }} path: ${{ runner.temp }}/incoming-distributions - name: Create repository-scoped writer token - if: steps.prepare.outputs.artifact-id + if: steps.prepare.outputs.artifact-ids id: token uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 with: @@ -329,7 +169,7 @@ jobs: permission-contents: write permission-pull-requests: read - name: Commit distributions if the PR head is unchanged - if: steps.prepare.outputs.artifact-id + if: steps.prepare.outputs.artifact-ids uses: $/actions/action-distributions with: operation: commit @@ -342,4 +182,4 @@ jobs: artifact-name: ${{ inputs.artifact-name }} commit-message: ${{ inputs.commit-message }} github-token: ${{ steps.token.outputs.token }} - artifact-path: ${{ runner.temp }}/incoming-distributions/distributions.json + artifact-path: ${{ runner.temp }}/incoming-distributions diff --git a/.github/workflows/publish-ci-reports.md b/.github/workflows/publish-ci-reports.md index 936dbb8e..cb1ed9ec 100644 --- a/.github/workflows/publish-ci-reports.md +++ b/.github/workflows/publish-ci-reports.md @@ -47,7 +47,7 @@ on: permissions: {} jobs: tests: - uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@36be3d131d95b6a0987a8819b7846f52369b8aac # PR #624 (unreleased) + uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@ec682a1547aa7f917034bd62a833aac7e09709d1 # PR #624 (unreleased) permissions: actions: read contents: read @@ -70,7 +70,7 @@ jobs: reports: needs: checks if: always() - uses: hoverkraft-tech/ci-github-common/.github/workflows/publish-ci-reports.yml@a57403ecded4ed077dc24a6574953f7c46e69224 # PR #683 (unreleased) + uses: hoverkraft-tech/ci-github-common/.github/workflows/publish-ci-reports.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 permissions: actions: read contents: read @@ -83,7 +83,7 @@ jobs: complete: needs: [checks, reports] if: always() - uses: hoverkraft-tech/ci-github-common/.github/workflows/check-jobs.yml@a4afe51a04cd4fcb7189f0f6e91ec479649af06f # PR #683 (unreleased) + uses: hoverkraft-tech/ci-github-common/.github/workflows/check-jobs.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 permissions: {} with: job-results: ${{ toJSON(needs) }} @@ -97,7 +97,7 @@ cancellations, invalid group outputs and unexpected skips fail the gate even if reporting succeeds. Publication remains independent of the completion decision. Common's [checks](__checks.yml) and [outer CI workflow](__shared-ci.yml) also show -this pattern. Common additionally checks its native-report bridge and publication +this pattern. Common additionally checks native report production and publication integration test, which are part of its own reusable workflow validation. ## Destinations diff --git a/.github/workflows/publish-ci-reports.yml b/.github/workflows/publish-ci-reports.yml index 6f7bf095..cad278a9 100644 --- a/.github/workflows/publish-ci-reports.yml +++ b/.github/workflows/publish-ci-reports.yml @@ -32,7 +32,7 @@ # permissions: {} # jobs: # tests: -# uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@36be3d131d95b6a0987a8819b7846f52369b8aac # PR #624 (unreleased) +# uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@ec682a1547aa7f917034bd62a833aac7e09709d1 # PR #624 (unreleased) # permissions: # actions: read # contents: read @@ -55,7 +55,7 @@ # reports: # needs: checks # if: always() -# uses: hoverkraft-tech/ci-github-common/.github/workflows/publish-ci-reports.yml@a57403ecded4ed077dc24a6574953f7c46e69224 # PR #683 (unreleased) +# uses: hoverkraft-tech/ci-github-common/.github/workflows/publish-ci-reports.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 # permissions: # actions: read # contents: read @@ -68,7 +68,7 @@ # complete: # needs: [checks, reports] # if: always() -# uses: hoverkraft-tech/ci-github-common/.github/workflows/check-jobs.yml@a4afe51a04cd4fcb7189f0f6e91ec479649af06f # PR #683 (unreleased) +# uses: hoverkraft-tech/ci-github-common/.github/workflows/check-jobs.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 # permissions: {} # with: # job-results: ${{ toJSON(needs) }} @@ -82,7 +82,7 @@ # reporting succeeds. Publication remains independent of the completion decision. # # Common's [checks](__checks.yml) and [outer CI workflow](__shared-ci.yml) also show -# this pattern. Common additionally checks its native-report bridge and publication +# this pattern. Common additionally checks native report production and publication # integration test, which are part of its own reusable workflow validation. # # ## Destinations diff --git a/.github/workflows/test-action-distributions.md b/.github/workflows/test-action-distributions.md deleted file mode 100644 index 275ffc8d..00000000 --- a/.github/workflows/test-action-distributions.md +++ /dev/null @@ -1,125 +0,0 @@ - - -# GitHub Reusable Workflow: Test action distributions - -
- Test action distributions -
- ---- - - - - -[![Release](https://img.shields.io/github/v/release/hoverkraft-tech/ci-github-common)](https://github.com/hoverkraft-tech/ci-github-common/releases) -[![License](https://img.shields.io/github/license/hoverkraft-tech/ci-github-common)](http://choosealicense.com/licenses/mit/) -[![Stars](https://img.shields.io/github/stars/hoverkraft-tech/ci-github-common?style=social)](https://img.shields.io/github/stars/hoverkraft-tech/ci-github-common?style=social) -[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/hoverkraft-tech/ci-github-common/blob/main/CONTRIBUTING.md) -![GitHub Verified Creator](https://img.shields.io/badge/GitHub-Verified%20Creator-4493F8?logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiIgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2IiBmaWxsPSJyZ2IoNjgsIDE0NywgMjQ4KSI+CiAgPHBhdGggZD0ibTkuNTg1LjUyLjkyOS42OGMuMTUzLjExMi4zMzEuMTg2LjUxOC4yMTVsMS4xMzguMTc1YTIuNjc4IDIuNjc4IDAgMCAxIDIuMjQgMi4yNGwuMTc0IDEuMTM5Yy4wMjkuMTg3LjEwMy4zNjUuMjE1LjUxOGwuNjguOTI4YTIuNjc3IDIuNjc3IDAgMCAxIDAgMy4xN2wtLjY4LjkyOGExLjE3NCAxLjE3NCAwIDAgMC0uMjE1LjUxOGwtLjE3NSAxLjEzOGEyLjY3OCAyLjY3OCAwIDAgMS0yLjI0MSAyLjI0MWwtMS4xMzguMTc1YTEuMTcgMS4xNyAwIDAgMC0uNTE4LjIxNWwtLjkyOC42OGEyLjY3NyAyLjY3NyAwIDAgMS0zLjE3IDBsLS45MjgtLjY4YTEuMTc0IDEuMTc0IDAgMCAwLS41MTgtLjIxNUwzLjgzIDE0LjQxYTIuNjc4IDIuNjc4IDAgMCAxLTIuMjQtMi4yNGwtLjE3NS0xLjEzOGExLjE3IDEuMTcgMCAwIDAtLjIxNS0uNTE4bC0uNjgtLjkyOGEyLjY3NyAyLjY3NyAwIDAgMSAwLTMuMTdsLjY4LS45MjhjLjExMi0uMTUzLjE4Ni0uMzMxLjIxNS0uNTE4bC4xNzUtMS4xNGEyLjY3OCAyLjY3OCAwIDAgMSAyLjI0LTIuMjRsMS4xMzktLjE3NWMuMTg3LS4wMjkuMzY1LS4xMDMuNTE4LS4yMTVsLjkyOC0uNjhhMi42NzcgMi42NzcgMCAwIDEgMy4xNyAwWk03LjMwMyAxLjcyOGwtLjkyNy42OGEyLjY3IDIuNjcgMCAwIDEtMS4xOC40ODlsLTEuMTM3LjE3NGExLjE3OSAxLjE3OSAwIDAgMC0uOTg3Ljk4N2wtLjE3NCAxLjEzNmEyLjY3NyAyLjY3NyAwIDAgMS0uNDg5IDEuMThsLS42OC45MjhhMS4xOCAxLjE4IDAgMCAwIDAgMS4zOTRsLjY4LjkyN2MuMjU2LjM0OC40MjQuNzUzLjQ4OSAxLjE4bC4xNzQgMS4xMzdjLjA3OC41MDkuNDc4LjkwOS45ODcuOTg3bDEuMTM2LjE3NGEyLjY3IDIuNjcgMCAwIDEgMS4xOC40ODlsLjkyOC42OGMuNDE0LjMwNS45NzkuMzA1IDEuMzk0IDBsLjkyNy0uNjhhMi42NyAyLjY3IDAgMCAxIDEuMTgtLjQ4OWwxLjEzNy0uMTc0YTEuMTggMS4xOCAwIDAgMCAuOTg3LS45ODdsLjE3NC0xLjEzNmEyLjY3IDIuNjcgMCAwIDEgLjQ4OS0xLjE4bC42OC0uOTI4YTEuMTc2IDEuMTc2IDAgMCAwIDAtMS4zOTRsLS42OC0uOTI3YTIuNjg2IDIuNjg2IDAgMCAxLS40ODktMS4xOGwtLjE3NC0xLjEzN2ExLjE3OSAxLjE3OSAwIDAgMC0uOTg3LS45ODdsLTEuMTM2LS4xNzRhMi42NzcgMi42NzcgMCAwIDEtMS4xOC0uNDg5bC0uOTI4LS42OGExLjE3NiAxLjE3NiAwIDAgMC0xLjM5NCAwWk0xMS4yOCA2Ljc4bC0zLjc1IDMuNzVhLjc1Ljc1IDAgMCAxLTEuMDYgMEw0LjcyIDguNzhhLjc1MS43NTEgMCAwIDEgLjAxOC0xLjA0Mi43NTEuNzUxIDAgMCAxIDEuMDQyLS4wMThMNyA4Ljk0bDMuMjItMy4yMmEuNzUxLjc1MSAwIDAgMSAxLjA0Mi4wMTguNzUxLjc1MSAwIDAgMSAuMDE4IDEuMDQyWiI+PC9wYXRoPgo8L3N2Zz4K) - - - - -## Overview - -Discover bundled Node.js actions and validate each checked-in distribution on a -host runner and in a Node.js container. Requires contents: read only. - -Packages at the root or under actions/ are discovered when they declare build -and check:dist scripts. Override working-directories with newline-separated -literal directories or glob patterns (`*`, `**`, `?`). An empty result skips testing. - -Each package must commit its npm lockfile and declare test:distribution. That -script runs package-owned contract tests which load process.env.ACTION_ENTRYPOINT. -The shared test action supplies an isolated dist/index.js, clears NODE_PATH and -NODE_OPTIONS, propagates test failures and removes temporary files. Tests may -use development dependencies; the bundle must include its runtime dependencies. - -check:dist must rebuild the distribution and reject modified or untracked output. -Dependency lifecycle scripts are disabled during installation. This workflow -never writes commits. Run source tests with the Node.js continuous-integration -workflow, and keep action integration tests and repository security checks in CI. - -### Permissions - -- **`contents`**: `read` - - - - -## Usage - -```yaml -name: Test action distributions -on: - push: - branches: - - main -permissions: {} -jobs: - test-action-distributions: - uses: hoverkraft-tech/ci-github-common/.github/workflows/test-action-distributions.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 - permissions: - contents: read - with: - # Newline-separated package directories or glob patterns. Empty discovers root and `actions/**` packages declaring build and check:dist scripts. - working-directories: "" - - # Bundle directory relative to each package, containing index.js. - # Default: `dist` - output-directory: dist - - # Node.js version installed for checks on both the host and Node.js 24 container. - # Default: `24` - node-version: "24" -``` - - - - -## Inputs - -### Workflow Call Inputs - -| **Input** | **Description** | **Required** | **Type** | **Default** | -| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------- | ----------- | -| **`working-directories`** | Newline-separated package directories or glob patterns. Empty discovers root and `actions/**` packages declaring build and check:dist scripts. | **false** | **string** | - | -| **`output-directory`** | Bundle directory relative to each package, containing index.js. | **false** | **string** | `dist` | -| **`node-version`** | Node.js version installed for checks on both the host and Node.js 24 container. | **false** | **string** | `24` | - - - - - - - - - - -## Contributing - -Contributions are welcome! Please see the [contributing guidelines](https://github.com/hoverkraft-tech/ci-github-common/blob/main/CONTRIBUTING.md) for more details. - - - - - - -## License - -This project is licensed under the MIT License. - -SPDX-License-Identifier: MIT - -Copyright © 2026 hoverkraft-tech - -For more details, see the [license](http://choosealicense.com/licenses/mit/). - - - - ---- - -This documentation was automatically generated by [CI Dokumentor](https://github.com/hoverkraft-tech/ci-dokumentor). - - diff --git a/.github/workflows/test-action-distributions.yml b/.github/workflows/test-action-distributions.yml deleted file mode 100644 index 807d38d4..00000000 --- a/.github/workflows/test-action-distributions.yml +++ /dev/null @@ -1,87 +0,0 @@ -# Discover bundled Node.js actions and validate each checked-in distribution on a -# host runner and in a Node.js container. Requires contents: read only. -# -# Packages at the root or under actions/ are discovered when they declare build -# and check:dist scripts. Override working-directories with newline-separated -# literal directories or glob patterns (`*`, `**`, `?`). An empty result skips testing. -# -# Each package must commit its npm lockfile and declare test:distribution. That -# script runs package-owned contract tests which load process.env.ACTION_ENTRYPOINT. -# The shared test action supplies an isolated dist/index.js, clears NODE_PATH and -# NODE_OPTIONS, propagates test failures and removes temporary files. Tests may -# use development dependencies; the bundle must include its runtime dependencies. -# -# check:dist must rebuild the distribution and reject modified or untracked output. -# Dependency lifecycle scripts are disabled during installation. This workflow -# never writes commits. Run source tests with the Node.js continuous-integration -# workflow, and keep action integration tests and repository security checks in CI. -name: Test action distributions - -on: - workflow_call: - inputs: - working-directories: - description: Newline-separated package directories or glob patterns. Empty discovers root and `actions/**` packages declaring build and check:dist scripts. - type: string - default: "" - output-directory: - description: Bundle directory relative to each package, containing index.js. - type: string - default: dist - node-version: - description: Node.js version installed for checks on both the host and Node.js 24 container. - type: string - default: "24" - -permissions: {} - -jobs: - discover: - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - contents: read - outputs: - directories: ${{ steps.packages.outputs.working-directories }} - steps: - - id: packages - uses: $/actions/action-distributions - with: - operation: discover - working-directories: ${{ inputs.working-directories }} - output-directory: ${{ inputs.output-directory }} - - test: - needs: discover - if: needs.discover.outputs.directories != '[]' - name: Distribution (${{ matrix.directory }}, ${{ matrix.environment }}) - runs-on: ubuntu-latest - timeout-minutes: 15 - permissions: - contents: read - strategy: - fail-fast: false - matrix: - directory: ${{ fromJSON(needs.discover.outputs.directories) }} - environment: [host, container] - container: ${{ matrix.environment == 'container' && 'node:24' || '' }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: ${{ inputs.node-version }} - package-manager-cache: false - - name: Trust the checked-out workspace in the container - if: matrix.environment == 'container' - run: git config --global --add safe.directory "$GITHUB_WORKSPACE" - - name: Install dependencies and verify the checked-in distribution - working-directory: ${{ matrix.directory }} - run: | - npm ci --ignore-scripts --no-audit --no-fund - npm run check:dist - - uses: $/actions/quality/test-action-distribution - with: - working-directory: ${{ matrix.directory }} - output-directory: ${{ inputs.output-directory }} diff --git a/Makefile b/Makefile index 4a609a41..82bcbfd7 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,10 @@ +GIT_COMMON_DIR := $(shell git rev-parse --path-format=absolute --git-common-dir) + SHELL := /bin/bash +.DEFAULT_GOAL := help +.PHONY: help lint lint-fix setup test build check-distributions deps-audit ci -.PHONY: help npm-update +ACTION_PACKAGES := $(sort $(patsubst %/package.json,%,$(shell find actions -name node_modules -prune -o -name dist -prune -o -name package.json -print))) help: ## Display help @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' @@ -17,59 +21,64 @@ lint-fix: ## Execute linting and fix -e FIX_BIOME_FORMAT=true \ ) -setup: ## Install npm dependencies for all package.json files under actions/ - @echo "Installing npm dependencies for all packages..." - $(call run_npm_for_packages,install) +setup: ## Install locked action development dependencies + $(call run_npm_for_packages,ci --ignore-scripts --no-audit --no-fund) -npm-update: ## Interactively update npm dependencies for all packages - $(call run_npm_for_packages,exec --yes --package=npm-check-updates -- ncu --interactive --cwd "$$pkg_dir") +test: ## Run action source tests + $(call run_npm_for_packages,test) -npm-audit-fix: ## Execute npm audit fix - @echo "Running npm audit fix for all packages..." - $(call run_npm_for_packages,audit fix) +build: ## Rebuild action distributions where present + $(call run_npm_for_packages,run --if-present build) -test: ## Execute tests - @echo "Running tests for all packages..." - $(call run_npm_for_packages,test) +check-distributions: build ## Verify committed distributions match their source + @set -eu; changes="$$(git status --porcelain --untracked-files=all -- ':(glob)actions/**/dist/**')"; \ + if [ -n "$$changes" ]; then \ + printf '%s\n' "$$changes"; \ + echo 'Run make build and commit the generated distributions.' >&2; \ + exit 1; \ + fi -ci: ## Execute CI tasks +deps-audit: ## Check action dependencies without changing lockfiles + $(call run_npm_for_packages,audit) + +ci: ## Install dependencies and run checks without applying fixes $(MAKE) setup - $(MAKE) npm-audit-fix || true - $(MAKE) lint-fix $(MAKE) test + $(MAKE) check-distributions + $(MAKE) lint define run_linter DEFAULT_WORKSPACE="$(CURDIR)"; \ - LINTER_IMAGE="linter:latest"; \ + LINTER_IMAGE="ci-github-common-linter:local"; \ VOLUME="$$DEFAULT_WORKSPACE:$$DEFAULT_WORKSPACE"; \ + DEFAULT_BRANCH="$$(git -C "$$DEFAULT_WORKSPACE" rev-parse --abbrev-ref HEAD)"; \ docker build --platform linux/amd64 --build-arg UID=$(shell id -u) --build-arg GID=$(shell id -g) --tag $$LINTER_IMAGE .; \ docker run \ + -v "$(GIT_COMMON_DIR):$(GIT_COMMON_DIR):ro" \ --platform linux/amd64 \ -v $$VOLUME \ --rm \ + -e RUN_LOCAL=true \ + -e IGNORE_GITIGNORED_FILES=true \ + -e USE_FIND_ALGORITHM=false \ -e DEFAULT_WORKSPACE="$$DEFAULT_WORKSPACE" \ + -e DEFAULT_BRANCH="$$DEFAULT_BRANCH" \ -e FILTER_REGEX_INCLUDE="$(filter-out $@,$(MAKECMDGOALS))" \ $(1) \ $$LINTER_IMAGE endef -define run_npm_for_packages - @set -uo pipefail; \ - overall_status=0; \ - packages="$$(find actions -type f -name package.json -not -path '*/node_modules/*' -not -path '*/dist/*' -print | sort)"; \ - for pkg in $$packages; do \ - pkg_dir="$$(dirname "$$pkg")"; \ - echo "---"; \ - echo "npm $(1) in $$pkg_dir"; \ - if ! npm --prefix "$$pkg_dir" $(1); then \ - overall_status=1; \ - fi; \ - done; \ - exit $$overall_status -endef - ############################# # Argument fix workaround ############################# +ifneq ($(filter lint lint-fix,$(firstword $(MAKECMDGOALS))),) %: @: +endif + +define run_npm_for_packages + @set -eu; \ + for directory in $(ACTION_PACKAGES); do \ + npm --prefix "$$directory" $(1); \ + done +endef diff --git a/README.md b/README.md index eb222aee..fb301e6b 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,6 @@ See the [documentation](docs/README.md) for detailed guides. ### Quality gates - [Check jobs](.github/workflows/check-jobs.md) - requires successful CI jobs and rejects unexpected skips. -- [Test action distributions](.github/workflows/test-action-distributions.md) - discovers bundled packages and validates their distributions on host and container runners. - [Action distributions](.github/workflows/action-distributions.md) - regenerates committed action bundles in dependency pull requests. - [Publish CI reports](.github/workflows/publish-ci-reports.md) - consolidates lint, tests and coverage into one CI comment and publishes validated coverage. - [Linter](.github/workflows/linter.md) - runs Super Linter and shared formatting checks across the repository. diff --git a/actions/action-distributions/README.md b/actions/action-distributions/README.md index 7358f8bc..d6148676 100644 --- a/actions/action-distributions/README.md +++ b/actions/action-distributions/README.md @@ -23,15 +23,15 @@ ## Overview -Discover, build or commit generated Node.js action distributions using validated PR policy. -The [reusable workflow](../../.github/workflows/action-distributions.md) handles -runner setup, artifacts, App tokens and event routing; use it for repository setup. +Collect already-built Node.js action distributions or commit them using validated PR policy. +Normal CI calls `collect` after a successful build, before checking committed output. +It uploads one artifact per package and run attempt, using actions/upload-artifact. +Collection never installs dependencies or executes package scripts. -This composite action owns the build and publication logic. Its -operations are `discover`, `prepare-build`, `build`, `prepare-commit` and `commit`. Preparation -validates the originating event and selects affected packages before execution. -Build operations require a read-only PR job. Commit operations require a trusted -default-branch workflow_run job and never execute or check out PR code. +The [reusable workflow](../../.github/workflows/action-distributions.md) owns the +trusted writer: it validates the originating CI run, downloads affected packages +and commits their output together. It never checks out or executes PR code. +`discover` exposes package discovery for workflows that need it. @@ -41,11 +41,11 @@ default-branch workflow_run job and never execute or check out PR code. ```yaml - uses: hoverkraft-tech/ci-github-common/actions/action-distributions@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 with: - # Operation to execute (discover, prepare-build, build, prepare-commit or commit). + # Operation to execute (discover, collect, prepare-commit or commit). # This input is required. operation: "" - # Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages declaring build and check:dist scripts. + # Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages with an action manifest and a build script. Collection requires one literal directory. working-directories: "" # Newline-separated generated directories or glob patterns (`*`, `**`, `?`) relative to each package. Patterns select committed directories from the trusted base revision; matches must be non-overlapping. @@ -53,38 +53,26 @@ default-branch workflow_run job and never execute or check out PR code. output-directory: dist # Newline-separated files required in every generated directory. Empty accepts any nonempty output. - # Default: `index.js - # licenses.txt - # ` - required-files: | - index.js - licenses.txt - - # JSON array of dependabot or renovate presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. + # Default: `index.js` + required-files: index.js + + # JSON array of dependabot, renovate or hoverkraft presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. # Default: `["dependabot","renovate"]` pull-request-authors: '["dependabot","renovate"]' - # Artifact name prefix. The run attempt is appended automatically. Use the same value for build and commit. + # Artifact name prefix. Run attempt and package identity are appended automatically. Use the same value for collection and commit. # Default: `action-distributions` artifact-name: action-distributions - # Package script name to run after a locked dependency installation. + # Build script name used to discover eligible packages; this action never runs it. # Default: `build` build-script: build - # Locked install command from ci-github-nodejs/get-package-manager. The executable must already be installed; arguments are passed without a shell. - # Default: `npm ci --no-audit --no-fund` - install-command: npm ci --no-audit --no-fund - - # Script command from ci-github-nodejs/get-package-manager, used for every selected package without a shell. - # Default: `npm run` - run-script-command: npm run - - # Disable install lifecycle scripts. Set false only in the read-only builder when the package requires approved hooks. - # Default: `true` - ignore-scripts: "true" + # Retention for uploaded artifacts, within the repository policy. + # Default: `1` + retention-days: "1" - # Maximum serialized artifact size in MiB (integer from 1 to 128). Use the same limit for build and writer. + # Maximum serialized artifact size in MiB (integer from 1 to 128). The writer also enforces this limit across all selected packages. # Default: `20` max-artifact-size: "20" @@ -92,15 +80,15 @@ default-branch workflow_run job and never execute or check out PR code. # Default: `build: regenerate action distributions` commit-message: "build: regenerate action distributions" - # Absolute path of the exact PR head checkout, required for build. + # Absolute path of the exact PR head checkout, required for collection. # Default: `${{ github.workspace }}` workspace: ${{ github.workspace }} - # Absolute JSON artifact path to write for build or read for commit. - # Default: `${{ runner.temp }}/action-distributions/distributions.json` - artifact-path: ${{ runner.temp }}/action-distributions/distributions.json + # Directory for collected or downloaded JSON artifacts. + # Default: `${{ runner.temp }}/action-distributions` + artifact-path: ${{ runner.temp }}/action-distributions - # GitHub token for API calls. Use a read-only token for building and an App token only for committing. + # GitHub token for API calls. Use a read-only token for collection and an App token only for committing. # Default: `${{ github.token }}` github-token: ${{ github.token }} ``` @@ -110,23 +98,21 @@ default-branch workflow_run job and never execute or check out PR code. ## Inputs -| **Input** | **Description** | **Required** | **Default** | -| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------- | -| **`operation`** | Operation to execute (discover, prepare-build, build, prepare-commit or commit). | **true** | - | -| **`working-directories`** | Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages declaring build and check:dist scripts. | **false** | - | -| **`output-directory`** | Newline-separated generated directories or glob patterns (`*`, `**`, `?`) relative to each package. Patterns select committed directories from the trusted base revision; matches must be non-overlapping. | **false** | `dist` | -| **`required-files`** | Newline-separated files required in every generated directory. Empty accepts any nonempty output. | **false** |
index.js
licenses.txt
| -| **`pull-request-authors`** | JSON array of dependabot or renovate presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. | **false** | `["dependabot","renovate"]` | -| **`artifact-name`** | Artifact name prefix. The run attempt is appended automatically. Use the same value for build and commit. | **false** | `action-distributions` | -| **`build-script`** | Package script name to run after a locked dependency installation. | **false** | `build` | -| **`install-command`** | Locked install command from ci-github-nodejs/get-package-manager. The executable must already be installed; arguments are passed without a shell. | **false** | `npm ci --no-audit --no-fund` | -| **`run-script-command`** | Script command from ci-github-nodejs/get-package-manager, used for every selected package without a shell. | **false** | `npm run` | -| **`ignore-scripts`** | Disable install lifecycle scripts. Set false only in the read-only builder when the package requires approved hooks. | **false** | `true` | -| **`max-artifact-size`** | Maximum serialized artifact size in MiB (integer from 1 to 128). Use the same limit for build and writer. | **false** | `20` | -| **`commit-message`** | Single-line commit headline. Per-author suffixes and a loop-prevention body trailer are appended. | **false** | `build: regenerate action distributions` | -| **`workspace`** | Absolute path of the exact PR head checkout, required for build. | **false** | `${{ github.workspace }}` | -| **`artifact-path`** | Absolute JSON artifact path to write for build or read for commit. | **false** | `${{ runner.temp }}/action-distributions/distributions.json` | -| **`github-token`** | GitHub token for API calls. Use a read-only token for building and an App token only for committing. | **false** | `${{ github.token }}` | +| **Input** | **Description** | **Required** | **Default** | +| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ----------------------------------------- | +| **`operation`** | Operation to execute (discover, collect, prepare-commit or commit). | **true** | - | +| **`working-directories`** | Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages with an action manifest and a build script. Collection requires one literal directory. | **false** | - | +| **`output-directory`** | Newline-separated generated directories or glob patterns (`*`, `**`, `?`) relative to each package. Patterns select committed directories from the trusted base revision; matches must be non-overlapping. | **false** | `dist` | +| **`required-files`** | Newline-separated files required in every generated directory. Empty accepts any nonempty output. | **false** | `index.js` | +| **`pull-request-authors`** | JSON array of dependabot, renovate or hoverkraft presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. | **false** | `["dependabot","renovate"]` | +| **`artifact-name`** | Artifact name prefix. Run attempt and package identity are appended automatically. Use the same value for collection and commit. | **false** | `action-distributions` | +| **`build-script`** | Build script name used to discover eligible packages; this action never runs it. | **false** | `build` | +| **`retention-days`** | Retention for uploaded artifacts, within the repository policy. | **false** | `1` | +| **`max-artifact-size`** | Maximum serialized artifact size in MiB (integer from 1 to 128). The writer also enforces this limit across all selected packages. | **false** | `20` | +| **`commit-message`** | Single-line commit headline. Per-author suffixes and a loop-prevention body trailer are appended. | **false** | `build: regenerate action distributions` | +| **`workspace`** | Absolute path of the exact PR head checkout, required for collection. | **false** | `${{ github.workspace }}` | +| **`artifact-path`** | Directory for collected or downloaded JSON artifacts. | **false** | `${{ runner.temp }}/action-distributions` | +| **`github-token`** | GitHub token for API calls. Use a read-only token for collection and an App token only for committing. | **false** | `${{ github.token }}` | @@ -135,12 +121,10 @@ default-branch workflow_run job and never execute or check out PR code. ## Outputs -| **Output** | **Description** | -| ------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| **`working-directories`** | JSON array of package directories selected by discover or affected packages selected by prepare-build for an eligible PR. | -| **`head-sha`** | Eligible current PR head selected by prepare-build; empty when skipped. | -| **`built`** | Whether build produced a validated distribution artifact. | -| **`artifact-id`** | Validated artifact selected by prepare-commit; empty when skipped. | +| **Output** | **Description** | +| ------------------------- | -------------------------------------------------------------------------------------- | +| **`working-directories`** | JSON array of package directories selected by discover. | +| **`artifact-ids`** | Comma-separated validated artifact IDs selected by prepare-commit; empty when skipped. | diff --git a/actions/action-distributions/action.yml b/actions/action-distributions/action.yml index 2058449e..3fe3cc4e 100644 --- a/actions/action-distributions/action.yml +++ b/actions/action-distributions/action.yml @@ -1,14 +1,14 @@ name: Action distributions description: | - Discover, build or commit generated Node.js action distributions using validated PR policy. - The [reusable workflow](../../.github/workflows/action-distributions.md) handles - runner setup, artifacts, App tokens and event routing; use it for repository setup. + Collect already-built Node.js action distributions or commit them using validated PR policy. + Normal CI calls `collect` after a successful build, before checking committed output. + It uploads one artifact per package and run attempt, using actions/upload-artifact. + Collection never installs dependencies or executes package scripts. - This composite action owns the build and publication logic. Its - operations are `discover`, `prepare-build`, `build`, `prepare-commit` and `commit`. Preparation - validates the originating event and selects affected packages before execution. - Build operations require a read-only PR job. Commit operations require a trusted - default-branch workflow_run job and never execute or check out PR code. + The [reusable workflow](../../.github/workflows/action-distributions.md) owns the + trusted writer: it validates the originating CI run, downloads affected packages + and commits their output together. It never checks out or executes PR code. + `discover` exposes package discovery for workflows that need it. author: hoverkraft branding: icon: package @@ -16,66 +16,52 @@ branding: inputs: operation: - description: Operation to execute (discover, prepare-build, build, prepare-commit or commit). + description: Operation to execute (discover, collect, prepare-commit or commit). required: true working-directories: - description: Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages declaring build and check:dist scripts. + description: Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages with an action manifest and a build script. Collection requires one literal directory. default: "" output-directory: description: Newline-separated generated directories or glob patterns (`*`, `**`, `?`) relative to each package. Patterns select committed directories from the trusted base revision; matches must be non-overlapping. default: dist required-files: description: Newline-separated files required in every generated directory. Empty accepts any nonempty output. - default: | - index.js - licenses.txt + default: index.js pull-request-authors: - description: JSON array of dependabot or renovate presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. + description: JSON array of dependabot, renovate or hoverkraft presets, or objects with login, numeric account ID and optional branch-prefix and commit-message-suffix. default: '["dependabot","renovate"]' artifact-name: - description: Artifact name prefix. The run attempt is appended automatically. Use the same value for build and commit. + description: Artifact name prefix. Run attempt and package identity are appended automatically. Use the same value for collection and commit. default: action-distributions build-script: - description: Package script name to run after a locked dependency installation. + description: Build script name used to discover eligible packages; this action never runs it. default: build - install-command: - description: Locked install command from ci-github-nodejs/get-package-manager. The executable must already be installed; arguments are passed without a shell. - default: npm ci --no-audit --no-fund - run-script-command: - description: Script command from ci-github-nodejs/get-package-manager, used for every selected package without a shell. - default: npm run - ignore-scripts: - description: Disable install lifecycle scripts. Set false only in the read-only builder when the package requires approved hooks. - default: "true" + retention-days: + description: Retention for uploaded artifacts, within the repository policy. + default: "1" max-artifact-size: - description: Maximum serialized artifact size in MiB (integer from 1 to 128). Use the same limit for build and writer. + description: Maximum serialized artifact size in MiB (integer from 1 to 128). The writer also enforces this limit across all selected packages. default: "20" commit-message: description: Single-line commit headline. Per-author suffixes and a loop-prevention body trailer are appended. default: "build: regenerate action distributions" workspace: - description: Absolute path of the exact PR head checkout, required for build. + description: Absolute path of the exact PR head checkout, required for collection. default: ${{ github.workspace }} artifact-path: - description: Absolute JSON artifact path to write for build or read for commit. - default: ${{ runner.temp }}/action-distributions/distributions.json + description: Directory for collected or downloaded JSON artifacts. + default: ${{ runner.temp }}/action-distributions github-token: - description: GitHub token for API calls. Use a read-only token for building and an App token only for committing. + description: GitHub token for API calls. Use a read-only token for collection and an App token only for committing. default: ${{ github.token }} outputs: working-directories: - description: JSON array of package directories selected by discover or affected packages selected by prepare-build for an eligible PR. + description: JSON array of package directories selected by discover. value: ${{ steps.distributions.outputs.working-directories }} - head-sha: - description: Eligible current PR head selected by prepare-build; empty when skipped. - value: ${{ steps.distributions.outputs.head-sha }} - built: - description: Whether build produced a validated distribution artifact. - value: ${{ steps.distributions.outputs.built }} - artifact-id: - description: Validated artifact selected by prepare-commit; empty when skipped. - value: ${{ steps.distributions.outputs.artifact-id }} + artifact-ids: + description: Comma-separated validated artifact IDs selected by prepare-commit; empty when skipped. + value: ${{ steps.distributions.outputs.artifact-ids }} runs: using: composite @@ -93,9 +79,6 @@ runs: REQUIRED_FILES: ${{ inputs.required-files }} PULL_REQUEST_AUTHORS: ${{ inputs.pull-request-authors }} ARTIFACT_NAME: ${{ inputs.artifact-name }} - INSTALL_COMMAND: ${{ inputs.install-command }} - RUN_SCRIPT_COMMAND: ${{ inputs.run-script-command }} - IGNORE_SCRIPTS: ${{ inputs.ignore-scripts }} MAX_ARTIFACT_SIZE: ${{ inputs.max-artifact-size }} BUILD_SCRIPT: ${{ inputs.build-script }} COMMIT_MESSAGE: ${{ inputs.commit-message }} @@ -109,3 +92,11 @@ runs: workspace: process.env.DISTRIBUTION_WORKSPACE, artifactPath: process.env.DISTRIBUTION_ARTIFACT_PATH, }); + - name: Upload built distribution + if: inputs.operation == 'collect' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ steps.distributions.outputs.artifact-name }} + path: ${{ steps.distributions.outputs.artifact-path }} + if-no-files-found: error + retention-days: ${{ inputs.retention-days }} diff --git a/actions/action-distributions/dist/index.js b/actions/action-distributions/dist/index.js index f8d1ff3f..6d0fa6ec 100644 --- a/actions/action-distributions/dist/index.js +++ b/actions/action-distributions/dist/index.js @@ -8646,8 +8646,6 @@ __nccwpck_require__.d(__webpack_exports__, { ;// CONCATENATED MODULE: external "node:assert/strict" const strict_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:assert/strict"); -;// CONCATENATED MODULE: external "node:child_process" -const external_node_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:child_process"); ;// CONCATENATED MODULE: external "node:crypto" const external_node_crypto_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); ;// CONCATENATED MODULE: external "node:fs" @@ -8722,7 +8720,13 @@ class DistributionCommit { ;// CONCATENATED MODULE: ./src/DistributionOptions.js + const AUTHOR_PRESETS = { + hoverkraft: { + login: "hoverkraft-bot[bot]", + id: 128996893, + "branch-prefix": "renovate/", + }, dependabot: { login: "dependabot[bot]", id: 49699333, @@ -8740,15 +8744,8 @@ class DistributionOptions { constructor(options = {}) { this.directories = this.lines(options.workingDirectories ?? ""); this.outputDirectories = this.lines(options.outputDirectory ?? "dist"); - this.installCommand = this.command( - options.installCommand ?? "npm ci --no-audit --no-fund", - ); - this.runScriptCommand = this.command(options.runScriptCommand ?? "npm run"); - this.ignoreScripts = options.ignoreScripts ?? "true"; this.maxBytes = Number(options.maxArtifactSize ?? 20) * 1024 * 1024; - this.requiredFiles = this.lines( - options.requiredFiles ?? "index.js\nlicenses.txt", - ); + this.requiredFiles = this.lines(options.requiredFiles ?? "index.js"); this.buildScript = options.buildScript ?? "build"; this.artifactName = options.artifactName ?? "action-distributions"; this.commitMessage = @@ -8781,10 +8778,6 @@ class DistributionOptions { "Invalid output directory", ); this.validateOutputDirectories(this.outputDirectories); - strict_namespaceObject( - ["true", "false"].includes(this.ignoreScripts), - "Invalid ignore-scripts value", - ); strict_namespaceObject( Number.isSafeInteger(this.maxBytes / 1024 / 1024) && this.maxBytes >= 1024 * 1024 && @@ -8811,19 +8804,6 @@ class DistributionOptions { ); } - command(value) { - strict_namespaceObject( - typeof value === "string" && value.trim(), - "Expected a package command", - ); - const parts = value.trim().split(/\s+/); - strict_namespaceObject( - parts.every((part) => /^[a-zA-Z0-9_./=:-]+$/.test(part)), - "Expected command arguments without shell syntax", - ); - return parts; - } - lines(value) { strict_namespaceObject(typeof value === "string", "Expected newline-separated input"); return value @@ -8908,8 +8888,13 @@ class DistributionOptions { ); } - artifact(attempt) { - return `${this.artifactName}-${attempt}`; + artifact(attempt, directory) { + strict_namespaceObject( + /^[1-9]\d*$/.test(String(attempt)), + "Expected a positive run attempt", + ); + const key = (0,external_node_crypto_namespaceObject.createHash)("sha256").update(directory).digest("hex"); + return `${this.artifactName}-${attempt}-${key}`; } headline(author) { @@ -8922,9 +8907,6 @@ class DistributionOptions { return { workingDirectories: process.env.WORKING_DIRECTORIES, outputDirectory: process.env.OUTPUT_DIRECTORY, - installCommand: process.env.INSTALL_COMMAND, - runScriptCommand: process.env.RUN_SCRIPT_COMMAND, - ignoreScripts: process.env.IGNORE_SCRIPTS, maxArtifactSize: process.env.MAX_ARTIFACT_SIZE, requiredFiles: process.env.REQUIRED_FILES, pullRequestAuthors: process.env.PULL_REQUEST_AUTHORS, @@ -9044,6 +9026,13 @@ class DistributionPackages { "Cannot discover packages from a truncated repository tree", ); const selected = patterns.length ? patterns : [".", "actions/**"]; + const actions = new Set( + data.tree + .filter((entry) => + ["action.yml", "action.yaml"].includes(external_node_path_namespaceObject.posix.basename(entry.path)), + ) + .map((entry) => external_node_path_namespaceObject.posix.dirname(entry.path)), + ); const packages = []; for (const entry of data.tree) { if (external_node_path_namespaceObject.posix.basename(entry.path) !== "package.json") continue; @@ -9064,6 +9053,7 @@ class DistributionPackages { continue; if (!selected.some((pattern) => external_node_path_namespaceObject.posix.matchesGlob(directory, pattern))) continue; + if (!patterns.length && !actions.has(directory)) continue; strict_namespaceObject( entry.type === "blob" && entry.mode === "100644", "Expected a regular package manifest", @@ -9077,11 +9067,8 @@ class DistributionPackages { Buffer.from(blob.content, "base64").toString("utf8"), ); if ( - [this.options.buildScript, "check:dist"].every( - (name) => - typeof manifest.scripts?.[name] === "string" && - manifest.scripts[name].trim(), - ) + typeof manifest.scripts?.[this.options.buildScript] === "string" && + manifest.scripts[this.options.buildScript].trim() ) packages.push(directory); } @@ -9212,7 +9199,6 @@ class DistributionWorkflow { - const GENERATED_BY = "Generated-by: ci-github-common/action-distributions"; const INLINE_COMMIT_BYTES = 20 * 1024 * 1024; @@ -9232,17 +9218,18 @@ class ActionDistributions { this.fullName = `${this.repo.owner}/${this.repo.repo}`; } - async run(operation, { workspace, artifactPath } = {}) { + async run( + operation, + { workspace, artifactPath, attempt = process.env.GITHUB_RUN_ATTEMPT } = {}, + ) { switch (operation) { case "discover": { const packages = await this.packages(this.context.sha); this.core.setOutput("working-directories", JSON.stringify(packages)); return; } - case "prepare-build": - return this.prepareBuild(); - case "build": - return this.build({ workspace, output: artifactPath }); + case "collect": + return this.collect({ workspace, output: artifactPath, attempt }); case "prepare-commit": return this.prepare(); case "commit": @@ -9305,70 +9292,40 @@ class ActionDistributions { return data.commit.message.split(/\r?\n/).includes(GENERATED_BY); } - async buildSource() { - const { pull_request: original, sender } = this.context.payload; - if (this.context.eventName !== "pull_request") return null; - const { data: pr } = await this.github.rest.pulls.get({ - ...this.repo, - pull_number: original.number, - }); - if ( - !this.eligible(pr, original.head.sha, original.head.ref, sender) || - (await this.generatedHead(pr.head.sha)) - ) - return null; - const packages = await this.affectedPackages(pr); - return packages.length ? { pr, packages } : null; - } - - async prepareBuild() { - const source = await this.buildSource(); - if (source) { - this.core.setOutput("head-sha", source.pr.head.sha); - this.core.setOutput( - "working-directories", - JSON.stringify(source.packages), - ); - } - } - - async build({ workspace, output, execute = external_node_child_process_namespaceObject.execFileSync }) { - const source = await this.buildSource(); - if (!source) return; - const { packages } = source; + async collect({ workspace, output, attempt }) { + const [directory] = this.options.directories; + strict_namespaceObject( + this.options.directories.length === 1 && !/[*?]/.test(directory), + "Collection requires one literal working directory", + ); + await this.outputs.resolve( + this.context.payload.pull_request?.base.sha ?? this.context.sha, + [directory], + ); const files = []; - for (const directory of packages) { - const cwd = external_node_path_namespaceObject.join(workspace, directory); - const [installer, ...installArgs] = this.options.installCommand; - if (this.options.ignoreScripts === "true") - installArgs.push("--ignore-scripts"); - execute(installer, installArgs, { cwd, stdio: "inherit" }); - const [runner, ...runArgs] = this.options.runScriptCommand; - execute(runner, [...runArgs, this.options.buildScript], { - cwd, - stdio: "inherit", - }); - for (const outputPath of this.outputs.paths(directory)) - this.collect(workspace, outputPath, files); - } + for (const outputPath of this.outputs.paths(directory)) + this.collectFiles(workspace, outputPath, files); const payload = JSON.stringify(files); strict_namespaceObject( Buffer.byteLength(payload) <= this.options.maxBytes, "Distribution artifact exceeds size limit", ); - external_node_fs_namespaceObject.mkdirSync(external_node_path_namespaceObject.dirname(output), { recursive: true }); - external_node_fs_namespaceObject.writeFileSync(output, payload); - this.readPayload(output, packages); - this.core.setOutput("built", "true"); + const name = this.options.artifact(attempt, directory); + const filename = external_node_path_namespaceObject.join(output, `${name}.json`); + external_node_fs_namespaceObject.mkdirSync(output, { recursive: true }); + external_node_fs_namespaceObject.writeFileSync(filename, payload); + this.readPayload(filename, [directory]); + this.core.setOutput("artifact-name", name); + this.core.setOutput("artifact-path", filename); } - collect(workspace, relative, files) { + collectFiles(workspace, relative, files) { const absolute = external_node_path_namespaceObject.join(workspace, relative); const stat = external_node_fs_namespaceObject.lstatSync(absolute); strict_namespaceObject(!stat.isSymbolicLink(), "Distribution symlinks are unsupported"); if (stat.isDirectory()) { for (const name of external_node_fs_namespaceObject.readdirSync(absolute).sort()) - this.collect(workspace, `${relative}/${name}`, files); + this.collectFiles(workspace, `${relative}/${name}`, files); return; } strict_namespaceObject(stat.isFile(), "Expected a regular distribution file"); @@ -9391,7 +9348,8 @@ class ActionDistributions { run_id: event.id, }); if ( - run.conclusion !== "success" || + run.status !== "completed" || + !["success", "failure"].includes(run.conclusion) || run.event !== "pull_request" || run.head_repository?.full_name !== this.fullName || !run.head_branch || @@ -9424,7 +9382,7 @@ class ActionDistributions { async prepare() { const source = await this.source(); if (!source) return; - const { run } = source; + const { run, packages } = source; const artifacts = await this.github.paginate( this.github.rest.actions.listWorkflowRunArtifacts, { @@ -9433,20 +9391,28 @@ class ActionDistributions { per_page: 100, }, ); - const matching = artifacts.filter( - (artifact) => artifact.name === this.options.artifact(run.run_attempt), - ); - strict_namespaceObject.equal( - matching.length, - 1, - "Expected one distribution artifact for this attempt", - ); + const matching = packages.map((directory) => { + const name = this.options.artifact(run.run_attempt, directory); + const found = artifacts.filter((artifact) => artifact.name === name); + strict_namespaceObject.equal( + found.length, + 1, + `Expected one distribution artifact for ${directory} in this attempt; rerun all CI jobs`, + ); + return found[0]; + }); strict_namespaceObject( - !matching[0].expired && - matching[0].size_in_bytes <= this.options.maxBytes, + matching.every((artifact) => !artifact.expired) && + matching.reduce( + (bytes, artifact) => bytes + artifact.size_in_bytes, + 0, + ) <= this.options.maxBytes, "Artifact expired or too large", ); - this.core.setOutput("artifact-id", matching[0].id); + this.core.setOutput( + "artifact-ids", + matching.map((artifact) => artifact.id).join(","), + ); } readPayload(filename, packages) { @@ -9504,8 +9470,21 @@ class ActionDistributions { return files; } - async changes(source, filename) { - const files = this.readPayload(filename, source.packages); + async changes(source, artifactPath) { + let bytes = 0; + const files = source.packages.flatMap((directory) => { + const filename = external_node_path_namespaceObject.join( + artifactPath, + `${this.options.artifact(source.run.run_attempt, directory)}.json`, + ); + bytes += external_node_fs_namespaceObject.statSync(filename).size; + strict_namespaceObject( + bytes <= this.options.maxBytes, + "Distribution artifacts exceed size limit", + ); + return this.readPayload(filename, [directory]); + }); + strict_namespaceObject(files.length <= 1000, "Invalid distribution file count"); const { data: tree } = await this.github.rest.git.getTree({ ...this.repo, tree_sha: source.pr.head.sha, diff --git a/actions/action-distributions/package.json b/actions/action-distributions/package.json index 3b25ad4d..d113c503 100644 --- a/actions/action-distributions/package.json +++ b/actions/action-distributions/package.json @@ -2,15 +2,12 @@ "name": "action-distributions", "version": "1.0.0", "private": true, - "description": "Build and commit generated action distributions with validated PR policy", + "description": "Collect and commit generated action distributions with validated PR policy", "scripts": { - "test": "node --test", + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js'", "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && ncc build src/index.js --out dist --target es2022 --no-cache --license licenses.txt", - "check:dist": "npm run build && git diff --exit-code -- dist && test -z \"$(git ls-files --others --exclude-standard -- dist)\"", "test:distribution": "node --test src/ActionDistributions.test.js", - "test:watch": "node --test --watch", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "test:watch": "node --test --watch" }, "author": "hoverkraft", "license": "MIT", diff --git a/actions/action-distributions/src/ActionDistributions.js b/actions/action-distributions/src/ActionDistributions.js index cca2326b..6f205c11 100644 --- a/actions/action-distributions/src/ActionDistributions.js +++ b/actions/action-distributions/src/ActionDistributions.js @@ -1,5 +1,4 @@ import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; @@ -29,17 +28,18 @@ class ActionDistributions { this.fullName = `${this.repo.owner}/${this.repo.repo}`; } - async run(operation, { workspace, artifactPath } = {}) { + async run( + operation, + { workspace, artifactPath, attempt = process.env.GITHUB_RUN_ATTEMPT } = {}, + ) { switch (operation) { case "discover": { const packages = await this.packages(this.context.sha); this.core.setOutput("working-directories", JSON.stringify(packages)); return; } - case "prepare-build": - return this.prepareBuild(); - case "build": - return this.build({ workspace, output: artifactPath }); + case "collect": + return this.collect({ workspace, output: artifactPath, attempt }); case "prepare-commit": return this.prepare(); case "commit": @@ -102,70 +102,40 @@ class ActionDistributions { return data.commit.message.split(/\r?\n/).includes(GENERATED_BY); } - async buildSource() { - const { pull_request: original, sender } = this.context.payload; - if (this.context.eventName !== "pull_request") return null; - const { data: pr } = await this.github.rest.pulls.get({ - ...this.repo, - pull_number: original.number, - }); - if ( - !this.eligible(pr, original.head.sha, original.head.ref, sender) || - (await this.generatedHead(pr.head.sha)) - ) - return null; - const packages = await this.affectedPackages(pr); - return packages.length ? { pr, packages } : null; - } - - async prepareBuild() { - const source = await this.buildSource(); - if (source) { - this.core.setOutput("head-sha", source.pr.head.sha); - this.core.setOutput( - "working-directories", - JSON.stringify(source.packages), - ); - } - } - - async build({ workspace, output, execute = execFileSync }) { - const source = await this.buildSource(); - if (!source) return; - const { packages } = source; + async collect({ workspace, output, attempt }) { + const [directory] = this.options.directories; + assert( + this.options.directories.length === 1 && !/[*?]/.test(directory), + "Collection requires one literal working directory", + ); + await this.outputs.resolve( + this.context.payload.pull_request?.base.sha ?? this.context.sha, + [directory], + ); const files = []; - for (const directory of packages) { - const cwd = path.join(workspace, directory); - const [installer, ...installArgs] = this.options.installCommand; - if (this.options.ignoreScripts === "true") - installArgs.push("--ignore-scripts"); - execute(installer, installArgs, { cwd, stdio: "inherit" }); - const [runner, ...runArgs] = this.options.runScriptCommand; - execute(runner, [...runArgs, this.options.buildScript], { - cwd, - stdio: "inherit", - }); - for (const outputPath of this.outputs.paths(directory)) - this.collect(workspace, outputPath, files); - } + for (const outputPath of this.outputs.paths(directory)) + this.collectFiles(workspace, outputPath, files); const payload = JSON.stringify(files); assert( Buffer.byteLength(payload) <= this.options.maxBytes, "Distribution artifact exceeds size limit", ); - fs.mkdirSync(path.dirname(output), { recursive: true }); - fs.writeFileSync(output, payload); - this.readPayload(output, packages); - this.core.setOutput("built", "true"); + const name = this.options.artifact(attempt, directory); + const filename = path.join(output, `${name}.json`); + fs.mkdirSync(output, { recursive: true }); + fs.writeFileSync(filename, payload); + this.readPayload(filename, [directory]); + this.core.setOutput("artifact-name", name); + this.core.setOutput("artifact-path", filename); } - collect(workspace, relative, files) { + collectFiles(workspace, relative, files) { const absolute = path.join(workspace, relative); const stat = fs.lstatSync(absolute); assert(!stat.isSymbolicLink(), "Distribution symlinks are unsupported"); if (stat.isDirectory()) { for (const name of fs.readdirSync(absolute).sort()) - this.collect(workspace, `${relative}/${name}`, files); + this.collectFiles(workspace, `${relative}/${name}`, files); return; } assert(stat.isFile(), "Expected a regular distribution file"); @@ -188,7 +158,8 @@ class ActionDistributions { run_id: event.id, }); if ( - run.conclusion !== "success" || + run.status !== "completed" || + !["success", "failure"].includes(run.conclusion) || run.event !== "pull_request" || run.head_repository?.full_name !== this.fullName || !run.head_branch || @@ -221,7 +192,7 @@ class ActionDistributions { async prepare() { const source = await this.source(); if (!source) return; - const { run } = source; + const { run, packages } = source; const artifacts = await this.github.paginate( this.github.rest.actions.listWorkflowRunArtifacts, { @@ -230,20 +201,28 @@ class ActionDistributions { per_page: 100, }, ); - const matching = artifacts.filter( - (artifact) => artifact.name === this.options.artifact(run.run_attempt), - ); - assert.equal( - matching.length, - 1, - "Expected one distribution artifact for this attempt", - ); + const matching = packages.map((directory) => { + const name = this.options.artifact(run.run_attempt, directory); + const found = artifacts.filter((artifact) => artifact.name === name); + assert.equal( + found.length, + 1, + `Expected one distribution artifact for ${directory} in this attempt; rerun all CI jobs`, + ); + return found[0]; + }); assert( - !matching[0].expired && - matching[0].size_in_bytes <= this.options.maxBytes, + matching.every((artifact) => !artifact.expired) && + matching.reduce( + (bytes, artifact) => bytes + artifact.size_in_bytes, + 0, + ) <= this.options.maxBytes, "Artifact expired or too large", ); - this.core.setOutput("artifact-id", matching[0].id); + this.core.setOutput( + "artifact-ids", + matching.map((artifact) => artifact.id).join(","), + ); } readPayload(filename, packages) { @@ -301,8 +280,21 @@ class ActionDistributions { return files; } - async changes(source, filename) { - const files = this.readPayload(filename, source.packages); + async changes(source, artifactPath) { + let bytes = 0; + const files = source.packages.flatMap((directory) => { + const filename = path.join( + artifactPath, + `${this.options.artifact(source.run.run_attempt, directory)}.json`, + ); + bytes += fs.statSync(filename).size; + assert( + bytes <= this.options.maxBytes, + "Distribution artifacts exceed size limit", + ); + return this.readPayload(filename, [directory]); + }); + assert(files.length <= 1000, "Invalid distribution file count"); const { data: tree } = await this.github.rest.git.getTree({ ...this.repo, tree_sha: source.pr.head.sha, diff --git a/actions/action-distributions/src/ActionDistributions.test.js b/actions/action-distributions/src/ActionDistributions.test.js index fe07f97c..7a8ae061 100644 --- a/actions/action-distributions/src/ActionDistributions.test.js +++ b/actions/action-distributions/src/ActionDistributions.test.js @@ -17,7 +17,7 @@ import { DistributionOptions } from "./DistributionOptions.js"; const PACKAGE = "actions/example"; const SHA = "a".repeat(40); const TRUSTED_SHA = "c".repeat(40); -const BUILDER_PATH = ".github/workflows/__rebuild-action-distributions.yml"; +const BUILDER_PATH = ".github/workflows/__pull-request-ci.yml"; const WRITER_PATH = ".github/workflows/__commit-action-distributions.yml"; const workflowFile = (path, text) => ({ name: path.split("/").at(-1), @@ -81,6 +81,7 @@ function fixture(t, options = {}) { id: 10, workflow_id: 3, run_attempt: 2, + status: "completed", conclusion: "success", event: "pull_request", head_sha: SHA, @@ -88,12 +89,15 @@ function fixture(t, options = {}) { head_repository: { full_name: "owner/repo" }, actor: { login: "dependabot[bot]", id: 49699333 }, }, - workflow: { path: ".github/workflows/__rebuild-action-distributions.yml" }, + workflow: { path: ".github/workflows/__pull-request-ci.yml" }, files: [{ filename: `${PACKAGE}/package-lock.json` }], artifacts: [ { id: 20, - name: "action-distributions-2", + name: new DistributionOptions(options).artifact( + 2, + options.workingDirectories ?? PACKAGE, + ), expired: false, size_in_bytes: 300, }, @@ -171,9 +175,16 @@ function fixture(t, options = {}) { }, }, }); - const filename = path.join(temporary, "distributions.json"); - const write = (files = [file("index.js"), file("licenses.txt")]) => - fs.writeFileSync(filename, JSON.stringify(files)); + const filename = path.join(temporary, "incoming"); + fs.mkdirSync(filename); + const write = ( + files = [file("index.js"), file("licenses.txt")], + directory = automation.options.directories[0] ?? PACKAGE, + ) => + fs.writeFileSync( + path.join(filename, `${automation.options.artifact(2, directory)}.json`), + JSON.stringify(files), + ); return { automation, state, context, temporary, filename, write, github }; } @@ -226,9 +237,9 @@ for (const [name, mutate] of [ }, ], [ - "failed run", + "cancelled run", (s) => { - s.run.conclusion = "failure"; + s.run.conclusion = "cancelled"; }, ], [ @@ -298,12 +309,12 @@ for (const [name, mutate] of [ mutate(state); await automation.prepare(); await automation.commit(filename); - assert.equal(state.outputs["artifact-id"], undefined); + assert.equal(state.outputs["artifact-ids"], undefined); assert.equal(state.commits.length, 0); }); } -test("selects only the artifact from the successful current attempt", async (t) => { +test("selects only the artifact from the completed current attempt", async (t) => { const { automation, state } = fixture(t); state.artifacts.push({ id: 19, @@ -311,7 +322,7 @@ test("selects only the artifact from the successful current attempt", async (t) expired: false, }); await automation.prepare(); - assert.equal(state.outputs["artifact-id"], 20); + assert.equal(state.outputs["artifact-ids"], "20"); }); for (const [name, mutate] of [ @@ -356,7 +367,7 @@ for (const [name, mutate] of [ const { automation, state } = fixture(t); mutate(state); await assert.rejects(automation.prepare()); - assert.equal(state.outputs["artifact-id"], undefined); + assert.equal(state.outputs["artifact-ids"], undefined); }); } @@ -372,7 +383,6 @@ for (const [name, files] of [ ], ["duplicate path", [file("index.js"), file("index.js")]], ["invalid encoding", [{ path: `${PACKAGE}/dist/index.js`, contents: "%%%" }]], - ["missing license", [file("index.js")]], ["missing entrypoint", [file("licenses.txt")]], ["empty artifact", []], ]) { @@ -428,111 +438,88 @@ test("grouped lockfile and bundler updates select all affected configured packag ]); }); -test("requires complete output for every package in a grouped update", async (t) => { +test("requires every affected package from the current attempt before committing a failed CI run", async (t) => { const { automation, state, filename, write } = fixture(t); automation.options.directories.push("actions/other"); state.files.push({ filename: "actions/other/package-lock.json" }); + state.run.conclusion = "failure"; write(); - await assert.rejects( - automation.commit(filename), - /Missing required distribution files/, - ); - write([ + await assert.rejects(automation.prepare(), /actions\/other/); + await assert.rejects(automation.commit(filename), /ENOENT/); + state.artifacts.push({ + ...state.artifacts[0], + id: 21, + name: automation.options.artifact(1, "actions/other"), + }); + await assert.rejects(automation.prepare(), /this attempt/); + state.artifacts[1].name = automation.options.artifact(2, "actions/other"); + const other = { + path: "actions/other/dist/index.js", + contents: encode("other"), + }; + write([other], "actions/other"); + await automation.prepare(); + assert.equal(state.outputs["artifact-ids"], "20,21"); + await automation.commit(filename); + assert.equal(state.commits.length, 1); + assert.deepEqual(state.commits[0].fileChanges.additions, [ file("index.js"), file("licenses.txt"), - { path: "actions/other/dist/index.js", contents: encode("other") }, - { path: "actions/other/dist/licenses.txt", contents: encode("MIT") }, + other, ]); - await automation.commit(filename); - assert.equal(state.commits.length, 1); - assert.equal(state.commits[0].fileChanges.additions.length, 4); -}); - -test("a human update and stale build do not execute dependency code", async (t) => { - const { automation, context, state, temporary, filename } = fixture(t); - context.eventName = "pull_request"; - context.payload.sender.login = "human"; - const execute = () => assert.fail("Unexpected execution"); - await automation.build({ workspace: temporary, output: filename, execute }); - context.payload.sender.login = "dependabot[bot]"; - state.pr.head.sha = "b".repeat(40); - await automation.build({ workspace: temporary, output: filename, execute }); - assert(!fs.existsSync(filename)); }); -test("builds with npm lifecycle scripts disabled and serializes generated bytes", async (t) => { - const { automation, context, temporary, filename, state } = fixture(t); - context.eventName = "pull_request"; - const calls = []; - await automation.build({ - workspace: temporary, - output: filename, - execute: (command, args, options) => { - calls.push({ command, args, cwd: options.cwd }); - if (args[0] !== "run") return; - fs.mkdirSync(path.join(options.cwd, "dist"), { recursive: true }); - fs.writeFileSync( - path.join(options.cwd, "dist/index.js"), - "module.exports = 42;", - ); - fs.writeFileSync(path.join(options.cwd, "dist/licenses.txt"), "MIT"); - }, - }); - assert.deepEqual( - calls.map((call) => call.args), - [ - ["ci", "--no-audit", "--no-fund", "--ignore-scripts"], - ["run", "build"], - ], - ); - assert( - calls.every( - (call) => - call.command === "npm" && call.cwd === path.join(temporary, PACKAGE), - ), - ); - assert.equal(automation.readPayload(filename, [PACKAGE]).length, 2); - assert.equal(state.outputs.built, "true"); +test("one package artifact cannot supply another package's output", async (t) => { + const { automation, state, filename, write } = fixture(t); + automation.options.directories.push("actions/other"); + state.files.push({ filename: "actions/other/package-lock.json" }); + write([ + file("index.js"), + { path: "actions/other/dist/index.js", contents: encode("other") }, + ]); + await assert.rejects(automation.commit(filename), /outside allowed/); + assert.equal(state.commits.length, 0); }); -test("builds a real package and supports no-change reruns", async (t) => { - const { automation, context, temporary, filename } = fixture(t); - context.eventName = "pull_request"; +test("collects existing output without installing or running package scripts", async (t) => { + const { automation, temporary, filename, state } = fixture(t); const directory = path.join(temporary, PACKAGE); - fs.mkdirSync(directory, { recursive: true }); + fs.mkdirSync(path.join(directory, "dist"), { recursive: true }); fs.writeFileSync( path.join(directory, "package.json"), - JSON.stringify({ - name: "fixture", - version: "1.0.0", - scripts: { build: "node build.cjs", preinstall: "exit 99" }, - }), + JSON.stringify({ scripts: { build: "exit 99", preinstall: "exit 99" } }), ); fs.writeFileSync( - path.join(directory, "package-lock.json"), - JSON.stringify({ - name: "fixture", - version: "1.0.0", - lockfileVersion: 3, - packages: { - "": { name: "fixture", version: "1.0.0", hasInstallScript: true }, - }, - }), - ); - fs.writeFileSync( - path.join(directory, "build.cjs"), - "const fs = require('node:fs'); fs.mkdirSync('dist', {recursive:true}); fs.writeFileSync('dist/index.js', 'example'); fs.writeFileSync('dist/licenses.txt', 'MIT');", + path.join(directory, "dist/index.js"), + "module.exports = 42;", ); - await automation.run("build", { - workspace: temporary, - artifactPath: filename, - }); - const first = fs.readFileSync(filename, "utf8"); - await automation.run("build", { + await automation.run("collect", { workspace: temporary, artifactPath: filename, + attempt: 2, }); - assert.equal(fs.readFileSync(filename, "utf8"), first); + assert.deepEqual( + automation.readPayload(state.outputs["artifact-path"], [PACKAGE]), + [file("index.js", "module.exports = 42;")], + ); + await automation.commit(filename); + assert.equal(state.commits.length, 1); +}); + +test("collection rejects incomplete output and symlinks before upload", async (t) => { + const { automation, temporary, filename, state } = fixture(t); + const directory = path.join(temporary, PACKAGE, "dist"); + fs.mkdirSync(directory, { recursive: true }); + const collect = () => + automation.run("collect", { + workspace: temporary, + artifactPath: filename, + attempt: 2, + }); + await assert.rejects(collect(), /file count/); + fs.symlinkSync("/etc/hosts", path.join(directory, "index.js")); + await assert.rejects(collect(), /symlinks/); + assert.deepEqual(state.outputs, {}); }); for (const [name, options] of [ @@ -569,14 +556,16 @@ const CUSTOM_AUTHOR = { "branch-prefix": "updates/", }; for (const author of [ + { login: "hoverkraft-bot[bot]", id: 128996893, "branch-prefix": "renovate/" }, { login: "renovate[bot]", id: 29139614, "branch-prefix": "renovate/" }, CUSTOM_AUTHOR, ]) { - test(`${author.login} builds and commits with its configured policy`, async (t) => { + test(`${author.login} commits with its configured policy`, async (t) => { const { automation, state, context, filename, write } = fixture(t, { pullRequestAuthors: JSON.stringify([ "dependabot", "renovate", + "hoverkraft", CUSTOM_AUTHOR, ]), artifactName: "custom-bundle", @@ -590,26 +579,20 @@ for (const author of [ context.payload.pull_request = structuredClone(state.pr); state.workflow.path = state.run.path = ".github/workflows/custom-build.yml"; state.definitions[1].name = "custom-build.yml"; - state.artifacts[0].name = "custom-bundle-2"; - context.eventName = "pull_request"; - await automation.prepareBuild(); - assert.equal(state.outputs["head-sha"], SHA); + state.artifacts[0].name = automation.options.artifact(2, PACKAGE); context.eventName = "workflow_run"; await automation.prepare(); - assert.equal(state.outputs["artifact-id"], 20); + assert.equal(state.outputs["artifact-ids"], "20"); write(); await automation.commit(filename); assert.equal(state.commits[0].message.headline, "build: update bundles"); assert.equal(state.commits[0].message.body, GENERATED_BY); state.message = `${state.commits[0].message.headline}\n\n${GENERATED_BY}`; state.outputs = {}; - context.eventName = "pull_request"; - await automation.prepareBuild(); - assert.equal(state.outputs["head-sha"], undefined); context.eventName = "workflow_run"; await automation.prepare(); await automation.commit(filename); - assert.equal(state.outputs["artifact-id"], undefined); + assert.equal(state.outputs["artifact-ids"], undefined); assert.equal( state.commits.length, 1, @@ -628,40 +611,30 @@ for (const target of ["author", "actor"]) { } await automation.prepare(); await automation.commit(filename); - context.eventName = "pull_request"; - await automation.prepareBuild(); assert.deepEqual(state.outputs, {}); assert.equal(state.commits.length, 0); }); } -test("builds and commits a root action using custom script, output and required files", async (t) => { - const { automation, context, state, temporary, filename } = fixture(t, { +test("collects and commits a root action with custom output and required files", async (t) => { + const { automation, state, temporary, filename } = fixture(t, { workingDirectories: ".", outputDirectory: "lib/bundle", requiredFiles: "main.cjs\nNOTICE", - buildScript: "bundle:ci", }); - context.eventName = "pull_request"; - const calls = []; - await automation.build({ + const destination = path.join(temporary, "lib/bundle"); + fs.mkdirSync(destination, { recursive: true }); + fs.writeFileSync(path.join(destination, "main.cjs"), "export default 42;"); + await assert.rejects( + automation.collect({ workspace: temporary, output: filename, attempt: 2 }), + /Missing required/, + ); + fs.writeFileSync(path.join(destination, "NOTICE"), "MIT"); + await automation.collect({ workspace: temporary, output: filename, - execute: (_command, args, { cwd }) => { - calls.push(args); - assert.equal(cwd, temporary); - if (args[0] !== "run") return; - const destination = path.join(cwd, "lib/bundle"); - fs.mkdirSync(destination, { recursive: true }); - fs.writeFileSync( - path.join(destination, "main.cjs"), - "export default 42;", - ); - fs.writeFileSync(path.join(destination, "NOTICE"), "MIT"); - }, + attempt: 2, }); - assert.deepEqual(calls[1], ["run", "bundle:ci"]); - context.eventName = "workflow_run"; await automation.commit(filename); assert.deepEqual( state.commits[0].fileChanges.additions.map((entry) => entry.path), @@ -689,13 +662,13 @@ test("an empty required-files input still requires output for each affected pack assert.equal(state.commits.length, 1); automation.options.directories.push("actions/other"); state.files.push({ filename: "actions/other/package.json" }); - await assert.rejects(automation.commit(filename), /Missing required/); + await assert.rejects(automation.commit(filename), /ENOENT/); }); test("the action entrypoint prepares and commits the validated artifact", async (t) => { const { automation, state, filename, write } = fixture(t); await automation.run("prepare-commit"); - assert.equal(state.outputs["artifact-id"], 20); + assert.equal(state.outputs["artifact-ids"], "20"); write(); await automation.run("commit", { artifactPath: filename }); assert.equal(state.commits.length, 1); @@ -739,6 +712,7 @@ test("automatic writer discovery uses only base manifests and rejects newly intr mode: "100644", sha: "manifest", }, + { path: `${PACKAGE}/action.yml`, type: "blob", mode: "100644" }, ], }, }; @@ -750,7 +724,7 @@ test("automatic writer discovery uses only base manifests and rejects newly intr encoding: "base64", content: encode( JSON.stringify({ - scripts: { build: "build", "check:dist": "check" }, + scripts: { build: "build" }, }), ), }, @@ -772,7 +746,7 @@ test("resolves the builder only from the writer's pinned default-branch configur state.run.name = "PR-controlled name"; state.workflow.name = "PR-controlled registry name"; await automation.prepare(); - assert.equal(state.outputs["artifact-id"], 20); + assert.equal(state.outputs["artifact-ids"], "20"); assert.deepEqual(state.workflowReads, [ { owner: "owner", @@ -908,7 +882,7 @@ for (const trigger of [ "run-name: &builder Build\non: {workflow_run: {workflows: [*builder]}}"; state.definitions[1].object.text = `name: Build\non: ${trigger}`; await automation.prepare(); - assert.equal(state.outputs["artifact-id"], 20); + assert.equal(state.outputs["artifact-ids"], "20"); }); } @@ -917,66 +891,38 @@ test("supports the workflow path as its default name and a scalar filter", async state.definitions[0].object.text = `on: {workflow_run: {workflows: ${BUILDER_PATH}}}`; state.definitions[1].object.text = "on: pull_request"; await automation.prepare(); - assert.equal(state.outputs["artifact-id"], 20); + assert.equal(state.outputs["artifact-ids"], "20"); }); for (const outputPattern of [false, true]) { - for (const ignoreScripts of ["true", "false"]) { - test(`builds and commits workspace outputs with glob=${outputPattern} and ignore-scripts=${ignoreScripts}`, async (t) => { - // Arrange - const outputs = ["actions/a/dist", "actions/b/dist"]; - const { automation, context, temporary, filename, state } = fixture(t, { - workingDirectories: ".", - outputDirectory: outputPattern ? "actions/**/dist" : outputs.join("\n"), - requiredFiles: "index.js", - installCommand: "pnpm install --frozen-lockfile", - runScriptCommand: "pnpm", - ignoreScripts, - buildScript: "package", - }); - context.eventName = "pull_request"; - state.files = [{ filename: "pnpm-lock.yaml" }]; - state.baseTree.tree = outputs.map((path) => ({ - path, - type: "tree", - mode: "040000", - })); - const calls = []; - // Act - await automation.build({ - workspace: temporary, - output: filename, - execute: (command, args, { cwd }) => { - calls.push({ command, args, cwd }); - if (args[0] !== "package") return; - for (const output of outputs) { - fs.mkdirSync(path.join(cwd, output), { recursive: true }); - fs.writeFileSync(path.join(cwd, output, "index.js"), "bundle"); - } - }, - }); - context.eventName = "workflow_run"; - await automation.commit(filename); - // Assert - assert.deepEqual(calls, [ - { - command: "pnpm", - args: [ - "install", - "--frozen-lockfile", - ...(ignoreScripts === "true" ? ["--ignore-scripts"] : []), - ], - cwd: temporary, - }, - { command: "pnpm", args: ["package"], cwd: temporary }, - ]); - assert.equal(state.commits.length, 1); - assert.deepEqual( - state.commits[0].fileChanges.additions.map((file) => file.path), - outputs.map((output) => `${output}/index.js`), - ); + test(`collects and commits workspace outputs with glob=${outputPattern}`, async (t) => { + const outputs = ["actions/a/dist", "actions/b/dist"]; + const { automation, temporary, filename, state } = fixture(t, { + workingDirectories: ".", + outputDirectory: outputPattern ? "actions/**/dist" : outputs.join("\n"), + }); + state.files = [{ filename: "pnpm-lock.yaml" }]; + state.baseTree.tree = outputs.map((path) => ({ + path, + type: "tree", + mode: "040000", + })); + for (const output of outputs) { + fs.mkdirSync(path.join(temporary, output), { recursive: true }); + fs.writeFileSync(path.join(temporary, output, "index.js"), "bundle"); + } + await automation.collect({ + workspace: temporary, + output: filename, + attempt: 2, }); - } + await automation.commit(filename); + assert.equal(state.commits.length, 1); + assert.deepEqual( + state.commits[0].fileChanges.additions.map((file) => file.path), + outputs.map((output) => `${output}/index.js`), + ); + }); } for (const outputDirectory of [ @@ -991,18 +937,12 @@ for (const outputDirectory of [ } for (const options of [ - { installCommand: "" }, - { installCommand: "npm ci && echo unsafe" }, - { installCommand: "npm ci;echo unsafe" }, - { runScriptCommand: "npm $(echo unsafe)" }, - { runScriptCommand: "" }, - { ignoreScripts: "yes" }, { maxArtifactSize: 0 }, { maxArtifactSize: 129 }, { maxArtifactSize: 1.5 }, { maxArtifactSize: "bad" }, ]) { - test(`rejects invalid build settings ${JSON.stringify(options)}`, () => { + test(`rejects invalid artifact limits ${JSON.stringify(options)}`, () => { assert.throws(() => new DistributionOptions(options)); }); } @@ -1134,67 +1074,13 @@ test("large artifacts use blob publication with a guarded single commit", async test("the trusted writer enforces its own size limit before reading an oversized payload", async (t) => { // Arrange - const { automation, state, filename } = fixture(t, { maxArtifactSize: 1 }); - const descriptor = fs.openSync(filename, "w"); - fs.ftruncateSync(descriptor, 1024 * 1024 + 1); - fs.closeSync(descriptor); + const { automation, state, filename, write } = fixture(t, { + maxArtifactSize: 1, + }); + write([file("index.js", "a".repeat(1024 * 1024))]); // Act const result = automation.commit(filename); // Assert await assert.rejects(result, /size limit/); assert.deepEqual(state.commits, []); }); - -test("preparation exposes only eligible affected directories for shared tooling setup", async (t) => { - // Arrange - const { automation, state, context } = fixture(t); - automation.options.directories.push("actions/unaffected"); - context.eventName = "pull_request"; - // Act - await automation.prepareBuild(); - // Assert - assert.deepEqual(state.outputs, { - "head-sha": SHA, - "working-directories": JSON.stringify([PACKAGE]), - }); -}); - -test("detected install commands run independently in every affected package", async (t) => { - // Arrange - const { automation, state, context, temporary, filename } = fixture(t, { - installCommand: "npm ci", - runScriptCommand: "npm run", - }); - automation.options.directories.push("actions/other"); - state.files.push({ filename: "actions/other/package-lock.json" }); - context.eventName = "pull_request"; - const calls = []; - // Act - await automation.build({ - workspace: temporary, - output: filename, - execute: (command, args, { cwd }) => { - calls.push({ command, args, cwd }); - if (args[0] !== "run") return; - fs.mkdirSync(path.join(cwd, "dist"), { recursive: true }); - fs.writeFileSync(path.join(cwd, "dist/index.js"), "bundle"); - fs.writeFileSync(path.join(cwd, "dist/licenses.txt"), "MIT"); - }, - }); - // Assert - assert.deepEqual( - calls.map(({ args }) => args), - [ - ["ci", "--ignore-scripts"], - ["run", "build"], - ["ci", "--ignore-scripts"], - ["run", "build"], - ], - ); - assert.deepEqual( - calls.map(({ cwd }) => cwd), - [PACKAGE, PACKAGE, "actions/other", "actions/other"].map((directory) => - path.join(temporary, directory), - ), - ); -}); diff --git a/actions/action-distributions/src/BuildWorkflow.test.js b/actions/action-distributions/src/BuildWorkflow.test.js deleted file mode 100644 index 9754853d..00000000 --- a/actions/action-distributions/src/BuildWorkflow.test.js +++ /dev/null @@ -1,63 +0,0 @@ -import assert from "node:assert/strict"; -import fs from "node:fs"; -import { test } from "node:test"; -import { parse } from "yaml"; - -test("configures eligible affected packages and forwards shared commands only to the read-only builder", () => { - // Arrange - const workflow = parse( - fs.readFileSync( - new URL( - "../../../.github/workflows/action-distributions.yml", - import.meta.url, - ), - "utf8", - ), - ); - const steps = workflow.jobs.rebuild.steps; - const sharedSetup = steps.find((step) => - step.uses?.startsWith( - "hoverkraft-tech/ci-github-nodejs/actions/setup-node@", - ), - ); - const commands = steps.find((step) => - step.uses?.startsWith( - "hoverkraft-tech/ci-github-nodejs/actions/get-package-manager@", - ), - ); - const runtime = steps.find((step) => - step.uses?.startsWith("actions/setup-node@"), - ); - const build = steps.find((step) => step.id === "build"); - // Act - const directory = sharedSetup.with["working-directory"]; - const writerActions = workflow.jobs.commit.steps.map((step) => step.uses); - // Assert - assert.equal( - directory, - `source/\${{ fromJSON(steps.prepare.outputs.working-directories)[0] }}`, - ); - assert.equal(commands.with["working-directory"], directory); - assert.equal(sharedSetup.with["install-dependencies"], "false"); - for (const step of [sharedSetup, commands, runtime, build]) - assert.equal(step.if, "steps.prepare.outputs.head-sha"); - assert(steps.indexOf(sharedSetup) < steps.indexOf(runtime)); - assert(steps.indexOf(runtime) < steps.indexOf(build)); - assert.equal(runtime.with["node-version"], `\${{ inputs.node-version }}`); - assert.equal( - build.with["install-command"], - `\${{ steps.package-manager.outputs.install-command }}`, - ); - assert.equal( - build.with["run-script-command"], - `\${{ steps.package-manager.outputs.run-script-command }}`, - ); - assert.equal(build.with["ignore-scripts"], `\${{ inputs.ignore-scripts }}`); - assert.deepEqual(workflow.jobs.rebuild.permissions, { - contents: "read", - "pull-requests": "read", - }); - assert( - !writerActions.some((action) => /ci-github-nodejs|setup-node/.test(action)), - ); -}); diff --git a/actions/action-distributions/src/DistributionOptions.js b/actions/action-distributions/src/DistributionOptions.js index 9cfa64b4..2ca963a4 100644 --- a/actions/action-distributions/src/DistributionOptions.js +++ b/actions/action-distributions/src/DistributionOptions.js @@ -1,6 +1,12 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; const AUTHOR_PRESETS = { + hoverkraft: { + login: "hoverkraft-bot[bot]", + id: 128996893, + "branch-prefix": "renovate/", + }, dependabot: { login: "dependabot[bot]", id: 49699333, @@ -18,15 +24,8 @@ class DistributionOptions { constructor(options = {}) { this.directories = this.lines(options.workingDirectories ?? ""); this.outputDirectories = this.lines(options.outputDirectory ?? "dist"); - this.installCommand = this.command( - options.installCommand ?? "npm ci --no-audit --no-fund", - ); - this.runScriptCommand = this.command(options.runScriptCommand ?? "npm run"); - this.ignoreScripts = options.ignoreScripts ?? "true"; this.maxBytes = Number(options.maxArtifactSize ?? 20) * 1024 * 1024; - this.requiredFiles = this.lines( - options.requiredFiles ?? "index.js\nlicenses.txt", - ); + this.requiredFiles = this.lines(options.requiredFiles ?? "index.js"); this.buildScript = options.buildScript ?? "build"; this.artifactName = options.artifactName ?? "action-distributions"; this.commitMessage = @@ -59,10 +58,6 @@ class DistributionOptions { "Invalid output directory", ); this.validateOutputDirectories(this.outputDirectories); - assert( - ["true", "false"].includes(this.ignoreScripts), - "Invalid ignore-scripts value", - ); assert( Number.isSafeInteger(this.maxBytes / 1024 / 1024) && this.maxBytes >= 1024 * 1024 && @@ -89,19 +84,6 @@ class DistributionOptions { ); } - command(value) { - assert( - typeof value === "string" && value.trim(), - "Expected a package command", - ); - const parts = value.trim().split(/\s+/); - assert( - parts.every((part) => /^[a-zA-Z0-9_./=:-]+$/.test(part)), - "Expected command arguments without shell syntax", - ); - return parts; - } - lines(value) { assert(typeof value === "string", "Expected newline-separated input"); return value @@ -186,8 +168,13 @@ class DistributionOptions { ); } - artifact(attempt) { - return `${this.artifactName}-${attempt}`; + artifact(attempt, directory) { + assert( + /^[1-9]\d*$/.test(String(attempt)), + "Expected a positive run attempt", + ); + const key = createHash("sha256").update(directory).digest("hex"); + return `${this.artifactName}-${attempt}-${key}`; } headline(author) { @@ -200,9 +187,6 @@ class DistributionOptions { return { workingDirectories: process.env.WORKING_DIRECTORIES, outputDirectory: process.env.OUTPUT_DIRECTORY, - installCommand: process.env.INSTALL_COMMAND, - runScriptCommand: process.env.RUN_SCRIPT_COMMAND, - ignoreScripts: process.env.IGNORE_SCRIPTS, maxArtifactSize: process.env.MAX_ARTIFACT_SIZE, requiredFiles: process.env.REQUIRED_FILES, pullRequestAuthors: process.env.PULL_REQUEST_AUTHORS, diff --git a/actions/action-distributions/src/DistributionPackages.js b/actions/action-distributions/src/DistributionPackages.js index 74acfa53..0525f546 100644 --- a/actions/action-distributions/src/DistributionPackages.js +++ b/actions/action-distributions/src/DistributionPackages.js @@ -24,6 +24,13 @@ class DistributionPackages { "Cannot discover packages from a truncated repository tree", ); const selected = patterns.length ? patterns : [".", "actions/**"]; + const actions = new Set( + data.tree + .filter((entry) => + ["action.yml", "action.yaml"].includes(path.basename(entry.path)), + ) + .map((entry) => path.dirname(entry.path)), + ); const packages = []; for (const entry of data.tree) { if (path.basename(entry.path) !== "package.json") continue; @@ -44,6 +51,7 @@ class DistributionPackages { continue; if (!selected.some((pattern) => path.matchesGlob(directory, pattern))) continue; + if (!patterns.length && !actions.has(directory)) continue; assert( entry.type === "blob" && entry.mode === "100644", "Expected a regular package manifest", @@ -57,11 +65,8 @@ class DistributionPackages { Buffer.from(blob.content, "base64").toString("utf8"), ); if ( - [this.options.buildScript, "check:dist"].every( - (name) => - typeof manifest.scripts?.[name] === "string" && - manifest.scripts[name].trim(), - ) + typeof manifest.scripts?.[this.options.buildScript] === "string" && + manifest.scripts[this.options.buildScript].trim() ) packages.push(directory); } diff --git a/actions/action-distributions/src/DistributionPackages.test.js b/actions/action-distributions/src/DistributionPackages.test.js index efe6583e..4946c069 100644 --- a/actions/action-distributions/src/DistributionPackages.test.js +++ b/actions/action-distributions/src/DistributionPackages.test.js @@ -3,16 +3,24 @@ import { test } from "node:test"; import { DistributionOptions } from "./DistributionOptions.js"; import { DistributionPackages } from "./DistributionPackages.js"; -function fixture(packages, options = {}) { +function fixture(packages, options = {}, actions = Object.keys(packages)) { const requests = []; const tree = { truncated: false, - tree: Object.keys(packages).map((directory) => ({ - path: directory === "." ? "package.json" : `${directory}/package.json`, - type: "blob", - mode: "100644", - sha: directory, - })), + tree: Object.keys(packages) + .map((directory) => ({ + path: directory === "." ? "package.json" : `${directory}/package.json`, + type: "blob", + mode: "100644", + sha: directory, + })) + .concat( + actions.map((directory) => ({ + path: directory === "." ? "action.yml" : `${directory}/action.yml`, + type: "blob", + mode: "100644", + })), + ), }; const github = { rest: { @@ -42,7 +50,7 @@ function fixture(packages, options = {}) { ), }; } -const bundled = { scripts: { build: "build", "check:dist": "check" } }; +const bundled = { scripts: { build: "build" } }; test("discovers nested action packages, excludes installed/generated manifests and non-bundled packages", async () => { const { packages, requests } = fixture({ @@ -52,7 +60,7 @@ test("discovers nested action packages, excludes installed/generated manifests a "actions/group/a/dist/dependency": bundled, "actions/.hidden": bundled, "tests/fixture": bundled, - ".": { scripts: { build: "build" } }, + ".": { scripts: { test: "test" } }, "actions/plain": { scripts: { test: "test" } }, }); assert.deepEqual(await packages.discover("revision"), [ @@ -69,6 +77,13 @@ test("discovers a standalone root action", async () => { ); }); +test("default discovery excludes application builds without an action manifest", async () => { + const { packages } = fixture({ ".": bundled, "actions/a": bundled }, {}, [ + "actions/a", + ]); + assert.deepEqual(await packages.discover("revision"), ["actions/a"]); +}); + for (const outputDirectory of [ "actions/a/dist\nactions/b/dist", "actions/**/dist", @@ -121,7 +136,7 @@ test("no eligible packages yields an empty matrix", async () => { test("discovery honors a configured build script", async () => { const { packages } = fixture( - { "actions/a": { scripts: { bundle: "bundle", "check:dist": "check" } } }, + { "actions/a": { scripts: { bundle: "bundle" } } }, { buildScript: "bundle" }, ); assert.deepEqual(await packages.discover("revision"), ["actions/a"]); diff --git a/actions/create-and-merge-pull-request/package.json b/actions/create-and-merge-pull-request/package.json index e03ff42b..1f9dd37b 100644 --- a/actions/create-and-merge-pull-request/package.json +++ b/actions/create-and-merge-pull-request/package.json @@ -5,9 +5,7 @@ "description": "Create scoped pull requests and merge the expected commit", "type": "module", "scripts": { - "test": "node --test", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js'" }, "author": "hoverkraft", "license": "MIT", diff --git a/actions/download-artifact/package.json b/actions/download-artifact/package.json index ba5aec1b..1af78e77 100644 --- a/actions/download-artifact/package.json +++ b/actions/download-artifact/package.json @@ -3,13 +3,9 @@ "version": "1.0.0", "description": "Download artifact IDs with bounded retries for delayed availability", "scripts": { - "test": "node --test", + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js'", "test:watch": "node --test --watch", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test", - "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && ncc build src/index.js --out dist --target es2022 --no-cache --minify --license licenses.txt", - "check:dist": "npm run build && git diff --exit-code -- dist && test -z \"$(git ls-files --others --exclude-standard -- dist)\"", - "test:distribution": "node --test src/index.test.js", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && ncc build src/index.js --out dist --target es2022 --no-cache --minify --license licenses.txt" }, "keywords": [ "github-action", diff --git a/actions/need-fix-to-issue/package.json b/actions/need-fix-to-issue/package.json index a53e1467..1b687ed6 100644 --- a/actions/need-fix-to-issue/package.json +++ b/actions/need-fix-to-issue/package.json @@ -5,9 +5,7 @@ "description": "Create and categorize TODO/FIXME issues and close duplicates", "type": "module", "scripts": { - "test": "node --test", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js'" }, "author": "hoverkraft", "license": "MIT", diff --git a/actions/quality/discard-report-fixtures/package.json b/actions/quality/discard-report-fixtures/package.json index 40446203..e6edfde3 100644 --- a/actions/quality/discard-report-fixtures/package.json +++ b/actions/quality/discard-report-fixtures/package.json @@ -5,12 +5,8 @@ "type": "module", "description": "Validate and remove negative reporting fixtures from the current run", "scripts": { - "test": "node --test \"src/**/*.test.js\"", - "build": "node -e \"require('node:fs').rmSync('dist', {recursive:true,force:true})\" && ncc build src/index.js --out dist --target es2022 --no-cache --minify --license licenses.txt", - "check:dist": "npm run build && git diff --exit-code -- dist && test -z \"$(git ls-files --others --exclude-standard -- dist)\"", - "test:distribution": "node --test \"src/**/*.test.js\"", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" \"src/**/*.test.js\"", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js' \"src/**/*.test.js\"", + "build": "node -e \"require('node:fs').rmSync('dist', {recursive:true,force:true})\" && ncc build src/index.js --out dist --target es2022 --no-cache --minify --license licenses.txt" }, "engines": { "node": ">=24.0.0" diff --git a/actions/quality/lint-pull-request-title/package.json b/actions/quality/lint-pull-request-title/package.json index 117a153b..81e08fe0 100644 --- a/actions/quality/lint-pull-request-title/package.json +++ b/actions/quality/lint-pull-request-title/package.json @@ -5,9 +5,7 @@ "description": "Validate pull request titles with the common Conventional Commits policy", "type": "module", "scripts": { - "test": "node --test", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js'" }, "author": "hoverkraft", "license": "MIT", diff --git a/actions/quality/prepare-ci-reports/README.md b/actions/quality/prepare-ci-reports/README.md index 4ddf5d93..1b4b8000 100644 --- a/actions/quality/prepare-ci-reports/README.md +++ b/actions/quality/prepare-ci-reports/README.md @@ -45,7 +45,7 @@ when the command fails, so diagnostic reports remain available. env: CI_REPORTS_DIR: ${{ steps.report-directory.outputs.path }} run: ./scripts/integration-tests -- uses: hoverkraft-tech/ci-github-common/actions/quality/prepare-ci-reports@d22d9532441a353f54431721affbf3ec7874034b # PR #683 +- uses: hoverkraft-tech/ci-github-common/actions/quality/prepare-ci-reports@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 if: ${{ !cancelled() && steps.report-directory.outcome == 'success' }} with: directory: ${{ steps.report-directory.outputs.path }} diff --git a/actions/quality/prepare-ci-reports/action.yml b/actions/quality/prepare-ci-reports/action.yml index c5d50758..6c8f1e37 100644 --- a/actions/quality/prepare-ci-reports/action.yml +++ b/actions/quality/prepare-ci-reports/action.yml @@ -18,7 +18,7 @@ # env: # CI_REPORTS_DIR: ${{ steps.report-directory.outputs.path }} # run: ./scripts/integration-tests -# - uses: hoverkraft-tech/ci-github-common/actions/quality/prepare-ci-reports@d22d9532441a353f54431721affbf3ec7874034b # PR #683 +# - uses: hoverkraft-tech/ci-github-common/actions/quality/prepare-ci-reports@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 # if: ${{ !cancelled() && steps.report-directory.outcome == 'success' }} # with: # directory: ${{ steps.report-directory.outputs.path }} diff --git a/actions/quality/prepare-ci-reports/package.json b/actions/quality/prepare-ci-reports/package.json index cf302245..b71e9c3e 100644 --- a/actions/quality/prepare-ci-reports/package.json +++ b/actions/quality/prepare-ci-reports/package.json @@ -10,7 +10,6 @@ "scripts": { "test": "npm run patch:dependencies && node --test src/*.test.js", "build": "npm run patch:dependencies && node -e \"require('node:fs').rmSync('dist', {recursive:true,force:true})\" && ncc build src/index.js -o dist --target es2022 --no-cache --minify --license licenses.txt && cp node_modules/ctrf/dist/ctrf-schema-*.json dist/", - "check:dist": "npm run build && git diff --exit-code -- dist && test -z \"$(git ls-files --others --exclude-standard -- dist)\"", "test:distribution": "node --test src/PrepareReports.test.js", "test:ci": "npm run patch:dependencies && node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" src/*.test.js", "patch:dependencies": "patch-package --error-on-fail", diff --git a/actions/quality/publish-ci-reports/package.json b/actions/quality/publish-ci-reports/package.json index 8fcd2ea0..0d2e7713 100644 --- a/actions/quality/publish-ci-reports/package.json +++ b/actions/quality/publish-ci-reports/package.json @@ -8,12 +8,8 @@ "node": ">=24" }, "scripts": { - "test": "node --test src/*.test.js tests/*.test.js", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" src/*.test.js tests/*.test.js", - "build": "node -e \"require('node:fs').rmSync('dist', {recursive:true,force:true})\" && ncc build src/index.js -o dist --target es2022 --no-cache --minify --license licenses.txt", - "check:dist": "npm run build && git diff --exit-code -- dist && test -z \"$(git ls-files --others --exclude-standard -- dist)\"", - "test:distribution": "npm test", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js' src/*.test.js tests/*.test.js", + "build": "node -e \"require('node:fs').rmSync('dist', {recursive:true,force:true})\" && ncc build src/index.js -o dist --target es2022 --no-cache --minify --license licenses.txt" }, "dependencies": { "handlebars": "4.7.10" diff --git a/actions/quality/test-action-distribution/README.md b/actions/quality/test-action-distribution/README.md index f03648a9..46b115d6 100644 --- a/actions/quality/test-action-distribution/README.md +++ b/actions/quality/test-action-distribution/README.md @@ -24,12 +24,13 @@ ## Overview Run a package's distribution contract tests against an isolated copy of its bundle. -The package must declare a `test:distribution` npm script. Its tests load the +The action runs the package's `test` npm script. An optional `test:distribution` +script selects a different contract suite. Tests load the absolute `ACTION_ENTRYPOINT` path supplied by this action instead of source. Dependencies needed by the tests may be installed in the package; the copied bundle has no adjacent node_modules. Temporary files are removed even on failure. -Use the [test workflow](../../../.github/workflows/test-action-distributions.md) -to discover packages, install dependencies and verify checked-in distributions. +Node.js [continuous integration](https://github.com/hoverkraft-tech/ci-github-nodejs/blob/main/.github/workflows/continuous-integration.md) +installs dependencies and verifies checked-in distributions for the selected package. diff --git a/actions/quality/test-action-distribution/action.yml b/actions/quality/test-action-distribution/action.yml index 5fd668b7..2832504f 100644 --- a/actions/quality/test-action-distribution/action.yml +++ b/actions/quality/test-action-distribution/action.yml @@ -1,12 +1,13 @@ name: Test action distribution description: | Run a package's distribution contract tests against an isolated copy of its bundle. - The package must declare a `test:distribution` npm script. Its tests load the + The action runs the package's `test` npm script. An optional `test:distribution` + script selects a different contract suite. Tests load the absolute `ACTION_ENTRYPOINT` path supplied by this action instead of source. Dependencies needed by the tests may be installed in the package; the copied bundle has no adjacent node_modules. Temporary files are removed even on failure. - Use the [test workflow](../../../.github/workflows/test-action-distributions.md) - to discover packages, install dependencies and verify checked-in distributions. + Node.js [continuous integration](https://github.com/hoverkraft-tech/ci-github-nodejs/blob/main/.github/workflows/continuous-integration.md) + installs dependencies and verifies checked-in distributions for the selected package. author: hoverkraft branding: icon: check-circle diff --git a/actions/quality/test-action-distribution/package.json b/actions/quality/test-action-distribution/package.json index 15acf502..1890dc3d 100644 --- a/actions/quality/test-action-distribution/package.json +++ b/actions/quality/test-action-distribution/package.json @@ -2,10 +2,8 @@ "name": "test-action-distribution", "private": true, "scripts": { - "test": "node --test", - "test:watch": "node --test --watch", - "test:ci": "node $(test \"${CI_TEST_COVERAGE:-true}\" = true && printf %s --experimental-test-coverage) --test-coverage-include='src/**' --test-coverage-exclude='src/**/*.test.js' --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/junit.xml\" --test-reporter=lcov --test-reporter-destination=\"${CI_REPORTS_DIR:-.reports}/lcov.info\" --test", - "pretest:ci": "mkdir -p \"${CI_REPORTS_DIR:-.reports}\"" + "test": "node --test '--test-coverage-include=src/**' '--test-coverage-exclude=src/**/*.test.js'", + "test:watch": "node --test --watch" }, "engines": { "node": ">=24.0.0" diff --git a/actions/quality/test-action-distribution/src/DistributionTest.js b/actions/quality/test-action-distribution/src/DistributionTest.js index 0a702796..11074e60 100644 --- a/actions/quality/test-action-distribution/src/DistributionTest.js +++ b/actions/quality/test-action-distribution/src/DistributionTest.js @@ -18,9 +18,13 @@ class DistributionTest { const manifest = JSON.parse( fs.readFileSync(path.join(cwd, "package.json"), "utf8"), ); + const script = Object.hasOwn(manifest.scripts || {}, "test:distribution") + ? "test:distribution" + : "test"; assert( - manifest.scripts?.["test:distribution"]?.trim(), - "Expected a test:distribution script that loads ACTION_ENTRYPOINT", + typeof manifest.scripts?.[script] === "string" && + manifest.scripts[script].trim(), + "Expected a test or test:distribution script that loads ACTION_ENTRYPOINT", ); assert( !path.isAbsolute(outputDirectory) && @@ -41,7 +45,7 @@ class DistributionTest { try { const distribution = path.join(temporary, "dist"); await this.io.cp(source, distribution, { recursive: true }); - await this.exec.exec("npm", ["run", "test:distribution"], { + await this.exec.exec("npm", ["run", script], { cwd, env: { ...process.env, diff --git a/actions/quality/test-action-distribution/src/DistributionTest.test.js b/actions/quality/test-action-distribution/src/DistributionTest.test.js index 7db28904..e8c3926c 100644 --- a/actions/quality/test-action-distribution/src/DistributionTest.test.js +++ b/actions/quality/test-action-distribution/src/DistributionTest.test.js @@ -15,7 +15,7 @@ function fixture(t) { fs.mkdirSync(temporary); fs.writeFileSync( path.join(workspace, "package.json"), - JSON.stringify({ scripts: { "test:distribution": "node contract.cjs" } }), + JSON.stringify({ scripts: { test: "node contract.cjs" } }), ); fs.writeFileSync( path.join(workspace, "contract.cjs"), @@ -50,6 +50,17 @@ test("executes the package's contracts against only the copied bundle and cleans assert.deepEqual(fs.readdirSync(temporary), []); }); +test("a dedicated distribution script takes precedence over source tests", async (t) => { + const { workspace, run } = fixture(t); + fs.writeFileSync( + path.join(workspace, "package.json"), + JSON.stringify({ + scripts: { test: "exit 1", "test:distribution": "node contract.cjs" }, + }), + ); + await run(); +}); + test("missing bundled dependencies fail even when installed beside source; cleanup still runs", async (t) => { const { workspace, run, temporary } = fixture(t); fs.mkdirSync(path.join(workspace, "node_modules/fixture-dependency"), { diff --git a/docs/README.md b/docs/README.md index a1918b55..01553294 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,3 +7,5 @@ - [ADR 0002: Distribute and maintain action-owned dependencies](adr/0002-audit-action-dependency-distributions.md) - [ADR 0003: Retry artifact consumption](adr/0003-retry-artifact-consumption.md) - [ADR 0004: Unified CI reporting](adr/0004-native-github-coverage.md) +- [ADR 0005: Simplify action development commands](adr/0005-action-development-contract.md) +- [ADR 0006: Reuse normal CI builds for distribution maintenance](adr/0006-reuse-ci-action-builds.md) diff --git a/docs/adr/0002-audit-action-dependency-distributions.md b/docs/adr/0002-audit-action-dependency-distributions.md index a1692076..cdfc853e 100644 --- a/docs/adr/0002-audit-action-dependency-distributions.md +++ b/docs/adr/0002-audit-action-dependency-distributions.md @@ -1,6 +1,7 @@ # ADR 0002: Distribute and maintain action-owned dependencies -- Status: Accepted +- Status: Accepted; package discovery and test-script requirements superseded by [ADR 0005](0005-action-development-contract.md) +- Distribution rebuilding superseded by [ADR 0006](0006-reuse-ci-action-builds.md) - Date: 2026-11-08 - Updated: 2026-11-09 - Related: [CI optimization issue](https://github.com/cloud-native-aixmarseille/pleey/issues/475) diff --git a/docs/adr/0005-action-development-contract.md b/docs/adr/0005-action-development-contract.md new file mode 100644 index 00000000..64c1213c --- /dev/null +++ b/docs/adr/0005-action-development-contract.md @@ -0,0 +1,54 @@ +# ADR 0005: Simplify action development commands + +- Status: Partially superseded by [ADR 0006](0006-action-project-ci.md) +- Date: 2026-12-05 +- Supersedes: The package-discovery and test-script requirements in [ADR 0002](0002-audit-action-dependency-distributions.md) + +## Context + +Action packages repeated distribution comparisons and CI reporter commands. +Aliases for distribution tests repeated the source test command. Host and container +jobs rebuilt the same package independently. These conventions obscure which +checks protect source behavior, committed distributions and action integration. + +## Decision + +An action package owns its native `test` and optional `build` commands. Node's +existing test preset configures CI reporting; custom commands remain available +for actual orchestration. Source coverage is collected once. Dedicated action +integration workflows remain responsible for their public behavior. + +Default distribution discovery selects root and `actions/**` packages with an +adjacent action manifest and the selected build script. A copied `check:dist` +script is no longer required. Explicit directory and glob overrides retain their +support for other layouts, including workspace builds. Missing committed output +must fail verification rather than remove a package from discovery. + +The shared test workflow owns freshness verification, including staged changes, +untracked files and deleted output. Only its host job rebuilds; both host and +container jobs execute the committed bundle in isolation. The isolated tester +uses `test` by default, or `test:distribution` when a different contract suite is +needed. Contract tests must load `ACTION_ENTRYPOINT` rather than source. + +The `hoverkraft` author preset centralizes the existing immutable bot ID and +Renovate branch restriction. It requires explicit opt-in and does not change the +default authorization policy. + +Repositories expose `make setup`, `make test`, `make build`, `make lint` and +`make ci`, with `make lint-fix` as a separate mutation. Setup uses lockfiles; +CI propagates failures and does not run audit or lint fixes. Native package +managers own dependency operations. Package lockfiles stay independent, including +for actions that install their own runtime dependencies; fixtures keep their +intentional package-manager differences. + +## Consequences + +The new shared workflow must be adopted before consumers remove `check:dist`. +The existing Node preset must be available before removing reporter-only +`test:ci` scripts. Common's distribution changes can release independently of +Node's reporting adoption, avoiding mutually dependent PR references. + +Committed bundles, licenses and necessary copied assets remain required. The +read-only PR builder and privileged default-branch writer remain separate. +Trusted-base allowlists, origin and identity validation, atomic head checks, +cleanup and failure propagation from ADR 0002 are unchanged. diff --git a/docs/adr/0006-action-project-ci.md b/docs/adr/0006-action-project-ci.md new file mode 100644 index 00000000..407c992c --- /dev/null +++ b/docs/adr/0006-action-project-ci.md @@ -0,0 +1,36 @@ +# ADR 0006: Use Node.js CI for action packages + +- Status: accepted +- Date: 2026-12-05 +- Partially supersedes [ADR 0005](0005-action-development-contract.md). + +## Original decision (superseded) + +Use one Node.js continuous-integration call to discover action packages, run +source tests and optional lint/build scripts, verify committed distributions and +execute isolated bundles on host and container runners. Keep Common's standalone +isolation action, but remove the separate distribution test workflow. + +The Node.js workflow owns project orchestration. Common owns bundle isolation and +the independent read-only rebuild/trusted writer workflow. Dedicated integration +workflows retain only actual action scenarios. Native runner options belong in the +normal package scripts; reporter configuration belongs in the shared actions. + +## Release order + +Release Common's distribution maintenance and isolation changes before Node.js. +Then release Node.js CI and adopt it here. The foundation stays independent of the +Node.js PR, avoiding a cyclic release dependency. + +## Revised decision: native caller matrix + +The extra internal workflow duplicated the public input contract and introduced +project discovery that GitHub's caller matrix already handles. Remove that layer. +Keep one `continuous-integration.yml` implementation and select each independent +package with its existing `working-directory` input. Repository callers list their +packages once in a native matrix and enable security scans on its first entry. + +Package scripts still select optional checks. Explicit commands remain required. +Normal builds verify committed bundles; the existing isolation action tests them. +No extra public inputs, shared package or custom matrix generator are introduced. +Adding an action package requires adding its directory to the caller matrix. diff --git a/docs/adr/0006-reuse-ci-action-builds.md b/docs/adr/0006-reuse-ci-action-builds.md new file mode 100644 index 00000000..45b75b30 --- /dev/null +++ b/docs/adr/0006-reuse-ci-action-builds.md @@ -0,0 +1,48 @@ +# ADR 0006: Reuse normal CI builds for distribution maintenance + +- Status: Accepted +- Date: 2026-12-05 +- Supersedes: The dedicated rebuild workflow in [ADR 0002](0002-audit-action-dependency-distributions.md) + +## Context + +Normal CI already builds each action and checks its committed distribution. A +second rebuild workflow repeats dependency installation, package-manager settings +and compilation. The security boundary requires a separate privileged writer, +but does not require a separate build workflow. + +## Decision + +Normal CI collects already-built output after a successful build, before checking +whether committed output is stale. Each package uploads its own artifact through +the official upload action. Artifact names include the package identity and run +attempt, so native matrix jobs can upload independently. + +Keep one default-branch writer, triggered by normal PR CI. Remove the dedicated +rebuild caller, helper installation and script execution, and their settings. +The writer uses the official download action, requires current-attempt output +for every affected package, validates each package separately and commits once. +It accepts completed successful or failed CI runs: stale committed output must +remain a failing check while valid build output is available to repair it. +Cancelled runs are rejected. Partial reruns require rerunning all CI jobs when +artifacts from the current attempt are incomplete. + +Retain the existing author and actor identity rules, trusted-base output allowlist, +workflow identity validation, unchanged PR head, atomic writes and loop prevention. +The writer never checks out or executes PR code. A default output must include +index.js; all generated licenses and assets are included, but a bundle with no +third-party dependencies does not need an empty licenses.txt. + +## Consequences + +Consumers keep normal CI plus one isolated writer caller. No new Node.js CI input +is needed. Package scripts remain the only source of build behavior. + +Common can release first: its existing distribution test workflow collects its +host build. Node.js then integrates collection into continuous-integration.yml. +Common's subsequent Node.js adoption removes the separate distribution test +workflow. This preserves an acyclic release order. + +The automatic write and subsequent bot rebase still require a dependency PR after +these workflows reach the default branch. Pre-merge CI can exercise collection, +artifact transport and writer contracts, but cannot activate workflow_run there. diff --git a/docs/development/actions.md b/docs/development/actions.md index 1857bc48..d8898792 100644 --- a/docs/development/actions.md +++ b/docs/development/actions.md @@ -51,18 +51,20 @@ it refuses deletion of successful evidence and uses GitHub's artifact SDK. ## Action test workflows -Each JavaScript action's dedicated test workflow calls the +The native GitHub matrix in [`__checks.yml`](../../.github/workflows/__checks.yml) +lists action package directories and calls [Node.js `continuous-integration.yml`](https://github.com/hoverkraft-tech/ci-github-nodejs/blob/main/.github/workflows/continuous-integration.yml) -workflow directly. It owns setup, dependency installation and package tests. -Keep action integration tests as separate jobs in the dedicated workflow. -CodeQL and dependency review run once for the repository through the same -Node.js workflow, with build, lint and tests disabled for that call. -See [download-artifact's tests](../../.github/workflows/__test-action-download-artifact.yml). - -All nine action packages collect source coverage in CI. Their `test:ci` scripts -honor `CI_TEST_COVERAGE` so secondary runtime-matrix jobs can retain detailed -tests without duplicate instrumentation. Isolated distribution checks do not -collect coverage: the source test run owns that measurement. +for each. Add new packages to that list. Package scripts define build, lint and +test behavior; the workflow handles installation and reporting. CodeQL and +dependency review run on the first matrix entry, once for the repository. +Keep actual action integration scenarios in their dedicated workflows. + +The Node test preset collects source coverage once and supplies native reporters. +Callers preserve package-specific test selection and coverage scope through native +arguments. Isolated distribution checks do not collect coverage. +The preparation package retains a custom `test:ci` command because it must apply +its temporary upstream parser patch before executing tests. Remove that command +alongside the patch when the fixed converter is adopted. The publication workflow has no separate JavaScript package. Its implementation is tested through the publication action's Node.js CI; its workflow test verifies @@ -77,21 +79,26 @@ The dedicated completion-workflow test calls the workflow and exercises its actual inline script for rejected results. It uses the hosted runner's `yq` and the Node.js assertion library, with no npm installation. -Common uses released Node.js tooling to preserve the release order. Until -[Node.js #624](https://github.com/hoverkraft-tech/ci-github-nodejs/pull/624) is -released, its existing test options retain native artifacts and disable legacy -PR comments. The outer workflow downloads those artifacts and calls local -`prepare-ci-reports` before publication. This temporary bridge requires JUnit -and LCOV for every package. The released -workflow still writes per-test summaries; the consolidated summary and comment -belong to the outer publication workflow. +Test callers select the action directory. Coverage is enabled by default for +all packages. Callers select native execution arguments where needed. +The Node.js action discovers the packages' JUnit and LCOV outputs automatically. +Callers do not configure report paths, publication destinations or comments. +Test results are required for every package; enabled coverage is also required. +One outer `publish-ci-reports.yml` call publishes the results from all checks. -After releasing Node.js's producer API, update these direct workflow calls and -remove the bridge and legacy publication options together. Keep the migration -after Common's release to avoid a circular dependency. +CI runs on every pull request, including changes targeting another PR branch. ## Validation +`make ci` fails on check errors and never applies audit or lint fixes. Commit +regenerated distributions before its freshness check. `make deps-audit` inspects +advisories without modifying dependencies. Fixture and action dependencies remain +independent. Common's shared distribution workflow rebuilds once on the host, +then tests the committed bundle on both host and container. The isolated tester +uses `test` unless a distinct `test:distribution` suite is declared. + +For focused checks: + ```sh npm ci --ignore-scripts --prefix actions/quality/prepare-ci-reports npm test --prefix actions/quality/prepare-ci-reports @@ -139,8 +146,11 @@ actions/{action-name}/ ## Development Workflow ```bash -make lint # Run Super Linter (dockerized) -make lint-fix # Run Super Linter with autofix enabled +make setup # Install locked action dependencies +make test # Run source tests +make build # Regenerate action distributions +make ci # Install, test, verify committed distributions and lint +make lint-fix # Explicitly apply lint fixes gh act -W .github/workflows/.yml # Exercise workflows locally when needed ```