From 39d275501cf843d69e1a39123859b83b63ff5327 Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Sat, 5 Dec 2026 08:40:59 +0100 Subject: [PATCH 1/3] refactor(actions)!: simplify distribution development contracts Discover action packages from their manifest and build script, default isolated contracts to npm test, and verify committed output once on the host. Preserve the trusted builder/writer split and centralize the Hoverkraft author preset. BREAKING CHANGE: Automatic distribution discovery requires an adjacent action manifest instead of check:dist. Workspace builds without an action manifest must select their working directories explicitly. --- .github/workflows/__checks.yml | 7 ++- .../__commit-action-distributions.yml | 2 +- .../__rebuild-action-distributions.yml | 2 +- .github/workflows/__shared-ci.yml | 4 +- ...__test-action-test-action-distribution.yml | 2 +- .github/workflows/action-distributions.md | 16 +++--- .github/workflows/action-distributions.yml | 10 ++-- .../workflows/test-action-distributions.md | 28 +++++----- .../workflows/test-action-distributions.yml | 35 ++++++++---- actions/action-distributions/README.md | 10 ++-- actions/action-distributions/action.yml | 4 +- actions/action-distributions/dist/index.js | 20 +++++-- .../src/ActionDistributions.test.js | 5 +- .../src/DistributionOptions.js | 5 ++ .../src/DistributionPackages.js | 15 ++++-- .../src/DistributionPackages.test.js | 35 ++++++++---- .../test-action-distribution/README.md | 5 +- .../test-action-distribution/action.yml | 3 +- .../src/DistributionTest.js | 10 ++-- .../src/DistributionTest.test.js | 13 ++++- docs/README.md | 1 + ...2-audit-action-dependency-distributions.md | 2 +- docs/adr/0005-action-development-contract.md | 54 +++++++++++++++++++ 23 files changed, 208 insertions(+), 80 deletions(-) create mode 100644 docs/adr/0005-action-development-contract.md diff --git a/.github/workflows/__checks.yml b/.github/workflows/__checks.yml index eece5a77..3ab802e0 100644 --- a/.github/workflows/__checks.yml +++ b/.github/workflows/__checks.yml @@ -23,14 +23,17 @@ jobs: test: "" code-ql: '{"languages":"javascript-typescript","config-file":".github/codeql/config.yml"}' test-bundled-actions: + name: Verify committed action distributions permissions: actions: read contents: read uses: $/.github/workflows/test-action-distributions.yml - test-action-distributions: + 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: diff --git a/.github/workflows/__commit-action-distributions.yml b/.github/workflows/__commit-action-distributions.yml index 1dc2ac32..99cc8d33 100644 --- a/.github/workflows/__commit-action-distributions.yml +++ b/.github/workflows/__commit-action-distributions.yml @@ -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/__rebuild-action-distributions.yml b/.github/workflows/__rebuild-action-distributions.yml index cf5ff291..edbda772 100644 --- a/.github/workflows/__rebuild-action-distributions.yml +++ b/.github/workflows/__rebuild-action-distributions.yml @@ -15,4 +15,4 @@ jobs: pull-requests: read with: pull-request-authors: | - ["dependabot", "renovate", {"login":"hoverkraft-bot[bot]","id":128996893,"branch-prefix":"renovate/"}] + ["dependabot", "renovate", "hoverkraft"] diff --git a/.github/workflows/__shared-ci.yml b/.github/workflows/__shared-ci.yml index 28b9e669..0481c65c 100644 --- a/.github/workflows/__shared-ci.yml +++ b/.github/workflows/__shared-ci.yml @@ -34,7 +34,7 @@ jobs: project: actions/create-and-merge-pull-request - job: test-action-discard-report-fixtures project: actions/quality/discard-report-fixtures - - job: test-action-distributions + - job: test-action-distribution-maintenance project: actions/action-distributions - job: test-action-download-artifact project: actions/download-artifact @@ -46,7 +46,7 @@ jobs: project: actions/quality/prepare-ci-reports - job: test-action-publish-ci-reports project: actions/quality/publish-ci-reports - - job: test-action-test-action-distribution + - job: test-action-distribution-isolation project: actions/quality/test-action-distribution steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.github/workflows/__test-action-test-action-distribution.yml b/.github/workflows/__test-action-test-action-distribution.yml index 4788d1b3..356b6d55 100644 --- a/.github/workflows/__test-action-test-action-distribution.yml +++ b/.github/workflows/__test-action-test-action-distribution.yml @@ -43,7 +43,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/action-distributions.md b/.github/workflows/action-distributions.md index 59cac917..7deb14d5 100644 --- a/.github/workflows/action-distributions.md +++ b/.github/workflows/action-distributions.md @@ -30,7 +30,7 @@ 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, +1. Each package needs an action manifest, a lockfile and a build script. 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 @@ -73,7 +73,7 @@ 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 +script and an adjacent action manifest. 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. @@ -100,7 +100,7 @@ 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/"}] + ["dependabot", "renovate", "hoverkraft"] ``` Verify an account's ID with `gh api 'users/ACCOUNT_LOGIN' --jq .id`. Custom rules @@ -187,7 +187,7 @@ on: permissions: {} jobs: action-distributions: - uses: hoverkraft-tech/ci-github-common/.github/workflows/action-distributions.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 + uses: hoverkraft-tech/ci-github-common/.github/workflows/action-distributions.yml@01fa3c532c0933ad19cc433e70e002a20cd177a6 # refactor/action-distribution-devx permissions: actions: read contents: read @@ -196,7 +196,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. @@ -211,7 +211,7 @@ jobs: 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. + # 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"]' @@ -256,10 +256,10 @@ jobs: | **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** | - | +| **`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
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"]` | +| **`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 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` | diff --git a/.github/workflows/action-distributions.yml b/.github/workflows/action-distributions.yml index 2c533393..b776eb05 100644 --- a/.github/workflows/action-distributions.yml +++ b/.github/workflows/action-distributions.yml @@ -6,7 +6,7 @@ # # ### Configure a repository # -# 1. Each package needs a lockfile and build and check:dist scripts. Defaults use Node.js 24, +# 1. Each package needs an action manifest, a lockfile and a build script. 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 @@ -49,7 +49,7 @@ # 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 +# script and an adjacent action manifest. 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. @@ -76,7 +76,7 @@ # # ```yaml # pull-request-authors: | -# ["dependabot", "renovate", {"login":"hoverkraft-bot[bot]","id":128996893,"branch-prefix":"renovate/"}] +# ["dependabot", "renovate", "hoverkraft"] # ``` # # Verify an account's ID with `gh api 'users/ACCOUNT_LOGIN' --jq .id`. Custom rules @@ -148,7 +148,7 @@ 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: @@ -162,7 +162,7 @@ on: index.js licenses.txt 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: diff --git a/.github/workflows/test-action-distributions.md b/.github/workflows/test-action-distributions.md index 275ffc8d..a8e0c63e 100644 --- a/.github/workflows/test-action-distributions.md +++ b/.github/workflows/test-action-distributions.md @@ -25,17 +25,19 @@ 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 +Packages at the root or under actions/ are discovered from their action manifest +and build script. 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. +Each package must commit its npm lockfile and declare a test script. An optional +test:distribution script selects a different suite. Contract tests 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. +The host job rebuilds once and rejects modified, staged, deleted or untracked +output. Both environments test the committed distribution in isolation. 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. @@ -58,18 +60,18 @@ on: permissions: {} jobs: test-action-distributions: - uses: hoverkraft-tech/ci-github-common/.github/workflows/test-action-distributions.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 + uses: hoverkraft-tech/ci-github-common/.github/workflows/test-action-distributions.yml@01fa3c532c0933ad19cc433e70e002a20cd177a6 # refactor/action-distribution-devx permissions: contents: read 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/**` actions with a build script. 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. + # Node.js version installed for tests on both the host and the pinned Node.js container. # Default: `24` node-version: "24" ``` @@ -81,11 +83,11 @@ 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`** | 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` | +| **Input** | **Description** | **Required** | **Type** | **Default** | +| ------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------- | ----------- | +| **`working-directories`** | Newline-separated package directories or glob patterns. Empty discovers root and `actions/**` actions with a build script. | **false** | **string** | - | +| **`output-directory`** | Bundle directory relative to each package, containing index.js. | **false** | **string** | `dist` | +| **`node-version`** | Node.js version installed for tests on both the host and the pinned Node.js container. | **false** | **string** | `24` | diff --git a/.github/workflows/test-action-distributions.yml b/.github/workflows/test-action-distributions.yml index 807d38d4..75e62e35 100644 --- a/.github/workflows/test-action-distributions.yml +++ b/.github/workflows/test-action-distributions.yml @@ -1,17 +1,19 @@ # 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 +# Packages at the root or under actions/ are discovered from their action manifest +# and build script. 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. +# Each package must commit its npm lockfile and declare a test script. An optional +# test:distribution script selects a different suite. Contract tests 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. +# The host job rebuilds once and rejects modified, staged, deleted or untracked +# output. Both environments test the committed distribution in isolation. # 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. @@ -21,7 +23,7 @@ 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/**` actions with a build script. type: string default: "" output-directory: @@ -29,7 +31,7 @@ on: type: string default: dist node-version: - description: Node.js version installed for checks on both the host and Node.js 24 container. + description: Node.js version installed for tests on both the host and the pinned Node.js container. type: string default: "24" @@ -64,7 +66,7 @@ jobs: matrix: directory: ${{ fromJSON(needs.discover.outputs.directories) }} environment: [host, container] - container: ${{ matrix.environment == 'container' && 'node:24' || '' }} + container: ${{ matrix.environment == 'container' && 'node:24@sha256:9a870218441ce75f25e49dff2ab2a8eefd47004b77da810b4b51986adf4cffcc' || '' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -76,11 +78,22 @@ jobs: - 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 + - name: Install locked dependencies working-directory: ${{ matrix.directory }} + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Verify the checked-in distribution + if: matrix.environment == 'host' + working-directory: ${{ matrix.directory }} + env: + OUTPUT_DIRECTORY: ${{ inputs.output-directory }} run: | - npm ci --ignore-scripts --no-audit --no-fund - npm run check:dist + npm run build + changes=$(git status --porcelain --untracked-files=all -- "$OUTPUT_DIRECTORY") + if [ -n "$changes" ]; then + printf '%s\n' "$changes" + echo '::error::Distribution is stale. Run npm run build in this package and commit its output.' + exit 1 + fi - uses: $/actions/quality/test-action-distribution with: working-directory: ${{ matrix.directory }} diff --git a/actions/action-distributions/README.md b/actions/action-distributions/README.md index 7358f8bc..f53f5917 100644 --- a/actions/action-distributions/README.md +++ b/actions/action-distributions/README.md @@ -39,13 +39,13 @@ default-branch workflow_run job and never execute or check out PR code. ## Usage ```yaml -- uses: hoverkraft-tech/ci-github-common/actions/action-distributions@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 +- uses: hoverkraft-tech/ci-github-common/actions/action-distributions@01fa3c532c0933ad19cc433e70e002a20cd177a6 # refactor/action-distribution-devx with: # Operation to execute (discover, prepare-build, build, 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. 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. @@ -60,7 +60,7 @@ default-branch workflow_run job and never execute or check out PR code. 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. + # 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"]' @@ -113,10 +113,10 @@ default-branch workflow_run job and never execute or check out PR code. | **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** | - | +| **`working-directories`** | Newline-separated package directories or glob patterns (`*`, `**`, `?`). Empty discovers root and `actions/**` packages with an action manifest and a build script. | **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"]` | +| **`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. 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` | diff --git a/actions/action-distributions/action.yml b/actions/action-distributions/action.yml index 2058449e..c3234fe2 100644 --- a/actions/action-distributions/action.yml +++ b/actions/action-distributions/action.yml @@ -19,7 +19,7 @@ inputs: description: Operation to execute (discover, prepare-build, build, 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. 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. @@ -30,7 +30,7 @@ inputs: index.js licenses.txt 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. diff --git a/actions/action-distributions/dist/index.js b/actions/action-distributions/dist/index.js index f8d1ff3f..183b2bcc 100644 --- a/actions/action-distributions/dist/index.js +++ b/actions/action-distributions/dist/index.js @@ -8723,6 +8723,11 @@ class DistributionCommit { const AUTHOR_PRESETS = { + hoverkraft: { + login: "hoverkraft-bot[bot]", + id: 128996893, + "branch-prefix": "renovate/", + }, dependabot: { login: "dependabot[bot]", id: 49699333, @@ -9044,6 +9049,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 +9076,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 +9090,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/ActionDistributions.test.js b/actions/action-distributions/src/ActionDistributions.test.js index fe07f97c..35c8a1ef 100644 --- a/actions/action-distributions/src/ActionDistributions.test.js +++ b/actions/action-distributions/src/ActionDistributions.test.js @@ -569,6 +569,7 @@ 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, ]) { @@ -577,6 +578,7 @@ for (const author of [ pullRequestAuthors: JSON.stringify([ "dependabot", "renovate", + "hoverkraft", CUSTOM_AUTHOR, ]), artifactName: "custom-bundle", @@ -739,6 +741,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 +753,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" }, }), ), }, diff --git a/actions/action-distributions/src/DistributionOptions.js b/actions/action-distributions/src/DistributionOptions.js index 9cfa64b4..aab96d45 100644 --- a/actions/action-distributions/src/DistributionOptions.js +++ b/actions/action-distributions/src/DistributionOptions.js @@ -1,6 +1,11 @@ import assert from "node:assert/strict"; const AUTHOR_PRESETS = { + hoverkraft: { + login: "hoverkraft-bot[bot]", + id: 128996893, + "branch-prefix": "renovate/", + }, dependabot: { login: "dependabot[bot]", id: 49699333, 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/quality/test-action-distribution/README.md b/actions/quality/test-action-distribution/README.md index f03648a9..463693c7 100644 --- a/actions/quality/test-action-distribution/README.md +++ b/actions/quality/test-action-distribution/README.md @@ -24,7 +24,8 @@ ## 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. @@ -37,7 +38,7 @@ to discover packages, install dependencies and verify checked-in distributions. ## Usage ```yaml -- uses: hoverkraft-tech/ci-github-common/actions/quality/test-action-distribution@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 +- uses: hoverkraft-tech/ci-github-common/actions/quality/test-action-distribution@01fa3c532c0933ad19cc433e70e002a20cd177a6 # refactor/action-distribution-devx with: # Package directory containing the distribution contract test script. # Default: `.` diff --git a/actions/quality/test-action-distribution/action.yml b/actions/quality/test-action-distribution/action.yml index 5fd668b7..e40972b0 100644 --- a/actions/quality/test-action-distribution/action.yml +++ b/actions/quality/test-action-distribution/action.yml @@ -1,7 +1,8 @@ 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. 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..9a9e53d4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,3 +7,4 @@ - [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) diff --git a/docs/adr/0002-audit-action-dependency-distributions.md b/docs/adr/0002-audit-action-dependency-distributions.md index a1692076..fa528286 100644 --- a/docs/adr/0002-audit-action-dependency-distributions.md +++ b/docs/adr/0002-audit-action-dependency-distributions.md @@ -1,6 +1,6 @@ # 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) - 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..c1a96fb9 --- /dev/null +++ b/docs/adr/0005-action-development-contract.md @@ -0,0 +1,54 @@ +# ADR 0005: Simplify action development commands + +- Status: Accepted +- 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. From 18450246417fff4c1355777b28dcbc21b135161f Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Sat, 5 Dec 2026 09:14:03 +0100 Subject: [PATCH 2/3] refactor(ci): align distribution check names --- .github/workflows/__checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/__checks.yml b/.github/workflows/__checks.yml index 3ab802e0..781158f8 100644 --- a/.github/workflows/__checks.yml +++ b/.github/workflows/__checks.yml @@ -22,7 +22,7 @@ jobs: lint: "" test: "" code-ql: '{"languages":"javascript-typescript","config-file":".github/codeql/config.yml"}' - test-bundled-actions: + test-action-distributions: name: Verify committed action distributions permissions: actions: read From f19f395c695e952a5b751b107db5a3e50807a74f Mon Sep 17 00:00:00 2001 From: Emilien Escalle Date: Sat, 5 Dec 2026 13:34:38 +0100 Subject: [PATCH 3/3] refactor(ci)!: reuse normal CI builds for action distributions --- .../__commit-action-distributions.yml | 2 +- .../__rebuild-action-distributions.yml | 18 - .../workflows/__test-action-distributions.yml | 12 +- .github/workflows/action-distributions.md | 271 ++++-------- .github/workflows/action-distributions.yml | 328 ++++----------- .../workflows/test-action-distributions.md | 5 +- .../workflows/test-action-distributions.yml | 16 +- actions/action-distributions/README.md | 102 ++--- actions/action-distributions/action.yml | 75 ++-- actions/action-distributions/dist/index.js | 177 ++++---- actions/action-distributions/package.json | 2 +- .../src/ActionDistributions.js | 136 +++--- .../src/ActionDistributions.test.js | 393 ++++++------------ .../src/BuildWorkflow.test.js | 63 --- .../src/DistributionOptions.js | 39 +- docs/README.md | 1 + ...2-audit-action-dependency-distributions.md | 1 + docs/adr/0006-reuse-ci-action-builds.md | 48 +++ 18 files changed, 606 insertions(+), 1083 deletions(-) delete mode 100644 .github/workflows/__rebuild-action-distributions.yml delete mode 100644 actions/action-distributions/src/BuildWorkflow.test.js create mode 100644 docs/adr/0006-reuse-ci-action-builds.md diff --git a/.github/workflows/__commit-action-distributions.yml b/.github/workflows/__commit-action-distributions.yml index 99cc8d33..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: {} diff --git a/.github/workflows/__rebuild-action-distributions.yml b/.github/workflows/__rebuild-action-distributions.yml deleted file mode 100644 index edbda772..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", "hoverkraft"] diff --git a/.github/workflows/__test-action-distributions.yml b/.github/workflows/__test-action-distributions.yml index 4cff36a6..af0241a5 100644 --- a/.github/workflows/__test-action-distributions.yml +++ b/.github/workflows/__test-action-distributions.yml @@ -32,12 +32,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 +41,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/action-distributions.md b/.github/workflows/action-distributions.md index 7deb14d5..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 an action manifest, a lockfile and a build script. 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 an adjacent action manifest. 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", "hoverkraft"] -``` - -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 @@ -187,7 +117,7 @@ on: permissions: {} jobs: action-distributions: - uses: hoverkraft-tech/ci-github-common/.github/workflows/action-distributions.yml@01fa3c532c0933ad19cc433e70e002a20cd177a6 # refactor/action-distribution-devx + uses: hoverkraft-tech/ci-github-common/.github/workflows/action-distributions.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 permissions: actions: read contents: read @@ -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 + # 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 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
licenses.txt
| -| **`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 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 b776eb05..46b53bb1 100644 --- a/.github/workflows/action-distributions.yml +++ b/.github/workflows/action-distributions.yml @@ -1,147 +1,77 @@ -# 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 an action manifest, a lockfile and a build script. 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 an adjacent action manifest. 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", "hoverkraft"] -# ``` -# -# 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: @@ -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, 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/test-action-distributions.md b/.github/workflows/test-action-distributions.md index a8e0c63e..04690839 100644 --- a/.github/workflows/test-action-distributions.md +++ b/.github/workflows/test-action-distributions.md @@ -37,7 +37,8 @@ NODE_OPTIONS, propagates test failures and removes temporary files. Tests may use development dependencies; the bundle must include its runtime dependencies. The host job rebuilds once and rejects modified, staged, deleted or untracked -output. Both environments test the committed distribution in isolation. +output. On PRs it first uploads built output for the isolated writer. +Both environments test the committed distribution in isolation. 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. @@ -60,7 +61,7 @@ on: permissions: {} jobs: test-action-distributions: - uses: hoverkraft-tech/ci-github-common/.github/workflows/test-action-distributions.yml@01fa3c532c0933ad19cc433e70e002a20cd177a6 # refactor/action-distribution-devx + uses: hoverkraft-tech/ci-github-common/.github/workflows/test-action-distributions.yml@26f3d6878844ec53849eec6ac75af8d14ea402e9 # 5.0.0 permissions: contents: read with: diff --git a/.github/workflows/test-action-distributions.yml b/.github/workflows/test-action-distributions.yml index 75e62e35..d8d972cd 100644 --- a/.github/workflows/test-action-distributions.yml +++ b/.github/workflows/test-action-distributions.yml @@ -13,7 +13,8 @@ # use development dependencies; the bundle must include its runtime dependencies. # # The host job rebuilds once and rejects modified, staged, deleted or untracked -# output. Both environments test the committed distribution in isolation. +# output. On PRs it first uploads built output for the isolated writer. +# Both environments test the committed distribution in isolation. # 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. @@ -71,6 +72,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + ref: ${{ github.event.pull_request.head.sha || github.sha }} - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ inputs.node-version }} @@ -81,13 +83,23 @@ jobs: - name: Install locked dependencies working-directory: ${{ matrix.directory }} run: npm ci --ignore-scripts --no-audit --no-fund + - name: Build action distribution + if: matrix.environment == 'host' + working-directory: ${{ matrix.directory }} + run: npm run build + - name: Collect built action distribution + if: matrix.environment == 'host' && github.event_name == 'pull_request' + uses: $/actions/action-distributions + with: + operation: collect + working-directories: ${{ matrix.directory }} + output-directory: ${{ inputs.output-directory }} - name: Verify the checked-in distribution if: matrix.environment == 'host' working-directory: ${{ matrix.directory }} env: OUTPUT_DIRECTORY: ${{ inputs.output-directory }} run: | - npm run build changes=$(git status --porcelain --untracked-files=all -- "$OUTPUT_DIRECTORY") if [ -n "$changes" ]; then printf '%s\n' "$changes" diff --git a/actions/action-distributions/README.md b/actions/action-distributions/README.md index f53f5917..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. @@ -39,13 +39,13 @@ default-branch workflow_run job and never execute or check out PR code. ## Usage ```yaml -- uses: hoverkraft-tech/ci-github-common/actions/action-distributions@01fa3c532c0933ad19cc433e70e002a20cd177a6 # refactor/action-distribution-devx +- 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 with an action manifest and a build script. + # 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 + # 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 + # Retention for uploaded artifacts, within the repository policy. + # Default: `1` + retention-days: "1" - # 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" - - # 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 with an action manifest and a build script. | **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, 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. 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 c3234fe2..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 with an action manifest and a build script. + 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, 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 183b2bcc..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,6 +8720,7 @@ class DistributionCommit { ;// CONCATENATED MODULE: ./src/DistributionOptions.js + const AUTHOR_PRESETS = { hoverkraft: { login: "hoverkraft-bot[bot]", @@ -8745,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 = @@ -8786,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 && @@ -8816,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 @@ -8913,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) { @@ -8927,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, @@ -9222,7 +9199,6 @@ class DistributionWorkflow { - const GENERATED_BY = "Generated-by: ci-github-common/action-distributions"; const INLINE_COMMIT_BYTES = 20 * 1024 * 1024; @@ -9242,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": @@ -9315,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"); @@ -9401,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 || @@ -9434,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, { @@ -9443,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) { @@ -9514,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..b3818fbe 100644 --- a/actions/action-distributions/package.json +++ b/actions/action-distributions/package.json @@ -2,7 +2,7 @@ "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", "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", 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 35c8a1ef..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 [ @@ -573,7 +560,7 @@ for (const author of [ { 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", @@ -592,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, @@ -630,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), @@ -691,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); @@ -775,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", @@ -911,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"); }); } @@ -920,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 [ @@ -994,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)); }); } @@ -1137,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 aab96d45..2ca963a4 100644 --- a/actions/action-distributions/src/DistributionOptions.js +++ b/actions/action-distributions/src/DistributionOptions.js @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; const AUTHOR_PRESETS = { hoverkraft: { @@ -23,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 = @@ -64,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 && @@ -94,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 @@ -191,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) { @@ -205,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/docs/README.md b/docs/README.md index 9a9e53d4..01553294 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,3 +8,4 @@ - [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 fa528286..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; 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/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.