Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(ci): publish a dev-accepted release in one run (#3069)

kekxy99c3bf50ece9
diff --git a/.github/actions/mdeploy/action.yml b/.github/actions/mdeploy/action.yml
index 3e47c78e8..5d023b1a2 100644
--- a/.github/actions/mdeploy/action.yml
+++ b/.github/actions/mdeploy/action.yml
@@ -13,6 +13,10 @@ inputs:
version:
description: Stable release selector or empty for a commit
default: ''
+ registry-digests:
+ description: Verified release manifest and image digests from the release resolver
+ required: false
+ default: ''
image-tag:
description: Resolved image identity
required: true
@@ -57,19 +61,23 @@ runs:
# What this job deploys, as an address rather than as the name it was
# given. The runner half says which of the two artifacts the stack
- # installs: a release names the version whose GitHub Release carries the
- # tarball, a commit names the object this run staged in the bucket. Both
+ # installs: a release names the candidate whose GHCR digests select the
+ # archive, a commit names the object this run staged in the bucket. Both
# are set explicitly so the mode is readable in the run rather than
# inferred from an absence.
- name: Address what this deploy installs
shell: bash
env:
+ RELEASE_PINS: ${{ inputs.registry-digests }}
IMAGE_TAG: ${{ inputs.image-tag }}
VERSION: ${{ inputs.version }}
SHA: ${{ inputs.sha }}
COMPONENTS: ${{ inputs.components }}
run: |
set -Eeuo pipefail
+ if [[ -n "$RELEASE_PINS" ]]; then
+ printf 'BOXLITE_RELEASE_DIGESTS=%s\n' "$RELEASE_PINS" >> "$GITHUB_ENV"
+ fi
# Build mode only when this run actually staged one. `plan` leaves the
# runner alone for `components: api`, so naming a build-mode binary
# there would point the fleet at `runner/<sha>/` in a bucket nothing
@@ -201,7 +209,7 @@ runs:
service_account: ${{ inputs.gcp-deployer }}
- name: Verify the images
- if: inputs.components != 'runner'
+ if: inputs.components != 'runner' && inputs.api-route != 'release-import'
working-directory: apps/infra
env:
STAGE: ${{ inputs.stage }}
diff --git a/.github/actions/release-candidate/action.yml b/.github/actions/release-candidate/action.yml
new file mode 100644
index 000000000..0f960659e
--- /dev/null
+++ b/.github/actions/release-candidate/action.yml
@@ -0,0 +1,40 @@
+name: Download verified release candidate
+description: Retrieve the exact candidate selected for acceptance or publication.
+inputs:
+ id:
+ description: Immutable candidate artifact ID
+ required: true
+ digest:
+ description: Expected SHA-256 of the release manifest
+ required: true
+ tag:
+ description: Product version tag
+ required: true
+ sha:
+ description: Tagged product commit
+ required: true
+ run:
+ description: Candidate producer run
+ required: false
+ default: ${{ github.run_id }}
+runs:
+ using: composite
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ artifact-ids: ${{ inputs.id }}
+ github-token: ${{ github.token }}
+ run-id: ${{ inputs.run }}
+ path: ${{ runner.temp }}/release-candidate
+ merge-multiple: true
+ - name: Check source and all file checksums
+ shell: bash
+ env:
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ inputs.sha }}
+ CANDIDATE_DIGEST: ${{ inputs.digest }}
+ RELEASE_ASSET_DIR: ${{ runner.temp }}/release-candidate
+ run: |
+ set -euo pipefail
+ node "$GITHUB_ACTION_PATH/../../../apps/infra/scripts/release-candidate.mjs" verify
+ printf 'RELEASE_ASSET_DIR=%s\n' "$RELEASE_ASSET_DIR" >> "$GITHUB_ENV"
diff --git a/.github/actions/setup-boxlite-runner/action.yml b/.github/actions/setup-boxlite-runner/action.yml
index a1015b319..2af4cd297 100644
--- a/.github/actions/setup-boxlite-runner/action.yml
+++ b/.github/actions/setup-boxlite-runner/action.yml
@@ -18,4 +18,4 @@ runs:
- name: Install native build prerequisites
if: inputs.native-build == 'true'
shell: bash
- run: sudo apt-get install -y --no-install-recommends build-essential pkg-config libssl-dev patchelf python3
+ run: sudo apt-get install -y --no-install-recommends build-essential pkg-config libssl-dev patchelf python3 jq
diff --git a/.github/workflows/README.md b/.github/workflows/README.md
index ccce5912c..3fb278671 100644
--- a/.github/workflows/README.md
+++ b/.github/workflows/README.md
@@ -19,7 +19,7 @@ The connection needs permission to register workers and quota for the requested
| Runner label | Jobs |
| --- | --- |
-| `boxlite` | Lightweight lint and setup, Python and Node SDK unit tests, Actions and Python CodeQL, plugin package validation, Go SDK release configuration, status and selected release artifact uploads |
+| `boxlite` | Lightweight lint and setup, Python and Node SDK unit tests, Actions and Python CodeQL, plugin package validation, Go SDK release configuration, status and runtime distribution staging |
| `boxlite-2vcpu-4gbmem-30gbdisk` | C/C++ CodeQL and Secret Server PostgreSQL integration |
| `boxlite-2vcpu-8gbmem-30gbdisk` | Dashboard tests and API client drift |
| `boxlite-4vcpu-8gbmem-30gbdisk` | Go CodeQL autobuild |
@@ -27,11 +27,12 @@ The connection needs permission to register workers and quota for the requested
| `boxlite-4vcpu-16gbmem-64gbdisk` | JavaScript/TypeScript and Rust CodeQL, Clippy, REST volume lifecycle E2E, Nix CLI build and boot, Linux x64 C SDK, Node addon, Python wheel and runtime/CLI builds, standalone guest artifacts and the non-publishing multiarch Box image build |
| GitHub-hosted Ubuntu | API tests, Go SDK coverage, Rust coverage, selected-ref C SDK builds, protected publishing and runner recovery |
-The Node release upload builds and packs the npm packages before attaching them.
-Uploads of prepared C SDK archives, runtime archives and Python wheels use the default worker.
+Each Node build packs its platform archive. The Node packaging job collects those archives, and `mbuild-release` attaches the verified release files on GitHub-hosted Ubuntu.
+
+Runtime, wheel and Node jobs load the BoxLite worker setup from the workflow commit before checking out the requested SDK or runtime source.
The C SDK workflow installs the BoxLite worker toolchain before source checkout.
-A caller-selected commit or an x64-only recovery build runs on GitHub-hosted Ubuntu.
+A full `mbuild-release` builds its pinned Linux x64 C SDK on `boxlite-4vcpu-16gbmem-64gbdisk`. Standalone builds pinned to a commit and x64-only Runner recovery use GitHub-hosted Ubuntu.
Linux ARM64 and macOS matrix jobs use their native platforms. Building an ARM64
container image with Buildx exercises a different path from native ARM64 SDK tests.
@@ -61,18 +62,22 @@ RELEASE VERSION PULL REQUEST release-dependency-audit (title-selected
BUILD + CACHE (weekly) build-runtime
-RELEASE CHAIN (workflow_run) build-c ──▶ build-go
- └──▶ build-runner-binary
+PRODUCT RELEASE (dispatch from main) mbuild-release creates or selects the draft for the tag
+ ├─ build-runtime · build-wheels · build-node · build-c
+ │ ├─ build-go
+ │ └─ build-runner-binary
+ └─ publish images to GHCR
+ Runner archive to GHCR ──▶ verify pins ──▶ approved dev deployment
+ └─▶ dev E2E with Linux clients
+ ├─▶ prod approval + deployment
+ complete distribution + Go tests + successful dev E2E ─┴─▶ attach files
+ ──▶ PyPI and npm ──▶ publish GitHub Release ──┬─▶ crates.io
+ └─▶ verify public C SDK downloads → Go tag
-SDK TEST BUILDS (manual dispatch) build-go ──▶ build-c ──▶ Go SDK tests
- build-runner-binary ──▶ build-c ──▶ Runner link
+SINGLE COMPONENT (dispatch from main) mbuild-release ──▶ component build + tests ──▶ component publication
+ build-only ──▶ artifacts from the selected source
-RELEASE (release event) build-runtime · build-c · build-node · build-wheels
- mbuild-release-on-release ──▶ mbuild-release
- GHCR images + required release assets ready
- ──▶ mdeploy-all (dev) ──▶ e2e-cloud (dev, release tag)
- ──▶ mdeploy-all (prod, awaiting approval) ──▶ Slack report
- apps/box-images/v* tag ──▶ release-box-images
+BOX IMAGES apps/box-images/v* tag ──▶ release-box-images
LEGACY AWS (manual dispatch) deploy-infra ─┬─▶ build-apps-api-image
├─▶ build-c ──▶ build-runner-binary
@@ -87,9 +92,7 @@ CONFIG ci-config action ◀── lint, test, c
## Workflows
-**Callable** marks a workflow another one can invoke with `uses:`. `config.yml` and `mbuild.yml` are
-the two that are *exclusively* callable; workflows with `workflow_dispatch` can also run on their
-own.
+**Callable** marks a workflow used by another workflow. The Triggers column lists each independent entry point.
| Workflow | Triggers | Callable | Purpose |
| --- | --- | --- | --- |
@@ -100,20 +103,19 @@ own.
| `codeql.yml` | push, PR, dispatch, weekly | — | CodeQL advanced setup, so fork PRs are scanned |
| `api-client-drift.yml` | PR | — | Fails if the committed generated clients no longer match their specs. It regenerates through the `generate:api-client` targets, `apps/hack` post-steps included, so regenerate with those targets rather than the bare generator |
| `author-review.yml` | PR (target), issue_comment, merge_group | — | Converts unacknowledged PRs to draft, posts author instructions, and publishes `Author reviewed the PR` on the current head. Merge queues carry forward the required PR admission check |
-| `build-runtime.yml` | weekly, release, dispatch | — | Builds runtime/CLI artifacts and populates sccache together; publishes crates on release |
-| `build-c.yml` | release, dispatch, `workflow_call` | yes | C SDK archives |
-| `build-go.yml` | `workflow_run`, dispatch | — | Pins release tests and the Go tag to the C build commit. Compares public archives with that run before testing. Manual tests build their own C archive. |
-| `build-node.yml` | release, dispatch | — | Node.js SDK, napi-rs addon and platform packages |
-| `build-wheels.yml` | release, dispatch | — | Builds Python wheels and verifies their native extension in cibuildwheel before publishing |
-| `build-runner-binary.yml` | `workflow_run`, dispatch, `workflow_call` | yes | Linux amd64 runner binary; manual builds first produce the selected commit's C archive |
+| `build-runtime.yml` | weekly, `workflow_call` | yes | Builds runtime and CLI archives. The release build also stages the installer and checksums. |
+| `build-c.yml` | `workflow_call` | yes | Stages the platform C SDK archives, including the static library used by Go and Runner. |
+| `build-go.yml` | `workflow_call` | yes | Tests the Go SDK against the matching C archive from this run. |
+| `build-node.yml` | `workflow_call` | yes | Builds and tests the Node.js addon and stages packed npm distributions. |
+| `build-wheels.yml` | `workflow_call` | yes | Builds and tests Python wheels with cibuildwheel and stages them as Actions Artifacts. |
+| `build-runner-binary.yml` | `workflow_call` | yes | Links the Linux amd64 Runner against the selected C library and stages the archive and checksum. |
| `build-apps-api-image.yml` | dispatch, `workflow_call` | yes | The `apps/api` image: build a commit, build a release, or promote one between stages. Retained legacy AWS path |
| `deploy-infra.yml` | dispatch | — | Builds and deploys one commit to a stage. Retained legacy AWS path |
| `deploy-release.yml` | dispatch | — | Deploys already-published artifacts for one `X.Y.Z`. Compiles nothing. Retained legacy AWS path |
| `e2e-cloud.yml` | dispatch, `workflow_call` | yes | End-to-end against a deployed stage: main suite, identity and isolated catalog lanes on `dev`/`stage`, `-m smoke` on `prod`. Run by `deploy-infra` after it applies, or dispatched with a `stage` |
-| `mdeploy-all.yml` | dispatch | — | Dev/stage accept SHA/PR; stage treats stable tags as commit references. Dev/prod release dispatches run from main and import existing GHCR images into the target cloud registry |
+| `mdeploy-all.yml` | dispatch, `workflow_call` | yes | Dev/stage accept SHA/PR; stage treats stable tags as commit references. Dev/prod release dispatches run from main and import existing GHCR images into the target cloud registry |
| `mbuild.yml` | `workflow_call` | call-only | Reusable wrapper for the shared stage-image action; mdeploy-all invokes it in its image preparation leg |
-| `mbuild-release.yml` | dispatch | — | Publishes GHCR images, waits for required release assets, dispatches dev deployment/E2E, creates a prod approval request, and reports to Slack; `build-only=true` selects publication only |
-| `mbuild-release-on-release.yml` | release | — | A stable published release dispatches `mbuild-release` from `main` using its default full pipeline |
+| `mbuild-release.yml` | dispatch | — | Owns product builds, GHCR publication, dev acceptance, draft attachment, package publication and approved prod deployment. Also dispatches individual component builds and publications. |
| `e2e-local.yml` | push, `pull_request_target`, dispatch | — | VM-based tests on a self-hosted GCP VM runner. Needs `/dev/kvm`; PRs need the `e2e-local` label |
| `build-box-images.yml` | PR, push, dispatch | — | Builds changed flavors for both arches; shared inputs and manual runs build every flavor |
| `release-box-images.yml` | `apps/box-images/v*` tag, dispatch | — | Publishes the curated box image flavors to GHCR |
@@ -121,9 +123,17 @@ own.
Longer treatments live with their subject rather than here: [E2E local
runbook](../../docs/contributing/development/e2e-local.md), [deployment](../../apps/infra/docs/deployment.md).
-The [release runbook](../../apps/infra/docs/release.md) documents fixed child inputs, timeouts, and recovery.
+Set `TAG` to the existing stable version tag and start the product release from `main`.
+
+```sh
+gh workflow run mbuild-release.yml --ref main -f tag="$TAG"
+```
+
+The parent creates or selects the draft, gathers the build outputs in Actions Artifacts and requests dev approval. Successful dev E2E allows the attachment job to upload the verified files. Once the attachments, PyPI and npm jobs succeed, the parent makes the Release public.
+
+Both full releases and standalone Go publication verify anonymous downloads of the versioned C SDK archives before pushing the Go module tag.
-Full releases require reviewers on the `prod` Environment. A full release can send #release a dev approval link before polling, then the E2E result and prod approval link.
+The prod Environment requires reviewers. The optional prod Slack message includes the dev E2E result and the approval link. See the [release runbook](../../apps/infra/docs/release.md) for package publisher setup and retry behavior.
Deployment applies can also notify #dev_deployment for dev or #release for prod before each approval batch. Each button opens the corresponding GitHub run.
@@ -341,10 +351,10 @@ Run them with `make test:apps:mdeploy`; workflow lint alone does not exercise lo
| `build-staged-runner` | 1 | mdeploy-all Runner preparation |
| `mdeploy` | 2 | mdeploy-all release apply and commit deploy |
| `ci-config` | 3 | config, lint, test |
-| `setup-rust` | 10 | build-c, build-node, build-runtime ×2, build-wheels, lint ×2, test ×3 |
+| `setup-rust` | 11 | build-c, build-node, build-runtime, build-wheels, mbuild-release, lint ×2, test ×4 |
| `sccache` | 7 | build-c, build-node, build-runtime, build-wheels, lint, test ×2 |
| `build-guest` | 4 | build-c, build-node, build-runtime, build-wheels |
-| `upload-to-release` | 5 | build-c, build-node, build-runner-binary, build-runtime, build-wheels |
+| `release-candidate` | 5 | e2e-cloud and the release attachment, npm, PyPI and finalization jobs |
| `run-in-manylinux` | 3 | build-c, build-node, build-runtime |
| `setup-go` | 4 | build-go, build-runner-binary, lint, test |
| `setup-python` | 5 | lint ×2, test ×3 |
@@ -403,7 +413,7 @@ scan private lockfiles created by root containers. A cold cache still requires a
Runtime, C, Node and wheel release builds can reuse compiler snapshots for their platform.
They still assemble their own SDK artifacts and perform cold builds when no compatible entry
-exists. Runtime distribution builds run weekly, manually and on releases; routine tests and
+exists. Runtime builds run weekly and through the release workflow; routine tests and
Clippy continue checking platform-specific code.
## Box image cache
@@ -428,38 +438,11 @@ The `analyze` job is a matrix over `actions`, `c-cpp`, `go`, `javascript-typescr
`rust`. All use `build-mode: none` (source only, no compile) except `go`, whose extractor has to
observe a real build and therefore uses `autobuild`.
-## Manual SDK and Runner builds
-
-Dispatching `build-runner-binary.yml` builds the selected full commit SHA's Linux x64 C SDK,
-then links the Runner against that same-run artifact. Its archive and version identity include
-the commit SHA. Dispatching `build-go.yml` builds the selected workflow ref's C SDK on all
-supported platforms, then tests each Go SDK against its matching artifact. Neither manual
-path requires a published release for the current `Cargo.toml` version.
+## Manual component builds
-The release chain still downloads the published C archives. Reusable Runner callers retain their explicit
-`libboxlite_source` selection: `deploy-infra.yml` supplies its existing C artifact without a
-second C build. A C build failure stops its consumers; manual runs publish no releases or tags.
+Select one of the six component commands in `mbuild-release.yml`. Go uses the matching C SDK matrix and Runner uses only the Linux x64 C archive. The parent runs the selected component’s checks before publishing it.
-Runner release uploads and Go module tagging run only after successful release-origin C SDK
-builds, followed by a successful Runner build or Go test matrix respectively.
-The manual `build-c` job is intentionally skipped on that path, so each publication job uses
-`!cancelled()` and explicit prerequisite-result checks to override the implicit `success()`
-check inherited through the dependency chain. Failed or skipped prerequisites and workflow
-cancellation still prevent publication; manual builds, reusable deployment builds, and
-non-release upstream runs do not publish through these jobs.
-
-## Do not rename these
-
-Two workflows chain off another's **display name**, not its filename. Changing the `name:` below
-silently stops the chain — no error, the downstream workflow simply never fires.
-
-| `name:` | Depended on by |
-| --- | --- |
-| `Build C SDK` | `build-go.yml`, `build-runner-binary.yml` |
-
-Go release tests require the canonical C workflow and read the platform matrix and toolchain
-at that run's commit. A missing or different C run archive stops testing. Before creating
-the Go module tag, the workflow checks that the remote product tag still points to the tested commit.
+For example, `publish-wheels` builds wheels for the supported platforms, verifies the files, attaches them to the selected Release and publishes them to PyPI. With `build-only`, a standalone run builds the selected source and stores its artifacts in Actions. See the [component commands and publication destinations](../../apps/infra/docs/release.md#build-and-publish-one-component).
## Adding a stage
@@ -501,11 +484,11 @@ legacy `boxlite` resources while mdeploy names `boxlite-app`; read the
Repository secrets, in Settings → Secrets and variables → Actions:
- `CARGO_REGISTRY_TOKEN` — crates.io, for the Rust crates
-- `PYPI_API_TOKEN` — PyPI, for the wheels
-- `NPM_TOKEN` — npm, for the Node packages
- `GH_APP_PRIVATE_KEY` — GitHub App key that registers the self-hosted E2E runner
-- `SLACK_WEBHOOK_URL` — optional #release webhook for release dev approvals, final reports and prod apply approvals
-- `SLACK_DEV_DEPLOYMENT_WEBHOOK_URL` — optional #dev_deployment webhook for dev apply approvals. An empty secret skips that channel.
+- `SLACK_WEBHOOK_URL` — optional #release webhook for release and prod approvals, deployment outcomes and release E2E reports
+- `SLACK_DEV_DEPLOYMENT_WEBHOOK_URL` — optional #dev_deployment webhook for standalone dev approvals and dev/stage deployment outcomes. An empty secret skips that channel.
+
+The top-level PyPI and npm jobs use trusted publishing. Configure each registry to authorize `mbuild-release.yml` for the packages it publishes.
## Plugin release artifacts
diff --git a/.github/workflows/build-c.yml b/.github/workflows/build-c.yml
index eaa2ad4e4..e729e2043 100644
--- a/.github/workflows/build-c.yml
+++ b/.github/workflows/build-c.yml
@@ -1,27 +1,7 @@
-# Build C SDK for all supported platforms.
-#
-# Self-contained workflow that builds libboxlite (static and shared libraries),
-# packages them with C headers, and uploads platform-specific archives to
-# GitHub Releases.
-#
-# Archive contents (per platform):
-# - lib/libboxlite.a (static library with Go symbols fixed)
-# - lib/libboxlite.dylib or lib/libboxlite.so (shared library)
-# - include/boxlite.h (C header)
-#
-# These archives are also used by the Go SDK (build-go.yml) which downloads
-# them via the auto-download tool.
-#
-# Triggers:
-# - release: When a GitHub release is published
-# - workflow_dispatch: Manual trigger for testing
-# - workflow_call: A deploy building a selected commit (deploy-infra.yml)
+# Stage C SDK archives for SDK consumers and release publication.
name: Build C SDK
on:
- release:
- types: [ published ]
- workflow_dispatch:
workflow_call:
inputs:
ref:
@@ -29,6 +9,10 @@ on:
required: false
default: ''
type: string
+ full_release:
+ description: 'Build the verified product release on the release matrix runners.'
+ type: boolean
+ default: false
linux_x64_only:
description: 'Build only the C archive the Linux AMD64 Runner consumes.'
required: false
@@ -39,24 +23,24 @@ env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: '0'
-# Least privilege by default; upload-to-release raises its own job to contents: write, which is
-# the only job here that writes anything back to the repository.
permissions:
contents: read
jobs:
- config:
- uses: ./.github/workflows/config.yml
-
resolve-ref:
- name: Resolve build commit
+ name: Prepare build configuration and commit
runs-on: ubuntu-latest
outputs:
sha: ${{ steps.ref.outputs.sha }}
+ platforms: ${{ steps.config.outputs.platforms }}
+ rust-toolchain: ${{ steps.config.outputs.rust-toolchain }}
+ artifact-retention-days: ${{ steps.config.outputs.artifact-retention-days }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
+ - uses: ./.github/actions/ci-config
+ id: config
- name: Validate build commit
id: ref
shell: bash
@@ -92,13 +76,14 @@ jobs:
# ============================================================================
build:
name: Build (${{ matrix.target }})
- needs: [ config, resolve-ref ]
- # Selected commits and runner recovery must build independently of the BoxLite fleet.
- runs-on: ${{ matrix.os == 'ubuntu-latest' && !inputs.ref && !inputs.linux_x64_only && 'boxlite-4vcpu-16gbmem-64gbdisk' || matrix.os }}
+ needs: resolve-ref
+ runs-on: >-
+ ${{ matrix.os == 'ubuntu-latest' && !inputs.linux_x64_only && (inputs.full_release || !inputs.ref)
+ && 'boxlite-4vcpu-16gbmem-64gbdisk' || matrix.os }}
strategy:
fail-fast: false
matrix:
- include: ${{ fromJson(inputs.linux_x64_only && '[{"os":"ubuntu-latest","target":"linux-x64-gnu","rust_target":"x86_64-unknown-linux-gnu"}]' || needs.config.outputs.platforms) }}
+ include: ${{ fromJson(inputs.linux_x64_only && '[{"os":"ubuntu-latest","target":"linux-x64-gnu","rust_target":"x86_64-unknown-linux-gnu"}]' || needs.resolve-ref.outputs.platforms) }}
steps:
- name: Install BoxLite worker build tools
@@ -106,7 +91,7 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends make ripgrep xz-utils zstd \
- build-essential pkg-config libssl-dev patchelf python3
+ build-essential pkg-config libssl-dev patchelf python3 jq
# This job builds a caller-selected commit, and a `uses: ./...` action is resolved from the
# checked-out tree rather than from this workflow's own ref. So the steps below need
@@ -121,7 +106,7 @@ jobs:
- uses: ./.github/actions/setup-rust
with:
- toolchain: ${{ needs.config.outputs.rust-toolchain }}
+ toolchain: ${{ needs.resolve-ref.outputs.rust-toolchain }}
cache: ${{ runner.os != 'Linux' }}
- uses: ./.github/actions/sccache
@@ -173,47 +158,19 @@ jobs:
tar czf "${ARCHIVE_DIR}.tar.gz" "${ARCHIVE_DIR}/"
rm -rf "${ARCHIVE_DIR}"
+ - name: Record build origin
+ working-directory: .
+ run: |
+ jq -n --arg sha "$(git rev-parse HEAD)" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha: $sha, run: $run, attempt: $attempt}' > producer.json
+
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
- name: c-sdk-${{ matrix.target }}
- path: boxlite-c-v*-${{ matrix.target }}.tar.gz
+ overwrite: true
if-no-files-found: error
- retention-days: ${{ needs.config.outputs.artifact-retention-days }}
-
- # ============================================================================
- # UPLOAD TO GITHUB RELEASE
- # ============================================================================
- # Uploads platform-specific C SDK archives to the GitHub Release.
- #
- # Users download the archive for their platform, which contains:
- # - lib/libboxlite.a (static library)
- # - lib/libboxlite.dylib or lib/libboxlite.so (shared library)
- # - include/boxlite.h (C header)
- # ============================================================================
- upload-to-release:
- name: Upload to GitHub Release
- needs: [ config, build ]
- if: github.event_name == 'release' && github.event.action == 'published'
- runs-on: boxlite
- permissions:
- contents: write # Required to upload assets to GitHub Release
-
- steps:
- # Before the download, not after: ./.github/actions/upload-to-release below is resolved from
- # the checked-out tree, and checkout cleans the workspace, which would take the artifacts
- # with it if it ran second.
- - uses: actions/checkout@v4
- with:
- persist-credentials: false # Only the action.yml is needed; nothing here runs git.
-
- - name: Download all artifacts
- uses: actions/download-artifact@v4
- with:
- path: dist
- pattern: c-sdk-*
- merge-multiple: true
-
- - uses: ./.github/actions/upload-to-release
- with:
- files: dist/boxlite-c-v*.tar.gz
+ name: c-sdk-${{ matrix.target }}
+ path: |
+ boxlite-c-v*-${{ matrix.target }}.tar.gz
+ ./producer.json
+ retention-days: ${{ needs.resolve-ref.outputs.artifact-retention-days }}
diff --git a/.github/workflows/build-go.yml b/.github/workflows/build-go.yml
index f326e8276..d69a2fc98 100644
--- a/.github/workflows/build-go.yml
+++ b/.github/workflows/build-go.yml
@@ -1,116 +1,36 @@
-# Test Go SDK and tag Go module for publishing.
-#
-# Release tests use the C release commit and compare its run artifact with the
-# public archive before linking. Manual tests build C from their own commit.
-#
-# User workflow:
-# go get github.com/boxlite-ai/boxlite/sdks/go
-# go run github.com/boxlite-ai/boxlite/sdks/go/cmd/setup
-# go build ./...
-#
-# Triggers:
-# - workflow_run: After a successful release C SDK build (archives are published)
-# - workflow_dispatch: Build and test the selected commit's C and Go SDKs together
name: Build Go SDK
on:
- workflow_run:
- workflows: ["Build C SDK"]
- types: [completed]
- workflow_dispatch:
+ workflow_call:
+ inputs:
+ ref:
+ required: true
+ type: string
permissions:
contents: read
jobs:
config:
- if: >-
- github.event_name != 'workflow_run' ||
- (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
runs-on: boxlite
- permissions:
- contents: read
- actions: read
outputs:
- sha: ${{ steps.checkout.outputs.commit }}
- tag: ${{ steps.release.outputs.tag }}
platforms: ${{ steps.config.outputs.platforms }}
go-version: ${{ steps.config.outputs.go-version }}
steps:
- - name: Install release configuration tools
- run: sudo apt-get update && sudo apt-get install -y --no-install-recommends gh jq
- - name: Verify C release producer
- if: github.event_name == 'workflow_run'
- shell: bash
- env:
- GH_TOKEN: ${{ github.token }}
- C_REPOSITORY: ${{ github.event.workflow_run.head_repository.full_name }}
- C_WORKFLOW_ID: ${{ github.event.workflow_run.workflow_id }}
- C_WORKFLOW_PATH: ${{ github.event.workflow_run.path }}
- C_SHA: ${{ github.event.workflow_run.head_sha }}
- C_RUN_ID: ${{ github.event.workflow_run.id }}
- run: |
- set -euo pipefail
- if [[ "$C_REPOSITORY" != "$GITHUB_REPOSITORY" || ! "$C_SHA" =~ ^[0-9a-f]{40}$ || ! "$C_RUN_ID" =~ ^[0-9]+$ ]]; then
- echo 'Invalid C release repository, commit, or run ID' >&2
- exit 1
- fi
- expected=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build-c.yml" --jq '.id')
- if [[ "$C_WORKFLOW_PATH" != .github/workflows/build-c.yml || ! "$expected" =~ ^[0-9]+$ || "$C_WORKFLOW_ID" != "$expected" ]]; then
- echo 'The triggering run is not the canonical Build C SDK workflow' >&2
- exit 1
- fi
-
- - uses: actions/checkout@v4
- id: checkout
+ - uses: actions/checkout@v5
with:
- ref: ${{ github.event.workflow_run.head_sha || github.sha }}
- fetch-depth: 0
persist-credentials: false
-
- - name: Verify C release tag
- id: release
- if: github.event_name == 'workflow_run'
- shell: bash
- env:
- C_SHA: ${{ github.event.workflow_run.head_sha }}
- RELEASE_TAG: ${{ github.event.workflow_run.head_branch }}
- run: |
- set -euo pipefail
- version=$(awk -F '"' '/^\[workspace\.package\]$/ { workspace=1; next } /^\[/ { workspace=0 } workspace && /^version = "/ { print $2; exit }' Cargo.toml)
- if [[ ! "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || "$RELEASE_TAG" != "v$version" ]]; then
- echo 'The C run did not originate from the canonical workspace release tag' >&2
- exit 1
- fi
- if [[ "$(git rev-parse --verify "refs/tags/$RELEASE_TAG^{commit}")" != "$C_SHA" ]] ||
- ! git merge-base --is-ancestor "$C_SHA" refs/remotes/origin/main; then
- echo 'The product tag must point to the C build commit on main' >&2
- exit 1
- fi
- printf 'tag=%s\n' "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
-
+ - name: Install configuration tools
+ run: sudo apt-get update && sudo apt-get install -y --no-install-recommends jq
- uses: ./.github/actions/ci-config
id: config
- build-c:
- name: Build manual commit C SDK
- if: github.event_name == 'workflow_dispatch'
- permissions:
- contents: write
- uses: ./.github/workflows/build-c.yml
- with:
- ref: ${{ github.sha }}
-
test:
name: Test (${{ matrix.target }})
- needs: [config, build-c]
+ needs: config
permissions:
contents: read
actions: read
- if: >-
- !cancelled() &&
- needs.config.result == 'success' &&
- (needs['build-c'].result == 'success' || needs['build-c'].result == 'skipped')
runs-on: ${{ matrix.os == 'ubuntu-latest' && 'boxlite-4vcpu-16gbmem-30gbdisk' || matrix.os }}
strategy:
fail-fast: false
@@ -120,7 +40,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
- ref: ${{ needs.config.outputs.sha }}
+ ref: ${{ inputs.ref || github.sha }}
persist-credentials: false
# The selected checkout can predate the shared BoxLite setup action.
@@ -134,46 +54,13 @@ jobs:
with:
go-version: ${{ needs.config.outputs.go-version }}
- - name: Download C release run artifact
- if: github.event_name == 'workflow_run'
- uses: actions/download-artifact@v4
- with:
- name: c-sdk-${{ matrix.target }}
- path: ${{ runner.temp }}/c-release-run
- github-token: ${{ github.token }}
- run-id: ${{ github.event.workflow_run.id }}
-
- - name: Download prebuilt library
- if: github.event_name != 'workflow_dispatch'
- shell: bash
- env:
- RELEASE_TAG: ${{ needs.config.outputs.tag }}
- PLATFORM: ${{ matrix.target }}
- run: |
- set -euo pipefail
- directory="boxlite-c-${RELEASE_TAG}-${PLATFORM}"
- archive="$directory.tar.gz"
- expected="$RUNNER_TEMP/c-release-run/$archive"
- test -f "$expected"
- stage=$(mktemp -d "$RUNNER_TEMP/go-c-release.XXXXXX")
- trap 'rm -rf -- "$stage"' EXIT
- curl -fsSL "https://github.com/$GITHUB_REPOSITORY/releases/download/$RELEASE_TAG/$archive" -o "$stage/$archive"
- if ! cmp -s "$expected" "$stage/$archive"; then
- echo "Public C archive $archive differs from the triggering run" >&2
- exit 1
- fi
- tar xzf "$expected" -C "$stage"
- cp "$stage/$directory/lib/libboxlite.a" sdks/go/
-
- name: Download commit libboxlite.a
- if: github.event_name == 'workflow_dispatch'
uses: actions/download-artifact@v4
with:
name: c-sdk-${{ matrix.target }}
path: /tmp/c-sdk
- name: Extract commit libboxlite.a
- if: github.event_name == 'workflow_dispatch'
env:
PLATFORM: ${{ matrix.target }}
run: |
@@ -188,55 +75,3 @@ jobs:
cd sdks/go
go build ./...
go test -v ./...
-
- tag-go-module:
- name: Tag Go Module
- needs: test
- # The manual C build is skipped on releases; publication must also override implicit success().
- if: >-
- !cancelled() &&
- needs.test.result == 'success' &&
- github.event_name == 'workflow_run' &&
- github.event.workflow_run.event == 'release'
- runs-on: boxlite
- permissions:
- contents: write
-
- steps:
- - uses: actions/checkout@v4
- with:
- ref: ${{ github.event.workflow_run.head_sha }}
- fetch-depth: 0
-
- - name: Create Go module tag
- shell: bash
- env:
- C_SHA: ${{ github.event.workflow_run.head_sha }}
- RELEASE_TAG: ${{ github.event.workflow_run.head_branch }}
- run: |
- set -euo pipefail
- product_ref="refs/tags/$RELEASE_TAG"
- go_ref="refs/tags/sdks/go/$RELEASE_TAG"
-
- # Fetch the current remote ref because the tag could have moved during the matrix.
- git fetch --no-tags origin "$product_ref"
- if [[ "$(git rev-parse --verify 'FETCH_HEAD^{commit}')" != "$C_SHA" ]]; then
- echo "Product tag $RELEASE_TAG moved during Go release tests" >&2
- exit 1
- fi
-
- if git ls-remote --exit-code --refs origin "$go_ref" >/dev/null; then
- git fetch --no-tags origin "$go_ref"
- if [[ "$(git rev-parse --verify 'FETCH_HEAD^{commit}')" != "$C_SHA" ]]; then
- echo "Go tag $go_ref points to a different commit" >&2
- exit 1
- fi
- echo "Go tag $go_ref already points to $C_SHA"
- exit 0
- else
- status=$?
- # ls-remote uses 2 for an absent ref. A transport error is not absence.
- if [[ "$status" != 2 ]]; then exit "$status"; fi
- fi
-
- git push origin "$C_SHA:$go_ref"
diff --git a/.github/workflows/build-node.yml b/.github/workflows/build-node.yml
index 3239a5edd..dec75e3a4 100644
--- a/.github/workflows/build-node.yml
+++ b/.github/workflows/build-node.yml
@@ -1,27 +1,19 @@
-# Build Node.js SDK for all supported platforms.
-#
-# Self-contained workflow that builds and publishes Node.js packages to npm.
-# Uses napi-rs for native Rust bindings with platform-specific packages.
-#
-# Package structure:
-# - @boxlite-ai/boxlite (main package with TypeScript wrappers)
-# - @boxlite-ai/boxlite-darwin-arm64 (macOS ARM64 native binary)
-# - @boxlite-ai/boxlite-linux-x64-gnu (Linux x64 glibc native binary)
-#
-# Triggers:
-# - release: When a GitHub release is published
-# - workflow_dispatch: Manual trigger for testing
name: Build Node.js
on:
- release:
- types: [ published ]
- workflow_dispatch:
+ workflow_call:
+ inputs:
+ ref:
+ required: true
+ type: string
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: '0'
+permissions:
+ contents: read
+
jobs:
config:
uses: ./.github/workflows/config.yml
@@ -51,15 +43,23 @@ jobs:
include: ${{ fromJson(needs.config.outputs.platforms) }}
steps:
- - uses: actions/checkout@v4
+ - name: Check out BoxLite runner setup
+ if: matrix.os == 'ubuntu-latest'
+ uses: actions/checkout@v4
with:
- submodules: recursive
-
+ ref: ${{ github.sha }}
+ sparse-checkout: .github/actions/setup-boxlite-runner
+ persist-credentials: false
- uses: ./.github/actions/setup-boxlite-runner
if: matrix.os == 'ubuntu-latest'
with:
native-build: 'true'
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ inputs.ref || github.sha }}
+ submodules: recursive
+
- name: Set up Node.js
uses: actions/setup-node@v4
with:
@@ -109,11 +109,45 @@ jobs:
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
+ overwrite: true
+ if-no-files-found: error
name: artifacts-${{ matrix.target }}
path: sdks/node/artifacts-${{ matrix.target }}.tar
- if-no-files-found: error
retention-days: ${{ needs.config.outputs.artifact-retention-days }}
+ - name: Pack the native package and the Linux acceptance clients
+ working-directory: sdks/node
+ env:
+ TARGET: ${{ matrix.target }}
+ run: |
+ set -euo pipefail
+ # The native build runs inside manylinux. Install the host tools in a clean checkout.
+ src="$RUNNER_TEMP/npm-release"
+ git worktree add --quiet --detach "$src" HEAD
+ tar xf "artifacts-$TARGET.tar" -C "$src/sdks/node"
+ cd "$src/sdks/node"
+ mkdir -p "$GITHUB_WORKSPACE/sdks/node/packages"
+ dest="$GITHUB_WORKSPACE/sdks/node/packages"
+ if [[ "$TARGET" == linux-x64-gnu ]]; then
+ npm install --ignore-scripts --workspaces=false
+ # The existing prepack hook writes optional dependencies for every supported target.
+ npx --no-install napi create-npm-dirs --npm-dir npm
+ npm run build
+ npm pack --pack-destination "$dest"
+ fi
+ test -s "npm/$TARGET/boxlite.$TARGET.node"
+ npm pack "./npm/$TARGET" --ignore-scripts --pack-destination "$dest"
+ jq -n --arg sha "$(git rev-parse HEAD)" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha:$sha,run:$run,attempt:$attempt}' > "$dest/producer.json"
+
+ - name: Stage platform npm packages
+ uses: actions/upload-artifact@v4
+ with:
+ name: npm-${{ matrix.target }}
+ overwrite: true
+ if-no-files-found: error
+ path: sdks/node/packages/
+
# ============================================================================
# TEST
# ============================================================================
@@ -135,13 +169,21 @@ jobs:
node-version: ${{ fromJson(needs.config.outputs.node-versions) }}
steps:
- - uses: actions/checkout@v4
+ - name: Check out BoxLite runner setup
+ if: runner.environment == 'self-hosted'
+ uses: actions/checkout@v4
with:
- submodules: recursive
-
+ ref: ${{ github.sha }}
+ sparse-checkout: .github/actions/setup-boxlite-runner
+ persist-credentials: false
- uses: ./.github/actions/setup-boxlite-runner
if: runner.environment == 'self-hosted'
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ inputs.ref || github.sha }}
+ submodules: recursive
+
- name: Set up Node.js
uses: actions/setup-node@v4
with:
@@ -171,151 +213,43 @@ jobs:
# ============================================================================
# PUBLISH TO NPM
- # ============================================================================
- # Publishes all packages to npm registry using OIDC Trusted Publishing.
- #
- # Key considerations:
- # - Runs on ubuntu-latest but publishes pre-built platform-specific binaries
- # - Install dependencies BEFORE downloading artifacts to avoid EBADPLATFORM
- # (if npm/* directories exist during install, npm validates platform restrictions
- # even with --workspaces=false, causing errors for darwin-arm64 on Linux)
- # - Must publish platform packages BEFORE main package (dependency order)
- # - Uses npm provenance for supply chain security
- # ============================================================================
- publish:
- name: Publish to npm
- needs: [ config, build, test ]
- if: github.event_name == 'release' && github.event.action == 'published'
- runs-on: ubuntu-latest
- permissions:
- id-token: write # Required for npm OIDC Trusted Publishing
- contents: read
-
- steps:
- - uses: actions/checkout@v4
- with:
- submodules: recursive
- - name: Set up Node.js
- uses: actions/setup-node@v4
- with:
- node-version: '24'
- registry-url: 'https://registry.npmjs.org'
-
- # Install BEFORE downloading artifacts to avoid EBADPLATFORM error.
- # If npm/* directories exist, npm validates platform restrictions even
- # with --workspaces=false, causing errors for darwin-arm64 on Linux.
- - name: Install dependencies
- run: cd sdks/node && npm install --ignore-scripts
-
- - name: Build TypeScript
- run: cd sdks/node && npm run build
-
- # Download pre-built artifacts from all platforms (darwin-arm64, linux-x64-gnu)
- # merge-multiple: true combines artifacts from different matrix jobs into one directory
- - name: Download all artifacts
- uses: actions/download-artifact@v4
- with:
- path: sdks/node/artifacts
- pattern: artifacts-*
- merge-multiple: true
-
- # Extract all tar archives to restore file permissions
- - name: Extract artifacts
- run: |
- cd sdks/node
- for tarball in artifacts/*.tar; do
- echo "Extracting $tarball..."
- tar -xvf "$tarball"
- done
-
- - name: List artifacts
- run: |
- ls -la sdks/node/native/
- ls -la sdks/node/npm/
-
- # -------------------------------------------------------------------------
- # NPM PUBLISH (Trusted Publishing via OIDC - no NPM_TOKEN needed)
- # -------------------------------------------------------------------------
- # IMPORTANT: Publish order matters!
- # 1. Platform packages first: @boxlite-ai/boxlite-darwin-arm64, etc.
- # 2. Main package last: @boxlite-ai/boxlite
- #
- # The main package has optionalDependencies pointing to platform packages.
- # If we publish main first, npm install will fail because the platform
- # packages don't exist yet on the registry.
- # -------------------------------------------------------------------------
- - name: Publish platform packages (workspaces)
- run: cd sdks/node && npm publish --provenance --access public --workspaces
-
- - name: Publish main package
- run: cd sdks/node && npm publish --provenance --access public
-
- # ============================================================================
- # UPLOAD TO GITHUB RELEASE
- # ============================================================================
- # Creates npm-compatible tarballs and uploads them to the GitHub Release.
- #
- # This provides an alternative installation method:
- # npm install https://github.com/boxlite-ai/boxlite/releases/download/v0.1.5/boxlite-ai-boxlite-0.1.5.tgz
- #
- # Uses `npm run pack:all` which:
- # - Creates properly versioned .tgz files (e.g., boxlite-ai-boxlite-0.1.5.tgz)
- # - Includes all platform packages and the main package
- # - Produces npm-installable tarballs (unlike raw tar.gz of directories)
- # ============================================================================
- upload-to-release:
- name: Upload to GitHub Release
+ package:
+ name: Pack npm distributions
needs: [ config, build, test ]
- if: github.event_name == 'release' && github.event.action == 'published'
runs-on: boxlite-4vcpu-16gbmem-30gbdisk
- permissions:
- contents: write # Required to upload assets to GitHub Release
steps:
- uses: actions/checkout@v4
-
- - uses: ./.github/actions/setup-boxlite-runner
-
- - name: Set up Node.js
- uses: actions/setup-node@v4
with:
- node-version: '24'
+ ref: ${{ inputs.ref || github.sha }}
- # Install BEFORE downloading artifacts to avoid EBADPLATFORM error.
- # (same reason as publish job - npm validates platform restrictions if npm/* exists)
- - name: Install dependencies
- run: cd sdks/node && npm install --ignore-scripts
+ - name: Install packaging tools
+ run: sudo apt-get update && sudo apt-get install -y --no-install-recommends jq
- # Download pre-built artifacts from all platforms (darwin-arm64, linux-x64-gnu)
- # merge-multiple: true combines artifacts from different matrix jobs into one directory
- - name: Download all artifacts
+ - name: Collect the packages built by each platform
uses: actions/download-artifact@v4
with:
- path: sdks/node/artifacts
- pattern: artifacts-*
- merge-multiple: true
+ pattern: npm-*
+ path: staged-npm
- # Extract all tar archives to restore file permissions
- - name: Extract artifacts
+ - name: Assemble npm distributions without repacking
run: |
- cd sdks/node
- for tarball in artifacts/*.tar; do
- echo "Extracting $tarball..."
- tar -xvf "$tarball"
- done
-
- # pack:all creates versioned .tgz files for all packages:
- # - boxlite-ai-boxlite-X.Y.Z.tgz (main package)
- # - boxlite-ai-boxlite-darwin-arm64-X.Y.Z.tgz
- # - boxlite-ai-boxlite-linux-x64-gnu-X.Y.Z.tgz
- - name: Build and pack packages
+ mkdir -p sdks/node/packages
+ cp staged-npm/*/*.tgz sdks/node/packages/
+
+ - name: Record build origin
+ working-directory: sdks/node/packages
run: |
- cd sdks/node
- npm run build
- npm run pack:all
- ls -la packages/
+ jq -n --arg sha "$(git rev-parse HEAD)" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha: $sha, run: $run, attempt: $attempt}' > producer.json
- - uses: ./.github/actions/upload-to-release
+ - name: Stage npm distributions
+ uses: actions/upload-artifact@v4
with:
- files: sdks/node/packages/*.tgz
+ overwrite: true
+ if-no-files-found: error
+ name: node-packages
+ path: |
+ sdks/node/packages/*.tgz
+ sdks/node/packages/producer.json
diff --git a/.github/workflows/build-runner-binary.yml b/.github/workflows/build-runner-binary.yml
index 2a7cf8531..208739ecb 100644
--- a/.github/workflows/build-runner-binary.yml
+++ b/.github/workflows/build-runner-binary.yml
@@ -1,30 +1,12 @@
-# Build the runner Go binary for Linux amd64.
-#
-# Builds against either the libboxlite.a published for a release or the Linux x64 C SDK artifact
-# produced from the same commit in the current workflow run. The latter is the dev path: the
-# Runner binary and its embedded runtime come from the exact checkout the API is deploying.
-#
-# The runner binary is fully self-contained: it links libboxlite.a, which
-# auto-extracts the embedded runtime at startup.
-#
-# Triggers:
-# - workflow_run: After a successful release C SDK build (libboxlite.a is published)
-# - workflow_dispatch: Build the selected commit's C SDK and Runner together
-# - workflow_call: A deploy building a selected commit (deploy-infra.yml)
name: Build Runner Binary
on:
- workflow_run:
- workflows: ["Build C SDK"]
- types: [completed]
- workflow_dispatch:
+ workflow_call:
inputs:
- ref:
- description: 'Full commit SHA to build with its matching C SDK.'
+ release_tag:
+ description: Product release whose runner is assembled from the same-run C artifact.
required: false
type: string
- workflow_call:
- inputs:
libboxlite_source:
description: 'Explicitly choose artifact for matching-commit deployments or release for published SDKs.'
required: true
@@ -41,33 +23,27 @@ env:
CARGO_TERM_COLOR: always
jobs:
- config:
- if: >-
- github.event_name != 'workflow_run' ||
- (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
- uses: ./.github/workflows/config.yml
-
resolve-ref:
- if: >-
- github.event_name != 'workflow_run' ||
- (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
- name: Resolve build commit
+ name: Prepare build configuration and commit
runs-on: ubuntu-latest
outputs:
sha: ${{ steps.ref.outputs.sha }}
+ go-version: ${{ steps.config.outputs.go-version }}
+ artifact-retention-days: ${{ steps.config.outputs.artifact-retention-days }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
+ - uses: ./.github/actions/ci-config
+ id: config
- name: Validate build commit
id: ref
shell: bash
env:
INPUT_REF: ${{ inputs.ref }}
- WORKFLOW_RUN_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
set -euo pipefail
- candidate="${INPUT_REF:-${WORKFLOW_RUN_SHA:-$GITHUB_SHA}}"
+ candidate="${INPUT_REF:-$GITHUB_SHA}"
[[ "$candidate" =~ ^[0-9a-f]{40}$ ]] || { echo "ref must be a full commit SHA" >&2; exit 1; }
# fetch-depth: 0 above only brings THIS repo's own branches. A commit proposed by an
# open pull request — same-repo or fork — isn't on any of them, so it isn't here yet;
@@ -77,26 +53,9 @@ jobs:
git cat-file -e "$candidate^{commit}"
echo "sha=$candidate" >> "$GITHUB_OUTPUT"
- build-c:
- name: Build manual commit C SDK
- needs: resolve-ref
- # Reusable callers supply a source, even when their event is workflow_dispatch.
- if: github.event_name == 'workflow_dispatch' && !inputs.libboxlite_source
- permissions:
- contents: write
- uses: ./.github/workflows/build-c.yml
- with:
- ref: ${{ needs['resolve-ref'].outputs.sha }}
- linux_x64_only: true
-
build:
name: Build Runner (linux-amd64)
- needs: [config, resolve-ref, build-c]
- if: >-
- !cancelled() &&
- needs.config.result == 'success' &&
- needs['resolve-ref'].result == 'success' &&
- (needs['build-c'].result == 'success' || needs['build-c'].result == 'skipped')
+ needs: resolve-ref
runs-on: ubuntu-latest
permissions:
contents: read
@@ -111,7 +70,7 @@ jobs:
- uses: ./.github/actions/setup-go
with:
- go-version: ${{ needs.config.outputs.go-version }}
+ go-version: ${{ needs.resolve-ref.outputs.go-version }}
- name: Install system dependencies
run: sudo apt-get update && sudo apt-get install -y libx11-dev libxtst-dev libxinerama-dev
@@ -121,12 +80,18 @@ jobs:
shell: bash
env:
BUILD_SHA: ${{ needs.resolve-ref.outputs.sha }}
- INPUT_SOURCE: ${{ inputs.libboxlite_source || (github.event_name == 'workflow_dispatch' && 'artifact' || 'release') }}
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ INPUT_SOURCE: ${{ inputs.libboxlite_source }}
run: |
set -euo pipefail
VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/.*"\(.*\)"/\1/')
- SOURCE="${INPUT_SOURCE:-release}"
- case "$SOURCE" in
+ SOURCE="$INPUT_SOURCE"
+ if [[ -n "$RELEASE_TAG" ]]; then
+ [[ "$RELEASE_TAG" == "v$VERSION" && "$SOURCE" == artifact ]] || exit 1
+ identity="$VERSION"
+ archive="boxlite-runner-$RELEASE_TAG-linux-amd64.tar.gz"
+ else
+ case "$SOURCE" in
release)
identity="$VERSION"
archive="boxlite-runner-v${VERSION}-linux-amd64.tar.gz"
@@ -136,7 +101,8 @@ jobs:
archive="boxlite-runner-v${VERSION}-${BUILD_SHA}-linux-amd64.tar.gz"
;;
*) echo "libboxlite_source must be release or artifact" >&2; exit 1 ;;
- esac
+ esac
+ fi
{
echo "version=$VERSION"
echo "source=$SOURCE"
@@ -208,52 +174,20 @@ jobs:
# Integrity manifest both user-data and the in-place updater verify before installing.
sha256sum "$ARCHIVE" > "$ARCHIVE.sha256"
+ - name: Record build origin
+ working-directory: .
+ run: |
+ jq -n --arg sha "$(git rev-parse HEAD)" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha: $sha, run: $run, attempt: $attempt}' > producer.json
+
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
+ overwrite: true
+ if-no-files-found: error
name: runner-linux-amd64
path: |
boxlite-runner-*-linux-amd64.tar.gz
boxlite-runner-*-linux-amd64.tar.gz.sha256
- if-no-files-found: error
- retention-days: ${{ needs.config.outputs.artifact-retention-days }}
-
- upload-to-release:
- name: Upload to GitHub Release
- needs: [config, resolve-ref, build]
- # The manual C build is skipped on releases; publication must also override implicit success().
- if: >-
- !cancelled() &&
- needs.config.result == 'success' &&
- needs['resolve-ref'].result == 'success' &&
- needs.build.result == 'success' &&
- github.event_name == 'workflow_run' &&
- github.event.workflow_run.event == 'release'
- runs-on: ubuntu-latest
- permissions:
- contents: write
-
- steps:
- - uses: actions/checkout@v4
- with:
- ref: ${{ needs.resolve-ref.outputs.sha }}
-
- - name: Determine version
- id: version
- run: |
- VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/.*"\(.*\)"/\1/')
- echo "version=$VERSION" >> "$GITHUB_OUTPUT"
-
- - name: Download artifacts
- uses: actions/download-artifact@v4
- with:
- path: dist
- pattern: runner-*
- merge-multiple: true
-
- - uses: ./.github/actions/upload-to-release
- with:
- tag-name: v${{ steps.version.outputs.version }}
- files: |
- dist/boxlite-runner-v*.tar.gz
- dist/boxlite-runner-v*.tar.gz.sha256
+ producer.json
+ retention-days: ${{ needs.resolve-ref.outputs.artifact-retention-days }}
diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml
index e38367a69..50207e15d 100644
--- a/.github/workflows/build-runtime.yml
+++ b/.github/workflows/build-runtime.yml
@@ -1,44 +1,19 @@
-# Build BoxLite core runtime + CLI, upload artifacts, and publish to crates.io.
-#
-# This workflow builds the Rust runtime and the `boxlite` CLI binary, then
-# populates the shared sccache cache.
-#
-# Triggers:
-# - weekly: validates distribution builds and refreshes compiler caches.
-# - release: published: builds and uploads
-# - boxlite-runtime-v<version>-<target>.tar.gz (for `cargo install` consumers)
-# - boxlite-cli-v<version>-<target>.tar.gz (self-contained CLI binary;
-# runtime embedded via include_bytes!)
-# - per-file <artifact>.sha256 sidecars
-# - SHA256SUMS (combined integrity manifest)
-# to the GitHub Release, then publishes Rust crates to crates.io
-# (requires CARGO_REGISTRY_TOKEN).
-# - workflow_dispatch: manual build, no publish.
-#
-# Note: SDK workflows (build-wheels, build-node, build-c) also gate on
-# `release: published`. To ship a release, push the tag and then create
-# the release (e.g. `gh release create v0.9.4 --generate-notes
-# --verify-tag`); the user-token-created release.published event fans out
-# to every workflow. Tag-only pushes do NOT publish — see the deferred
-# RELEASE_PAT alternative if that UX is wanted.
-#
-# Platform-specific considerations:
-# - Linux: Uses manylinux_2_28 container for glibc compatibility
-# - Guest binary built on host first (Ubuntu has musl-tools, manylinux doesn't)
-# - Shim/libkrun built in container (needs glibc 2.28)
-# - macOS: Builds directly on runner (ARM64 only)
name: Build Runtime
on:
schedule:
- cron: '0 1 * * 1'
- release:
- types: [published]
- workflow_dispatch:
-
-concurrency:
- group: build-runtime-${{ github.event_name }}-${{ github.ref }}
- cancel-in-progress: false
+ workflow_call:
+ inputs:
+ ref:
+ required: true
+ type: string
+ tag:
+ required: true
+ type: string
+
+permissions:
+ contents: read
env:
CARGO_TERM_COLOR: always
@@ -59,15 +34,23 @@ jobs:
include: ${{ fromJson(needs.config.outputs.platforms) }}
steps:
- - uses: actions/checkout@v4
+ - name: Check out BoxLite runner setup
+ if: matrix.os == 'ubuntu-latest'
+ uses: actions/checkout@v4
with:
- submodules: recursive
-
+ ref: ${{ github.sha }}
+ sparse-checkout: .github/actions/setup-boxlite-runner
+ persist-credentials: false
- uses: ./.github/actions/setup-boxlite-runner
if: matrix.os == 'ubuntu-latest'
with:
native-build: 'true'
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ inputs.ref || github.sha }}
+ submodules: recursive
+
- uses: ./.github/actions/setup-rust
with:
toolchain: ${{ needs.config.outputs.rust-toolchain }}
@@ -102,6 +85,8 @@ jobs:
- name: Upload runtime artifact
uses: actions/upload-artifact@v4
with:
+ overwrite: true
+ if-no-files-found: error
name: runtime-${{ matrix.target }}
path: boxlite-runtime-v*-${{ matrix.target }}.tar.gz
retention-days: 7
@@ -113,30 +98,46 @@ jobs:
[ -f "$CLI_BIN" ] || { echo "ERROR: CLI binary not found at $CLI_BIN"; exit 1; }
tar czf "boxlite-cli-v${VERSION}-${{ matrix.rust_target }}.tar.gz" -C target/release boxlite
+ - name: Record CLI build origin
+ if: inputs.tag && matrix.target == 'linux-x64-gnu'
+ run: |
+ jq -n --arg sha "$(git rev-parse HEAD)" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha:$sha,run:$run,attempt:$attempt}' > producer.json
+
- name: Upload CLI artifact
uses: actions/upload-artifact@v4
with:
+ overwrite: true
+ if-no-files-found: error
name: cli-${{ matrix.target }}
- path: boxlite-cli-v*-${{ matrix.rust_target }}.tar.gz
+ path: |
+ boxlite-cli-v*-${{ matrix.rust_target }}.tar.gz
+ producer.json
retention-days: 7
- upload_to_release:
- name: Upload to GitHub Release
+ package:
+ name: Stage runtime distribution
needs: build
runs-on: boxlite
- if: github.event_name == 'release'
+ if: inputs.tag != ''
permissions:
- contents: write
+ contents: read
id-token: write
attestations: write
steps:
+ - name: Install packaging tools
+ run: sudo apt-get update && sudo apt-get install -y --no-install-recommends jq
+
- name: Checkout (for scripts/release/install.sh.template)
uses: actions/checkout@v4
+ with:
+ ref: ${{ inputs.ref || github.sha }}
- name: Download all build artifacts
uses: actions/download-artifact@v4
with:
+ pattern: "@(runtime|cli)-*"
path: dist
merge-multiple: true
@@ -153,16 +154,8 @@ jobs:
- name: Render install.sh for this release
working-directory: dist
env:
- REF_NAME: ${{ github.ref_name }}
+ VERSION: ${{ inputs.tag }}
run: |
- # github.ref_name on a tag push is the bare tag (e.g. "v0.9.4");
- # on a release event, the release's tag_name is exposed the same way.
- VERSION="$REF_NAME"
- case "$VERSION" in
- v*) ;;
- *) VERSION="v$VERSION" ;; # normalize for safety
- esac
-
sha_for() {
awk '{print $1}' < "boxlite-cli-${VERSION}-$1.tar.gz.sha256"
}
@@ -221,126 +214,16 @@ jobs:
dist/boxlite-cli-*.tar.gz
dist/install.sh
- # Step name retained: scripts/release/test_install.sh locates this block by
- # `- name: Upload to release` to assert dist/install.sh.sha256 ships with the release.
- - name: Upload to release
- uses: ./.github/actions/upload-to-release
- with:
- files: |
- dist/boxlite-runtime-*.tar.gz
- dist/boxlite-cli-*.tar.gz
- dist/*.sha256
- dist/SHA256SUMS
- dist/install.sh
- dist/install.sh.sha256
-
- # Publish Rust crates to crates.io after runtime tarballs are on GitHub Release.
- # Runtime tarballs must exist first because crates.io consumers download them
- # via boxlite/build.rs (auto_detect_registry -> download_prebuilt_runtime).
- #
- # Publish order matters: leaf crates (Tier 1: boxlite-shared, the -sys crates
- # and the VMM crates) before boxlite (Tier 2).
- # BOXLITE_DEPS_STUB=1 skips native builds during cargo publish verification.
- publish_crates:
- name: Publish to crates.io
- needs: upload_to_release
- runs-on: ubuntu-latest
- if: github.event_name == 'release'
- env:
- BOXLITE_DEPS_STUB: "1"
-
- steps:
- - uses: actions/checkout@v4
-
- - uses: ./.github/actions/setup-rust
-
- - name: Install protoc
- run: sudo apt-get update && sudo apt-get install -y protobuf-compiler
-
- - name: Publish leaf crates (Tier 1)
- env:
- CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
- run: |
- set -euo pipefail
-
- publish_crate() {
- local crate="$1"
- shift
- local extra_args="$*"
- echo "::group::Publishing $crate"
- if cargo publish -p "$crate" $extra_args 2>&1 | tee /tmp/publish-"$crate".log; then
- echo "$crate published successfully"
- else
- if grep -q "already uploaded" /tmp/publish-"$crate".log; then
- echo "$crate already on crates.io, skipping"
- else
- echo "::error::Failed to publish $crate"
- exit 1
- fi
- fi
- echo "::endgroup::"
- }
-
- # Pure-Rust crate verifies normally
- publish_crate boxlite-shared
-
- # -sys crates skip verification: vendor sources excluded from package,
- # real build already succeeded in the build job above
- publish_crate libkrun-sys --no-verify
- publish_crate e2fsprogs-sys --no-verify
- publish_crate libgvproxy-sys --no-verify
- publish_crate bubblewrap-sys --no-verify
-
- # boxlite-vmm resolves boxlite-hypervisor from crates.io. Give the
- # index time before publishing the dependent crate.
- publish_crate boxlite-hypervisor
- sleep 60
- publish_crate boxlite-vmm
-
- - name: Wait for crates.io indexing
- run: sleep 60
-
- # boxlite uses --no-verify because the boxlite-shim binary links libkrun,
- # which isn't available in stub mode. The real build already succeeded in the
- # build job, so skipping verification is safe.
- - name: Publish boxlite (Tier 2)
- env:
- CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ - name: Record build origin
+ working-directory: dist
run: |
- set -euo pipefail
- echo "::group::Publishing boxlite"
- if cargo publish -p boxlite --no-verify 2>&1 | tee /tmp/publish-boxlite.log; then
- echo "boxlite published successfully"
- else
- if grep -q "already uploaded" /tmp/publish-boxlite.log; then
- echo "boxlite already on crates.io, skipping"
- else
- echo "::error::Failed to publish boxlite"
- exit 1
- fi
- fi
- echo "::endgroup::"
-
- - name: Wait for boxlite indexing
- run: sleep 60
+ jq -n --arg sha "$(git rev-parse HEAD)" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha: $sha, run: $run, attempt: $attempt}' > producer.json
- # boxlite-cli uses --no-verify because verification would download the
- # prebuilt runtime from GitHub Releases (slow and unnecessary since the
- # real build already succeeded in the build job above).
- - name: Publish boxlite-cli (Tier 3)
- env:
- CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
- run: |
- set -euo pipefail
- echo "::group::Publishing boxlite-cli"
- if cargo publish -p boxlite-cli --no-verify 2>&1 | tee /tmp/publish-boxlite-cli.log; then
- echo "boxlite-cli published successfully"
- else
- if grep -q "already uploaded" /tmp/publish-boxlite-cli.log; then
- echo "boxlite-cli already on crates.io, skipping"
- else
- echo "::error::Failed to publish boxlite-cli"
- exit 1
- fi
- fi
- echo "::endgroup::"
+ - name: Stage release files
+ uses: actions/upload-artifact@v4
+ with:
+ overwrite: true
+ if-no-files-found: error
+ name: runtime-distribution
+ path: dist/
diff --git a/.github/workflows/build-wheels.yml b/.github/workflows/build-wheels.yml
index a46d0e0e9..777f00d83 100644
--- a/.github/workflows/build-wheels.yml
+++ b/.github/workflows/build-wheels.yml
@@ -1,9 +1,11 @@
name: Build Wheels
on:
- release:
- types: [ published ]
- workflow_dispatch: # Allow manual triggering
+ workflow_call:
+ inputs:
+ ref:
+ required: true
+ type: string
env:
SKIP_INSTALL_NODEJS: '1'
@@ -24,16 +26,24 @@ jobs:
include: ${{ fromJson(needs.config.outputs.platforms) }}
steps:
- - name: Checkout code
- uses: actions/checkout@v5
+ - name: Check out BoxLite runner setup
+ if: matrix.os == 'ubuntu-latest'
+ uses: actions/checkout@v4
with:
- submodules: recursive
-
+ ref: ${{ github.sha }}
+ sparse-checkout: .github/actions/setup-boxlite-runner
+ persist-credentials: false
- uses: ./.github/actions/setup-boxlite-runner
if: matrix.os == 'ubuntu-latest'
with:
native-build: 'true'
+ - name: Checkout code
+ uses: actions/checkout@v5
+ with:
+ ref: ${{ inputs.ref || github.sha }}
+ submodules: recursive
+
# cibuildwheel uses this interpreter range with environment updates disabled.
# Its host interpreter needs the library path from the BoxLite tool cache.
- name: Set up the Python interpreter used by cibuildwheel
@@ -68,63 +78,19 @@ jobs:
sudo chown -R "$(id -u):$(id -g)" "$SCCACHE_DIR"
fi
+ - name: Record build origin
+ working-directory: wheelhouse
+ run: |
+ jq -n --arg sha "$(git rev-parse HEAD)" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha: $sha, run: $run, attempt: $attempt}' > producer.json
+
- name: Upload wheels as artifacts
uses: actions/upload-artifact@v4
with:
+ overwrite: true
+ if-no-files-found: error
name: wheels-${{ matrix.os }}
- path: ./wheelhouse/*.whl
+ path: |
+ ./wheelhouse/*.whl
+ wheelhouse/producer.json
retention-days: 7
-
- # cibuildwheel verifies each installed wheel before build_wheels can succeed.
- publish:
- name: Publish to PyPI
- needs: build_wheels
- runs-on: ubuntu-latest
- if: github.event_name == 'release' && github.event.action == 'published'
- permissions:
- id-token: write # IMPORTANT: this permission is mandatory for trusted publishing
-
- steps:
- - name: Download all wheels
- uses: actions/download-artifact@v5
- with:
- path: dist
- pattern: wheels-*
- merge-multiple: true
-
- - name: List wheels
- run: ls -lh dist/
-
- - name: Publish to PyPI
- uses: pypa/gh-action-pypi-publish@release/v1
- with:
- packages-dir: dist/
- skip-existing: true
-
- upload_to_release:
- name: Upload wheels to GitHub Release
- needs: build_wheels
- runs-on: boxlite
- if: github.event_name == 'release' && github.event.action == 'published'
- permissions:
- contents: write # Required to upload to releases
-
- steps:
- # Before the download, not after: ./.github/actions/upload-to-release below is resolved from
- # the checked-out tree, and checkout cleans the workspace, which would take the wheels with
- # it if it ran second.
- - uses: actions/checkout@v5
- with:
- persist-credentials: false # Only the action.yml is needed; nothing here runs git.
-
- - name: Download all wheels
- uses: actions/download-artifact@v5
- with:
- path: dist
- pattern: wheels-*
- merge-multiple: true
-
- - name: Upload wheels to release
- uses: ./.github/actions/upload-to-release
- with:
- files: dist/*.whl
diff --git a/.github/workflows/deploy-infra.yml b/.github/workflows/deploy-infra.yml
index 9a3e3240a..de7c1942f 100644
--- a/.github/workflows/deploy-infra.yml
+++ b/.github/workflows/deploy-infra.yml
@@ -507,6 +507,9 @@ jobs:
name: E2E suite against ${{ inputs.stage }}
needs: [resolve-ref, deploy]
if: ${{ inputs.apply }}
+ permissions:
+ contents: read
+ actions: read
uses: ./.github/workflows/e2e-cloud.yml
with:
ref: ${{ needs.resolve-ref.outputs.sha }}
diff --git a/.github/workflows/e2e-cloud.yml b/.github/workflows/e2e-cloud.yml
index 746509154..0e443ff11 100644
--- a/.github/workflows/e2e-cloud.yml
+++ b/.github/workflows/e2e-cloud.yml
@@ -121,7 +121,21 @@ run-name: E2E cloud against ${{ inputs.stage || 'dev' }}${{ inputs.tag && format
on:
workflow_call:
+ outputs:
+ release_result:
+ description: Outcome of the release acceptance suite
+ value: ${{ jobs.e2e.outputs.release_result }}
inputs:
+ candidate_id: { required: false, type: string }
+ candidate_digest: { required: false, type: string }
+ release_sha:
+ description: Exact tagged commit deployed by release acceptance.
+ required: false
+ type: string
+ deployment_attempt:
+ description: Release dev apply attempt required for acceptance.
+ required: false
+ type: string
ref:
# The commit the caller deployed. Without it the suite would build
# its SDKs from whatever main points at now, while the stack under
@@ -218,6 +232,7 @@ on:
# the tree. Widening this hands that job the deploy role.
permissions:
contents: read
+ actions: read
# One group per stage: runs against the same stage would race over shared
# boxes, while dev and prod share nothing.
@@ -241,6 +256,7 @@ permissions:
concurrency:
group: e2e-cloud-${{ inputs.stage || 'dev' }}
cancel-in-progress: false
+ queue: max
env:
BOXLITE_DEPS_STUB: '1'
@@ -254,7 +270,10 @@ jobs:
name: E2E suite (${{ inputs.stage || 'dev' }})
if: ${{ contains(fromJSON('["dev", "stage", "prod"]'), inputs.stage || 'dev') }}
runs-on: ubuntu-latest
- timeout-minutes: 45
+ timeout-minutes: ${{ inputs.candidate_id && 165 || 45 }}
+ cache-mode: read
+ outputs:
+ release_result: ${{ steps.acceptance.outputs.result }}
env:
# Precedence: a dispatch input overrides for one run; otherwise the
# repo variable is the configured stack; otherwise the built-in
@@ -278,20 +297,77 @@ jobs:
ref: ${{ inputs.ref || github.sha }}
persist-credentials: false
+ - name: Download the dev deployment's release candidate
+ if: inputs.candidate_id
+ uses: ./.github/actions/release-candidate
+ with:
+ id: ${{ inputs.candidate_id }}
+ digest: ${{ inputs.candidate_digest }}
+ tag: ${{ inputs.tag }}
+ sha: ${{ inputs.release_sha }}
+
+ - name: Locate this run's Linux client artifacts
+ if: inputs.candidate_id
+ id: clients
+ env:
+ GH_TOKEN: ${{ github.token }}
+ SHA: ${{ inputs.release_sha }}
+ TAG: ${{ inputs.tag }}
+ run: |
+ set -euo pipefail
+ ids=$(node apps/infra/scripts/release-candidate.mjs client-ids)
+ echo "ids=$ids" >> "$GITHUB_OUTPUT"
+
+ - name: Download only the Linux client artifacts
+ if: inputs.candidate_id
+ uses: actions/download-artifact@v4
+ with:
+ artifact-ids: ${{ steps.clients.outputs.ids }}
+ path: ${{ runner.temp }}/release-clients
+
+ - name: Verify and stage Linux acceptance clients
+ if: inputs.candidate_id
+ env:
+ CANDIDATE_DIGEST: ${{ inputs.candidate_digest }}
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ inputs.release_sha }}
+ CLIENT_ARTIFACT_DIR: ${{ runner.temp }}/release-clients
+ run: node apps/infra/scripts/release-candidate.mjs clients
+
- name: Validate client release
- if: ${{ inputs.tag != '' }}
+ if: inputs.tag || inputs.deployment_attempt
env:
GH_TOKEN: ${{ github.token }}
run: bash scripts/ci/install-e2e-release.sh validate
+ - name: Resolve the published SDK commit
+ id: release_commit
+ if: inputs.deployment_attempt || (inputs.tag && (inputs.stage || 'dev') == 'dev')
+ env:
+ DEPLOYMENT_ATTEMPT: ${{ inputs.deployment_attempt }}
+ RELEASE_SHA: ${{ inputs.release_sha }}
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ sha=$(gh api "repos/boxlite-ai/boxlite/commits/refs%2Ftags%2F$RELEASE_TAG" --jq .sha)
+ [[ "$sha" =~ ^[0-9a-f]{40}$ ]] ||
+ { echo '::error::GitHub did not return a full release commit SHA'; exit 1; }
+ if [[ -n "$DEPLOYMENT_ATTEMPT" ]]; then
+ [[ "$DEPLOYMENT_ATTEMPT" == "$GITHUB_RUN_ATTEMPT" ]] ||
+ { echo '::error::Repeat dev deployment before rerunning release E2E'; exit 1; }
+ [[ "$sha" == "$RELEASE_SHA" ]] ||
+ { echo '::error::Release tag differs from the dev deployment'; exit 1; }
+ fi
+ echo "sha=$sha" >> "$GITHUB_OUTPUT"
+
- name: Checkout release SDK sources for subdomain clients
if: ${{ inputs.tag != '' && (inputs.stage || 'dev') == 'dev' }}
- uses: actions/checkout@v5
- with:
- repository: boxlite-ai/boxlite
- ref: ${{ inputs.tag }}
- path: target/e2e-release
- persist-credentials: false
+ env:
+ RELEASE_SDK_SHA: ${{ steps.release_commit.outputs.sha }}
+ run: |
+ set -euo pipefail
+ git fetch --no-tags --depth=1 https://github.com/boxlite-ai/boxlite.git "$RELEASE_SDK_SHA"
+ git worktree add --detach target/e2e-release "$RELEASE_SDK_SHA"
- name: Require the shared subdomain (dev)
if: ${{ (inputs.stage || 'dev') == 'dev' }}
@@ -539,3 +615,32 @@ jobs:
pytest-identities.xml
pytest-catalog.xml
if-no-files-found: ignore
+
+ - name: Record the deployed pins and tested client hashes
+ if: success() && inputs.candidate_id && inputs.deployment_attempt
+ env:
+ CANDIDATE: ${{ inputs.candidate_id }}
+ DIGEST: ${{ inputs.candidate_digest }}
+ SHA: ${{ inputs.release_sha }}
+ run: |
+ jq -n --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" --argjson id "$CANDIDATE" \
+ --arg digest "$DIGEST" --arg tag "$RELEASE_TAG" --arg sha "$SHA" --slurpfile clients "$RELEASE_ASSET_DIR/tested-clients.json" \
+ '{run:$run,attempt:$attempt,candidate:$id,digest:$digest,tag:$tag,sha:$sha,clients:$clients[0]}' > acceptance.json
+
+ - name: Save dev acceptance for production retries
+ if: success() && inputs.candidate_id && inputs.deployment_attempt
+ uses: actions/upload-artifact@v4
+ with:
+ name: dev-accepted-${{ inputs.candidate_id }}
+ path: acceptance.json
+ if-no-files-found: error
+ overwrite: true
+
+ - name: Summarize release acceptance
+ id: acceptance
+ if: always() && inputs.deployment_attempt
+ env:
+ E2E_RESULT: ${{ job.status }}
+ run: |
+ echo "result=$E2E_RESULT" >> "$GITHUB_OUTPUT"
+ echo "Dev cloud E2E for $RELEASE_TAG — $E2E_RESULT" >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/mbuild-release-on-release.yml b/.github/workflows/mbuild-release-on-release.yml
deleted file mode 100644
index 2b4182c64..000000000
--- a/.github/workflows/mbuild-release-on-release.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-name: Publish Release Images
-run-name: publish ${{ github.event.release.tag_name }} images to GHCR
-
-on:
- release:
- types: [published]
-
-permissions: {}
-
-jobs:
- dispatch:
- name: Dispatch mbuild-release from main
- if: ${{ !github.event.release.prerelease }}
- permissions:
- actions: write
- runs-on: ubuntu-latest
- steps:
- - name: Publish release images to GHCR
- env:
- GH_TOKEN: ${{ github.token }}
- TAG: ${{ github.event.release.tag_name }}
- run: |
- set -Eeuo pipefail
- gh workflow run mbuild-release.yml \
- --repo "$GITHUB_REPOSITORY" \
- --ref main \
- -f command=publish \
- -f tag="$TAG"
diff --git a/.github/workflows/mbuild-release.yml b/.github/workflows/mbuild-release.yml
index f0ee97058..617be6b70 100644
--- a/.github/workflows/mbuild-release.yml
+++ b/.github/workflows/mbuild-release.yml
@@ -1,29 +1,35 @@
-# Release publication and dispatch orchestration hold no cloud Environment.
+# The rollout workflow owns the cloud Environment and stage concurrency.
name: mbuild-release
-run-name: publish ${{ inputs.tag }} to GHCR${{ !inputs['build-only'] && ' · dev acceptance · prod review' || '' }}
+run-name: ${{ inputs.command }} ${{ inputs.tag || inputs['source-ref'] || github.ref_name }}${{ inputs['build-only'] && ' · build only' || '' }}
on:
workflow_dispatch:
inputs:
command:
- description: Publish release images to GHCR
+ description: Full release, fresh component publication, or repair from an accepted candidate
required: true
default: publish
type: choice
- options: [publish]
+ options: [publish, publish-runtime, publish-wheels, publish-node, publish-c, publish-go, publish-runner, repair-runtime, repair-wheels, repair-node, repair-c]
+ candidate-id:
+ description: 'For repair, the Actions artifact ID of the dev-accepted release candidate'
+ type: string
tag:
- description: 'Release tag v<X.Y.Z>, naming a commit on main'
- required: true
+ description: 'Stable tag on main, required for publication'
+ type: string
+ source-ref:
+ description: 'Optional commit or branch for a standalone build-only run; defaults to main'
type: string
build-only:
- description: Build and upload only; skip deployment, E2E and Slack reporting
+ description: Stage standalone build artifacts, or publish only GHCR artifacts for a full build
required: true
default: false
type: boolean
concurrency:
- group: mbuild-release-${{ inputs.tag }}
+ group: mbuild-release-run-${{ inputs.command == 'publish' && inputs.tag || github.run_id }}
cancel-in-progress: false
+ queue: max
permissions:
contents: read
@@ -33,12 +39,23 @@ env:
jobs:
resolve:
+ concurrency:
+ group: mbuild-release-assets-${{ !inputs['build-only'] && inputs.tag || github.run_id }}
+ queue: max
name: resolve ${{ inputs.tag }}
if: ${{ github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
+ permissions:
+ contents: write
outputs:
- sha: ${{ steps.ref.outputs.sha }}
+ sha: ${{ steps.ref.outputs.sha || steps.source.outputs.sha }}
+ mode: ${{ steps.selection.outputs.mode }}
+ builds: ${{ steps.selection.outputs.builds }}
+ group: ${{ steps.selection.outputs.group }}
+ producer: ${{ steps.selection.outputs.producer }}
+ public_release: ${{ steps.draft.outputs.public }}
artifacts: ${{ steps.artifacts.outputs.names }}
+ release_id: ${{ steps.draft.outputs.id }}
steps:
- uses: actions/checkout@v5
with:
@@ -47,8 +64,33 @@ jobs:
# check below compares against. A shallow checkout carries neither.
fetch-depth: 0
+ - name: Select builds and publication scope
+ id: selection
+ env:
+ COMMAND: ${{ inputs.command }}
+ BUILD_ONLY: ${{ inputs['build-only'] }}
+ CANDIDATE: ${{ inputs['candidate-id'] }}
+ SOURCE: ${{ inputs['source-ref'] }}
+ run: node apps/infra/scripts/release-selection.mjs
+
+ - name: Resolve standalone build source
+ id: source
+ if: steps.selection.outputs.mode == 'build'
+ env:
+ SOURCE: ${{ inputs['source-ref'] }}
+ TAG: ${{ inputs.tag }}
+ run: |
+ set -euo pipefail
+ [[ -z "$SOURCE" || -z "$TAG" ]] || { echo 'Choose one source ref or tag' >&2; exit 1; }
+ ref="${SOURCE:-${TAG:-$GITHUB_SHA}}"
+ encoded=$(jq -rn --arg ref "$ref" '$ref | @uri')
+ sha=$(gh api "repos/$GITHUB_REPOSITORY/commits/$encoded" --jq .sha)
+ [[ "$sha" =~ ^[0-9a-f]{40}$ ]]
+ echo "sha=$sha" >> "$GITHUB_OUTPUT"
+
- name: Require a released version
id: version
+ if: steps.selection.outputs.mode != 'build'
shell: bash
env:
TAG: ${{ inputs.tag }}
@@ -85,15 +127,40 @@ jobs:
# `branch` is what refuses a tag whose commit main does not contain — the
# release's bytes and the branch that produces them, checked together.
- id: ref
+ if: steps.selection.outputs.mode != 'build'
uses: ./.github/actions/resolve-ref
with:
ref: ${{ steps.version.outputs.ref }}
branch: ${{ github.ref_name }}
+ - name: Create or select the release draft
+ id: draft
+ if: ${{ !inputs['build-only'] }}
+ env:
+ TAG: ${{ inputs.tag }}
+ COMMAND: ${{ inputs.command }}
+ SHA: ${{ steps.ref.outputs.sha }}
+ run: |
+ set -euo pipefail
+ version=$(git show "$SHA:Cargo.toml" | awk -F '"' '/^\[workspace\.package\]$/ {workspace=1; next} /^\[/ {workspace=0} workspace && /^version = "/ {print $2}')
+ [[ "$TAG" == "v$version" ]] || { echo 'Tag differs from workspace version' >&2; exit 1; }
+ if [[ "$COMMAND" != publish ]]; then
+ release=$(gh release view "$TAG" --json databaseId,isDraft)
+ jq -r '"id=\(.databaseId)\npublic=\(.isDraft | not)"' <<< "$release" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ if ! gh release view "$TAG" --json databaseId >/dev/null; then
+ gh release create "$TAG" --draft --verify-tag --target "$SHA" --generate-notes
+ fi
+ release=$(gh release view "$TAG" --json databaseId,isDraft,tagName)
+ id=$(jq -er --arg tag "$TAG" 'select(.isDraft and .tagName == $tag) | .databaseId' <<< "$release")
+ echo "id=$id" >> "$GITHUB_OUTPUT"
+
# Read out of the released commit with `git show` rather than a second
# checkout: one file is wanted, and the working tree is still main's.
- name: Read the artifacts this release declares
id: artifacts
+ if: inputs.command == 'publish'
shell: bash
env:
SHA: ${{ steps.ref.outputs.sha }}
@@ -108,7 +175,64 @@ jobs:
echo "names=$names" >> "$GITHUB_OUTPUT"
echo "$SHA declares $names"
+ build-runtime:
+ needs: resolve
+ if: ${{ github.ref == 'refs/heads/main' && contains(fromJSON(needs.resolve.outputs.builds), 'runtime') }}
+ uses: ./.github/workflows/build-runtime.yml
+ permissions:
+ contents: read
+ id-token: write
+ attestations: write
+ with:
+ ref: ${{ needs.resolve.outputs.sha }}
+ tag: ${{ needs.resolve.outputs.mode != 'build' && inputs.tag || '' }}
+
+ build-wheels:
+ needs: resolve
+ if: ${{ github.ref == 'refs/heads/main' && contains(fromJSON(needs.resolve.outputs.builds), 'wheels') }}
+ uses: ./.github/workflows/build-wheels.yml
+ with:
+ ref: ${{ needs.resolve.outputs.sha }}
+
+ build-node:
+ needs: resolve
+ if: ${{ github.ref == 'refs/heads/main' && contains(fromJSON(needs.resolve.outputs.builds), 'node') }}
+ uses: ./.github/workflows/build-node.yml
+ with:
+ ref: ${{ needs.resolve.outputs.sha }}
+
+ build-c:
+ needs: resolve
+ if: ${{ github.ref == 'refs/heads/main' && contains(fromJSON(needs.resolve.outputs.builds), 'c') }}
+ uses: ./.github/workflows/build-c.yml
+ with:
+ ref: ${{ needs.resolve.outputs.sha }}
+ full_release: ${{ needs.resolve.outputs.mode == 'release' }}
+ linux_x64_only: ${{ inputs.command == 'publish-runner' }}
+
+ build-go:
+ needs: [resolve, build-c]
+ if: ${{ github.ref == 'refs/heads/main' && contains(fromJSON(needs.resolve.outputs.builds), 'go') }}
+ permissions:
+ contents: read
+ actions: read
+ uses: ./.github/workflows/build-go.yml
+ with:
+ ref: ${{ needs.resolve.outputs.sha }}
+
+ build-runner-binary:
+ needs: [resolve, build-c]
+ if: ${{ github.ref == 'refs/heads/main' && contains(fromJSON(needs.resolve.outputs.builds), 'runner') }}
+ uses: ./.github/workflows/build-runner-binary.yml
+ with:
+ ref: ${{ needs.resolve.outputs.sha }}
+ libboxlite_source: artifact
+ release_tag: ${{ needs.resolve.outputs.mode != 'build' && inputs.tag || '' }}
+
publish:
+ concurrency:
+ group: mbuild-release-ghcr-${{ matrix.artifact }}-${{ inputs.tag }}
+ queue: max
name: publish ${{ inputs.tag }} · ${{ matrix.artifact }}
needs: [resolve]
if: ${{ inputs.command == 'publish' && github.ref == 'refs/heads/main' }}
@@ -151,22 +275,19 @@ jobs:
MSTAGE_ENV_CONFIG: ${{ github.workspace }}/release-source/apps/infra/mstage.env.json
run: |
set -Eeuo pipefail
- for attempt in 1 2 3; do
- npm run --silent mbuild publish -- --tag "$SHA" --ghcr "$GHCR_REPOSITORY" --artifact "$ARTIFACT" --version "$TAG" && exit 0
- status=$?
- if [ "$status" -eq 65 ]; then
- echo "::error title=publish::$ARTIFACT at $SHA failed the dependency audit; details are above"
- exit 1
- fi
- if [ "$status" -eq 78 ]; then
- echo "::error title=publish::$ARTIFACT at $SHA was refused by the image scan gate; findings are above"
- exit 1
- fi
- echo "Publish failed (attempt $attempt/3, exit $status); retrying in $((attempt * 15))s"
- sleep $((attempt * 15))
- done
- echo "::error title=publish::Could not publish $ARTIFACT for $TAG to GHCR after 3 attempts"
- exit 1
+ npm run --silent mbuild publish -- --tag "$SHA" --ghcr "$GHCR_REPOSITORY" --artifact "$ARTIFACT" --version "$TAG" \
+ --replace --output "$GITHUB_WORKSPACE/image.json"
+ jq -n --arg sha "$SHA" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha: $sha, run: $run, attempt: $attempt}' > "$GITHUB_WORKSPACE/producer.json"
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: ghcr-${{ matrix.artifact }}
+ overwrite: true
+ if-no-files-found: error
+ path: |
+ image.json
+ producer.json
- name: Report
if: always()
@@ -190,76 +311,573 @@ jobs:
echo 'Image scanning runs after import into the deployment stage.'
} >> "$GITHUB_STEP_SUMMARY"
- assets:
- name: Wait for release assets
- needs: [resolve, publish]
- if: ${{ !inputs['build-only'] && github.ref == 'refs/heads/main' }}
+ publish-runner:
+ concurrency:
+ group: mbuild-release-ghcr-runner-${{ inputs.tag }}
+ queue: max
+ if: ${{ needs.resolve.outputs.mode != 'build' && github.ref == 'refs/heads/main' }}
+ name: Publish Runner archive to GHCR
+ needs: [resolve, build-runner-binary]
runs-on: ubuntu-latest
- timeout-minutes: 185
+ permissions:
+ contents: read
+ packages: write
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ name: runner-linux-amd64
+ - uses: oras-project/setup-oras@5e2f2482b30b0cb3e14e67f89a80c88c659a7c63 # v2.0.3
+ with:
+ version: 1.3.6
+ - name: Push the exact Runner archive
+ env:
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ needs.resolve.outputs.sha }}
+ run: |
+ set -euo pipefail
+ tarball="boxlite-runner-$TAG-linux-amd64.tar.gz"
+ sha256sum --check --strict "$tarball.sha256"
+ repo="ghcr.io/$GITHUB_REPOSITORY/runner"
+ layout="$RUNNER_TEMP/runner-layout:release"
+ oras push --oci-layout "$layout" --artifact-type application/vnd.boxlite.runner.v1 \
+ --annotation "org.opencontainers.image.revision=$SHA" --annotation "org.opencontainers.image.version=$TAG" \
+ --annotation "org.opencontainers.image.source=$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" "$tarball:application/gzip"
+ manifest=$(oras resolve --oci-layout "$layout")
+ archive="sha256:$(sha256sum "$tarball" | cut -d' ' -f1)"
+ registry_config="$RUNNER_TEMP/oras-registry.json"
+ printf '%s' "$GH_TOKEN" | oras login ghcr.io -u "$GITHUB_ACTOR" --password-stdin --registry-config "$registry_config"
+ oras cp --from-oci-layout --to-registry-config "$registry_config" "$layout" "$repo:$TAG-$SHA"
+ [[ "$(oras resolve --registry-config "$registry_config" "$repo:$TAG-$SHA")" == "$manifest" ]]
+ oras manifest fetch --registry-config "$registry_config" "$repo@$manifest" | jq -e --arg archive "$archive" \
+ '.layers | length == 1 and .[0].digest == $archive' >/dev/null
+ # A fresh host has no Actions token. Exercise its read boundary before dev approval.
+ printf '{"auths":{}}\n' > "$RUNNER_TEMP/anonymous-registry.json"
+ oras manifest fetch --registry-config "$RUNNER_TEMP/anonymous-registry.json" "$repo@$manifest" >/dev/null
+ oras blob fetch --descriptor --registry-config "$RUNNER_TEMP/anonymous-registry.json" "$repo@$archive" >/dev/null
+ jq -n --arg manifest "$manifest" --arg archive "$archive" '{manifest: $manifest, archive: $archive}' > runner.json
+ jq -n --arg sha "$SHA" --argjson run "$GITHUB_RUN_ID" --argjson attempt "$GITHUB_RUN_ATTEMPT" \
+ '{sha: $sha, run: $run, attempt: $attempt}' > producer.json
+ - uses: actions/upload-artifact@v4
+ with:
+ name: ghcr-runner
+ overwrite: true
+ if-no-files-found: error
+ path: |
+ runner.json
+ producer.json
+
+ distribution:
+ if: >-
+ ${{ !cancelled() && github.ref == 'refs/heads/main' &&
+ ((needs.resolve.outputs.mode == 'release' && needs.publish.result == 'success' && needs.publish-runner.result == 'success' &&
+ needs.build-runtime.result == 'success' && needs.build-wheels.result == 'success' && needs.build-node.result == 'success' && needs.build-c.result == 'success') ||
+ (needs.resolve.outputs.mode == 'component' && needs.resolve.outputs.group != '' && needs[needs.resolve.outputs.producer].result == 'success')) }}
+ name: Verify release files
+ needs: [resolve, publish, publish-runner, build-runtime, build-wheels, build-node, build-c]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ actions: read
+ outputs:
+ candidate_id: ${{ steps.upload.outputs.artifact-id }}
+ digest: ${{ steps.stage.outputs.digest }}
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
- - uses: actions/setup-node@v4
+ - uses: actions/download-artifact@v4
with:
- node-version: '22'
- - name: Validate optional release webhook and require release assets
+ pattern: ${{ needs.resolve.outputs.mode == 'component' && (inputs.command == 'publish-runner' && '@(runner-linux-amd64|ghcr-runner)' || format('{0}*', needs.resolve.outputs.group)) || '@(runtime-distribution|wheels-*|node-packages|c-sdk-*|runner-linux-amd64|ghcr-*)' }}
+ path: staged
+ - name: Validate the candidate
+ id: stage
env:
+ SHA: ${{ needs.resolve.outputs.sha }}
TAG: ${{ inputs.tag }}
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
- run: node apps/infra/scripts/release-pipeline.mjs assets
+ IMAGES: ${{ needs.resolve.outputs.artifacts || '[]' }}
+ COMPONENT_GROUP: ${{ needs.resolve.outputs.group }}
+ OPERATION: ${{ needs.resolve.outputs.mode == 'component' && 'component' || 'stage' }}
+ run: |
+ set -euo pipefail
+ digest=$(node apps/infra/scripts/release-candidate.mjs "$OPERATION")
+ echo "digest=$digest" >> "$GITHUB_OUTPUT"
+ - uses: actions/upload-artifact@v4
+ id: upload
+ with:
+ name: ${{ needs.resolve.outputs.mode == 'component' && inputs.command || 'release-candidate' }}-${{ github.run_attempt }}
+ compression-level: 0
+ if-no-files-found: error
+ path: candidate/
- pipeline:
- name: Validate dev and request prod review
- needs: [resolve, assets]
- if: ${{ !inputs['build-only'] && github.ref == 'refs/heads/main' }}
- permissions:
+ dev:
+ name: Dev deployment and acceptance
+ needs: [resolve, publish, publish-runner]
+ if: ${{ needs.resolve.outputs.mode == 'release' && github.ref == 'refs/heads/main' }}
+ permissions: &rollout-permissions
contents: read
- actions: write
+ actions: read
+ pull-requests: read
+ packages: read
+ id-token: write
+ uses: ./.github/workflows/mdeploy-all.yml
+ with:
+ stage: dev
+ ref: ${{ inputs.tag }}
+ release_sha: ${{ needs.resolve.outputs.sha }}
+ release_images: ${{ needs.resolve.outputs.artifacts }}
+ components: api+runner
+ apply: true
+ confirm: true
+ secrets:
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
+ BOXLITE_DEV_API_KEY: ${{ secrets.BOXLITE_DEV_API_KEY }}
+ BOXLITE_DEV_P2_API_KEY: ${{ secrets.BOXLITE_DEV_P2_API_KEY }}
+ BOXLITE_DEV_P2_READONLY_API_KEY: ${{ secrets.BOXLITE_DEV_P2_READONLY_API_KEY }}
+
+ accepted-candidate:
+ name: Locate the previously accepted candidate
+ needs: resolve
+ if: ${{ github.ref == 'refs/heads/main' && needs.resolve.outputs.mode == 'repair' }}
runs-on: ubuntu-latest
- timeout-minutes: 250
+ permissions:
+ actions: read
+ contents: read
+ outputs:
+ id: ${{ steps.receipt.outputs.id }}
+ run: ${{ steps.receipt.outputs.run }}
+ digest: ${{ steps.receipt.outputs.digest }}
+ steps:
+ - id: receipt
+ env:
+ ID: ${{ inputs['candidate-id'] }}
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ needs.resolve.outputs.sha }}
+ run: |
+ set -euo pipefail
+ [[ "$ID" =~ ^[1-9][0-9]*$ ]]
+ api="repos/$GITHUB_REPOSITORY/actions"
+ run=$(gh api "$api/artifacts/$ID" --jq 'select(.expired == false and (.name | test("^release-candidate-[0-9]+$"))) | .workflow_run.id')
+ [[ "$run" =~ ^[1-9][0-9]*$ ]]
+ gh api "$api/runs/$run" | jq -e '.path == ".github/workflows/mbuild-release.yml" and .head_branch == "main" and .event == "workflow_dispatch"' >/dev/null
+ gh run download "$run" --repo "$GITHUB_REPOSITORY" --name "dev-accepted-$ID" --dir "$RUNNER_TEMP/accepted"
+ digest=$(jq -er --arg tag "$TAG" --arg sha "$SHA" --argjson id "$ID" --argjson run "$run" '
+ select(.tag == $tag and .sha == $sha and .candidate == $id and .run == $run)
+ | .digest | select(test("^sha256:[0-9a-f]{64}$"))' "$RUNNER_TEMP/accepted/acceptance.json")
+ printf 'id=%s\nrun=%s\ndigest=%s\n' "$ID" "$run" "$digest" >> "$GITHUB_OUTPUT"
+
+ attach:
concurrency:
- group: mbuild-release-dev-validation
- cancel-in-progress: false
+ group: mbuild-release-assets-${{ inputs.tag }}
+ queue: max
+ name: Attach verified release files
+ needs: [resolve, distribution, build-go, dev, accepted-candidate]
+ if: ${{ !cancelled() && github.ref == 'refs/heads/main' && ((needs.dev.outputs.accepted_attempt != '' && needs.distribution.result == 'success' && needs.build-go.result == 'success') || needs.accepted-candidate.result == 'success' || (needs.resolve.outputs.mode == 'component' && needs.distribution.result == 'success')) }}
outputs:
- phase: ${{ steps.pipeline.outputs.phase }}
- dev_run_id: ${{ steps.pipeline.outputs.dev_run_id }}
- dev_result: ${{ steps.pipeline.outputs.dev_result }}
- e2e_run_id: ${{ steps.pipeline.outputs.e2e_run_id }}
- e2e_result: ${{ steps.pipeline.outputs.e2e_result }}
- prod_run_id: ${{ steps.pipeline.outputs.prod_run_id }}
+ candidate: ${{ needs.distribution.outputs.candidate_id || needs.accepted-candidate.outputs.id }}
+ digest: ${{ needs.distribution.outputs.digest || needs.accepted-candidate.outputs.digest }}
+ run: ${{ needs.accepted-candidate.outputs.run || github.run_id }}
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ actions: read
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
+ - uses: ./.github/actions/release-candidate
+ with:
+ run: ${{ needs.accepted-candidate.outputs.run || github.run_id }}
+ id: ${{ needs.distribution.outputs.candidate_id || needs.accepted-candidate.outputs.id }}
+ digest: ${{ needs.distribution.outputs.digest || needs.accepted-candidate.outputs.digest }}
+ tag: ${{ inputs.tag }}
+ sha: ${{ needs.resolve.outputs.sha }}
+ - name: Match release files to the client bytes accepted by dev
+ if: inputs.command == 'publish'
+ env:
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ needs.resolve.outputs.sha }}
+ CANDIDATE_DIGEST: ${{ needs.distribution.outputs.digest }}
+ DEPLOYMENT_ID: ${{ needs.dev.outputs.candidate_id }}
+ DEPLOYMENT_DIGEST: ${{ needs.dev.outputs.candidate_digest }}
+ DEPLOYMENT_PINS: ${{ needs.dev.outputs.registry_digests }}
+ ACCEPTED_ATTEMPT: ${{ needs.dev.outputs.accepted_attempt }}
+ run: |
+ set -euo pipefail
+ gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" --name "dev-accepted-$DEPLOYMENT_ID" --dir "$RUNNER_TEMP/dev-receipt"
+ ACCEPTANCE_FILE="$RUNNER_TEMP/dev-receipt/acceptance.json" node apps/infra/scripts/release-candidate.mjs check-acceptance
+ - name: Record the exact candidate accepted by dev
+ if: inputs.command == 'publish'
+ env:
+ CANDIDATE: ${{ needs.distribution.outputs.candidate_id }}
+ DIGEST: ${{ needs.distribution.outputs.digest }}
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ needs.resolve.outputs.sha }}
+ ACCEPTED: ${{ needs.dev.outputs.accepted_attempt }}
+ run: |
+ jq -n --argjson run "$GITHUB_RUN_ID" --argjson attempt "$ACCEPTED" --argjson id "$CANDIDATE" \
+ --arg digest "$DIGEST" --arg tag "$TAG" --arg sha "$SHA" \
+ '{run: $run, attempt: $attempt, candidate: $id, digest: $digest, tag: $tag, sha: $sha}' > acceptance.json
+ - uses: actions/upload-artifact@v4
+ if: inputs.command == 'publish'
+ with:
+ name: dev-accepted-${{ needs.distribution.outputs.candidate_id }}
+ path: acceptance.json
+ overwrite: true
+ if-no-files-found: error
+ - name: Verify selected release attachments
+ env:
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ needs.resolve.outputs.sha }}
+ REPAIR_GROUP: ${{ needs.resolve.outputs.group }}
+ CANDIDATE_DIGEST: ${{ needs.distribution.outputs.digest || needs.accepted-candidate.outputs.digest }}
+ RELEASE_ID: ${{ needs.resolve.outputs.release_id }}
+ run: node apps/infra/scripts/release-candidate.mjs attach
+
+ npm:
+ concurrency:
+ group: mbuild-release-npm-${{ inputs.tag }}
+ queue: max
+ if: >-
+ ${{ github.ref == 'refs/heads/main' && contains(fromJSON('["publish","publish-node","repair-node"]'), inputs.command) &&
+ !cancelled() && needs.attach.result == 'success' }}
+ name: Publish verified npm packages
+ needs: [resolve, attach]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ actions: read
+ id-token: write
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+ - uses: ./.github/actions/release-candidate
+ with:
+ run: ${{ needs.attach.outputs.run }}
+ id: ${{ needs.attach.outputs.candidate }}
+ digest: ${{ needs.attach.outputs.digest }}
+ tag: ${{ inputs.tag }}
+ sha: ${{ needs.resolve.outputs.sha }}
- uses: actions/setup-node@v4
with:
- node-version: '22'
- - name: Dispatch existing workflows
- id: pipeline
+ node-version: '24'
+ registry-url: https://registry.npmjs.org
+ - name: Publish platform packages before the main package
env:
TAG: ${{ inputs.tag }}
- RELEASE_SHA: ${{ needs.resolve.outputs.sha }}
- SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
- run: node apps/infra/scripts/release-pipeline.mjs run
+ run: |
+ set -euo pipefail
+ cd "$RELEASE_ASSET_DIR"
+ missing_files=()
+ missing_packages=()
+ missing_integrities=()
+ for file in boxlite-ai-boxlite-*-"${TAG#v}.tgz" "boxlite-ai-boxlite-${TAG#v}.tgz"; do
+ name=$(tar -xOzf "$file" package/package.json | jq -er .name)
+ version=$(tar -xOzf "$file" package/package.json | jq -er .version)
+ [[ "$name" == @boxlite-ai/boxlite* && "$version" == "${TAG#v}" ]]
+ integrity="sha512-$(openssl dgst -sha512 -binary "$file" | openssl base64 -A)"
+ package="$name@$version"
+ if existing=$(npm view "$package" dist.integrity --json 2> "$RUNNER_TEMP/npm-view.log"); then
+ if [[ "$(jq -r . <<< "$existing")" != "$integrity" ]]; then
+ echo "Conflicting npm integrity for $package" >&2
+ exit 1
+ fi
+ else
+ grep -q E404 "$RUNNER_TEMP/npm-view.log" || { cat "$RUNNER_TEMP/npm-view.log" >&2; exit 1; }
+ missing_files+=("$file")
+ missing_packages+=("$package")
+ missing_integrities+=("$integrity")
+ fi
+ done
+
+ for i in "${!missing_files[@]}"; do
+ npm publish "./${missing_files[i]}" --access public --provenance
+ published=$(npm view "${missing_packages[i]}" dist.integrity)
+ if [[ "$published" != "${missing_integrities[i]}" ]]; then
+ echo "Uploaded npm integrity differs for ${missing_packages[i]}" >&2
+ exit 1
+ fi
+ done
+
+ pypi:
+ concurrency:
+ group: mbuild-release-pypi-${{ inputs.tag }}
+ queue: max
+ if: >-
+ ${{ github.ref == 'refs/heads/main' && contains(fromJSON('["publish","publish-wheels","repair-wheels"]'), inputs.command) &&
+ !cancelled() && needs.attach.result == 'success' }}
+ name: Publish to PyPI
+ needs: [resolve, attach]
+ runs-on: ubuntu-latest
+ permissions:
+ id-token: write
+ actions: read
+ contents: read
+
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+ - uses: ./.github/actions/release-candidate
+ with:
+ run: ${{ needs.attach.outputs.run }}
+ id: ${{ needs.attach.outputs.candidate }}
+ digest: ${{ needs.attach.outputs.digest }}
+ tag: ${{ inputs.tag }}
+ sha: ${{ needs.resolve.outputs.sha }}
+ - name: Select accepted wheels
+ run: mkdir dist && cp "$RELEASE_ASSET_DIR"/*.whl dist/
+
+ - name: Check existing PyPI wheels before uploading
+ env:
+ TAG: ${{ inputs.tag }}
+ run: bash scripts/release/verify-pypi-wheels.sh before
+
+ - name: Publish to PyPI
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ packages-dir: dist/
+ skip-existing: true
+ - name: Verify PyPI recorded the accepted wheel hashes
+ env:
+ TAG: ${{ inputs.tag }}
+ run: bash scripts/release/verify-pypi-wheels.sh after
+
+ tag-go-module:
+ concurrency:
+ group: mbuild-release-go-${{ inputs.tag }}
+ queue: max
+ if: >-
+ ${{ github.ref == 'refs/heads/main' && !cancelled() &&
+ ((inputs.command == 'publish' && needs.finalize.result == 'success') ||
+ (inputs.command == 'publish-go' && !inputs['build-only'] && needs.build-go.result == 'success')) }}
+ name: Tag Go Module
+ needs: [resolve, finalize, build-go]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ fetch-depth: 0
+
+ - name: Verify public C SDK downloads
+ env:
+ TAG: ${{ inputs.tag }}
+ RELEASE_ID: ${{ needs.resolve.outputs.release_id }}
+ run: node apps/infra/scripts/release-candidate.mjs verify-public-c
+
+ - name: Create Go module tag
+ shell: bash
+ env:
+ C_SHA: ${{ needs.resolve.outputs.sha }}
+ RELEASE_TAG: ${{ inputs.tag }}
+ run: |
+ set -euo pipefail
+ product_ref="refs/tags/$RELEASE_TAG"
+ go_ref="refs/tags/sdks/go/$RELEASE_TAG"
+
+ # Fetch the current remote ref because the tag could have moved during the matrix.
+ git fetch --no-tags origin "$product_ref"
+ if [[ "$(git rev-parse --verify 'FETCH_HEAD^{commit}')" != "$C_SHA" ]]; then
+ echo "Product tag $RELEASE_TAG moved during Go release tests" >&2
+ exit 1
+ fi
+
+ if git ls-remote --exit-code --refs origin "$go_ref" >/dev/null; then
+ git fetch --no-tags origin "$go_ref"
+ if [[ "$(git rev-parse --verify 'FETCH_HEAD^{commit}')" != "$C_SHA" ]]; then
+ echo "Go tag $go_ref points to a different commit" >&2
+ exit 1
+ fi
+ echo "Go tag $go_ref already points to $C_SHA"
+ exit 0
+ else
+ status=$?
+ # ls-remote uses 2 for an absent ref. A transport error is not absence.
+ if [[ "$status" != 2 ]]; then exit "$status"; fi
+ fi
+
+ git push origin "$C_SHA:$go_ref"
+
+ publish_crates:
+ concurrency:
+ group: mbuild-release-crates-${{ inputs.tag }}
+ queue: max
+ if: >-
+ ${{ github.ref == 'refs/heads/main' && !cancelled() &&
+ ((inputs.command == 'publish' && needs.finalize.result == 'success') ||
+ (inputs.command == 'publish-runtime' && needs.resolve.outputs.public_release == 'true' && needs.attach.result == 'success')) }}
+ name: Publish to crates.io
+ needs: [resolve, finalize, attach]
+ runs-on: ubuntu-latest
+ env:
+ BOXLITE_DEPS_STUB: "1"
+
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ needs.resolve.outputs.sha }}
+
+ - uses: ./.github/actions/setup-rust
+
+ - name: Install protoc
+ run: sudo apt-get update && sudo apt-get install -y protobuf-compiler
+
+ - name: Publish leaf crates (Tier 1)
+ env:
+ CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ run: |
+ set -euo pipefail
+
+ publish_crate() {
+ local crate="$1"
+ shift
+ local extra_args="$*"
+ echo "::group::Publishing $crate"
+ if cargo publish -p "$crate" $extra_args 2>&1 | tee /tmp/publish-"$crate".log; then
+ echo "$crate published successfully"
+ else
+ if grep -q "already uploaded" /tmp/publish-"$crate".log; then
+ echo "$crate already on crates.io, skipping"
+ else
+ echo "::error::Failed to publish $crate"
+ exit 1
+ fi
+ fi
+ echo "::endgroup::"
+ }
+
+ # Pure-Rust crate verifies normally
+ publish_crate boxlite-shared
+
+ # -sys crates skip verification: vendor sources excluded from package,
+ # real build already succeeded in the build job above
+ publish_crate libkrun-sys --no-verify
+ publish_crate e2fsprogs-sys --no-verify
+ publish_crate libgvproxy-sys --no-verify
+ publish_crate bubblewrap-sys --no-verify
+
+ # boxlite-vmm resolves boxlite-hypervisor from crates.io. Give the
+ # index time before publishing the dependent crate.
+ publish_crate boxlite-hypervisor
+ sleep 60
+ publish_crate boxlite-vmm
+
+ - name: Wait for crates.io indexing
+ run: sleep 60
+
+ # boxlite uses --no-verify because the boxlite-shim binary links libkrun,
+ # which isn't available in stub mode. The real build already succeeded in the
+ # build job, so skipping verification is safe.
+ - name: Publish boxlite (Tier 2)
+ env:
+ CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ run: |
+ set -euo pipefail
+ echo "::group::Publishing boxlite"
+ if cargo publish -p boxlite --no-verify 2>&1 | tee /tmp/publish-boxlite.log; then
+ echo "boxlite published successfully"
+ else
+ if grep -q "already uploaded" /tmp/publish-boxlite.log; then
+ echo "boxlite already on crates.io, skipping"
+ else
+ echo "::error::Failed to publish boxlite"
+ exit 1
+ fi
+ fi
+ echo "::endgroup::"
+
+ - name: Wait for boxlite indexing
+ run: sleep 60
+
+ # boxlite-cli uses --no-verify because verification would download the
+ # prebuilt runtime from GitHub Releases (slow and unnecessary since the
+ # real build already succeeded in the build job above).
+ - name: Publish boxlite-cli (Tier 3)
+ env:
+ CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ run: |
+ set -euo pipefail
+ echo "::group::Publishing boxlite-cli"
+ if cargo publish -p boxlite-cli --no-verify 2>&1 | tee /tmp/publish-boxlite-cli.log; then
+ echo "boxlite-cli published successfully"
+ else
+ if grep -q "already uploaded" /tmp/publish-boxlite-cli.log; then
+ echo "boxlite-cli already on crates.io, skipping"
+ else
+ echo "::error::Failed to publish boxlite-cli"
+ exit 1
+ fi
+ fi
+ echo "::endgroup::"
+
+ finalize:
+ concurrency:
+ group: mbuild-release-assets-${{ inputs.tag }}
+ queue: max
+ if: >-
+ ${{ github.ref == 'refs/heads/main' && inputs.command == 'publish' &&
+ !cancelled() && needs.npm.result == 'success' &&
+ needs.pypi.result == 'success' && needs.attach.result == 'success' }}
+ name: Publish the verified GitHub Release
+ needs: [resolve, distribution, attach, pypi, npm]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ actions: read
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+ - uses: ./.github/actions/release-candidate
+ with:
+ id: ${{ needs.distribution.outputs.candidate_id }}
+ digest: ${{ needs.distribution.outputs.digest }}
+ tag: ${{ inputs.tag }}
+ sha: ${{ needs.resolve.outputs.sha }}
+ - name: Recheck release attachments and publish
+ env:
+ TAG: ${{ inputs.tag }}
+ SHA: ${{ needs.resolve.outputs.sha }}
+ CANDIDATE_DIGEST: ${{ needs.distribution.outputs.digest }}
+ RELEASE_ID: ${{ needs.resolve.outputs.release_id }}
+ run: node apps/infra/scripts/release-candidate.mjs finalize
+
+ prod:
+ name: Production deployment
+ needs: [resolve, dev]
+ if: ${{ github.ref == 'refs/heads/main' && needs.resolve.outputs.mode == 'release' && needs.dev.outputs.accepted_attempt != '' }}
+ permissions: *rollout-permissions
+ uses: ./.github/workflows/mdeploy-all.yml
+ with:
+ stage: prod
+ ref: ${{ inputs.tag }}
+ release_sha: ${{ needs.resolve.outputs.sha }}
+ candidate_id: ${{ needs.dev.outputs.candidate_id }}
+ candidate_digest: ${{ needs.dev.outputs.candidate_digest }}
+ registry_digests: ${{ needs.dev.outputs.registry_digests }}
+ accepted_attempt: ${{ needs.dev.outputs.accepted_attempt }}
+ components: api+runner
+ apply: true
+ confirm: true
+ secrets:
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
report:
- name: Report release results
+ name: Report release failure
+ needs: [resolve, build-runtime, build-wheels, build-node, build-c, build-go, build-runner-binary, publish, publish-runner, distribution, dev, accepted-candidate, attach, pypi, npm, tag-go-module, finalize, publish_crates]
+ if: ${{ always() && !inputs['build-only'] && github.ref == 'refs/heads/main' && (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) }}
permissions:
contents: read
actions: read
- needs: [resolve, publish, assets, pipeline]
- if: ${{ always() && !inputs['build-only'] && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
- timeout-minutes: 10
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
- - uses: actions/setup-node@v4
- with:
- node-version: '22'
- - name: Publish summary and Slack notification
+ - name: Report release failure to Slack
env:
TAG: ${{ inputs.tag }}
RELEASE_RESULTS: ${{ toJSON(needs) }}
diff --git a/.github/workflows/mbuild.yml b/.github/workflows/mbuild.yml
index 3a3084137..210014736 100644
--- a/.github/workflows/mbuild.yml
+++ b/.github/workflows/mbuild.yml
@@ -30,6 +30,7 @@ concurrency:
# rather than as the race it is.
group: mbuild-${{ inputs.command }}-${{ inputs.stage || inputs.to }}
cancel-in-progress: false
+ queue: max
permissions:
contents: read
diff --git a/.github/workflows/mdeploy-all.yml b/.github/workflows/mdeploy-all.yml
index 82e6f9e6b..c3c215366 100644
--- a/.github/workflows/mdeploy-all.yml
+++ b/.github/workflows/mdeploy-all.yml
@@ -14,6 +14,41 @@ run-name: >-
${{ inputs.ref || github.sha }} · ${{ inputs.components }}${{ inputs.requested_by != '' && inputs.request_id != '' && format(' · @{0} · {1}', inputs.requested_by, inputs.request_id) || '' }}
on:
+ workflow_call:
+ inputs:
+ stage: { required: true, type: string }
+ ref: { required: true, type: string }
+ release_images: { required: false, type: string }
+ candidate_id: { required: false, type: string }
+ candidate_digest: { required: false, type: string }
+ registry_digests: { required: false, type: string }
+ release_sha: { required: true, type: string }
+ accepted_attempt: { required: false, type: string }
+ components: { required: true, type: string }
+ apply: { required: true, type: boolean }
+ confirm: { required: true, type: boolean }
+ secrets:
+ SLACK_WEBHOOK_URL: { required: false }
+ SLACK_DEV_DEPLOYMENT_WEBHOOK_URL: { required: false }
+ BOXLITE_DEV_API_KEY: { required: false }
+ BOXLITE_DEV_P2_API_KEY: { required: false }
+ BOXLITE_DEV_P2_READONLY_API_KEY: { required: false }
+ outputs:
+ candidate_id:
+ description: Immutable Actions artifact containing the deployment candidate
+ value: ${{ jobs.resolve.outputs.candidate_id }}
+ candidate_digest:
+ description: SHA-256 of the deployment candidate manifest
+ value: ${{ jobs.resolve.outputs.candidate_digest }}
+ registry_digests:
+ description: Verified image and Runner digests used by dev
+ value: ${{ jobs.resolve.outputs.registry_digests }}
+ accepted_attempt:
+ description: Release deployment attempt that passed cloud acceptance
+ value: ${{ jobs.e2e.outputs.release_result == 'success' && jobs.plan.outputs.deployment_attempt || '' }}
+ e2e_result:
+ description: Dev cloud acceptance outcome for release failure reporting
+ value: ${{ jobs.e2e.outputs.release_result }}
workflow_dispatch:
inputs:
requested_by:
@@ -69,6 +104,7 @@ concurrency:
# and two applies against one stage would read and write the same checkpoint.
group: mdeploy-all-${{ inputs.stage }}
cancel-in-progress: false
+ queue: max
permissions:
contents: read
@@ -89,7 +125,7 @@ jobs:
# would cost an approval before the run could tell the operator their ref was
# a typo.
resolve:
- name: resolve ${{ inputs.ref || github.sha }}
+ name: ${{ inputs.release_sha && inputs.stage == 'dev' && format('Verify digests and prepare dev deployment {0}', inputs.ref) || format('resolve {0}', inputs.ref || github.sha) }}
# Dev and stage can exercise candidate workflow branches. Other stages
# retain the main-only guard; release refs are checked separately below.
if: ${{ github.ref == 'refs/heads/main' || inputs.stage == 'dev' || inputs.stage == 'stage' }}
@@ -108,6 +144,9 @@ jobs:
sha: ${{ steps.tag.outputs.sha }}
version: ${{ steps.classify.outputs.version }}
image_tag: ${{ steps.tag.outputs.image }}
+ candidate_id: ${{ steps.upload.outputs.artifact-id }}
+ candidate_digest: ${{ steps.stage.outputs.digest }}
+ registry_digests: ${{ steps.stage.outputs.pins || steps.pins.outputs.digests }}
line: ${{ steps.classify.outputs.line }}
prepare_components: ${{ steps.tag.outputs.prepare_components }}
steps:
@@ -266,52 +305,6 @@ jobs:
echo "#$PR ($([ "$fork" = 'true' ] && echo fork || echo same-repo)) head is $head; deploying merge $sha"
printf 'sha=%s\n' "$sha" >> "$GITHUB_OUTPUT"
- # A tag is not a release. The runner binary a release-path deploy installs
- # is an asset on the GitHub Release — `stack/runner-binary.ts:270` composes
- # that URL — so a tag that was pushed but never released, or released
- # before its build finished, resolves to a download that 404s on the host
- # at boot. Both halves are asked here, where the answer costs one API read
- # instead of a rolled-out fleet that cannot start.
- - name: Require the release this tag names
- if: steps.classify.outputs.version != ''
- shell: bash
- env:
- VERSION: ${{ steps.classify.outputs.version }}
- COMPONENTS: ${{ inputs.components }}
- run: |
- set -Eeuo pipefail
- if ! release="$(gh release view "$VERSION" --repo "$GITHUB_REPOSITORY" --json isDraft,assets 2>&1)"; then
- echo "::error title=release::$VERSION has no GitHub Release; cut one before deploying it${release:+ ($release)}"
- exit 1
- fi
- if [ "$(printf '%s' "$release" | jq -r '.isDraft')" = 'true' ]; then
- echo "::error title=release::$VERSION is still a draft release; publishing it is what starts its builds"
- exit 1
- fi
- # API-only updates do not install a Runner binary.
- if [ "$COMPONENTS" = 'api' ]; then exit 0; fi
- # The names are `build-runner-binary.yml`'s and `runnerArtifactFor`'s.
- # Asked by name rather than by count, because a release carries the
- # SDK archives too.
- tarball="boxlite-runner-${VERSION}-linux-amd64.tar.gz"
- for asset in "$tarball" "${tarball}.sha256"; do
- held="$(printf '%s' "$release" | jq -r --arg name "$asset" '[.assets[] | select(.name == $name)] | length')"
- if [ "$held" = '0' ]; then
- echo "::error title=release::$VERSION carries no $asset; the runner build for that release has not finished or did not succeed"
- exit 1
- fi
- done
- echo "$VERSION carries $tarball and its checksum"
-
- # A tag or a commit becomes a commit here. A pull request took the step
- # above instead, because its merge commit sits on no branch and this
- # check could only refuse it.
- #
- # Every job below addresses these bytes rather than the name they were
- # given: a tag that moved between two resolutions would build one commit
- # and deploy another. `branch` refuses a commit the dispatched branch
- # does not contain — existing is not enough, because a commit on a
- # force-pushed branch still resolves and still names bytes.
- id: ref
if: steps.classify.outputs.pr == ''
uses: ./.github/actions/resolve-ref
@@ -351,8 +344,103 @@ jobs:
esac
fi
+ - name: Validate release caller and published commit
+ if: github.workflow_ref != format('{0}/.github/workflows/mdeploy-all.yml@{1}', github.repository, github.ref)
+ env:
+ RELEASE_SHA: ${{ inputs.release_sha }}
+ RESOLVED: ${{ steps.tag.outputs.sha }}
+ VERSION: ${{ steps.classify.outputs.version }}
+ STAGE: ${{ inputs.stage }}
+ run: |
+ set -euo pipefail
+ [[ "$GITHUB_WORKFLOW_REF" == "$GITHUB_REPOSITORY/.github/workflows/mbuild-release.yml@refs/heads/main" &&
+ "$GITHUB_REF" == refs/heads/main && -n "$VERSION" && "$RELEASE_SHA" == "$RESOLVED" ]] ||
+ { echo '::error::Release caller or published commit mismatch'; exit 1; }
+ case "$STAGE" in
+ dev) ;;
+ prod)
+ gh api "repos/$GITHUB_REPOSITORY/environments/prod" | jq -e 'any(.protection_rules[]?; .type == "required_reviewers" and (.reviewers | length) > 0)' >/dev/null
+ ;;
+ *) exit 1 ;;
+ esac
+
+ - name: Download release digest records
+ if: inputs.release_sha && inputs.stage == 'dev'
+ uses: actions/download-artifact@v4
+ with:
+ pattern: 'ghcr-*'
+ path: staged
+ - name: Verify deployment image and Runner digests
+ if: inputs.release_sha && inputs.stage == 'dev'
+ id: stage
+ env:
+ SHA: ${{ steps.tag.outputs.sha }}
+ TAG: ${{ steps.classify.outputs.version }}
+ IMAGES: ${{ inputs.release_images }}
+ run: |
+ set -euo pipefail
+ digest=$(node apps/infra/scripts/release-candidate.mjs deployment)
+ echo "digest=$digest" >> "$GITHUB_OUTPUT"
+ echo "pins=$(jq -c '{tag,sha,images,runner}' candidate/release-candidate.json)" >> "$GITHUB_OUTPUT"
+ - name: Save the deployment candidate
+ if: inputs.release_sha && inputs.stage == 'dev'
+ uses: actions/upload-artifact@v4
+ id: upload
+ with:
+ name: deployment-candidate-${{ github.run_attempt }}
+ compression-level: 0
+ if-no-files-found: error
+ path: candidate/
+
+ - &verify-dev-acceptance
+ name: Verify dev acceptance for the production candidate
+ if: inputs.release_sha && inputs.stage == 'prod'
+ env:
+ ACCEPTED_ATTEMPT: ${{ inputs.accepted_attempt }}
+ CANDIDATE: ${{ inputs.candidate_id }}
+ DIGEST: ${{ inputs.candidate_digest }}
+ TAG: ${{ inputs.ref }}
+ SHA: ${{ inputs.release_sha }}
+ run: |
+ set -euo pipefail
+ [[ "$CANDIDATE" =~ ^[1-9][0-9]*$ && "$DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]]
+ [[ "$ACCEPTED_ATTEMPT" =~ ^[1-9][0-9]*$ && "$ACCEPTED_ATTEMPT" -le "$GITHUB_RUN_ATTEMPT" ]]
+ receipt=$(mktemp -d "$RUNNER_TEMP/acceptance.XXXXXX")
+ gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" --name "dev-accepted-$CANDIDATE" --dir "$receipt"
+ jq -e --argjson run "$GITHUB_RUN_ID" --argjson id "$CANDIDATE" --argjson attempt "$ACCEPTED_ATTEMPT" \
+ --arg digest "$DIGEST" --arg tag "$TAG" --arg sha "$SHA" \
+ '.run == $run and .candidate == $id and .attempt == $attempt and .digest == $digest and .tag == $tag and .sha == $sha' \
+ "$receipt/acceptance.json" >/dev/null
+
+ - name: Read immutable release image and Runner digests
+ id: pins
+ if: steps.classify.outputs.version != '' && !(inputs.release_sha && inputs.stage == 'dev')
+ env:
+ TAG: ${{ steps.classify.outputs.version }}
+ SHA: ${{ steps.tag.outputs.sha }}
+ PINS: ${{ inputs.registry_digests }}
+ CANDIDATE_ID: ${{ inputs.candidate_id }}
+ CANDIDATE_DIGEST: ${{ inputs.candidate_digest }}
+ RELEASE_CALLER: ${{ inputs.release_sha }}
+ run: |
+ set -euo pipefail
+ if [[ -n "$RELEASE_CALLER" ]]; then
+ [[ "$CANDIDATE_ID" =~ ^[1-9][0-9]*$ && "$CANDIDATE_DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]]
+ printf '%s' "$PINS" > release-pins.json
+ else
+ gh release view "$TAG" --json isDraft | jq -e '.isDraft == false' >/dev/null
+ gh release download "$TAG" --pattern release-candidate.json --dir "$RUNNER_TEMP"
+ cp "$RUNNER_TEMP/release-candidate.json" release-pins.json
+ fi
+ pins=$(jq -ce --arg tag "$TAG" --arg sha "$SHA" '
+ select(.tag == $tag and .sha == $sha and (.images | length > 0))
+ | {tag, sha, images, runner}
+ | select(all(.images[], .runner.manifest, .runner.archive; type == "string" and test("^sha256:[a-f0-9]{64}$")))
+ ' release-pins.json)
+ echo "digests=$pins" >> "$GITHUB_OUTPUT"
+
- name: Notify dev reviewers
- if: inputs.apply && inputs.stage == 'dev'
+ if: inputs.apply && inputs.stage == 'dev' && !inputs.release_sha
continue-on-error: true
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEV_DEPLOYMENT_WEBHOOK_URL }}
@@ -360,19 +448,21 @@ jobs:
APPROVAL_PHASE: ${{ steps.classify.outputs.version != '' && 'Release deployment approval' || 'Commit preparation approval' }}
run: node apps/infra/scripts/release-pipeline.mjs approval
- - name: Notify prod reviewers
- if: inputs.apply && inputs.stage == 'prod'
+ - name: Notify release reviewers
+ if: inputs.apply && (inputs.stage == 'prod' || (inputs.stage == 'dev' && inputs.release_sha))
continue-on-error: true
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
DEPLOY_ENVIRONMENT: ${{ inputs.stage }}
APPROVAL_PHASE: Release deployment approval
+ ACCEPTED_TAG: ${{ inputs.stage == 'prod' && inputs.accepted_attempt && inputs.ref || '' }}
run: node apps/infra/scripts/release-pipeline.mjs approval
# Each commit artifact plans/builds on its own runner; releases use one apply leg.
plan:
name: ${{ matrix.component == 'release' && 'deploy release' || format('plan and build {0}', matrix.component) }} ${{ inputs.stage }}
permissions:
+ actions: read
contents: read
id-token: write
packages: read
@@ -380,6 +470,8 @@ jobs:
if: ${{ !cancelled() && !failure() && (github.ref == 'refs/heads/main' || inputs.stage == 'dev' || inputs.stage == 'stage') }}
environment: ${{ inputs.stage }}
runs-on: ubuntu-latest
+ outputs:
+ deployment_attempt: ${{ steps.applied.outputs.attempt }}
strategy:
fail-fast: false
max-parallel: 2
@@ -388,7 +480,9 @@ jobs:
concurrency:
group: ${{ matrix.component == 'runner' && 'runner-build' || 'mbuild-publish' }}-${{ inputs.stage }}
cancel-in-progress: false
+ queue: max
steps:
+ - *verify-dev-acceptance
- uses: actions/checkout@v5
with:
persist-credentials: false
@@ -432,8 +526,7 @@ jobs:
# Two answers, and every input to them is a read. The runner's answer is
# shorter than it used to be: on the release path there is nothing to
- # decide, because the binary is an asset on the Release and the stack
- # downloads it at boot rather than this run staging it anywhere.
+ # stage locally because the candidate already identifies its GHCR manifest.
- name: Decide
id: plan
working-directory: apps/infra
@@ -454,14 +547,6 @@ jobs:
*api*)
held=0
if [ -n "$VERSION" ]; then
- npm run --silent mbuild verify -- --tag "$SHA" --ghcr "$GHCR_REPOSITORY" --version "$VERSION" || held=$?
- if [ "$held" -eq 66 ]; then
- echo "::error title=missing release::GHCR is missing images for $IMAGE_TAG. Run manually: gh workflow run mbuild-release.yml --repo $GITHUB_REPOSITORY --ref main -f command=publish -f tag=$VERSION"
- exit 1
- elif [ "$held" -ne 0 ]; then
- echo "::error title=registry::could not read GHCR images for $IMAGE_TAG; mbuild verify exited $held"
- exit 1
- fi
api=release-import
else
npm run --silent mbuild verify -- --tag "$IMAGE_TAG" --stage "$STAGE" || held=$?
@@ -483,7 +568,7 @@ jobs:
# Nothing to do here. `stack/runner-binary.ts` addresses the
# GitHub Release asset directly, and `resolve` already proved it
# is attached.
- echo "$VERSION installs the runner tarball from its GitHub Release"
+ echo "$VERSION installs the Runner pinned by its release candidate from GHCR"
else
# `--check` reads the same answer the build itself would, without
# the checkout and the compile behind it. `--tag "$SHA"` because
@@ -552,12 +637,18 @@ jobs:
sha: ${{ needs.resolve.outputs.sha }}
version: ${{ needs.resolve.outputs.version }}
image-tag: ${{ needs.resolve.outputs.image_tag }}
+ registry-digests: ${{ needs.resolve.outputs.registry_digests }}
line: ${{ needs.resolve.outputs.line }}
components: ${{ inputs.components }}
api-route: ${{ steps.plan.outputs.api }}
apply: ${{ inputs.apply }}
confirm: ${{ inputs.confirm }}
+ - name: Record the approved dev apply
+ id: applied
+ if: inputs.release_sha && inputs.stage == 'dev'
+ run: echo "attempt=$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"
+
notify-deploy:
name: Notify reviewers of the commit deployment
continue-on-error: true
@@ -607,8 +698,59 @@ jobs:
sha: ${{ needs.resolve.outputs.sha }}
version: ${{ needs.resolve.outputs.version }}
image-tag: ${{ needs.resolve.outputs.image_tag }}
+ registry-digests: ${{ needs.resolve.outputs.registry_digests }}
line: ${{ needs.resolve.outputs.line }}
components: ${{ inputs.components }}
api-route: skip
apply: ${{ inputs.apply }}
confirm: ${{ inputs.confirm }}
+
+ result:
+ name: Notify deployment result
+ needs: [resolve, plan, deploy]
+ if: ${{ always() && !cancelled() && inputs.apply && needs.resolve.result != 'skipped' && contains(fromJSON('["dev","stage","prod"]'), inputs.stage) }}
+ permissions:
+ contents: read
+ actions: read
+ runs-on: ubuntu-latest
+ env:
+ DEPLOY_ENVIRONMENT: ${{ inputs.stage }}
+ DEPLOY_REF: ${{ inputs.ref || github.sha }}
+ DEPLOY_RESULT: ${{ needs.resolve.result == 'success' && needs.plan.result == 'success' && (needs.resolve.outputs.version || needs.deploy.result == 'success') && 'success' || 'failure' }}
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+ - name: Send release deployment outcome
+ if: inputs.release_sha || inputs.stage == 'prod'
+ continue-on-error: true
+ env:
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
+ run: node apps/infra/scripts/release-pipeline.mjs result
+ - name: Send standalone dev or stage deployment outcome
+ if: ${{ !inputs.release_sha && inputs.stage != 'prod' }}
+ continue-on-error: true
+ env:
+ SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEV_DEPLOYMENT_WEBHOOK_URL }}
+ run: node apps/infra/scripts/release-pipeline.mjs result
+
+ e2e:
+ name: Dev release E2E
+ needs: [resolve, plan]
+ if: inputs.release_sha && inputs.stage == 'dev'
+ permissions:
+ contents: read
+ actions: read
+ uses: ./.github/workflows/e2e-cloud.yml
+ with:
+ stage: dev
+ ref: ${{ github.sha }}
+ release_sha: ${{ needs.resolve.outputs.sha }}
+ tag: ${{ inputs.ref }}
+ candidate_id: ${{ needs.resolve.outputs.candidate_id }}
+ candidate_digest: ${{ needs.resolve.outputs.candidate_digest }}
+ deployment_attempt: ${{ needs.plan.outputs.deployment_attempt || 'missing' }}
+ secrets:
+ BOXLITE_DEV_API_KEY: ${{ secrets.BOXLITE_DEV_API_KEY }}
+ BOXLITE_DEV_P2_API_KEY: ${{ secrets.BOXLITE_DEV_P2_API_KEY }}
+ BOXLITE_DEV_P2_READONLY_API_KEY: ${{ secrets.BOXLITE_DEV_P2_READONLY_API_KEY }}
diff --git a/apps/infra/deployment/release-safety.test.ts b/apps/infra/deployment/release-safety.test.ts
index 4ad40cea6..0995debe3 100644
--- a/apps/infra/deployment/release-safety.test.ts
+++ b/apps/infra/deployment/release-safety.test.ts
@@ -29,7 +29,6 @@ const RELEASE_DEPLOY_WORKFLOW = join(REPO_ROOT, '.github/workflows/deploy-releas
const API_IMAGE_BUILD_WORKFLOW = join(REPO_ROOT, '.github/workflows/build-apps-api-image.yml')
const BUILD_C_WORKFLOW = join(REPO_ROOT, '.github/workflows/build-c.yml')
const BUILD_RUNNER_WORKFLOW = join(REPO_ROOT, '.github/workflows/build-runner-binary.yml')
-const BUILD_GO_WORKFLOW = join(REPO_ROOT, '.github/workflows/build-go.yml')
const E2E_CLOUD_WORKFLOW = join(REPO_ROOT, '.github/workflows/e2e-cloud.yml')
const DEV_DEPLOY_ROLE_TRUST = join(REPO_ROOT, 'apps/infra/bootstrap/aws/deploy-role-trust.json')
const DEV_DEPLOY_ROLE_POLICY = join(REPO_ROOT, 'apps/infra/bootstrap/aws/deploy-role-policy.json')
@@ -1365,123 +1364,21 @@ function workflowExpression(expression: string, context: Record<string, unknown>
return runInNewContext(expression.replace(/^\s*\$\{\{|\}\}\s*$/g, ''), context)
}
-for (const [file, consumer, linuxOnly, name] of [
- [BUILD_RUNNER_WORKFLOW, 'build', true, 'Runner'],
- [BUILD_GO_WORKFLOW, 'test', false, 'Go'],
-] as const) {
- test(`${name} manual builds produce their commit C SDK before consuming it`, () => {
- const workflow = load(readFileSync(file, 'utf8'))
- const producer = workflow.jobs['build-c']
- assert.ok(producer, 'manual builds must produce a C SDK instead of linking the published version')
- assert.equal(producer.uses, './.github/workflows/build-c.yml')
- assert.equal(producer.with.linux_x64_only ?? false, linuxOnly)
- assert.ok(workflow.jobs[consumer].needs.includes('build-c'))
- const sha = 'a'.repeat(40)
- const context = {
- github: { event_name: 'workflow_dispatch', sha },
- inputs: {},
- needs: {
- config: { result: 'success' },
- 'resolve-ref': { result: 'success', outputs: { sha } },
- 'build-c': { result: 'success' },
- },
- cancelled: () => false,
- }
- assert.equal(workflowExpression(producer.if, context), true)
- assert.equal(workflowExpression(producer.with.ref, context), sha)
- assert.equal(workflowExpression(workflow.jobs[consumer].if, context), true)
- for (const result of ['failure', 'cancelled']) {
- context.needs['build-c'].result = result
- assert.equal(workflowExpression(workflow.jobs[consumer].if, context), false, result)
- }
- context.github.event_name = 'workflow_run'
- context.needs['build-c'].result = 'skipped'
- assert.equal(workflowExpression(producer.if, context), false)
- assert.equal(workflowExpression(workflow.jobs[consumer].if, context), true)
- assert.equal(workflowExpression(workflow.jobs[consumer].if, { ...context, cancelled: () => true }), false)
- })
-}
-
-for (const [file, publication, requiredJobs, name] of [
- [BUILD_RUNNER_WORKFLOW, 'upload-to-release', ['config', 'resolve-ref', 'build'], 'Runner'],
- [BUILD_GO_WORKFLOW, 'tag-go-module', ['test'], 'Go'],
-] as const) {
- test(`${name} release publication survives a skipped manual C build without widening publication`, () => {
- const workflow = load(readFileSync(file, 'utf8'))
- const job = workflow.jobs[publication]
- for (const prerequisite of requiredJobs) {
- assert.ok([job.needs].flat().includes(prerequisite), `publication must wait for ${prerequisite}`)
- }
- const context = {
- github: { event_name: 'workflow_run', event: { workflow_run: { event: 'release' } } },
- inputs: {},
- needs: Object.fromEntries(requiredJobs.map((prerequisite) => [prerequisite, { result: 'success' }])),
- cancelled: () => false,
- always: () => true,
- success: () => false,
- failure: () => false,
- }
- assert.equal(workflowExpression(workflow.jobs['build-c'].if, context), false)
- // Actions adds success() when no status function is present. A skipped ancestor
- // makes that default false even after the immediate build/test job succeeds.
- assert.match(
- job.if,
- /\b(?:always|cancelled|success|failure)\s*\(/,
- 'release publication must override implicit success() after the manual C build is skipped',
- )
- assert.equal(workflowExpression(job.if, context), true, 'a successful release must publish')
- assert.equal(workflowExpression(job.if, { ...context, cancelled: () => true }), false)
-
- for (const prerequisite of requiredJobs) {
- for (const result of ['failure', 'cancelled', 'skipped']) {
- assert.equal(
- workflowExpression(job.if, {
- ...context,
- needs: { ...context.needs, [prerequisite]: { result } },
- }),
- false,
- `${prerequisite}=${result} must prevent publication`,
- )
- }
- }
- for (const [event, upstreamEvent] of [
- ['workflow_dispatch', 'release'],
- ['workflow_call', 'release'],
- ['push', 'release'],
- ['workflow_run', 'push'],
- ['workflow_run', 'pull_request'],
- ['workflow_run', 'workflow_dispatch'],
- ['workflow_run', 'schedule'],
- ]) {
- assert.equal(
- workflowExpression(job.if, {
- ...context,
- github: { event_name: event, event: { workflow_run: { event: upstreamEvent } } },
- }),
- false,
- `${event}/${upstreamEvent} must not publish`,
- )
- }
- })
-}
-
-test('manual Runner identity uses its own C artifact while reusable callers keep their selected source', () => {
+test('reusable Runner builds link the selected C artifact or published library', () => {
const workflow = load(readFileSync(BUILD_RUNNER_WORKFLOW, 'utf8'))
const step = workflow.jobs.build.steps.find((step: any) => step.name === 'Resolve artifact identity')
const fixture = mkdtempSync(join(tmpdir(), 'boxlite-runner-source-'))
try {
for (const [event, inputSource, expected] of [
- ['workflow_dispatch', '', 'artifact'],
['workflow_dispatch', 'artifact', 'artifact'],
['workflow_dispatch', 'release', 'release'],
- ['workflow_run', '', 'release'],
]) {
const output = join(fixture, `${event}-${inputSource || 'direct'}`)
const context = { github: { event_name: event }, inputs: { libboxlite_source: inputSource } }
const source = workflowExpression(step.env.INPUT_SOURCE, context) ?? ''
const result = spawnSync('bash', ['-euo', 'pipefail', '-c', step.run], {
cwd: REPO_ROOT,
- env: { ...process.env, BUILD_SHA: 'a'.repeat(40), INPUT_SOURCE: source, GITHUB_OUTPUT: output },
+ env: { ...process.env, BUILD_SHA: 'a'.repeat(40), RELEASE_TAG: '', INPUT_SOURCE: source, GITHUB_OUTPUT: output },
encoding: 'utf8',
})
assert.equal(result.status, 0, result.stderr)
@@ -1493,205 +1390,29 @@ test('manual Runner identity uses its own C artifact while reusable callers keep
)
assert.equal(fields.source, expected, `${event}: ${inputSource || 'direct'}`)
assert.equal(fields.archive.includes('a'.repeat(40)), expected === 'artifact')
- if (inputSource) assert.equal(workflowExpression(workflow.jobs['build-c'].if, context), false)
}
} finally {
rmSync(fixture, { recursive: true, force: true })
}
})
-test('Go builds select their C artifact by trigger', () => {
- const workflow = load(readFileSync(BUILD_GO_WORKFLOW, 'utf8'))
- const steps = workflow.jobs.test.steps
- const download = steps.find((step: any) => step.name === 'Download commit libboxlite.a')
- assert.ok(download, 'manual Go tests must consume their same-run C SDK artifact')
- const extract = steps.find((step: any) => step.name === 'Extract commit libboxlite.a')
- assert.ok(extract, 'manual Go tests must extract their same-run C SDK artifact')
- assertShellLine(
- extract.run,
- /cp "\/tmp\/\$\(basename "\$archive" \.tar\.gz\)\/lib\/libboxlite\.a" sdks\/go\/libboxlite\.a/,
- )
- const release = steps.find((step: any) => step.name === 'Download prebuilt library')
- const context = {
- github: { event_name: 'workflow_dispatch' },
- }
- assert.equal(workflowExpression(download.if, context), true)
- assert.equal(workflowExpression(extract.if, context), true)
- assert.equal(workflowExpression(release.if, context), false)
- for (const target of ['linux-x64-gnu', 'linux-arm64-gnu', 'darwin-arm64']) {
- const name = download.with.name.replace(/\$\{\{(.*?)\}\}/g, (_match: string, expression: string) =>
- workflowExpression(expression, { matrix: { target } }),
- )
- assert.equal(name, `c-sdk-${target}`)
- }
- context.github.event_name = 'workflow_run'
- assert.equal(workflowExpression(download.if, context), false)
- assert.equal(workflowExpression(extract.if, context), false)
- assert.equal(workflowExpression(release.if, context), true)
-})
-
-test('Go release checkout and archive follow the C run when main has advanced', () => {
- const workflow = load(readFileSync(BUILD_GO_WORKFLOW, 'utf8'))
- const releaseSha = 'a'.repeat(40)
- const mainSha = 'b'.repeat(40)
- const github = { event_name: 'workflow_run', sha: mainSha, run_id: 20, event: { workflow_run: { head_sha: releaseSha, id: 10 } } }
- const configJob = workflow.jobs.config.uses
- ? load(readFileSync(join(REPO_ROOT, '.github/workflows/config.yml'), 'utf8')).jobs.config
- : workflow.jobs.config
- const checkout = configJob.steps.find((step: any) => step.uses?.startsWith('actions/checkout@'))
- assert.equal(checkout.with?.ref ? workflowExpression(checkout.with.ref, { github }) : github.sha, releaseSha)
- const testCheckout = workflow.jobs.test.steps.find((step: any) => step.uses?.startsWith('actions/checkout@'))
- assert.equal(workflowExpression(testCheckout.with?.ref ?? 'github.sha', {
- github,
- needs: { config: { outputs: { sha: releaseSha } } },
- }), releaseSha)
- const tagCheckout = workflow.jobs['tag-go-module'].steps.find((step: any) => step.uses?.startsWith('actions/checkout@'))
- assert.equal(workflowExpression(tagCheckout.with?.ref ?? 'github.sha', { github }), releaseSha)
- const artifact = workflow.jobs.test.steps.find((step: any) => step.name === 'Download C release run artifact')
- assert.equal(workflowExpression(artifact?.with?.['run-id'] ?? 'github.run_id', { github }), 10)
-})
-
-test('Go release refuses a same-name workflow before trusting its run', () => {
- const workflow = load(readFileSync(BUILD_GO_WORKFLOW, 'utf8'))
- const github = {
- event_name: 'workflow_run',
- event: { workflow_run: { conclusion: 'success', event: 'release' } },
- }
- const step = workflow.jobs.config.steps?.find((candidate: any) => candidate.name === 'Verify C release producer')
- if (!step) {
- assert.equal(workflowExpression(workflow.jobs.config.if, { github }), false, 'a name-only producer enters Go configuration')
- return
- }
- const fixture = mkdtempSync(join(tmpdir(), 'boxlite-go-producer-'))
- try {
- writeFileSync(join(fixture, 'gh'), '#!/bin/sh\nprintf "245927919\\n"\n', { mode: 0o755 })
- const env = {
- ...process.env,
- PATH: fixture + ':' + process.env.PATH,
- GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
- C_REPOSITORY: 'boxlite-ai/boxlite',
- C_WORKFLOW_PATH: '.github/workflows/build-c.yml',
- C_SHA: 'a'.repeat(40),
- C_RUN_ID: '10',
- }
- const run = (id: string, path = env.C_WORKFLOW_PATH) => spawnSync('bash', ['-c', step.run], {
- env: { ...env, C_WORKFLOW_ID: id, C_WORKFLOW_PATH: path },
- encoding: 'utf8',
- })
- const accepted = run('245927919')
- assert.equal(accepted.status, 0, accepted.stderr)
- assert.notEqual(run('245927920').status, 0, 'the producer ID must match')
- assert.notEqual(run('245927919', '.github/workflows/other.yml').status, 0, 'the producer path must match')
- } finally {
- rmSync(fixture, { recursive: true, force: true })
- }
-})
-
-test('Go publication refuses a product tag that moves during the matrix', () => {
- const workflow = load(readFileSync(BUILD_GO_WORKFLOW, 'utf8'))
- const step = workflow.jobs['tag-go-module'].steps.find((candidate: any) => candidate.name === 'Create Go module tag')
- const fixture = mkdtempSync(join(tmpdir(), 'boxlite-go-release-tag-'))
- const origin = join(fixture, 'remote.git')
- // Git hooks export repository selectors that override the fixture's cwd.
- const fixtureEnvironment = Object.fromEntries(
- Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')),
- )
- const git = (...args: string[]) => {
- const result = spawnSync('git', args, { cwd: fixture, encoding: 'utf8', env: fixtureEnvironment })
- assert.equal(result.status, 0, result.stderr)
- return result.stdout.trim()
- }
- try {
- git('init', '--quiet', '-b', 'main')
- git('init', '--quiet', '--bare', origin)
- git('config', 'user.name', 'BoxLite test')
- git('config', 'user.email', '[email protected]')
- writeFileSync(join(fixture, 'Cargo.toml'), '[workspace.package]\nversion = "0.12.0"\n')
- git('add', 'Cargo.toml')
- git('commit', '--quiet', '-m', 'release')
- const releaseSha = git('rev-parse', 'HEAD')
- git('remote', 'add', 'origin', origin)
- git('tag', 'v0.12.0', releaseSha)
- git('push', '--quiet', 'origin', 'refs/tags/v0.12.0')
- git('commit', '--quiet', '--allow-empty', '-m', 'new main')
- git('push', '--quiet', '--force', 'origin', 'HEAD:refs/tags/v0.12.0')
- git('checkout', '--quiet', '--detach', releaseSha)
- const run = () => spawnSync('bash', ['-c', step.run], {
- cwd: fixture,
- env: { ...fixtureEnvironment, C_SHA: releaseSha, RELEASE_TAG: 'v0.12.0' },
- encoding: 'utf8',
- })
- assert.notEqual(run().status, 0, 'a moved product tag must block the Go module tag')
- assert.equal(git('ls-remote', 'origin', 'refs/tags/sdks/go/v0.12.0'), '')
- git('push', '--quiet', 'origin', ':refs/tags/v0.12.0')
- assert.notEqual(run().status, 0, 'a deleted product tag must block publication')
- git('push', '--quiet', 'origin', 'refs/tags/v0.12.0')
- const published = run()
- assert.equal(published.status, 0, published.stderr)
- assert.equal(git('ls-remote', 'origin', 'refs/tags/sdks/go/v0.12.0').split(/\s/)[0], releaseSha)
- const retry = run()
- assert.equal(retry.status, 0, retry.stderr)
- git('tag', '-a', 'sdks/go/v0.12.0', '-m', 'annotated release', releaseSha)
- git('push', '--quiet', '--force', 'origin', 'refs/tags/sdks/go/v0.12.0')
- const annotated = git('ls-remote', '--refs', 'origin', 'refs/tags/sdks/go/v0.12.0')
- git('remote', 'set-url', '--push', 'origin', join(fixture, 'read-only-remote'))
- const annotatedRetry = run()
- assert.equal(annotatedRetry.status, 0, annotatedRetry.stderr)
- assert.equal(git('ls-remote', '--refs', 'origin', 'refs/tags/sdks/go/v0.12.0'), annotated)
- } finally {
- rmSync(fixture, { recursive: true, force: true })
- }
-})
-
-test('Go release compares the public tarball before extracting the C library', () => {
- const workflow = load(readFileSync(BUILD_GO_WORKFLOW, 'utf8'))
- const step = workflow.jobs.test.steps.find((candidate: any) => candidate.name === 'Download prebuilt library')
- const fixture = mkdtempSync(join(tmpdir(), 'boxlite-go-archive-'))
- const version = `9000.${process.pid}.${Date.now()}`
- const target = 'linux-x64-gnu'
- const archiveDir = `boxlite-c-v${version}-${target}`
- const publicArchive = join(fixture, 'public.tar.gz')
- const runArchive = join(fixture, 'c-release-run', `${archiveDir}.tar.gz`)
- const library = join(fixture, 'sdks/go/libboxlite.a')
- try {
- mkdirSync(join(fixture, 'payload', archiveDir, 'lib'), { recursive: true })
- mkdirSync(join(fixture, 'c-release-run'))
- mkdirSync(join(fixture, 'sdks/go'), { recursive: true })
- writeFileSync(join(fixture, 'payload', archiveDir, 'lib/libboxlite.a'), 'public C bytes')
- writeFileSync(join(fixture, 'Cargo.toml'), `[workspace.package]\nversion = "${version}"\n`)
- const tar = spawnSync('tar', ['czf', publicArchive, '-C', join(fixture, 'payload'), archiveDir], { encoding: 'utf8' })
- assert.equal(tar.status, 0, tar.stderr)
- writeFileSync(join(fixture, 'curl'), [
- '#!/bin/sh',
- 'while [ "$#" -gt 0 ]; do',
- ' if [ "$1" = "-o" ]; then exec cp "$PUBLIC_ARCHIVE" "$2"; fi',
- ' shift',
- 'done',
- 'exec cat "$PUBLIC_ARCHIVE"',
- '',
- ].join('\n'), { mode: 0o755 })
- const run = () => spawnSync('bash', ['-c', step.run.replaceAll('${{ matrix.target }}', target)], {
- cwd: fixture,
- env: {
- ...process.env, PATH: fixture + ':' + process.env.PATH, PUBLIC_ARCHIVE: publicArchive,
- RUNNER_TEMP: fixture, GITHUB_REPOSITORY: 'boxlite-ai/boxlite', RELEASE_TAG: `v${version}`, PLATFORM: target,
- },
- encoding: 'utf8',
- })
- writeFileSync(runArchive, 'different C run bytes')
- assert.notEqual(run().status, 0, 'different public bytes must not enter Go tests')
- assert.equal(existsSync(library), false)
- rmSync(runArchive)
- assert.notEqual(run().status, 0, 'the C run tarball is required')
- assert.equal(existsSync(library), false)
- writeFileSync(runArchive, readFileSync(publicArchive))
- const verified = run()
- assert.equal(verified.status, 0, verified.stderr)
- assert.equal(readFileSync(library, 'utf8'), 'public C bytes')
- } finally {
- rmSync(join(tmpdir(), archiveDir), { recursive: true, force: true })
- rmSync(fixture, { recursive: true, force: true })
+test('the C archive reaches Go and Runner through the same release run and Go tagging follows public release', () => {
+ const release = load(readFileSync(join(REPO_ROOT, '.github/workflows/mbuild-release.yml'), 'utf8'))
+ for (const name of ['build-go', 'build-runner-binary']) {
+ assert.ok(release.jobs[name].needs.includes('build-c'))
+ assert.equal(release.jobs[name].with.ref, '${{ needs.resolve.outputs.sha }}')
+ const build = load(readFileSync(join(REPO_ROOT, '.github/workflows', name + '.yml'), 'utf8'))
+ assert.deepEqual(Object.keys(build.on).sort(), ['workflow_call'])
+ const steps = (build.jobs.test ?? build.jobs.build).steps
+ const download = steps.find((step: any) => step.name === 'Download commit libboxlite.a')
+ assert.match(download.uses, /^actions\/download-artifact@/)
+ assert.match(download.with.name, /^c-sdk-/)
+ assert.ok(!('run-id' in download.with))
}
+ assert.equal(release.jobs['build-runner-binary'].with.libboxlite_source, 'artifact')
+ assert.ok(release.jobs['tag-go-module'].needs.includes('finalize'))
+ assert.ok(release.jobs.attach.needs.includes('dev'))
+ assert.ok(release.jobs.finalize.needs.includes('attach'))
})
test('the cloud E2E suite is reachable only from a deploy or a human', () => {
@@ -1989,11 +1710,8 @@ test('a job calling a reusable workflow grants at least what that workflow asks
checked += 1
}
}
- // The same eleven the input sweep below counts: five `config.yml` loads,
- // deploy-infra's four and two manual SDK builds. The exact count, not a
- // floor, so a call that stops being swept fails here rather than being
- // absorbed — and adding one means changing this number in the same commit.
- assert.equal(checked, 11, `expected every local reusable call to be swept, saw ${checked}`)
+ // Keep the permission sweep in sync with every local workflow call.
+ assert.equal(checked, 16, `expected every local reusable call to be swept, saw ${checked}`)
})
test('every reusable workflow is called with the inputs it declares', () => {
@@ -2033,14 +1751,8 @@ test('every reusable workflow is called with the inputs it declares', () => {
checked += 1
}
}
- // Every local `uses:` in the directory, not just the deploy path's: five
- // build workflows load `config.yml`, `deploy-infra.yml` calls four, and
- // the manual Runner and Go builds each call
- // build-c to pair their SDK sources with the native library from that commit.
- // The exact count, not a floor: a call that stops being swept is the drop
- // this exists to catch, and one that appears is a caller nobody reviewed.
- // Adding a legitimate one means changing this number in the same commit.
- assert.equal(checked, 11, `expected every reusable-workflow call swept, saw ${checked}`)
+ // Three configuration calls, four deploy-infra calls, eight release calls and one mdeploy-all E2E call.
+ assert.equal(checked, 16, `expected every reusable-workflow call swept, saw ${checked}`)
})
/**
@@ -2459,3 +2171,20 @@ test('the runtime boundary admits the bucket the Runner is actually pointed at',
const admits = prefixes.some((pattern: any) => new RegExp(`^${pattern.replace(/\*/g, '.*')}$`).test(`${bucket}/runner/x`))
assert.ok(admits, `no BoxLiteBucketObjects prefix admits ${bucket}/runner/*; prefixes: ${prefixes.join(', ')}`)
})
+
+test('product release builds form one run with shared C artifacts', () => {
+ const workflows = join(REPO_ROOT, '.github/workflows')
+ const parent = load(readFileSync(join(workflows, 'mbuild-release.yml'), 'utf8'))
+ for (const producer of ['build-runtime', 'build-wheels', 'build-node', 'build-c', 'build-go', 'build-runner-binary']) {
+ const path = './.github/workflows/' + producer + '.yml'
+ const workflow = load(readFileSync(join(REPO_ROOT, path), 'utf8'))
+ assert.equal(workflow.on.release, undefined, producer + ' still starts an independent release run')
+ assert.equal(workflow.on.workflow_run, undefined, producer + ' still starts an independent downstream run')
+ assert.ok(workflow.on.workflow_call, producer + ' must be reusable')
+ const caller = values(parent.jobs).find((job) => job.uses === path)
+ assert.ok(caller, 'mbuild-release must own ' + producer)
+ if (producer === 'build-go' || producer === 'build-runner-binary') {
+ assert.ok([caller.needs].flat().includes('build-c'), producer + ' must wait for the same C artifacts')
+ }
+ }
+})
diff --git a/apps/infra/deployment/workflow-checks.test.ts b/apps/infra/deployment/workflow-checks.test.ts
index 7e7252620..fc313b228 100644
--- a/apps/infra/deployment/workflow-checks.test.ts
+++ b/apps/infra/deployment/workflow-checks.test.ts
@@ -108,6 +108,22 @@ test('the C SDK worker installs its host tools before checking out a selected co
assert.match(steps[bootstrap].run, /apt-get install/)
})
+for (const [file, job] of [
+ ['build-node.yml', 'build'], ['build-node.yml', 'test'],
+ ['build-runtime.yml', 'build'], ['build-wheels.yml', 'build_wheels'],
+]) {
+ test(`${file}/${job} loads worker setup from the workflow commit before checking out the build source`, () => {
+ const steps = workflow(file).jobs[job].steps
+ const setupIndex = steps.findIndex((step: any) => step.uses === './.github/actions/setup-boxlite-runner')
+ const sourceIndex = steps.findIndex((step: any) => step.uses?.startsWith('actions/checkout@') && step.with?.ref?.includes('inputs.ref'))
+ assert.ok(setupIndex >= 0 && setupIndex < sourceIndex, 'older source commits can lack the worker setup action')
+ const tools = steps[setupIndex - 1]
+ assert.match(tools.uses, /^actions\/checkout@/)
+ assert.equal(tools.with.ref, '${{ github.sha }}')
+ assert.equal(tools.if, steps[setupIndex].if)
+ })
+}
+
test('Linux x64 wheel packaging initializes the host Python used by cibuildwheel', () => {
const steps = workflow('build-wheels.yml').jobs.build_wheels.steps
const python = steps.findIndex((step: any) => step.uses?.startsWith('actions/setup-python@'))
@@ -266,10 +282,14 @@ test('Go vet and golangci-lint reuse the Linux coverage build', () => {
assert.ok(!formatting.some((step: any) => /dev:go|setup:build/.test(step.run ?? '')), 'formatting must not build the native runtime')
})
-test('distribution runtime builds retain release, weekly and manual triggers without push rebuilds', () => {
- const triggers = workflow('build-runtime.yml').on
- assert.equal('push' in triggers, false)
- assert.ok('release' in triggers && 'schedule' in triggers && 'workflow_dispatch' in triggers)
+test('all six manual component builds are selected through mbuild-release', () => {
+ const commands = workflow('mbuild-release.yml').on.workflow_dispatch.inputs.command.options
+ for (const component of ['runtime', 'wheels', 'node', 'c', 'go', 'runner']) {
+ const file = component === 'runner' ? 'build-runner-binary.yml' : 'build-' + component + '.yml'
+ const triggers = workflow(file).on
+ assert.deepEqual(Object.keys(triggers).sort(), component === 'runtime' ? ['schedule', 'workflow_call'] : ['workflow_call'], file)
+ assert.ok(commands.includes('publish-' + component), component)
+ }
})
for (const event of ['pull_request', 'push', 'merge_group', 'schedule', 'workflow_dispatch']) {
diff --git a/apps/infra/docs/deployment.md b/apps/infra/docs/deployment.md
index 31baf2a68..22b4ac67b 100644
--- a/apps/infra/docs/deployment.md
+++ b/apps/infra/docs/deployment.md
@@ -112,7 +112,8 @@ Deploy waits for the complete preparation matrix to succeed; commit routes do no
Rerunning a preparation leg repeats its checks and reuses existing artifacts.
A failed import or build stops deployment.
Apply is never automatically retried; inspect failed applies and any retained state lock before rerunning.
-The release pipeline's separate E2E workflow retains its own Environment gate.
+Release dev deployments keep the stage lock through cloud E2E. The result and both Environment approvals appear in the release run.
+Standalone dev/stage apply results go to dev Slack. Release and prod apply results go to #release. Each result links to the run.
### Caller attribution
diff --git a/apps/infra/docs/release.md b/apps/infra/docs/release.md
index 35e0583af..4798df7a2 100644
--- a/apps/infra/docs/release.md
+++ b/apps/infra/docs/release.md
@@ -1,181 +1,93 @@
## TL;DR
-Publish a stable release to build its artifacts, validate dev and request prod approval in GitHub. Optional Slack messages link reviewers to each deployment.
+Start `mbuild-release` on `main` to build a draft release, test its files on dev and publish the verified version.
## Release runbook
-The examples use `v0.10.3`; replace it with your stable `vX.Y.Z` release tag.
-Pre-release suffixes are unsupported.
-
-### Before you start
-
-- Merge the version bump into `main` and pass its required checks.
-- Configure required reviewers on the `prod` GitHub Environment.
-- Ensure the dev/prod stage declarations, cloud credentials, and cloud E2E credentials are configured.
-- Have permission to start workflows and approve the deployment Environments.
-
-Publication needs package write permission; orchestration needs Actions write permission.
-Neither job binds a cloud Environment; the existing deployment and E2E workflows retain their own approvals.
-
-### 1. Publish the GitHub Release
-
-Sync `main`, then create and push the release tag:
+Merge the version bump and tag its commit on `main`. The tag must match the stable workspace version in `Cargo.toml`.
```bash
-git switch main
-git pull --rebase origin main
-
-TAG=v0.10.3
-git tag "$TAG"
-git push origin "$TAG"
-gh release create "$TAG" \
- --repo boxlite-ai/boxlite \
- --verify-tag \
- --generate-notes
-```
-
-Pushing the tag starts no release build; publishing the Release starts the SDK/runtime builds and
-`Publish Release Images`. The latter dispatches `mbuild-release` from `main` with `build-only=false` by default.
-The successful release C SDK build starts `Build Go SDK` and `Build Runner Binary`.
-
-### 2. Follow the dev acceptance pipeline
-
-Open **Actions → mbuild-release**:
-
-```text
-Publish all declared images to GHCR
- → Wait for required GitHub Release assets
- → dispatch mdeploy-all: dev, this tag → notify #release → wait for that dev run
- → dispatch e2e-cloud: dev, this tag → wait for success
- → verify dev deployment history and prod reviewers
- → dispatch mdeploy-all: prod, this tag (approval pending)
- → write the GitHub job summary and optionally send the release report to #release
+TAG=v0.15.0
+gh workflow run mbuild-release.yml --ref main -f tag="$TAG"
```
-The publisher reads the tagged commit's artifact declaration and builds its current four images:
-`api`, `proxy`, `otel-collector`, and `registry-proxy`.
-Their address is `ghcr.io/boxlite-ai/boxlite/<artifact>:vX.Y.Z-<full-commit-sha>`.
-Publication logs manifest digests and reuses existing images without overwriting them.
-Dependency audit failures stop publication; receiving cloud registries enforce image scans after import.
+The run creates the draft or selects the existing draft for that tag. Configure the package trusted publisher for PyPI and each npm package with `mbuild-release.yml` as the workflow filename. The prod GitHub Environment needs required reviewers.
-Asset readiness checks the Release API for uploaded, nonempty files, rather than waiting for every SDK workflow:
+### What runs
-| Consumer | Required release assets |
+| Stage | Outputs and checks |
| --- | --- |
-| Runner | `boxlite-runner-vX.Y.Z-linux-amd64.tar.gz` and its `.sha256` |
-| Python E2E | `boxlite-X.Y.Z-cp312-cp312-manylinux_2_28_x86_64.whl` |
-| Node E2E | `boxlite-ai-boxlite-X.Y.Z.tgz`, `boxlite-ai-boxlite-linux-x64-gnu-X.Y.Z.tgz` |
-| C E2E | `boxlite-c-vX.Y.Z-linux-x64-gnu.tar.gz` |
-| CLI E2E | `boxlite-cli-vX.Y.Z-x86_64-unknown-linux-gnu.tar.gz`, `install.sh` |
+| Build | Runtime and CLI, wheels, npm packages and C SDK archives build in parallel and enter Actions Artifacts. Go tests and the Linux Runner build link the C archives from this run. |
+| Prepare dev | `mbuild publish` pushes the declared images to GHCR. The Runner job uploads the original tarball as an OCI layer. Once the GHCR producers finish, the dev preparation job verifies image and Runner digests, saves the deployment candidate and requests dev approval. SDK tests and distribution packaging continue in parallel. |
+| Dev approval and E2E | Approve the dev Environment in the run. The cloud suite reads only the Linux x64 CLI, Python wheel, C SDK and two npm tarballs from this run. It records their checksums with the accepted deployment digests. |
+| Publish | Dev E2E success opens prod approval immediately. In parallel, publication waits for the complete distribution and Go tests, compares the tested client bytes, and attaches the verified files to the draft. The top-level PyPI and npm jobs publish the accepted packages. |
+| Release and prod | When those publishers succeed, the workflow marks the draft public. Rust crates can then publish, and the Go job verifies the public C SDK downloads before tagging the tested commit. Approved prod deployment uses the same GHCR digests and can finish while the release is still a draft. |
-The existing installer and deployment workflow verify/download these assets when they consume them.
-Asset waiting is limited to three hours; dev deployment to three hours; E2E to one hour.
-Approve dev/E2E Environment requests within those limits.
+The C SDK and Runner workflows each load CI configuration and validate the build commit in one preparation job. A regular release skips the lookup for a previous acceptance receipt. Once its own attachments succeed, npm and PyPI can start. Finalization requires both to succeed.
-All child workflows run from `main`, with these fixed inputs:
-
-| Workflow | Inputs |
-| --- | --- |
-| Dev `mdeploy-all.yml` | `stage=dev`, `ref=<release tag>`, `components=api+runner`, `apply=true`, `confirm=true` |
-| `e2e-cloud.yml` | `stage=dev`, `tag=<release tag>`; retain all other defaults |
-| Prod `mdeploy-all.yml` | `stage=prod`, `ref=<release tag>`, `components=api+runner`, `apply=true`, `confirm=true` |
+The Runner package at `ghcr.io/boxlite-ai/boxlite/runner` must allow anonymous pulls from hosts. First boot and in-place upgrade verify the OCI manifest against the release tag, source commit and archive digest before extracting the binary. Dev and prod receive those pins from the candidate. A version-only manual rollout reads the same pins from the published `release-candidate.json`.
-The pipeline waits for the exact run IDs returned by GitHub dispatch.
-A failed, cancelled, or timed-out dev/E2E run prevents the prod request.
-The GitHub summary includes the E2E result and the prod run link after success, or the failed or interrupted phase.
+### Retries
-### Slack approval notices
+Rerunning the API build replaces that API version's GHCR tag with the rebuilt manifest. Other successful matrix entries keep their digests. A failed Docker upload retries the image already built by that job.
-Configure each incoming webhook as a repository Actions secret for its channel. Each deployment notification step references only its destination’s secret by name.
+For a failed production job, use **Re-run failed jobs** in the original release run. Before requesting approval and after approval, production checks the saved dev acceptance against the run ID, accepted attempt, candidate artifact ID, manifest digest, tag and source commit. A different candidate needs its own dev E2E.
-| Sender | When | Channel and secret |
-| --- | --- | --- |
-| `mbuild-release` | After dev dispatch and before polling, then again with the final E2E result and prod link on success | #release · `SLACK_WEBHOOK_URL` |
-| `mdeploy-all` dev apply | Before the release deployment or commit preparation, and again after successful commit preparation | #dev_deployment · `SLACK_DEV_DEPLOYMENT_WEBHOOK_URL` |
-| `mdeploy-all` prod apply | Before the release deployment | #release · `SLACK_WEBHOOK_URL` |
+If finalization loses the GitHub response after publishing, retry the failed job. It verifies the published files and their digests without modifying them. PyPI compares existing wheel hashes before it uploads any missing files and verifies the full set afterward.
-Each notice shows the sending workflow, its run title, GitHub actor, environment and phase. Buttons open GitHub, where reviewers approve the Environment.
+A same-version Runner rebuild changes the pinned manifest. Hosts record the installed manifest and archive digests and reapply when either changes.
-For a release-driven dev deployment, both channels receive a link to the same dev child run. A commit with parallel preparation jobs gets one notice for that batch.
-Previews, stage deployments and build-only releases skip these notices.
+Each Runtime or CLI tarball sidecar and the installer sidecar `install.sh.sha256` occupies one entry in the release inventory. The Release attachment job checks all existing selected files before uploading missing files. If a digest conflicts, the job stops before its first upload so the operator can inspect the originating run.
-An empty or unset secret skips delivery to its channel. Review a run directly in GitHub if its notice fails.
+The npm publisher checks all existing platform packages and the main package before its first upload. It publishes missing platform packages before the main package and verifies each new registry digest. A retry reuses matching packages.
-A supplied malformed release webhook fails the asset preflight. A final delivery failure leaves the GitHub summary available.
+### Roll back to a release that predates the manifest
-### 3. Approve the prod request
+A version-only installation requires a published `release-candidate.json`. For a historical release missing the file, complete this one-time backfill before selecting the version for installation or rollback.
-After successful dev acceptance, Slack's **Review prod deployment** button opens the already-created prod run.
-Check the release tag and approve its `prod` Environment in GitHub.
-Each release deployment run has one protected job covering artifact checks, import and apply.
-The run actor is the Actions bot; GitHub records the human reviewer separately.
-Clicking the Slack link opens GitHub; deployment proceeds only after approval.
+1. Resolve the product tag to its original commit and download the original Linux AMD64 Runner tarball and its checksum from that GitHub Release. Verify the exact filename and SHA-256 against the recorded checksum and the GitHub asset digest. Stop if the original bytes or independent evidence cannot be verified.
+2. With approval to update that version, publish those verified bytes as the single `application/gzip` layer to `ghcr.io/boxlite-ai/boxlite/runner`. Use the same OCI artifact type and source, revision and version annotations as the **Push the exact Runner archive** step. Check the manifest and blob by digest with anonymous credentials.
+3. Record the original `tag`, resolved commit in `sha`, OCI digest in `runner.manifest` and archive digest in `runner.archive`. For an `mdeploy-all` rollout, also populate `images` with the original verified manifest digest of each application image. Abort if a digest cannot be tied to the historical release.
+4. Attach the verified metadata as `release-candidate.json` to that version and check its downloaded SHA-256. Preserve any existing manifest and investigate conflicting bytes. A rollback can then select the version and use the usual downgrade approval.
-A successful `mbuild-release` means dev acceptance passed and the prod request was created.
-The release is live only when that prod `mdeploy-all` run succeeds.
-It imports the selected GHCR digests directly into prod's AR/ECR registry, verifies them, scans, and deploys.
-Dev uses its own independent GHCR import.
+The host fetches its Runner bytes from GHCR by digest. Backfilling metadata does not confer a dev E2E acceptance receipt or make the historical build eligible for component repairs.
-### Manual runs and publication recovery
+### Build and publish one component
-`mbuild-release` accepts:
+Run `mbuild-release.yml` from `main` and select an existing product Release tag. Each command builds its own files, runs the component checks and publishes within this run. Standalone runs skip cloud deployment, dev E2E, prod approval and draft promotion.
-| Input | Default | Meaning |
-| --- | --- | --- |
-| `command` | `publish` | Publish the declared release images |
-| `tag` | Required | Stable tag whose commit is on `main` |
-| `build-only` | `false` | `false`: full pipeline; `true`: image build/upload only |
+| Command | Builds and publishes |
+| --- | --- |
+| `publish-runtime` | Runtime, CLI, installer and checksums → GitHub Release. An already public Release also permits crates.io publication. |
+| `publish-wheels` | Platform wheels → GitHub Release and PyPI. |
+| `publish-node` | Platform packages and main npm package → GitHub Release and npm. |
+| `publish-c` | Platform C SDK archives → GitHub Release. |
+| `publish-go` | Builds the C SDK matrix, tests Go, then tags `sdks/go/vX.Y.Z` only after downloading every versioned C SDK archive anonymously from the public Release and verifying its GitHub asset digest. |
+| `publish-runner` | Builds the Linux x64 C SDK and Runner, pushes the Runner to GHCR and attaches its archive and checksum to GitHub Release. |
-For publication recovery, choose `build-only=true` to fill missing GHCR images without starting deployment, E2E, or Slack reporting:
+If Go tagging fails on a draft, finish the full release first. On a public Release, `publish-c` rebuilds every C archive. Fresh tar timestamps can change an existing archive's digest and block all uploads, including the missing archive.
-```bash
-TAG=v0.10.3
-gh workflow run mbuild-release.yml \
- --repo boxlite-ai/boxlite \
- --ref main \
- -f command=publish \
- -f tag="$TAG" \
- -f build-only=true
-```
+- If the original distribution artifact and its dev acceptance receipt are available, run `repair-c` for the same tag. Set `candidate-id` to that distribution artifact's ID. After the repair restores the missing archives, retry `publish-go`.
+- If either artifact has expired, follow the [full release procedure](#release-runbook) with a new patch version and tag. The new version goes through dev acceptance and publishes its own C archives and Go module tag.
-Omit `build-only` or set it to `false` to request the full pipeline.
-The publication-only path does not wait for release assets and needs no Slack secret.
-For an intentional manual deployment, use the [deployment runbook](deployment.md#deploy-through-github-actions).
+For example, `gh workflow run mbuild-release.yml --ref main -f command=publish-wheels -f tag=v1.2.3` selects fresh wheel publication. Set `build-only=true` to keep a standalone build in Actions. Use `source-ref` to build a branch or commit. A complete `publish` with `build-only=true` stages the GHCR images and Runner.
-### Validation and recovery boundaries
+Component builds can overlap while a full release waits for prod approval. Jobs writing the same Release assets take a per-tag lock. Package publishers take a lock per registry and version. GitHub allows up to 100 pending jobs per group with `queue: max`.
-Keep release tags and assets immutable.
-The pipeline compares the tag's commit with the publisher's resolved commit before every dispatch.
-Changes after the prod request is created remain an operator responsibility.
+On a full release retry, a rebuilt macOS wheel changes the distribution manifest. The run verifies all files again. It can reuse successful dev E2E if every tested Linux client hash and every deployment digest still matches the receipt.
-Full pipelines share one dev validation concurrency group.
-Before requesting prod, the pipeline checks for overlapping dev applies, including failed/cancelled attempts and manual reruns.
-It inspects at most 500 `mdeploy-all` runs and 50 attempts per run.
-Missing timing, unknown overlapping applies, or truncated history prevents the prod request.
-This check covers `mdeploy-all`; avoid other deployment paths during acceptance.
+### Manually republish a component
-GitHub's native concurrency queues can replace older pending runs with newer requests.
-This applies to queued release pipelines and prod deployments awaiting approval.
-A Slack link identifies an exact prod run; it does not reserve a permanent queue position.
-Inspect that run's current state before approving or recovering it.
+Open **Actions → mbuild-release → Run workflow** on `main`, select the product tag and choose `repair-runtime`, `repair-wheels`, `repair-node` or `repair-c`. Enter the candidate artifact ID from the original run. The matching dev acceptance receipt and candidate artifact must still be available. This command rechecks the tag and candidate and restores the selected attachments. Wheel and Node repairs also run the top-level PyPI or npm publisher. A repair on a draft leaves publication and prod approval to the original run.
-Parent timeouts/cancellation leave dispatched children under GitHub's control.
-Inspect their exact run links before retrying; an interrupted apply may still be running.
-An uncertain dispatch response is never retried automatically because GitHub may already have created the run.
-If only Slack delivery failed, use the GitHub report summary and rerun only the report job.
-Rerunning the whole pipeline can create another deployment request.
+### Approvals and notifications
-### Common failures
+Approve each cloud Environment in the parent run. The dev deployment and E2E share the dev stage concurrency lock. Prod uses the separate prod lock.
-| Failure | Response |
+| Event | Slack destination |
| --- | --- |
-| Missing GitHub Release | Publish the Release matching the tag |
-| Missing required assets | Inspect the runtime/C/Node/wheels/Runner builds; the Runner build follows the C SDK build |
-| Invalid release webhook | Correct or clear `SLACK_WEBHOOK_URL` before rerunning asset preflight |
-| Missing GHCR image | Recover with `build-only=true`, then inspect downstream runs before restarting |
-| Invalid tag or tag moved | Use an immutable stable release tag whose commit is on `main` |
-| Overlapping dev apply | Finish deployment activity and repeat dev acceptance for the intended release |
-| Missing prod reviewers | Configure required reviewers on the `prod` Environment before retrying |
-
-See [deployment mechanics](deployment.md#deploy-through-github-actions) for digest conflicts,
-registry authentication, and manual rollout diagnostics.
+| Release dev deployment, acceptance failure, prod approval and rollout results | Release Slack |
+| Standalone dev and stage rollout results | Dev Slack |
+| Standalone prod approval and rollout result | Release Slack |
+
+Deployment results include a button to the originating run. The prod approval message includes successful dev acceptance. For standalone deployments, use the [deployment runbook](deployment.md#deploy-through-github-actions).
diff --git a/apps/infra/mbuild/README.md b/apps/infra/mbuild/README.md
index 5d7c544eb..bba889812 100644
--- a/apps/infra/mbuild/README.md
+++ b/apps/infra/mbuild/README.md
@@ -51,7 +51,7 @@ npm run mbuild import-release -- --tag <full-commit-sha> --version vX.Y.Z --ghcr
This publication-only example skips deployment, E2E, and Slack reporting.
Omit `build-only` for the default [release pipeline](../docs/release.md):
-wait for release assets, validate dev, and create the same tag's prod deployment for human approval.
+check release assets, deploy and validate dev, report E2E to Slack, then deploy the approved tag to prod within the release run.
The address is `ghcr.io/<owner>/<repository>/<artifact>:vX.Y.Z-<full-sha>`.
Artifact names and tags match Artifact Registry's layout; GHCR has no stage suffix.
diff --git a/apps/infra/mbuild/bin/mbuild.ts b/apps/infra/mbuild/bin/mbuild.ts
index 996d09349..4117daad1 100755
--- a/apps/infra/mbuild/bin/mbuild.ts
+++ b/apps/infra/mbuild/bin/mbuild.ts
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+import { writeFile } from 'node:fs/promises'
/*
* `npm run mbuild publish -- --tag <sha> --stage dev`
@@ -18,7 +19,7 @@
import { loadConfig as loadStageConfig, type StageConfig } from 'mstage/config'
import { loadArtifactConfig, loadBuildConfig, onlyArtifact, registryFor, type BuildConfig } from '../src/config.ts'
-import { assertTag, ghcrRegistryFor, releaseTagFor, resolveRegistry } from '../src/address.ts'
+import { assertTag, ghcrRegistryFor, releaseImageDigests, releaseTagFor, resolveRegistry } from '../src/address.ts'
import { assertPromotable, coordinatesOf, type Coordinates } from '../src/coordinates.ts'
import {
AuditFailedError,
@@ -188,14 +189,19 @@ const main = async (): Promise<number> => {
if (command === 'import-release') {
const stage = required(argv, 'stage')
const target = resolveRegistry({ config, stage, region: regionOf(stage), ...(await coordinates(config, stage)) })
- for (const outcome of await promote({ config: selected, tag, from: { stage: 'ghcr', registry }, to: { stage, registry: target }, run, log })) {
+ const pins = process.env.BOXLITE_RELEASE_DIGESTS
+ const digests = pins ? releaseImageDigests(pins, tag) : undefined
+ for (const outcome of await promote({ config: selected, tag, digests, from: { stage: 'ghcr', registry }, to: { stage, registry: target }, run, log })) {
console.log(`${outcome.artifact}=${outcome.address}`)
}
} else {
- const operation = command === 'publish' ? publish : verifyPublished
- for (const outcome of await operation({ config: selected, stage: 'ghcr', registry, tag, run, log })) {
- console.log(`${outcome.artifact}=${outcome.address}`)
- }
+ const options = { config: selected, stage: 'ghcr', registry, tag, run, log }
+ const outcomes = command === 'publish'
+ ? await publish({ ...options, replace: argv.includes('--replace') })
+ : await verifyPublished(options)
+ for (const outcome of outcomes) console.log(`${outcome.artifact}=${outcome.address}`)
+ const output = option(argv, 'output')
+ if (output && command === 'publish') await writeFile(output, JSON.stringify(outcomes) + '\n')
}
return 0
}
diff --git a/apps/infra/mbuild/src/address.ts b/apps/infra/mbuild/src/address.ts
index 4f0ba9efb..d4379d7ee 100644
--- a/apps/infra/mbuild/src/address.ts
+++ b/apps/infra/mbuild/src/address.ts
@@ -145,7 +145,7 @@ export const addressFor = ({
tag: string
}): string => {
assertArtifact(config, artifact)
- assertTag(tag)
+ if (registry.kind === 'ghcr' || !/^sha256-[a-f0-9]{64}$/.test(tag)) assertTag(tag)
switch (registry.kind) {
case 'ghcr':
if (!tag.startsWith('v')) throw new ImageAddressError('GHCR requires a version-qualified release tag')
@@ -166,18 +166,43 @@ export const ghcrRegistryFor = (repository: string): Extract<Registry, { kind: '
return { kind: 'ghcr', host: 'ghcr.io', repository: normalized }
}
+export const digestTag = (digest: string): string => {
+ if (!/^sha256:[a-f0-9]{64}$/.test(digest)) throw new ImageAddressError('Expected a full SHA-256 image digest')
+ return digest.replace(':', '-')
+}
+
+export const releaseImageDigests = (manifest: string, tag: string): Record<string, string> => {
+ const { tag: version, sha, images } = JSON.parse(manifest)
+ if (releaseTagFor({ version, sha }) !== tag || !images || typeof images !== 'object' || Array.isArray(images)) {
+ throw new ImageAddressError('Release manifest does not identify the selected version and commit')
+ }
+ for (const digest of Object.values(images)) {
+ if (typeof digest !== 'string') throw new ImageAddressError('Invalid image digest in release manifest')
+ digestTag(digest)
+ }
+ return images
+}
+
/** Every artifact at one commit, which is what a publish iterates over. */
export const addressesFor = ({
config,
registry,
tag,
+ digests,
}: {
config: BuildConfig
registry: Registry
tag: string
+ digests?: Record<string, string>
}): Record<string, string> =>
Object.fromEntries(
- Object.keys(config.artifacts).map((artifact) => [artifact, addressFor({ config, registry, artifact, tag })]),
+ Object.keys(config.artifacts).map((artifact) => {
+ const address = addressFor({ config, registry, artifact, tag })
+ if (!digests) return [artifact, address]
+ const digest = digests[artifact] ?? ''
+ digestTag(digest)
+ return [artifact, address.slice(0, address.lastIndexOf(':')) + '@' + digest]
+ }),
)
/** The ECR host for an account and region; the address shape lives only here. */
diff --git a/apps/infra/mbuild/src/publish.ts b/apps/infra/mbuild/src/publish.ts
index 6088098d9..a999db004 100644
--- a/apps/infra/mbuild/src/publish.ts
+++ b/apps/infra/mbuild/src/publish.ts
@@ -29,7 +29,7 @@ import { createHash } from 'node:crypto'
import { mkdir, rm } from 'node:fs/promises'
import { setTimeout as sleep } from 'node:timers/promises'
import type { AuditConfig, BuildConfig, ScanPolicy, ScanSeverity } from './config.ts'
-import { addressFor, assertTag, type Registry } from './address.ts'
+import { addressFor, digestTag, assertTag, type Registry } from './address.ts'
import { ghcrRegistrar } from './ghcr.ts'
export class PublishError extends Error {
@@ -117,6 +117,7 @@ const RUNTIME_PLATFORM = 'linux/amd64'
export type PublishOutcome = {
artifact: string
address: string
+ digest?: string
/** False when the commit was already there and nothing was built or moved. */
built: boolean
}
@@ -621,6 +622,7 @@ type PublishOptions = {
config: BuildConfig
stage: string
registry: Registry
+ replace?: boolean
tag: string
run: Run
log?: (line: string) => void
@@ -632,6 +634,7 @@ const publishImages = async ({
stage,
registry,
tag,
+ replace = false,
run,
log = console.log,
clock = systemClock,
@@ -660,7 +663,7 @@ const publishImages = async ({
const dockerfile = join(config.repository, declared.dockerfile)
const context = join(config.repository, declared.context)
const address = addressFor({ config, registry, artifact, tag })
- if (await registrar.isPublished(artifact, tag)) {
+ if (!replace && await registrar.isPublished(artifact, tag)) {
log(`${address} is already published; nothing to do.`)
outcomes.push({ artifact, address, built: false })
continue
@@ -679,8 +682,15 @@ const publishImages = async ({
// The exit code, not the output: docker already wrote the reason above.
if (built.code !== 0) throw new PublishError(`Could not build ${artifact}: docker build exited ${built.code}`)
log(`Pushing ${address}`)
- const pushed = await run('docker', ['push', ...(registry.kind === 'ghcr' ? ['--platform', RUNTIME_PLATFORM] : []), address], { echo: true })
- if (pushed.code !== 0) throw new PublishError(`Could not push ${address}: docker push exited ${pushed.code}`)
+ const pushArgs = ['push', ...(registry.kind === 'ghcr' ? ['--platform', RUNTIME_PLATFORM] : []), address]
+ const attempts = registry.kind === 'ghcr' ? 3 : 1
+ for (let attempt = 1; attempt <= attempts; attempt++) {
+ const pushed = await run('docker', pushArgs, { echo: true })
+ if (pushed.code === 0) break
+ if (attempt === attempts) throw new PublishError(`Could not push ${address}: docker push exited ${pushed.code}`)
+ log(`Retrying upload of the built ${artifact} image (attempt ${attempt + 1}/${attempts})`)
+ await clock.wait(15000 * attempt)
+ }
log(`Pushed ${address}`)
outcomes.push({ artifact, address, built: true })
}
@@ -689,6 +699,7 @@ const publishImages = async ({
for (const outcome of outcomes) {
const digest = await registrar.digestOf(outcome.artifact, tag)
if (!digest) throw new NotPublishedError(`GHCR did not retain ${outcome.address}`)
+ outcome.digest = digest
log(`${outcome.address}@${digest}; image scanning runs after cloud import`)
}
} else {
@@ -699,7 +710,10 @@ const publishImages = async ({
/** Workflow concurrency owns cross-run exclusion; atomic directories cover CLI processes inside one job. */
export const publish = async (options: PublishOptions): Promise<PublishOutcome[]> => {
- if (options.registry.kind !== 'ghcr') return publishImages(options)
+ if (options.registry.kind !== 'ghcr') {
+ if (options.replace) throw new PublishError('Only GHCR release tags may be replaced')
+ return publishImages(options)
+ }
for (const artifact of Object.keys(options.config.artifacts)) addressFor({ config: options.config, registry: options.registry, artifact, tag: options.tag })
const repository = process.env.GITHUB_REPOSITORY
const temporary = process.env.RUNNER_TEMP
@@ -797,6 +811,7 @@ const copyImage = async ({ sourceAddress, address, run, log }: {
export const promote = async ({
config,
tag,
+ digests,
from,
to,
run,
@@ -805,6 +820,7 @@ export const promote = async ({
}: {
config: BuildConfig
tag: string
+ digests?: Record<string, string>
from: { stage: string; registry: Registry }
to: { stage: string; registry: Registry }
run: Run
@@ -822,34 +838,41 @@ export const promote = async ({
if (from.registry.kind === 'ghcr') {
const sources = new Map<string, string>()
for (const artifact of artifacts) {
- const digest = await source.digestOf(artifact, tag)
+ const digest = digests ? digests[artifact] : await source.digestOf(artifact, tag)
if (!digest) throw new NotPublishedError(`GHCR is missing ${artifact}:${tag}; run mbuild-release.yml command=publish first`)
+ digestTag(digest)
sources.set(artifact, digest)
}
await destination.ensureRepository()
await source.login()
await destination.login()
// Refuse every existing mismatch before writing any image.
+ const destinationTag = (artifact: string) => digests ? digestTag(sources.get(artifact)!) : tag
const existing = new Set<string>()
for (const artifact of artifacts) {
- const digest = await destination.digestOf(artifact, tag)
+ const digest = await destination.digestOf(artifact, destinationTag(artifact))
if (digest && digest !== sources.get(artifact)) throw new PublishError(`${artifact}:${tag} in ${to.stage} differs from GHCR; refusing to overwrite`)
if (digest) existing.add(artifact)
}
const outcomes: PromoteOutcome[] = []
for (const artifact of artifacts) {
- const address = addressFor({ config, registry: to.registry, artifact, tag })
+ const address = addressFor({ config, registry: to.registry, artifact, tag: destinationTag(artifact) })
const sourceAddress = addressFor({ config, registry: from.registry, artifact, tag })
const pinned = `${sourceAddress.slice(0, sourceAddress.lastIndexOf(':'))}@${sources.get(artifact)}`
if (!existing.has(artifact)) {
// Copy raw registry content, without converting it through Docker's local image store.
const copied = await run('docker', ['buildx', 'imagetools', 'create', '--prefer-index=false', '--tag', address, pinned], { echo: true })
if (copied.code !== 0) throw new PublishError(`Could not import ${address}: docker buildx exited ${copied.code}`)
- if (await destination.digestOf(artifact, tag) !== sources.get(artifact)) throw new PublishError(`Imported ${address} differs from GHCR`)
+ if (await destination.digestOf(artifact, destinationTag(artifact)) !== sources.get(artifact)) throw new PublishError(`Imported ${address} differs from GHCR`)
}
outcomes.push({ artifact, address, from: pinned, built: !existing.has(artifact) })
}
- await assertNoBlockingFindings({ registrar: destination, scan: config.stages[to.stage]!.scan, outcomes, tag, clock, log })
+ for (const outcome of outcomes) {
+ await assertNoBlockingFindings({
+ registrar: destination, scan: config.stages[to.stage]!.scan, outcomes: [outcome],
+ tag: destinationTag(outcome.artifact), clock, log,
+ })
+ }
return outcomes
}
const missing = await missingFrom({ registrar: source, artifacts, tag })
diff --git a/apps/infra/mbuild/test/address.test.ts b/apps/infra/mbuild/test/address.test.ts
index 3289e991b..5eaf73a0d 100644
--- a/apps/infra/mbuild/test/address.test.ts
+++ b/apps/infra/mbuild/test/address.test.ts
@@ -10,6 +10,7 @@ import {
ImageAddressError,
RELEASE_VERSION,
releaseTagFor,
+ releaseImageDigests,
resolveRegistry,
} from '../src/address.ts'
import { BuildConfigError, onlyArtifact, parseBuildConfig, registryFor } from '../src/config.ts'
@@ -402,3 +403,18 @@ test('a release build and a commit build of one commit never share an address',
addressFor({ config, registry: dev, artifact: 'api', tag: releaseTagFor({ version: VERSION, sha: SHA }) }),
)
})
+
+test('release addresses bind each cloud image to its own digest at the exact version and SHA', () => {
+ const config = onArtifactRegistry()
+ const sha = 'a'.repeat(40)
+ const tag = releaseTagFor({version:'v1.2.3', sha})
+ const images = { api: 'sha256:' + 'b'.repeat(64), console: 'sha256:' + 'c'.repeat(64) }
+ const json = (overrides: object = {}) => JSON.stringify({tag:'v1.2.3',sha,images,...overrides})
+ const digests = releaseImageDigests(json(),tag)
+ const registry = resolveRegistry({config,stage:'dev',region:'us-central1',project:'boxlite-fixture'})
+ const addresses = addressesFor({config,registry,tag,digests})
+ for (const [artifact, digest] of Object.entries(images)) assert.ok(addresses[artifact]?.endsWith('@'+digest))
+ assert.throws(()=>releaseImageDigests(json({sha:'d'.repeat(40)}),tag))
+ assert.throws(()=>releaseImageDigests(json({images:{api:null}}),tag))
+ assert.throws(()=>addressesFor({config,registry,tag,digests:{api:images.api}}))
+})
diff --git a/apps/infra/mbuild/test/audit-retry.test.ts b/apps/infra/mbuild/test/audit-retry.test.ts
index 37bea942c..d5418bdbb 100644
--- a/apps/infra/mbuild/test/audit-retry.test.ts
+++ b/apps/infra/mbuild/test/audit-retry.test.ts
@@ -91,6 +91,7 @@ exec "$AUDIT_TEST_NODE" --import "$AUDIT_TEST_LOADER" --conditions=development "
GITHUB_RUN_ID: '123',
GITHUB_RUN_ATTEMPT: '1',
RUNNER_TEMP: directory,
+ GITHUB_WORKSPACE: directory,
TAG: 'v1.2.3',
}
return {
@@ -153,14 +154,16 @@ for (const [filename, job] of [
if (filename === 'mbuild-release.yml')
probe.env.MSTAGE_CONFIG = join(probe.env.MSTAGE_ENV_CONFIG, 'no-cloud-stage')
const result = probe.run('bash', ['-c', shell])
- assert.equal(result.status, 1, result.stderr)
+ assert.equal(result.status, filename === 'mbuild-release.yml' ? 65 : 1, result.stderr)
assert.match(result.stderr, new RegExp(`${manager} audit did not pass`))
assert.deepEqual(probe.calls(), ['audit'])
- assert.match(result.stdout, /dependency audit/)
+ if (filename === 'mbuild.yml') assert.match(result.stdout, /dependency audit/)
assert.doesNotMatch(result.stdout, /retrying/)
})
}
+ // The release publisher retries the Docker upload itself; ghcr-publication tests that boundary.
+ if (filename === 'mbuild-release.yml') continue
for (const scanRefused of [true, false]) {
test(`${filename} ${scanRefused ? 'stops on scan refusal' : 'retries a transient publication failure'}`, (t) => {
const probe = fixture(t, 'yarn')
diff --git a/apps/infra/mbuild/test/ghcr-publication.test.ts b/apps/infra/mbuild/test/ghcr-publication.test.ts
index 78d5a5311..189b654d8 100644
--- a/apps/infra/mbuild/test/ghcr-publication.test.ts
+++ b/apps/infra/mbuild/test/ghcr-publication.test.ts
@@ -97,3 +97,35 @@ process.disconnect();`)
assert.equal((await retry.message).kind, 'effect', 'a failed publisher retained its lock')
const retried = once(retry.child, 'exit'); retry.child.send('release'); await retried
})
+
+test('rebuilding a selected GHCR image replaces that tag without rebuilding its siblings', async () => {
+ const p = probe()
+ const options = { config, stage: 'ghcr', registry: ghcr, tag, run: p.run, log: () => {} }
+ await publish(options)
+ p.calls.length = 0
+ const rebuild = { ...options, config: onlyArtifact(config, 'api'), replace: true }
+ const outcomes = await publish(rebuild)
+ assert.deepEqual(outcomes.map(({ artifact, built }) => [artifact, built]), [['api', true]])
+ const pushes = p.calls.filter(({ args }) => args[0] === 'push')
+ assert.equal(pushes.length, 1)
+ assert.match(pushes[0]!.args.at(-1)!, /\/api:/)
+})
+
+test('a failed GHCR upload retries the same built image', async () => {
+ const p = probe()
+ const pushes: string[] = []
+ const run: Run = async (file, args, options) => {
+ if (file === 'docker' && args[0] === 'push') {
+ pushes.push(args.at(-1)!)
+ if (pushes.length === 1) return { code: 1, stdout: '', stderr: 'registry unavailable' }
+ }
+ return p.run(file, args, options)
+ }
+ await publish({
+ config: onlyArtifact(config, 'api'), stage: 'ghcr', registry: ghcr,
+ tag, run, replace: true, clock: { now: Date.now, wait: async () => {} }, log: () => {},
+ })
+ assert.equal(p.calls.filter(({ args }) => args[0] === 'build').length, 1)
+ assert.equal(pushes.length, 2)
+ assert.equal(pushes[0], pushes[1])
+})
diff --git a/apps/infra/mbuild/test/mbuild-release-trigger-workflow.test.ts b/apps/infra/mbuild/test/mbuild-release-trigger-workflow.test.ts
index e9d228f2c..e735e8726 100644
--- a/apps/infra/mbuild/test/mbuild-release-trigger-workflow.test.ts
+++ b/apps/infra/mbuild/test/mbuild-release-trigger-workflow.test.ts
@@ -5,47 +5,13 @@ import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { load } from 'js-yaml'
-const workflowsDirectory = fileURLToPath(
- new URL('../../../../.github/workflows/', import.meta.url),
-)
+const directory = fileURLToPath(new URL('../../../../.github/workflows/', import.meta.url))
-const withoutComments = (source: string): string =>
- source
- .split('\n')
- .filter((line) => !/^\s*#/.test(line))
- .join('\n')
-
-test('a published GitHub Release dispatches mbuild-release from main', () => {
- const trigger = readdirSync(workflowsDirectory)
- .filter((name) => name.endsWith('.yml'))
- .map((name) => {
- const source = readFileSync(join(workflowsDirectory, name), 'utf8')
- return { name, source, commands: withoutComments(source) }
- })
- .find(({ commands }) => /gh workflow run mbuild-release\.yml/.test(commands))
-
- assert.ok(trigger, 'a published GitHub Release does not dispatch mbuild-release')
-
- const workflow = load(trigger.source) as any
- assert.deepEqual(workflow.on?.release?.types, ['published'])
- assert.deepEqual(workflow.permissions, {}, `${trigger.name} grants workflow-wide permissions`)
-
- const jobs = Object.entries<any>(workflow.jobs ?? {})
- assert.equal(jobs.length, 1, `${trigger.name} does more than bridge the release event`)
- const [jobName, job] = jobs[0]!
- assert.match(String(job.if ?? ''), /!github\.event\.release\.prerelease/)
- assert.deepEqual(job.permissions, { actions: 'write' })
- assert.equal(job.environment, undefined, `${jobName} binds an Environment before mbuild-release`)
-
- const step = job.steps?.find((candidate: any) =>
- /gh workflow run mbuild-release\.yml/.test(String(candidate.run ?? '')),
- )
- assert.ok(step, `${jobName} has no mbuild-release dispatch step`)
- assert.equal(step.env?.GH_TOKEN, '${{ github.token }}')
- assert.equal(step.env?.TAG, '${{ github.event.release.tag_name }}')
- assert.match(step.run, /--repo "\$GITHUB_REPOSITORY"/)
- assert.match(step.run, /--ref main/)
- assert.match(step.run, /-f command=publish/)
- assert.match(step.run, /-f tag="\$TAG"/)
- assert.doesNotMatch(trigger.commands, /actions\/checkout|id-token:/)
+test('publishing a product release cannot dispatch a second build workflow', () => {
+ for (const name of readdirSync(directory).filter((entry) => entry.endsWith('.yml'))) {
+ const workflow = load(readFileSync(join(directory, name), 'utf8')) as any
+ assert.equal(workflow.on?.release, undefined, name + ' listens for product Release events')
+ const producers = workflow.on?.workflow_run?.workflows ?? []
+ assert.equal(producers.includes('Build C SDK'), false, name + ' starts a separate C consumer run')
+ }
})
diff --git a/apps/infra/mbuild/test/mbuild-release-workflow.test.ts b/apps/infra/mbuild/test/mbuild-release-workflow.test.ts
index 452e5a413..7eaabdaf4 100644
--- a/apps/infra/mbuild/test/mbuild-release-workflow.test.ts
+++ b/apps/infra/mbuild/test/mbuild-release-workflow.test.ts
@@ -18,7 +18,7 @@ test('release publication runs from main with package write access and no cloud
assert.equal(workflow.jobs.publish.permissions.packages, 'write')
assert.equal(workflow.permissions['id-token'], undefined)
assert.doesNotMatch(commands, /configure-aws-credentials|google-github-actions|mstage login|--stage dev|--to prod/)
- assert.deepEqual(workflow.on.workflow_dispatch.inputs.command.options, ['publish'])
+ assert.deepEqual(workflow.on.workflow_dispatch.inputs.command.options, ['publish', 'publish-runtime', 'publish-wheels', 'publish-node', 'publish-c', 'publish-go', 'publish-runner', 'repair-runtime', 'repair-wheels', 'repair-node', 'repair-c'])
assert.equal(workflow.on.workflow_call, undefined)
})
@@ -74,8 +74,16 @@ test('current tooling builds the release source using its declaration without lo
assert.ok(commands.indexOf('DOCKER_CONFIG=$RUNNER_TEMP/docker') < commands.indexOf('mbuild publish'))
})
-test('all publication attempts for one release queue together', () => {
- assert.equal(workflow.concurrency.group, 'mbuild-release-${{ inputs.tag }}')
- assert.equal(workflow.concurrency['cancel-in-progress'], false)
- assert.match(workflow['run-name'], /GHCR/)
+test('component runs overlap and serialize writes by tag and destination', () => {
+ assert.equal(workflow.concurrency.group, "mbuild-release-run-${{ inputs.command == 'publish' && inputs.tag || github.run_id }}")
+ assert.equal(workflow.concurrency.queue, 'max')
+ const { jobs } = workflow
+ assert.equal(jobs.attach.concurrency.group, jobs.finalize.concurrency.group)
+ assert.equal(jobs.resolve.concurrency.group, "mbuild-release-assets-${{ !inputs['build-only'] && inputs.tag || github.run_id }}")
+ for (const name of ['build-go', 'build-c', 'build-node', 'build-runtime', 'build-wheels', 'build-runner-binary'])
+ assert.equal(jobs[name].concurrency, undefined, name)
+ for (const name of ['resolve', 'attach', 'finalize', 'pypi', 'npm', 'tag-go-module', 'publish_crates', 'publish', 'publish-runner'])
+ assert.equal(jobs[name].concurrency.queue, 'max', name)
+ const locks = ['attach', 'pypi', 'npm', 'tag-go-module', 'publish_crates', 'publish', 'publish-runner'].map(name => jobs[name].concurrency.group)
+ assert.equal(new Set(locks).size, locks.length)
})
diff --git a/apps/infra/mdeploy/README.md b/apps/infra/mdeploy/README.md
index df13825fc..b886a7907 100644
--- a/apps/infra/mdeploy/README.md
+++ b/apps/infra/mdeploy/README.md
@@ -125,7 +125,8 @@ To test this PR's deployment program, dispatch the workflow with
Runner hosts retain local box state and are protected against replacement. Boot-image, startup and
attached-disk changes are ignored for existing hosts; binary and unit-environment updates have a separate path.
-Updates verify artifact checksums and readiness. Already-converged hosts need no restart;
+For a staged Runner, first boot and upgrades match the literal archive name in its sidecar and verify the SHA-256 before extraction.
+Updates also verify readiness. Already-converged hosts need no restart;
release downgrade requires the explicit operator command. Follow [GCP runner convergence](../docs/gcp/runners.md)
or [AWS runner convergence](../docs/aws/runners.md) for the update mechanism and its completion boundary.
diff --git a/apps/infra/mdeploy/package.json b/apps/infra/mdeploy/package.json
index a998fb91a..9c50fbe60 100644
--- a/apps/infra/mdeploy/package.json
+++ b/apps/infra/mdeploy/package.json
@@ -27,7 +27,8 @@
"dependencies": {
"mbuild": "file:../mbuild",
"mstage": "file:../mstage",
- "naming": "file:../naming"
+ "naming": "file:../naming",
+ "shell-quote": "^1.10.0"
},
"devDependencies": {
"@types/node": "^22.10.0",
diff --git a/apps/infra/mdeploy/stack/image.ts b/apps/infra/mdeploy/stack/image.ts
index 2f28257a5..399e6b0c3 100644
--- a/apps/infra/mdeploy/stack/image.ts
+++ b/apps/infra/mdeploy/stack/image.ts
@@ -14,7 +14,7 @@
* ignorant of registries entirely.
*/
-import { addressesFor, resolveRegistry } from 'mbuild/address'
+import { addressesFor, releaseImageDigests, resolveRegistry } from 'mbuild/address'
import { loadBuildConfig, type BuildConfig } from 'mbuild/config'
export type ImagesRequest = {
@@ -22,6 +22,10 @@ export type ImagesRequest = {
tag: string
}
+const imageDigests = (tag: string) => process.env.BOXLITE_RELEASE_DIGESTS
+ ? releaseImageDigests(process.env.BOXLITE_RELEASE_DIGESTS, tag)
+ : undefined
+
/** Artifact name to the address its runtime pulls from. */
export type Images = Record<string, $util.Output<string>>
@@ -43,6 +47,7 @@ export const awsImages =
config,
registry: resolveRegistry({ config, stage, region, accountId: account }),
tag: request.tag,
+ digests: imageDigests(request.tag),
})[artifact]!,
),
]),
@@ -65,6 +70,6 @@ export const gcpImages =
(request: ImagesRequest): Images =>
Object.fromEntries(
Object.entries(
- addressesFor({ config, registry: resolveRegistry({ config, stage, region, project }), tag: request.tag }),
+ addressesFor({ config, registry: resolveRegistry({ config, stage, region, project }), tag: request.tag, digests: imageDigests(request.tag) }),
).map(([artifact, address]) => [artifact, $util.output(address)]),
)
diff --git a/apps/infra/mdeploy/stack/runner-binary.ts b/apps/infra/mdeploy/stack/runner-binary.ts
index cebe8376d..6b0a4130c 100644
--- a/apps/infra/mdeploy/stack/runner-binary.ts
+++ b/apps/infra/mdeploy/stack/runner-binary.ts
@@ -7,7 +7,7 @@
*
* Two sources, one shape:
*
- * release → the assets published for a stable X.Y.Z, over public HTTPS
+ * release → the GHCR manifest and archive pinned by the release candidate
* build → an object staged for one commit, read with the host's own identity
* rather than published; S3 on AWS, Cloud Storage on GCP, one key
*
@@ -18,18 +18,15 @@
* whatever was current the day someone seeded it, and would drift from the
* commit the rest of the deploy is shipping.
*
- * Synchronous, and no network. Both engines evaluate the stack synchronously, so
- * a resolver that reached for a digest could not be called from it at all. What
- * this produces is therefore a *pair of addresses* — the tarball and its
- * `.sha256` sidecar — and the host is what compares the bytes it downloaded
- * against the manifest it fetched beside them. `runner-boot.ts` does that at
- * first boot and `runner-upgrade.ts` does it on every later deploy, from one
- * rendering of the same three lines.
+ * Resolution is synchronous. Hosts verify release manifest and archive digests,
+ * or the staged checksum sidecar for a commit build, before installation.
*
* Every string here is interpolated into bash that runs as root on a host, so
* each is validated where it enters rather than where it is spent.
*/
+import { releaseRunner, runnerRegistry, registryDownload, type ReleaseRunner } from './runner-registry.ts'
+import { quote } from 'shell-quote'
import { readFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
@@ -40,15 +37,6 @@ export class RunnerBinaryError extends Error {
}
}
-/**
- * Where a published runner asset lives.
- *
- * A constant rather than a setting, and the same one `artifacts/runner-release
- * .ts` uses: the release is this repository's own, so a stage that could point
- * it elsewhere is a stage that could install a binary nobody here published.
- */
-const RELEASE_DOWNLOAD_ROOT = 'https://github.com/boxlite-ai/boxlite/releases/download'
-
/** Stable X.Y.Z only. A prerelease has no ordering the upgrade guard can use. */
const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/
/** Full git object names only: an abbreviation addresses a different object. */
@@ -65,6 +53,7 @@ export type RunnerBinarySelector =
/** The two addresses a source resolves to, and how each is read. */
export type RunnerArtifact = {
+ release?: ReleaseRunner
tarballName: string
tarballUrl: string
checksumUrl: string
@@ -260,19 +249,22 @@ export const gcpRunnerArtifactsBucket = ({
*/
export const runnerArtifactFor = ({
selector,
+ metadata,
staging = null,
}: {
selector: RunnerBinarySelector
+ metadata?: string
/** Where a build-mode object is staged. The root knows it; a release needs none. */
staging?: ArtifactStaging | null
}): RunnerArtifact => {
if (selector.kind === 'release') {
const tarballName = `boxlite-runner-v${selector.version}-linux-amd64.tar.gz`
- const release = `${RELEASE_DOWNLOAD_ROOT}/v${selector.version}`
+ const release = releaseRunner(selector.version, metadata)
return {
+ release,
tarballName,
- tarballUrl: `${release}/${tarballName}`,
- checksumUrl: `${release}/${tarballName}.sha256`,
+ tarballUrl: `${runnerRegistry}/blobs/${release.pins?.archive ?? '$RUNNER_ARCHIVE'}`,
+ checksumUrl: `${runnerRegistry}/manifests/${release.pins?.manifest ?? '$RUNNER_MANIFEST'}`,
transport: 'https',
}
}
@@ -342,20 +334,11 @@ export const artifactFetchCommand = ({
return `aws --cli-connect-timeout 10 --cli-read-timeout 300 s3 cp --region ${region} "${url}" "${destination}"`
}
-/**
- * The bytes are what the manifest beside them says, or nothing is installed.
- *
- * Fail-closed on all three counts, and each is a real failure mode:
- *
- * - a manifest that does not name this tarball is a valid checksum for
- * another file, which a digest comparison alone would not catch. The name is
- * matched as an awk ERE, so its dots are escaped — unescaped they are
- * wildcards, and a differently-named asset could satisfy the check.
- * - a first field that is not a lowercase digest means the manifest was not
- * the format assumed, and the comparison below would be garbage against
- * garbage.
- * - a mismatch is fatal rather than a warning: this binary runs as root.
- */
+// Upgrades unpack under a private directory created by the host. Expand only that prefix.
+const checksumPath = (path: string): string =>
+ path.startsWith('$WORK/') ? '"$WORK"/' + quote([path.slice('$WORK/'.length)]) : quote([String(path)])
+
+/** Match the literal archive name, then verify its lowercase SHA-256 before installation. */
export const verifyAgainstManifest = ({
tarballName,
tarball,
@@ -367,14 +350,18 @@ export const verifyAgainstManifest = ({
/** Shell path of the downloaded `.sha256` sidecar. */
manifest: string
}): string => {
- const pattern = tarballName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
- return `EXPECTED=$(awk '$2 ~ /^\\*?${pattern}$/ {print $1}' "${manifest}")
-[ -n "$EXPECTED" ] || { echo "FATAL: the checksum manifest does not name ${tarballName}" >&2; exit 1; }
+ return `export RUNNER_TARBALL_NAME=${quote([String(tarballName)])}
+EXPECTED=$(awk '{
+ digest = $1
+ sub(/^[^[:space:]]+[[:space:]]+/, "")
+ if ($0 == ENVIRON["RUNNER_TARBALL_NAME"] || $0 == "*" ENVIRON["RUNNER_TARBALL_NAME"]) print digest
+}' < ${checksumPath(manifest)})
+[ -n "$EXPECTED" ] || { echo "FATAL: the checksum manifest does not name $RUNNER_TARBALL_NAME" >&2; exit 1; }
case "$EXPECTED" in
- *[!0-9a-f]* | "") echo "FATAL: the checksum manifest names no lowercase sha256 for ${tarballName}" >&2; exit 1 ;;
+ *[!0-9a-f]* | "") echo "FATAL: the checksum manifest names no lowercase sha256 for $RUNNER_TARBALL_NAME" >&2; exit 1 ;;
esac
[ \${#EXPECTED} -eq 64 ] || { echo "FATAL: the checksum manifest digest is not 64 hex characters" >&2; exit 1; }
-ACTUAL=$(sha256sum "${tarball}" | awk '{print $1}')
+ACTUAL=$(sha256sum < ${checksumPath(tarball)} | awk '{print $1}')
[ "$EXPECTED" = "$ACTUAL" ] || {
echo "FATAL: runner checksum mismatch (want $EXPECTED got $ACTUAL)" >&2
exit 1
@@ -382,6 +369,19 @@ ACTUAL=$(sha256sum "${tarball}" | awk '{print $1}')
echo "runner tarball checksum verified ($ACTUAL)"`
}
+/** Render both downloads and verification together so a host cannot install unverified bytes. */
+export function fetchVerifiedRunner(binary: RunnerArtifact, phase: 'boot' | 'upgrade', region?: string | null): string {
+ const [tarball, manifest] = phase === 'boot'
+ ? ['/tmp/boxlite-runner.tar.gz', '/tmp/boxlite-runner.sha256'] as const
+ : ['$WORK/runner.tar.gz', '$WORK/runner.sha256'] as const
+ if (binary.release) return `RUNNER_ARCHIVE_FILE="${tarball}"\nRUNNER_MANIFEST_FILE="${manifest}"\n${registryDownload}`
+ return [
+ artifactFetchCommand({ artifact: binary, url: binary.tarballUrl, destination: tarball, region }),
+ artifactFetchCommand({ artifact: binary, url: binary.checksumUrl, destination: manifest, region }),
+ verifyAgainstManifest({ tarballName: binary.tarballName, tarball, manifest }),
+ ].join('\n')
+}
+
/**
* One deploy's runner binary, from the checkout to the addresses a host reads.
*
@@ -406,7 +406,7 @@ export const resolveRunnerBinary = ({
}): ResolvedRunnerBinary => {
const selector = selectRunnerBinary({ environment, workspaceVersion: readVersion({ from: configRoot }) })
return {
- ...runnerArtifactFor({ selector, staging }),
+ ...runnerArtifactFor({ selector, staging, metadata: environment.BOXLITE_RELEASE_DIGESTS }),
source: selector.kind,
version: selector.version,
identity: selector.kind === 'build' ? `${selector.version}+${selector.ref}` : selector.version,
diff --git a/apps/infra/mdeploy/stack/runner-boot.ts b/apps/infra/mdeploy/stack/runner-boot.ts
index 0017bf345..aa2403bfe 100644
--- a/apps/infra/mdeploy/stack/runner-boot.ts
+++ b/apps/infra/mdeploy/stack/runner-boot.ts
@@ -37,7 +37,8 @@
* the wrapper fetches it like any other secret.
*/
-import { artifactFetchCommand, verifyAgainstManifest, type RunnerArtifact } from './runner-binary.ts'
+import { registrySetup, runnerInstallLock, recordRunnerDigest } from './runner-registry.ts'
+import { fetchVerifiedRunner, type RunnerArtifact } from './runner-binary.ts'
import { kernelDeployment } from './runner-kernel.ts'
import { renderRunnerEnvironment } from './runner-environment.ts'
@@ -101,20 +102,8 @@ export type BootInput = {
apiUrl: string
/** Where it ships telemetry. */
otlpUrl: string
- /**
- * What to install: the tarball, and the manifest that has to name it.
- *
- * Two addresses rather than a literal digest, because the stack that renders
- * this is evaluated synchronously and can read neither. See
- * `runner-binary.ts` — the same pair the in-place upgrade uses, verified by
- * the same three lines.
- */
- binary: {
- tarballUrl: string
- checksumUrl: string
- tarballName: string
- transport: RunnerArtifact['transport']
- }
+ /** Release candidate or per-commit artifact verified before extracting. */
+ binary: RunnerArtifact
/** The region an `s3://` address is read from. Null for a public one. */
region?: string | null
/** The port the runner multiplexes everything onto. */
@@ -139,15 +128,6 @@ export const renderRunnerBoot = (input: BootInput): string => {
...Object.keys(platform.unitEnvironment),
])
const region = input.region ?? null
- const fetch = (url: string, destination: string) =>
- artifactFetchCommand({ artifact: input.binary, url, destination, region })
- const fetchTarball = fetch(input.binary.tarballUrl, '/tmp/boxlite-runner.tar.gz')
- const fetchManifest = fetch(input.binary.checksumUrl, '/tmp/boxlite-runner.sha256')
- const verify = verifyAgainstManifest({
- tarballName: input.binary.tarballName,
- tarball: '/tmp/boxlite-runner.tar.gz',
- manifest: '/tmp/boxlite-runner.sha256',
- })
const execStart = platform.startWrapper ? platform.startWrapper.path : '/usr/local/bin/boxlite-runner'
const unitEnvironment = {
BOXLITE_API_URL: runnerApiUrl(input.apiUrl),
@@ -184,12 +164,9 @@ ${platform.prepareKvm}
# box is a silent one.
[ -e /dev/kvm ] || { echo "FATAL: /dev/kvm is absent; this host cannot run boxes" >&2; exit 1; }
-# Fetch the binary and verify it before installing: it runs as root. A mismatch
-# is fatal rather than a warning. The manifest is fetched beside the tarball and
-# has to name it -- runner-binary.ts says what each check catches.
-${fetchTarball}
-${fetchManifest}
-${verify}
+${runnerInstallLock}
+${input.binary.release ? registrySetup(input.binary.release) : ''}
+${fetchVerifiedRunner(input.binary, 'boot', region)}
tar -xzf /tmp/boxlite-runner.tar.gz -C /usr/local/bin/
rm -f /tmp/boxlite-runner.tar.gz /tmp/boxlite-runner.sha256
chmod +x /usr/local/bin/boxlite-runner
@@ -240,6 +217,7 @@ mkdir -p ${RUNNER_HOME}
systemctl daemon-reload
systemctl enable boxlite-runner
systemctl start boxlite-runner
+${input.binary.release ? recordRunnerDigest : ''}
echo "Runner setup complete"
`
diff --git a/apps/infra/mdeploy/stack/runner-registry.ts b/apps/infra/mdeploy/stack/runner-registry.ts
new file mode 100644
index 000000000..78c86ec0f
--- /dev/null
+++ b/apps/infra/mdeploy/stack/runner-registry.ts
@@ -0,0 +1,77 @@
+/** Quote one literal word in generated POSIX or Bash source. */
+function shellLiteral(value: string) {
+ return `'${String(value).replaceAll("'", `'"'"'`)}'`
+}
+
+/** Public OCI artifact produced by the release workflow. Hosts need only anonymous pull access. */
+const repository = 'boxlite-ai/boxlite/runner'
+export const runnerRegistry = `https://ghcr.io/v2/${repository}`
+// All host writers share this lock through the binary swap, health probe, and digest record.
+export const runnerInstallLock = `exec 8>/run/lock/boxlite-runner-upgrade.lock
+flock -w 120 8 || { echo 'Timed out waiting for the Runner installer' >&2; exit 1; }`
+export const runnerDigestFile = '/usr/local/bin/boxlite-runner.oci-digest'
+const sha256 = /^sha256:[0-9a-f]{64}$/
+export type ReleaseRunner = { tag: string; pins?: { manifest: string; archive: string; sha: string } }
+
+export function releaseRunner(version: string, metadata?: string): ReleaseRunner {
+ const tag = 'v' + version
+ if (!/^v\d+\.\d+\.\d+$/.test(tag)) throw new Error('Invalid Runner release version')
+ if (metadata === undefined) return { tag }
+ const { tag: recorded, sha, runner } = JSON.parse(metadata)
+ if (
+ recorded !== tag ||
+ typeof sha !== 'string' ||
+ !/^[0-9a-f]{40}$/.test(sha) ||
+ typeof runner?.manifest !== 'string' ||
+ !sha256.test(runner.manifest) ||
+ typeof runner.archive !== 'string' ||
+ !sha256.test(runner.archive)
+ ) {
+ throw new Error('Invalid release candidate pins for Runner ' + tag)
+ }
+ return { tag, pins: { sha, manifest: runner.manifest, archive: runner.archive } }
+}
+
+const curl =
+ "curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --connect-timeout 10 --max-time 300 --retry 3 --retry-max-time 300"
+
+/** A draft supplies pins inline. A version-only operator invocation reads the same published receipt. */
+export function registrySetup({ tag, pins }: ReleaseRunner): string {
+ if (pins)
+ return `RUNNER_TAG=${shellLiteral(tag)}
+RUNNER_MANIFEST=${shellLiteral(pins.manifest)}
+RUNNER_ARCHIVE=${shellLiteral(pins.archive)}
+RUNNER_REVISION=${shellLiteral(pins.sha)}`
+ return `RUNNER_TAG=${shellLiteral(tag)}
+RUNNER_RECEIPT=$(${curl} "https://github.com/boxlite-ai/boxlite/releases/download/$RUNNER_TAG/release-candidate.json" | python3 -c '
+import json, re, sys
+m = json.load(sys.stdin)
+r = m["runner"]
+if m["tag"] != sys.argv[1] or not re.fullmatch("[a-f0-9]{40}", m["sha"]) or not all(re.fullmatch("sha256:[a-f0-9]{64}", r[k]) for k in ("manifest","archive")):
+ sys.exit("invalid Runner release receipt")
+print(r["manifest"], r["archive"], m["sha"])
+' "$RUNNER_TAG") || { echo "Cannot read valid release-candidate.json for $RUNNER_TAG. For a historical release, backfill its verified Runner into GHCR before installing." >&2; exit 1; }
+read -r RUNNER_MANIFEST RUNNER_ARCHIVE RUNNER_REVISION <<< "$RUNNER_RECEIPT"`
+}
+
+/** Verify the manifest bytes before reading its descriptors, then verify the layer before extraction. */
+export const registryDownload = `RUNNER_TOKEN=$(${curl} 'https://ghcr.io/token?service=ghcr.io&scope=repository:${repository}:pull' | python3 -c 'import json,sys; print(json.load(sys.stdin)["token"])')
+${curl} -H "Authorization: Bearer $RUNNER_TOKEN" -H 'Accept: application/vnd.oci.image.manifest.v1+json' "${runnerRegistry}/manifests/$RUNNER_MANIFEST" -o "$RUNNER_MANIFEST_FILE"
+printf '%s %s\\n' "\${RUNNER_MANIFEST#sha256:}" "$RUNNER_MANIFEST_FILE" | sha256sum -c -
+python3 - "$RUNNER_MANIFEST_FILE" "$RUNNER_TAG" "$RUNNER_REVISION" "$RUNNER_ARCHIVE" <<'VERIFY_RUNNER'
+import json, sys
+path, tag, revision, archive = sys.argv[1:]
+with open(path) as f:
+ manifest = json.load(f)
+layers = manifest["layers"]
+annotations = manifest["annotations"]
+if (manifest.get("artifactType") != "application/vnd.boxlite.runner.v1"
+ or annotations.get("org.opencontainers.image.version") != tag
+ or annotations.get("org.opencontainers.image.revision") != revision
+ or len(layers) != 1 or layers[0]["digest"] != archive or layers[0]["mediaType"] != "application/gzip"):
+ sys.exit("Runner manifest does not match this release")
+VERIFY_RUNNER
+${curl} -H "Authorization: Bearer $RUNNER_TOKEN" "${runnerRegistry}/blobs/$RUNNER_ARCHIVE" -o "$RUNNER_ARCHIVE_FILE"
+printf '%s %s\\n' "\${RUNNER_ARCHIVE#sha256:}" "$RUNNER_ARCHIVE_FILE" | sha256sum -c -`
+
+export const recordRunnerDigest = `printf '%s\\n' "$RUNNER_MANIFEST $RUNNER_ARCHIVE" > ${runnerDigestFile}.new && mv -f ${runnerDigestFile}.new ${runnerDigestFile}`
diff --git a/apps/infra/mdeploy/stack/runner-upgrade.ts b/apps/infra/mdeploy/stack/runner-upgrade.ts
index 72f5bf84f..fab76d61b 100644
--- a/apps/infra/mdeploy/stack/runner-upgrade.ts
+++ b/apps/infra/mdeploy/stack/runner-upgrade.ts
@@ -25,10 +25,8 @@
* operator key and the organization-infrastructure flag, none of which a deploy
* has — the same trade the incumbent path made, recorded rather than implied.
*
- * What the payload converges on is the identity the runner reports on its own
- * health route, not a file it wrote. A marker file says what an install
- * intended; the health route says what is actually serving, which is the only
- * answer that repairs a host whose last upgrade half-finished.
+ * The health route identifies the running version. For release installs the
+ * verified OCI digests distinguish two builds that report the same version.
*/
import { RUNNER_ENV_FILE, runnerApiUrl } from './runner-boot.ts'
@@ -36,7 +34,8 @@ import { CLOUD_RUNNER_KERNEL, kernelDeployment } from './runner-kernel.ts'
import { renderRunnerEnvironment, RUNNER_ENV_BEGIN, RUNNER_ENV_END } from './runner-environment.ts'
import { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
-import { artifactFetchCommand, verifyAgainstManifest } from './runner-binary.ts'
+import { registrySetup, runnerInstallLock, recordRunnerDigest, runnerDigestFile } from './runner-registry.ts'
+import { fetchVerifiedRunner } from './runner-binary.ts'
import { runnerDataDiskNameFor, type RunnerBinary, type RunnerSlot } from './runners.ts'
/** Stable X.Y.Z, optionally carrying the commit a build was produced from. */
@@ -179,17 +178,15 @@ export type UpgradeTarget = {
}
/**
- * Runner identity, artifact name and kernel digest determine when to upgrade.
- * The kernel pin can change independently of the runner package. The runner's
- * own checksum is read on the host, so republishing a runner asset under the
- * same identity is still invisible here; see `runner-binary.ts`.
+ * A manifest change triggers an upgrade even when the reported version stays
+ * the same. Commit builds use their commit-specific archive name.
*
* The instance id is added by the provider, because a replaced host is also due
* an upgrade.
*/
export const upgradeTrigger = (
- target: Pick<UpgradeTarget, 'identity' | 'kernel'> & { binary: Pick<RunnerBinary, 'tarballName'> },
-): string => `${target.identity}:${target.binary.tarballName}:${(target.kernel ?? CLOUD_RUNNER_KERNEL).sha256}`
+ target: Pick<UpgradeTarget, 'identity' | 'kernel'> & { binary: Pick<RunnerBinary, 'tarballName' | 'release'> },
+): string => `${target.identity}:${target.binary.release?.pins?.manifest ?? target.binary.tarballName}:${(target.kernel ?? CLOUD_RUNNER_KERNEL).sha256}`
/**
* Never move a host backwards by accident.
@@ -403,7 +400,7 @@ probe_identity() {
* environment after it still runs. Passing the statement rather than a code is
* what keeps one copy of the checks.
*/
-const guards = (satisfied: string, kernelCheck = ''): string => `if [ ! -x /usr/local/bin/boxlite-runner ] ||
+const guards = (target: UpgradeTarget, satisfied: string, kernelCheck = ''): string => `if [ ! -x /usr/local/bin/boxlite-runner ] ||
[ ! -f /etc/systemd/system/boxlite-runner.service ] ||
{ ! systemctl is-enabled --quiet boxlite-runner 2>/dev/null &&
! systemctl is-active --quiet boxlite-runner; }; then
@@ -411,9 +408,10 @@ const guards = (satisfied: string, kernelCheck = ''): string => `if [ ! -x /usr/
${satisfied}
fi
+${target.binary.release ? registrySetup(target.binary.release) : ''}
CURRENT=$(probe_identity || true)
echo "current identity: \${CURRENT:-<not serving>}"
-if [ "$CURRENT" = "$TARGET" ]${kernelCheck}; then
+if [ "$CURRENT" = "$TARGET" ]${target.binary.release ? ` && [ "$(cat ${runnerDigestFile} 2>/dev/null)" = "$RUNNER_MANIFEST $RUNNER_ARCHIVE" ]` : ''}${kernelCheck}; then
echo "already serving $TARGET; leaving the unit untouched"
${satisfied}
fi
@@ -423,14 +421,10 @@ fi
/** Steps 3 to 5, in the shell's own grading: fall off the end, or exit 1. */
const swapSequence = (target: UpgradeTarget, refused = 'exit 0'): string => {
const region = target.region ?? null
- const fetch = (url: string, destination: string) =>
- artifactFetchCommand({ artifact: target.binary, url, destination, region })
return `${downgradeGuard(target.binary.source, refused)}
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
-${fetch(target.binary.tarballUrl, '$WORK/runner.tar.gz')}
-${fetch(target.binary.checksumUrl, '$WORK/runner.sha256')}
-${verifyAgainstManifest({ tarballName: target.binary.tarballName, tarball: '$WORK/runner.tar.gz', manifest: '$WORK/runner.sha256' })}
+${fetchVerifiedRunner(target.binary, 'upgrade', region)}
tar -xzf "$WORK/runner.tar.gz" -C "$WORK"
test -x "$WORK/boxlite-runner" || { echo "FATAL: the tarball has no boxlite-runner binary" >&2; exit 1; }
@@ -440,6 +434,7 @@ if [ -x /usr/local/bin/boxlite-runner ]; then
cp -a /usr/local/bin/boxlite-runner /usr/local/bin/boxlite-runner.bak
HAD_PREVIOUS=true
fi
+rm -f ${runnerDigestFile}
systemctl stop boxlite-runner || true
wait_for_target() {
@@ -455,6 +450,7 @@ if install -m 0755 "$WORK/boxlite-runner" /usr/local/bin/boxlite-runner \\
&& systemctl start boxlite-runner \\
&& systemctl is-active --quiet boxlite-runner \\
&& wait_for_target; then
+ ${target.binary.release ? recordRunnerDigest : ''}
if [ "$HAD_PREVIOUS" = true ]; then rm -f /usr/local/bin/boxlite-runner.bak; fi
echo "systemd unit: active"
echo "new identity: $(probe_identity)"
@@ -474,7 +470,8 @@ export const renderUpgradePayload = (target: UpgradeTarget): string => {
assertUpgradeTarget(target)
return `set -euo pipefail
(
-${preamble(target)}${guards('exit 0')}${swapSequence(target)}
+${runnerInstallLock}
+${preamble(target)}${guards(target, 'exit 0')}${swapSequence(target)}
)
${kernelDeployment(target.kernel, target.port).enforce}`
}
@@ -503,7 +500,7 @@ const SHEBANG = '#!/bin/bash\n'
export const renderPolicyScripts = (target: UpgradeTarget): UpgradePolicyScripts => {
assertUpgradeTarget(target)
return {
- validate: `${SHEBANG}${preamble(target)}${kernelDeployment(target.kernel, target.port).setup}${guards('exit 100', ' && runner_kernel_matches')}echo "runner binary or kernel needs updating"
+ validate: `${SHEBANG}${preamble(target)}${kernelDeployment(target.kernel, target.port).setup}${guards(target, 'exit 100', ' && runner_kernel_matches')}echo "runner binary or kernel needs updating"
exit 101
`,
/*
@@ -788,8 +785,9 @@ exit 101
*/
export const renderHostConvergence = (target: UpgradeTarget): string => {
assertUpgradeTarget(target)
- const binary = `upgrade_binary() {
-${guards('return 0')}${swapSequence(target, 'return 0')}}
+ const binary = `upgrade_binary() (
+${runnerInstallLock}
+${guards(target, 'return 0')}${swapSequence(target, 'return 0')})
`
const environment = target.apiUrl
? `${unitEnvironmentBlock({
diff --git a/apps/infra/mdeploy/stack/runners.ts b/apps/infra/mdeploy/stack/runners.ts
index 09d355fd1..3f446bac6 100644
--- a/apps/infra/mdeploy/stack/runners.ts
+++ b/apps/infra/mdeploy/stack/runners.ts
@@ -63,32 +63,8 @@ export type RunnerSlot = {
*/
export type RunnerAssignment = { slot: RunnerSlot; token: $util.Input<string> }
-/**
- * What a host installs: two addresses, and the identity it must then report.
- *
- * One shape for both sources — a published release and a per-commit object —
- * because the host does the same thing with either: fetch the tarball, fetch the
- * `.sha256` sidecar beside it, refuse to install unless the manifest names
- * exactly that tarball and its digest matches.
- *
- * The digest travels as an address rather than a value because the stack is
- * evaluated synchronously by both engines: nothing here can read it. That is
- * also why `identity` is carried separately — the in-place upgrade converges on
- * what a live host *reports*, and a running runner cannot be asked for a digest.
- *
- * Resolved by `runner-binary.ts`, from the checkout, before any machine exists.
- * Plain strings, every one of them: nothing here comes from another resource, so
- * a provider renders the boot script and the upgrade payload without resolving
- * anything — which is also what lets both be tested without an engine.
- */
-export type RunnerBinary = {
- tarballUrl: string
- /** The `.sha256` manifest beside it, which the host verifies against. */
- checksumUrl: string
- /** The filename the manifest must name. Not derivable from the URL on the host. */
- tarballName: string
- /** How both addresses are read: public HTTPS, or an object only a role may read. */
- transport: RunnerArtifact['transport']
+/** Both providers install the same verified artifact and probe the version reported by the service. */
+export type RunnerBinary = RunnerArtifact & {
/** Which source this came from. Decides whether ordering can be guarded. */
source: 'release' | 'build'
/**
diff --git a/apps/infra/mdeploy/test/component-release.test.ts b/apps/infra/mdeploy/test/component-release.test.ts
index 4ead3e7c9..54ef3d644 100644
--- a/apps/infra/mdeploy/test/component-release.test.ts
+++ b/apps/infra/mdeploy/test/component-release.test.ts
@@ -1,53 +1,53 @@
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
-import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { load } from 'js-yaml'
-test('API-only releases skip Runner attachments while every selection still requires a published release', () => {
+test('candidate and standalone release plans validate the exact tag, commit and pins', (t) => {
const workflow = load(
readFileSync(new URL('../../../../.github/workflows/mdeploy-all.yml', import.meta.url), 'utf8'),
) as any
- const gate = workflow.jobs.resolve.steps.find((step: any) => step.name === 'Require the release this tag names')
- const directory = mkdtempSync(join(tmpdir(), 'mdeploy-release-scope-'))
- try {
- const gh = join(directory, 'gh')
- writeFileSync(gh, '#!/bin/bash\nprintf "%s" "$RELEASE"\nexit "${GH_STATUS:-0}"\n')
- chmodSync(gh, 0o755)
- const run = (components: string, draft: boolean, attached: boolean, status = 0) =>
- spawnSync('bash', ['-c', gate.run], {
- encoding: 'utf8',
- env: {
- PATH: `${directory}:${process.env.PATH}`,
- VERSION: 'v1.2.3',
- COMPONENTS: components,
- GITHUB_REPOSITORY: 'example/fixture',
- GH_STATUS: String(status),
- RELEASE: JSON.stringify({
- isDraft: draft,
- assets: attached
- ? [
- { name: 'boxlite-runner-v1.2.3-linux-amd64.tar.gz' },
- { name: 'boxlite-runner-v1.2.3-linux-amd64.tar.gz.sha256' },
- ]
- : [],
- }),
- },
- })
- for (const component of ['api', 'runner', 'api+runner']) {
- assert.equal(run(component, false, true).status, 0)
- assert.notEqual(run(component, true, true).status, 0, `${component} admitted a draft`)
- assert.notEqual(run(component, false, true, 1).status, 0, `${component} admitted a missing release`)
- const missingAssets = run(component, false, false)
- if (component === 'api') assert.equal(missingAssets.status, 0, missingAssets.stdout)
- else {
- assert.notEqual(missingAssets.status, 0)
- assert.match(missingAssets.stdout, /carries no boxlite-runner/)
- }
- }
- } finally {
- rmSync(directory, { recursive: true, force: true })
+ const step = workflow.jobs.resolve.steps.find((s: any) => s.id === 'pins')
+ const dir = mkdtempSync(join(tmpdir(), 'mdeploy-release-pins-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const sha = 'a'.repeat(40),
+ hash = 'sha256:' + 'f'.repeat(64)
+ const pins = { tag: 'v1.2.3', sha, images: { api: hash }, runner: { manifest: hash, archive: hash } }
+ writeFileSync(
+ join(dir, 'gh'),
+ `#!/bin/bash
+if [[ "$2" == view ]]; then printf '{"isDraft":%s}' "$DRAFT"; else printf '%s' "$PINS" > "$RUNNER_TEMP/release-candidate.json"; fi
+`,
+ { mode: 0o755 },
+ )
+ const run = (candidate: boolean, data: object, draft = false) =>
+ spawnSync('bash', ['-c', step.run], {
+ cwd: dir,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ PATH: dir + ':' + process.env.PATH,
+ GITHUB_OUTPUT: join(dir, 'output'),
+ RUNNER_TEMP: dir,
+ TAG: pins.tag,
+ SHA: sha,
+ CANDIDATE_ID: '12',
+ CANDIDATE_DIGEST: hash,
+ RELEASE_CALLER: candidate ? sha : '',
+ PINS: JSON.stringify(data),
+ DRAFT: String(draft),
+ },
+ })
+ for (const candidate of [true, false]) {
+ const ok = run(candidate, pins)
+ assert.equal(ok.status, 0, ok.stderr)
+ assert.notEqual(run(candidate, { ...pins, tag: 'v2.0.0' }).status, 0)
+ assert.notEqual(run(candidate, { ...pins, sha: 'b'.repeat(40) }).status, 0)
+ assert.notEqual(run(candidate, { ...pins, runner: { archive: hash } }).status, 0)
}
+ assert.notEqual(run(false, pins, true).status, 0)
+ assert.equal(run(true, pins, true).status, 0)
})
diff --git a/apps/infra/mdeploy/test/ghcr-workflow.test.ts b/apps/infra/mdeploy/test/ghcr-workflow.test.ts
index 97400659b..62332e2df 100644
--- a/apps/infra/mdeploy/test/ghcr-workflow.test.ts
+++ b/apps/infra/mdeploy/test/ghcr-workflow.test.ts
@@ -62,10 +62,8 @@ esac
`runner=${components.includes('runner') && missing ? 'build' : 'skip'}\n`,
)
const invoked = readFileSync(calls, 'utf8')
- if (components.includes('api')) {
- assert.match(invoked, /mbuild verify/)
- if (release) assert.match(invoked, /--ghcr example\/fixture --version v1\.2\.3/)
- else assert.match(invoked, /--tag selected-tag --stage dev/)
+ if (components.includes('api') && !release) {
+ assert.match(invoked, /mbuild verify .*--tag selected-tag --stage dev/)
} else assert.doesNotMatch(invoked, /mbuild/)
if (components.includes('runner') && !release) assert.match(invoked, /runner:build .*--check/)
else assert.doesNotMatch(invoked, /runner:build/)
@@ -74,64 +72,6 @@ esac
}
}
-for (const stage of ['dev', 'prod']) {
- for (const [cloudPresent, ghcrStatus] of [
- [false, 66],
- [true, 66],
- [false, 1],
- [true, 1],
- ] as const) {
- test(`${stage} refuses GHCR status ${ghcrStatus} when cloud images are ${cloudPresent ? 'present' : 'absent'}`, (t) => {
- const directory = mkdtempSync(join(tmpdir(), 'ghcr-plan-'))
- t.after(() => rmSync(directory, { recursive: true, force: true }))
- writeFileSync(join(directory, 'calls'), '')
- writeFileSync(join(directory, 'output'), '')
- writeFileSync(join(directory, 'summary'), '')
- writeFileSync(
- join(directory, 'npm'),
- `#!/bin/bash
-echo "$*" >> "$PLAN_CALLS"
-if [[ "$*" == *"--ghcr"* ]]; then exit ${ghcrStatus}; fi
-exit ${cloudPresent ? 0 : 66}
-`,
- { mode: 0o755 },
- )
- const step = workflow.jobs.plan.steps.find((candidate: any) => candidate.id === 'plan')
- const result = spawnSync('bash', ['-c', step.run], {
- encoding: 'utf8',
- timeout: 10_000,
- env: {
- ...process.env,
- PATH: `${directory}:${process.env.PATH}`,
- PLAN_CALLS: join(directory, 'calls'),
- GITHUB_OUTPUT: join(directory, 'output'),
- RUNNER_TEMP: directory,
- GITHUB_STEP_SUMMARY: join(directory, 'summary'),
- GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
- GHCR_REPOSITORY: 'boxlite-ai/boxlite',
- VERSION: 'v1.2.3',
- SHA: 'a'.repeat(40),
- IMAGE_TAG: `v1.2.3-${'a'.repeat(40)}`,
- LINE: 'release v1.2.3',
- STAGE: stage,
- COMPONENTS: 'api',
- },
- })
- assert.equal(result.status, 1, `GHCR verification errors must stop planning:\n${result.stdout}\n${result.stderr}`)
- if (ghcrStatus === 66)
- assert.match(result.stdout + result.stderr, /Run manually: gh workflow run mbuild-release\.yml/)
- else {
- assert.match(result.stdout + result.stderr, /could not read GHCR images/)
- assert.doesNotMatch(result.stdout + result.stderr, /Run manually|gh workflow run/)
- }
- const calls = readFileSync(join(directory, 'calls'), 'utf8')
- assert.match(calls, /mbuild verify .*--ghcr/)
- assert.doesNotMatch(calls, /publish|promote|workflow run/)
- assert.doesNotMatch(readFileSync(join(directory, 'output'), 'utf8'), /release-publish|release-promote|api=build/)
- })
- }
-}
-
test('tag deployment imports before image verification and never calls the release builder', () => {
assert.equal(Object.values<any>(workflow.jobs).some((job) => job.uses?.includes('mbuild-release.yml')), false)
const steps = actionSteps('mdeploy')
diff --git a/apps/infra/mdeploy/test/parallel-build.test.ts b/apps/infra/mdeploy/test/parallel-build.test.ts
index 455dad61d..bb9e56288 100644
--- a/apps/infra/mdeploy/test/parallel-build.test.ts
+++ b/apps/infra/mdeploy/test/parallel-build.test.ts
@@ -80,7 +80,8 @@ esac
}
assert.equal(plan.strategy.matrix.component, '${{ fromJSON(needs.resolve.outputs.prepare_components) }}')
assert.equal(workflow.jobs.resolve.outputs.prepare_components, '${{ steps.tag.outputs.prepare_components }}')
- assert.equal(plan.outputs, undefined, 'matrix outputs must not choose the commit deployment route')
+ assert.deepEqual(plan.outputs, { deployment_attempt: '${{ steps.applied.outputs.attempt }}' })
+ assert.equal(plan.steps.find((s: any) => s.id === 'applied').if, "inputs.release_sha && inputs.stage == 'dev'")
assert.equal(workflow.jobs.deploy.steps.find((step: any) => step.uses === './.github/actions/mdeploy').with['api-route'], 'skip')
assert.deepEqual(workflow.jobs.deploy.needs, ['resolve', 'plan', 'notify-deploy'])
})
diff --git a/apps/infra/mdeploy/test/release-runner-digest.test.ts b/apps/infra/mdeploy/test/release-runner-digest.test.ts
new file mode 100644
index 000000000..9dc12a597
--- /dev/null
+++ b/apps/infra/mdeploy/test/release-runner-digest.test.ts
@@ -0,0 +1,205 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { resolveRunnerBinary } from '../stack/runner-binary.ts'
+import { renderRunnerBoot } from '../stack/runner-boot.ts'
+import { renderUpgradePayload, renderHostConvergence, upgradeTrigger } from '../stack/runner-upgrade.ts'
+
+import { createHash } from 'node:crypto'
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { spawnSync } from 'node:child_process'
+import { registrySetup, runnerDigestFile } from '../stack/runner-registry.ts'
+
+const sha = 'a'.repeat(40)
+function target(manifest: string, archive: string) {
+ const environment = {
+ VERSION: '1.2.3',
+ BOXLITE_RELEASE_DIGESTS: JSON.stringify({
+ tag: 'v1.2.3',
+ sha,
+ runner: { manifest, archive },
+ }),
+ }
+ const binary = resolveRunnerBinary({ configRoot: process.cwd(), environment })
+ return { binary, identity: binary.identity, port: 3003 }
+}
+const digest = (digit: string) => 'sha256:' + digit.repeat(64)
+test('draft host installs using the release candidate alone', () => {
+ const candidate = target(digest('1'), digest('2'))
+ const boot = renderRunnerBoot({
+ ...candidate,
+ apiUrl: 'https://api.example.com',
+ otlpUrl: 'http://localhost:4318',
+ environment: {},
+ platform: {
+ hostAddress: '',
+ installVolumeMount: '',
+ prepareKvm: '',
+ prepareHome: '',
+ startWrapper: null,
+ unitEnvironment: {},
+ },
+ })
+ const script = Buffer.from(boot, 'base64').toString()
+ assert.ok(script.includes(digest('1')) && script.includes(digest('2')), 'host discarded the candidate pins')
+ assert.ok(!script.includes('github.com/boxlite-ai/boxlite/releases/download/v1.2.3/'))
+})
+test('replacing a same-version runner changes both upgrade trigger and payload', () => {
+ const old = target(digest('1'), digest('2'))
+ const next = target(digest('3'), digest('4'))
+ assert.notEqual(upgradeTrigger(old), upgradeTrigger(next))
+ assert.notEqual(renderUpgradePayload(old), renderUpgradePayload(next))
+})
+
+test('fresh host verifies GHCR bytes without a Release attachment; a replaced digest reaches the swap', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'release-runner-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const archive = 'candidate archive'
+ const hash = (data: string) => 'sha256:' + createHash('sha256').update(data).digest('hex')
+ const layer = hash(archive)
+ const manifest = JSON.stringify({
+ artifactType: 'application/vnd.boxlite.runner.v1',
+ annotations: { 'org.opencontainers.image.version': 'v1.2.3', 'org.opencontainers.image.revision': sha },
+ layers: [{ digest: layer, mediaType: 'application/gzip' }],
+ })
+ const image = hash(manifest)
+ const candidate = target(image, layer)
+ const boot = Buffer.from(
+ renderRunnerBoot({
+ ...candidate,
+ apiUrl: 'https://api.example.com',
+ otlpUrl: 'http://localhost:4318',
+ environment: {},
+ platform: {
+ hostAddress: '',
+ installVolumeMount: '',
+ prepareKvm: '',
+ prepareHome: '',
+ startWrapper: null,
+ unitEnvironment: {},
+ },
+ }),
+ 'base64',
+ ).toString()
+ const start = boot.indexOf('RUNNER_TAG=')
+ const end = boot.indexOf('tar -xzf /tmp/boxlite-runner.tar.gz', start)
+ assert.ok(start >= 0 && end > start)
+ const download = boot.slice(start, end).replaceAll('/tmp/boxlite-runner.', dir + '/download.')
+ writeFileSync(join(dir, 'manifest'), manifest)
+ writeFileSync(join(dir, 'bytes'), archive)
+ const mock = `curl() {
+ case "$*" in
+ *ghcr.io/token*) printf '%s' '{"token":"fixture"}' ;;
+ *ghcr.io/v2/boxlite-ai/boxlite/runner/manifests/${image}*) cp "$FIXTURE/manifest" "\${@: -1}" ;;
+ *ghcr.io/v2/boxlite-ai/boxlite/runner/blobs/${layer}*) cp "$FIXTURE/bytes" "\${@: -1}" ;;
+ *127.0.0.1*) printf '%s' '{"version":"1.2.3"}' ;;
+ *) return 22 ;;
+ esac
+ }
+ systemctl() { return 0; }`
+ const run = (fragment: string) =>
+ spawnSync('bash', ['-c', 'set -euo pipefail\n' + mock + '\n' + fragment], {
+ encoding: 'utf8',
+ env: { ...process.env, FIXTURE: dir },
+ })
+ let result = run(download)
+ assert.equal(result.status, 0, result.stderr)
+ assert.equal(readFileSync(join(dir, 'download.tar.gz'), 'utf8'), archive)
+ writeFileSync(join(dir, 'bytes'), 'wrong archive')
+ assert.notEqual(run(download).status, 0)
+ writeFileSync(join(dir, 'manifest'), manifest + ' ')
+ assert.notEqual(run(download).status, 0)
+
+ const script = renderUpgradePayload(candidate)
+ const guardEnd = script.indexOf('\nfi\n', script.indexOf('already serving $TARGET'))
+ const guard = script
+ .slice(script.indexOf('TARGET='), guardEnd + 4)
+ .replaceAll(runnerDigestFile, join(dir, 'installed'))
+ .replaceAll('/usr/local/bin/boxlite-runner', join(dir, 'binary'))
+ .replaceAll('/etc/systemd/system/boxlite-runner.service', join(dir, 'unit'))
+ writeFileSync(join(dir, 'binary'), 'fixture')
+ chmodSync(join(dir, 'binary'), 0o755)
+ writeFileSync(join(dir, 'unit'), 'fixture')
+ writeFileSync(join(dir, 'installed'), image + ' ' + layer + '\n')
+ result = run(guard + '\necho SWAP')
+ assert.equal(result.status, 0, result.stderr)
+ assert.doesNotMatch(result.stdout, /SWAP/)
+ writeFileSync(join(dir, 'installed'), digest('3') + ' ' + digest('4') + '\n')
+ result = run(guard + '\necho SWAP')
+ assert.equal(result.status, 0, result.stderr)
+ assert.match(result.stdout, /SWAP/)
+})
+
+test('version-only manual installation reads the same pins from the published receipt', () => {
+ const manual = resolveRunnerBinary({ configRoot: process.cwd(), environment: { VERSION: '1.2.3' } })
+ const receipt = { tag: 'v1.2.3', sha, runner: { manifest: digest('a'), archive: digest('b') } }
+ const script = registrySetup(manual.release!)
+ const read = (data: object) =>
+ spawnSync(
+ 'bash',
+ [
+ '-c',
+ `set -euo pipefail
+curl() {
+ [[ "$*" == *"https://github.com/boxlite-ai/boxlite/releases/download/v1.2.3/release-candidate.json" ]] || return 22
+ printf '%s' "$RECEIPT"
+}
+${script}
+printf '%s %s %s' "$RUNNER_MANIFEST" "$RUNNER_ARCHIVE" "$RUNNER_REVISION"`,
+ ],
+ { encoding: 'utf8', env: { ...process.env, RECEIPT: JSON.stringify(data) } },
+ )
+ const selected = read(receipt)
+ assert.equal(selected.status, 0, selected.stderr)
+ assert.equal(selected.stdout, [receipt.runner.manifest, receipt.runner.archive, sha].join(' '))
+ assert.notEqual(read({ ...receipt, tag: 'v1.2.4' }).status, 0)
+ assert.notEqual(read({ ...receipt, runner: { ...receipt.runner, archive: 'invalid' } }).status, 0)
+ assert.match(read({}).stderr, /backfill/i, 'missing metadata must identify the required backfill')
+ assert.throws(() => target(digest('a'), 'invalid'), /Invalid release candidate pins/)
+})
+
+test('concurrent host installers stop before reading or swapping the installed Runner', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'runner-lock-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const item = target(digest('1'), digest('2'))
+ const boot = renderRunnerBoot({
+ ...item,
+ environment: {},
+ apiUrl: 'https://api.example.com',
+ otlpUrl: 'http://localhost:4318',
+ platform: {
+ hostAddress: '',
+ installVolumeMount: '',
+ prepareHome: '',
+ prepareKvm: '',
+ unitEnvironment: {},
+ startWrapper: null,
+ },
+ })
+ const lock = join(dir, 'boxlite-runner-upgrade.lock')
+ for (const payload of [
+ renderUpgradePayload(item),
+ renderHostConvergence(item),
+ Buffer.from(boot, 'base64').toString(),
+ ]) {
+ const start = payload.indexOf('exec 8>')
+ const guard = payload.indexOf('if [ ! -x /usr/local/bin/boxlite-runner ]', start)
+ const end = guard < 0 ? payload.indexOf('RUNNER_TAG=', start) : guard
+ const critical = payload
+ .slice(Math.max(0, start), end)
+ .replaceAll('/run/lock/boxlite-runner-upgrade.lock', lock)
+ .replace('flock -w 120 8', 'flock -n 8')
+ const run = (held: boolean) =>
+ spawnSync(
+ 'bash',
+ [
+ '-ec',
+ (held ? 'exec 9>"$TEST_LOCK"; flock -n 9; ' : '') + '(\n' + (start < 0 ? '' : critical) + '\necho READY\n)',
+ ],
+ { env: { ...process.env, TEST_LOCK: lock }, encoding: 'utf8' },
+ )
+ assert.notEqual(run(true).status, 0, 'a second installer entered the binary swap')
+ assert.equal(run(false).status, 0, 'lock must release when the installer exits')
+ }
+})
diff --git a/apps/infra/mdeploy/test/runner-binary.test.ts b/apps/infra/mdeploy/test/runner-binary.test.ts
index 675eebb1b..1fbe0c085 100644
--- a/apps/infra/mdeploy/test/runner-binary.test.ts
+++ b/apps/infra/mdeploy/test/runner-binary.test.ts
@@ -96,8 +96,8 @@ test('a release resolves to the assets the publisher actually uploads', () => {
selector: { kind: 'release', version: '0.10.0' },
})
assert.equal(tarballName, 'boxlite-runner-v0.10.0-linux-amd64.tar.gz')
- assert.equal(tarballUrl, `https://github.com/boxlite-ai/boxlite/releases/download/v0.10.0/${tarballName}`)
- assert.equal(checksumUrl, `${tarballUrl}.sha256`)
+ assert.equal(tarballUrl, 'https://ghcr.io/v2/boxlite-ai/boxlite/runner/blobs/$RUNNER_ARCHIVE')
+ assert.equal(checksumUrl, 'https://ghcr.io/v2/boxlite-ai/boxlite/runner/manifests/$RUNNER_MANIFEST')
assert.equal(transport, 'https')
})
@@ -215,11 +215,6 @@ test('the manifest is verified before the bytes are trusted', () => {
* Ordering only. What the fragment *does* — refusing a manifest that names
* another file, an uppercase digest, a wrong length, a mismatch — is proved
* by running it, in `runner-payload.test.ts`.
- *
- * Deliberately not asserted here: the escaped awk pattern. A test that
- * spelled it out would be this file writing the pattern and then finding it,
- * and it would keep passing with the escaping removed — which is exactly the
- * defect that matters, since unescaped dots are wildcards.
*/
const script = verifyAgainstManifest({
tarballName: 'boxlite-runner-v0.10.0-linux-amd64.tar.gz',
diff --git a/apps/infra/mdeploy/test/runner-boot.test.ts b/apps/infra/mdeploy/test/runner-boot.test.ts
index 7a72171e8..0e4348e57 100644
--- a/apps/infra/mdeploy/test/runner-boot.test.ts
+++ b/apps/infra/mdeploy/test/runner-boot.test.ts
@@ -95,8 +95,8 @@ test('the manifest this host verifies against is the one it fetched beside the t
// uppercase-digest cases. What matters here is that a boot script renders it
// at all, and against the file it just downloaded rather than some other one.
const script = render()
- assert.match(script, /EXPECTED=\$\(awk .* "\/tmp\/boxlite-runner\.sha256"\)/)
- assert.match(script, /ACTUAL=\$\(sha256sum "\/tmp\/boxlite-runner\.tar\.gz"/)
+ assert.match(script, /EXPECTED=\$\(awk '[^']*' < \/tmp\/boxlite-runner\.sha256\)/)
+ assert.match(script, /ACTUAL=\$\(sha256sum < \/tmp\/boxlite-runner\.tar\.gz \|/)
})
test('the manifest is fetched beside the tarball, not derived on the host', () => {
diff --git a/apps/infra/mdeploy/test/runner-payload.test.ts b/apps/infra/mdeploy/test/runner-payload.test.ts
index 9a8ad1ee8..0403df2e7 100644
--- a/apps/infra/mdeploy/test/runner-payload.test.ts
+++ b/apps/infra/mdeploy/test/runner-payload.test.ts
@@ -16,9 +16,9 @@
import assert from 'node:assert/strict'
import { execFileSync, spawnSync } from 'node:child_process'
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import test from 'node:test'
import {
renderHostConvergence,
@@ -86,6 +86,20 @@ test('bytes that match the manifest are accepted', digestsLocally, () => {
assert.match(result.out, /checksum verified/)
})
+test('the checksum verifier treats the archive name and both local paths literally', digestsLocally, (t) => {
+ const tarballName = "Runner's release candidate.tar.gz"
+ const files = fixture((digest) => `${digest} ${tarballName}\n`)
+ const directory = dirname(files.tarball)
+ t.after(() => rmSync(directory, { recursive: true, force: true }))
+ const tarball = join(directory, 'download "A".tar.gz')
+ const manifest = join(directory, 'checksums "A".txt')
+ renameSync(files.tarball, tarball)
+ renameSync(files.manifest, manifest)
+ const result = bash(verifyAgainstManifest({ tarballName, tarball, manifest }))
+ assert.equal(result.code, 0, result.out)
+ assert.match(result.out, /checksum verified/)
+})
+
test('the binary-mode asterisk sha256sum writes is part of the format', digestsLocally, () => {
assert.equal(verify((digest) => `${digest} *${TARBALL}\n`).code, 0)
})
diff --git a/apps/infra/mdeploy/test/runner-workflow.test.ts b/apps/infra/mdeploy/test/runner-workflow.test.ts
index 7effa5565..69a249f20 100644
--- a/apps/infra/mdeploy/test/runner-workflow.test.ts
+++ b/apps/infra/mdeploy/test/runner-workflow.test.ts
@@ -58,13 +58,7 @@ test('staging is not retried, because neither of its failures is transient', ()
})
test('a release rollout compiles no runner at all', () => {
- /*
- * The property the release line exists for. `runnerArtifactFor` addresses
- * `boxlite-runner-v<X.Y.Z>-linux-amd64.tar.gz` on the GitHub Release, which
- * is the artifact the release was cut from; rebuilding that commit would
- * produce different bytes under the same version, because gzip alone stamps
- * an mtime into the tarball.
- */
+
assert.match(
String(workflow.jobs.plan.steps.find((step: any) => step.uses === './.github/actions/build-staged-runner').if),
/steps\.plan\.outputs\.runner == 'build'/,
@@ -73,7 +67,7 @@ test('a release rollout compiles no runner at all', () => {
const plan = source.slice(source.indexOf('- name: Decide'))
assert.match(
plan.slice(0, plan.indexOf('printf')),
- /if \[ -n "\$VERSION" \]; then\n(?:[^\n]*\n)*?\s*echo "\$VERSION installs the runner tarball from its GitHub Release"/,
+ /if \[ -n "\$VERSION" \]; then\n(?:[^\n]*\n)*?\s*echo "\$VERSION installs the Runner pinned by its release candidate from GHCR"/,
'the plan compiles a runner for a released version',
)
})
@@ -117,32 +111,7 @@ test('a run that was not about the runner never installs one this run did not st
assert.match(plan.slice(0, plan.indexOf('printf')), /case "\$COMPONENTS" in\n\s*\*runner\*\)/)
})
-test('a release is refused unless the tarball it will install is already attached', () => {
- /*
- * A git tag is not a release, and a release whose runner build has not
- * finished carries no tarball. Either way the download 404s on the host at
- * boot — long after the apply reported success — so both are asked for here,
- * where the answer costs one API read.
- *
- * The names are the publisher's: `build-runner-binary.yml` uploads exactly
- * these and `runnerArtifactFor` composes them, so a third spelling here would
- * pass against assets nothing installs.
- */
- const gate = source.slice(
- source.indexOf('- name: Require the release this tag names'),
- source.indexOf('- id: ref', source.indexOf('- name: Require the release this tag names')),
- )
- assert.match(gate, /gh release view "\$VERSION"/, 'a tag is taken as a release')
- assert.match(gate, /isDraft/, 'a draft release is taken as published')
- assert.match(gate, /boxlite-runner-\$\{VERSION\}-linux-amd64\.tar\.gz/)
- assert.match(gate, /"\$\{tarball\}\.sha256"/, 'the checksum is not required')
-
- // API-only updates leave Runner policies unchanged; every path installing a Runner still checks its assets.
- assert.match(gate, /if \[ "\$COMPONENTS" = 'api' \]; then exit 0; fi/)
- const addressing = source.slice(source.indexOf('- name: Address what this deploy installs'))
- assert.match(
- addressing.slice(0, addressing.indexOf('GITHUB_ENV')),
- /elif \[ -n "\$VERSION" \]; then\n\s*(?:#[^\n]*\n\s*)*printf 'VERSION=%s/,
- 'the inline program still needs its explicit release version',
- )
+test('release apply forwards verified pins to the stack', () => {
+ assert.match(source, /registry-digests: \$\{\{ needs.resolve.outputs.registry_digests/)
+ assert.match(source, /BOXLITE_RELEASE_DIGESTS=%s/)
})
diff --git a/apps/infra/mdeploy/test/stage-e2e.test.ts b/apps/infra/mdeploy/test/stage-e2e.test.ts
index 9f6a286c1..a2cab4117 100644
--- a/apps/infra/mdeploy/test/stage-e2e.test.ts
+++ b/apps/infra/mdeploy/test/stage-e2e.test.ts
@@ -61,7 +61,7 @@ test('cloud E2E selects only the requested stage credentials and keeps prod narr
assert.equal(evaluate(sweep.if, stage).coerceString(), String(stage === 'dev'))
assert.equal(evaluate(sweep.if, stage, false).coerceString(), 'false')
}
- assert.deepEqual(workflow.permissions, { contents: 'read' })
+ assert.deepEqual(workflow.permissions, { contents: 'read', actions: 'read' })
const suite = steps.find((step: any) => step.name === 'Run E2E suite')
assert.match(suite.run, /if \[ "\$STAGE" = prod \]; then[\s\S]*-m smoke/)
})
@@ -132,7 +132,5 @@ test('cloud release clients preserve source defaults and stage coverage', () =>
const validate = steps.find((step: any) => step.name === 'Validate client release')
assert.ok(steps.indexOf(validate) < steps.indexOf(configure))
const checkout = steps.find((step: any) => step.name === 'Checkout release SDK sources for subdomain clients')
- assert.equal(checkout.with.ref, '${{ inputs.tag }}')
- assert.equal(checkout.with['persist-credentials'], false)
- assert.equal(checkout.with.path, 'target/e2e-release')
+ assert.equal(checkout.env.RELEASE_SDK_SHA, '${{ steps.release_commit.outputs.sha }}')
})
diff --git a/apps/infra/mdeploy/test/workflow.test.ts b/apps/infra/mdeploy/test/workflow.test.ts
index 86c862c3b..d925b58dd 100644
--- a/apps/infra/mdeploy/test/workflow.test.ts
+++ b/apps/infra/mdeploy/test/workflow.test.ts
@@ -78,10 +78,11 @@ test('component-specific artifact and cloud checks stay aligned with the public
assert.equal(steps[gate].if, "inputs.components != 'api+runner' && steps.config.outputs.kind != 'artifact-registry'")
assert.notEqual(spawnSync('bash', ['-c', steps[gate].run]).status, 0)
const images = actionSteps('mdeploy').find((step: any) => step.name === 'Verify the images')
- assert.equal(images.if, "inputs.components != 'runner'")
- const release = parsed.jobs.resolve.steps.find((step: any) => step.name === 'Require the release this tag names')
- assert.equal(release.env.COMPONENTS, '${{ inputs.components }}')
- assert.ok(release.run.indexOf('"$COMPONENTS" = \'api\'') < release.run.indexOf('tarball='))
+ assert.equal(images.if, "inputs.components != 'runner' && inputs.api-route != 'release-import'")
+ const importer = actionSteps('mdeploy').find((s: any) => s.run?.includes('mbuild import-release'))
+ assert.match(importer.if, /release-import/)
+ assert.ok(parsed.jobs.resolve.steps.some((s: any) => s.id === 'pins'))
+
})
/** What the workflow runs, with the commentary that discusses it removed. */
@@ -393,9 +394,9 @@ test('only dev and stage deploy workflows run off main', () => {
// exactly the workflow that is strictest.
const workflows = ['mdeploy-all.yml', 'mbuild.yml']
for (const name of workflows) {
- const text = workflowSource(name)
- const guards = [...text.matchAll(/^\s*if: [^\n]*(?:\n\s{6}[^\n]*)*/gm)]
- .map((match) => match[0])
+ const parsed = load(readFileSync(new URL('../../../../.github/workflows/' + name, import.meta.url), 'utf8')) as any
+ const guards = Object.values<any>(parsed.jobs)
+ .map((job) => job.if ?? '')
.filter((guard) => guard.includes('refs/heads/main'))
assert.ok(guards.length > 0, `${name} guards no job by branch`)
for (const guard of guards) {
diff --git a/apps/infra/package-lock.json b/apps/infra/package-lock.json
index 77634ed5a..fafd2f4fc 100644
--- a/apps/infra/package-lock.json
+++ b/apps/infra/package-lock.json
@@ -63,7 +63,8 @@
"dependencies": {
"mbuild": "file:../mbuild",
"mstage": "file:../mstage",
- "naming": "file:../naming"
+ "naming": "file:../naming",
+ "shell-quote": "^1.10.0"
},
"bin": {
"mdeploy": "bin/mdeploy.ts"
diff --git a/apps/infra/scripts/release-candidate-stage.test.mjs b/apps/infra/scripts/release-candidate-stage.test.mjs
new file mode 100644
index 000000000..3f3c3446e
--- /dev/null
+++ b/apps/infra/scripts/release-candidate-stage.test.mjs
@@ -0,0 +1,184 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import test from 'node:test'
+import { fileURLToPath } from 'node:url'
+import { linuxClients, verifyAcceptedDistribution, verifyCandidate } from './release-candidate.mjs'
+
+const command = fileURLToPath(new URL('./release-candidate.mjs', import.meta.url))
+const config = new URL('../../../.github/ci-config.json', import.meta.url)
+const hash = (data) => 'sha256:' + createHash('sha256').update(data).digest('hex')
+
+test('stage binds candidate files and GHCR pins to the tagged commit and producer run', async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'candidate-stage-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ mkdirSync(join(dir, '.github'))
+ cpSync(config, join(dir, '.github/ci-config.json'))
+ const index = []
+ const version = '1.2.3',
+ tag = 'v' + version,
+ sha = 'a'.repeat(40)
+ function group(name, files) {
+ const path = join(dir, 'staged', name)
+ mkdirSync(path, { recursive: true })
+ writeFileSync(join(path, 'producer.json'), JSON.stringify({ run: 10, attempt: 1, sha }))
+ for (const [key, bytes] of Object.entries(files)) writeFileSync(join(path, key), bytes)
+ index.push({ id: index.length + 1, name, expired: false })
+ return path
+ }
+ const runtime = { 'install.sh': 'installer', 'install.sh.sha256': hash('installer'), SHA256SUMS: 'checksums' }
+ const packages = { ['boxlite-ai-boxlite-' + version + '.tgz']: 'main package' }
+ for (const { os, target, rust_target } of JSON.parse(readFileSync(config)).platforms) {
+ for (const base of ['boxlite-runtime-' + tag + '-' + target, 'boxlite-cli-' + tag + '-' + rust_target]) {
+ runtime[base + '.tar.gz'] = base
+ runtime[base + '.tar.gz.sha256'] = hash(base)
+ }
+ packages['boxlite-ai-boxlite-' + target + '-' + version + '.tgz'] = target
+ group('c-sdk-' + target, { ['boxlite-c-' + tag + '-' + target + '.tar.gz']: target })
+ const wheel = target === 'linux-x64-gnu' ? linuxClients(tag)['wheels-ubuntu-latest'][0] : 'boxlite-' + version + '-cp312-' + target + '.whl'
+ group('wheels-' + os, { [wheel]: os })
+ }
+ group('node-packages', packages)
+ const runtimeDir = group('runtime-distribution', runtime)
+ const archive = 'boxlite-runner-' + tag + '-linux-amd64.tar.gz'
+ group('runner-linux-amd64', { [archive]: 'runner', [archive + '.sha256']: hash('runner') })
+ const pins = { manifest: hash('manifest'), archive: hash('runner') }
+ group('ghcr-runner', { 'runner.json': JSON.stringify(pins) })
+ group('ghcr-api', { 'image.json': JSON.stringify([{ artifact: 'api', digest: hash('api') }]) })
+ writeFileSync(join(dir, 'index.json'), JSON.stringify([{ artifacts: index }]))
+ writeFileSync(
+ join(dir, 'gh'),
+ `#!/bin/sh
+case "$*" in
+ *commits/refs%2Ftags%2F*) printf '{"sha":"%s"}\\n' "$SHA" ;;
+ *actions/runs/10/artifacts*) cat index.json ;;
+ *attempts/2/jobs*) cat jobs.json ;;
+ *releases/7/assets*) jq -s '[.]' uploads.jsonl ;;
+ *releases/7) printf '{"tag_name":"v1.2.3","draft":true}' ;;
+ 'release upload '*) name=$(basename "$4"); digest=$(shasum -a 256 "$4" | cut -d' ' -f1); jq -nc --arg name "$name" --arg digest "sha256:$digest" '{name:$name,digest:$digest,state:"uploaded"}' >>uploads.jsonl ;;
+ *) exit 2 ;;
+esac
+`,
+ { mode: 0o755 },
+ )
+ const stage = (output, mode = 'stage', extra = {}) =>
+ spawnSync(process.execPath, [command, mode], {
+ cwd: dir,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ PATH: dir + ':' + process.env.PATH,
+ GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
+ GITHUB_RUN_ATTEMPT: '2',
+ GITHUB_RUN_ID: '10',
+ TAG: tag,
+ SHA: sha,
+ IMAGES: '["api"]',
+ RELEASE_ASSET_DIR: output,
+ ...extra,
+ },
+ })
+ const early = stage('deploy', 'deployment')
+ assert.equal(early.status, 0, early.stderr)
+ const deploy = await verifyCandidate(join(dir, 'deploy'), { tag, sha, fingerprint: early.stdout.trim() })
+ assert.deepEqual(deploy.assets, {})
+ assert.deepEqual(deploy.runner, pins)
+ const result = stage('candidate')
+ assert.equal(result.status, 0, result.stderr)
+ const fingerprint = result.stdout.trim()
+ const receipt = await verifyCandidate(join(dir, 'candidate'), { tag, sha, fingerprint })
+ assert.deepEqual(receipt.runner, pins)
+ assert.deepEqual(receipt.images, { api: hash('api') })
+ assert.equal(receipt.producers['ghcr-api'].attempt, 1)
+ assert.equal(receipt.assets['install.sh.sha256'].group, 'runtime-distribution')
+ const runtimeNames = Object.keys(receipt.assets).filter(name => receipt.assets[name].group === 'runtime-distribution')
+ const conflict = { name: runtimeNames.at(-1), digest: hash('different release bytes'), state: 'uploaded' }
+ const existing = JSON.stringify(conflict) + '\n'
+ writeFileSync(join(dir, 'uploads.jsonl'), existing)
+ const rejected = stage('candidate', 'attach', { CANDIDATE_DIGEST: fingerprint, RELEASE_ID: '7', REPAIR_GROUP: 'runtime-distribution' })
+ assert.match(rejected.stderr, /Release already holds different bytes/)
+ assert.equal(readFileSync(join(dir, 'uploads.jsonl'), 'utf8'), existing, 'a conflicting attachment must block earlier missing uploads')
+ writeFileSync(join(dir, 'uploads.jsonl'), '')
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const attached = stage('candidate', 'attach', { CANDIDATE_DIGEST: fingerprint, RELEASE_ID: '7', REPAIR_GROUP: 'runtime-distribution' })
+ assert.equal(attached.status, 0, attached.stderr)
+ const names = readFileSync(join(dir, 'uploads.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line).name)
+ assert.deepEqual(names.sort(), Object.keys(runtime).sort(), 'Each runtime file, including install.sh.sha256, uploads exactly once across retries')
+ }
+ const e2e = join(dir, 'linux-clients')
+ const clients = {}
+ for (const [group, files] of Object.entries(linuxClients(tag))) {
+ const path = join(e2e, group)
+ mkdirSync(path, { recursive: true })
+ writeFileSync(join(path, 'producer.json'), JSON.stringify({ run: 10, attempt: 1, sha }))
+ for (const name of files) {
+ const bytes = readFileSync(join(dir, 'candidate', name))
+ writeFileSync(join(path, name), bytes)
+ clients[name] = hash(bytes)
+ }
+ }
+ const prepare = () => stage('deploy', 'clients', { CLIENT_ARTIFACT_DIR: e2e, CANDIDATE_DIGEST: early.stdout.trim() })
+ const prepared = prepare()
+ assert.equal(prepared.status, 0, prepared.stderr)
+ const tested = JSON.parse(readFileSync(join(dir, 'deploy', 'tested-clients.json')))
+ assert.deepEqual(tested, clients)
+ const full = receipt
+ const acceptance = { tag, sha, run: 10, clients: tested }
+ verifyAcceptedDistribution(full, acceptance, deploy)
+ const macWheel = 'boxlite-1.2.3-cp312-darwin-arm64.whl'
+ const macGroup = receipt.assets[macWheel].group
+ writeFileSync(join(dir, 'staged', macGroup, macWheel), 'rebuilt macOS wheel')
+ writeFileSync(join(dir, 'staged', macGroup, 'producer.json'), JSON.stringify({ run: 10, attempt: 2, sha }))
+ const rebuild = stage('rebuilt')
+ assert.equal(rebuild.status, 0, rebuild.stderr)
+ const changed = await verifyCandidate(join(dir, 'rebuilt'), { tag, sha, fingerprint: rebuild.stdout.trim() })
+ assert.notEqual(changed.assets[macWheel].digest, full.assets[macWheel].digest)
+ verifyAcceptedDistribution(changed, acceptance, deploy)
+ writeFileSync(join(dir, 'rebuilt', macWheel), 'changed after verification')
+ await assert.rejects(verifyCandidate(join(dir, 'rebuilt'), { tag, sha, fingerprint: rebuild.stdout.trim() }), /Changed release asset/)
+ const single = stage('wheels', 'component', { COMPONENT_GROUP: 'wheels-' })
+ assert.equal(single.status, 0, single.stderr)
+ const wheels = await verifyCandidate(join(dir, 'wheels'), { tag, sha, fingerprint: single.stdout.trim() })
+ assert.deepEqual(Object.keys(wheels.producers).sort(), index.map((entry) => entry.name).filter((name) => name.startsWith('wheels-')).sort())
+ assert.ok(Object.values(wheels.assets).every(({ group }) => group.startsWith('wheels-')))
+ assert.throws(() => verifyAcceptedDistribution(full, { ...acceptance, clients: {} }, deploy))
+ const file = Object.keys(tested)[0]
+ assert.throws(
+ () => verifyAcceptedDistribution(full, { ...acceptance, clients: { ...tested, [file]: hash('rebuilt') } }, deploy),
+ /differs from dev/,
+ )
+ assert.throws(() => verifyAcceptedDistribution(full, acceptance, { ...deploy, images: { api: hash('new image') } }))
+ writeFileSync(join(e2e, 'npm-linux-x64-gnu', 'producer.json'), JSON.stringify({ run: 11, attempt: 1, sha }))
+ assert.notEqual(prepare().status, 0)
+ for (const name of Object.keys(linuxClients(tag))) {
+ if (!index.some((item) => item.name === name)) index.push({ name, id: index.length + 1, expired: false })
+ }
+ writeFileSync(join(dir, 'index.json'), JSON.stringify([{ artifacts: index }]))
+ writeFileSync(
+ join(dir, 'jobs.json'),
+ JSON.stringify([{ jobs: [{ name: 'build-runtime / Build Runtime (darwin-arm64)', status: 'in_progress' }] }]),
+ )
+ const ready = stage('unused', 'client-ids')
+ assert.equal(ready.status, 0, ready.stderr)
+ assert.deepEqual(
+ ready.stdout.trim().split(',').map(Number),
+ Object.keys(linuxClients(tag)).map((name) => index.find((item) => item.name === name).id),
+ )
+ writeFileSync(
+ join(dir, 'jobs.json'),
+ JSON.stringify([
+ { jobs: [{ name: 'build-node / Build (linux-x64-gnu)', status: 'completed', conclusion: 'failure' }] },
+ ]),
+ )
+ assert.match(stage('unused', 'client-ids').stderr, /Linux client build failed/)
+ writeFileSync(join(dir, 'candidate', archive), 'different')
+ await assert.rejects(verifyCandidate(join(dir, 'candidate'), { tag, sha, fingerprint }), /Changed release asset/)
+ writeFileSync(join(runtimeDir, 'producer.json'), JSON.stringify({ run: 99, attempt: 1, sha }))
+ assert.notEqual(stage('wrong-run').status, 0)
+ writeFileSync(join(runtimeDir, 'producer.json'), JSON.stringify({ run: 10, attempt: 1, sha }))
+ rmSync(join(runtimeDir, 'install.sh.sha256'))
+ assert.match(stage('missing-sidecar').stderr, /Missing install.sh.sha256/)
+})
diff --git a/apps/infra/scripts/release-candidate.mjs b/apps/infra/scripts/release-candidate.mjs
new file mode 100644
index 000000000..d078e1b1c
--- /dev/null
+++ b/apps/infra/scripts/release-candidate.mjs
@@ -0,0 +1,341 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 BoxLite AI
+
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { createReadStream } from 'node:fs'
+import { copyFile, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+import { pathToFileURL } from 'node:url'
+
+const digestPattern = /^sha256:[a-f0-9]{64}$/
+const assetName = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,200}$/
+const metadata = 'release-candidate.json'
+const raw = 'staged'
+const bundle = process.env.RELEASE_ASSET_DIR || 'candidate'
+const readJson = async (path) => JSON.parse(await readFile(path, 'utf8'))
+
+export async function fileDigest(path) {
+ const hash = createHash('sha256')
+ for await (const chunk of createReadStream(path)) hash.update(chunk)
+ return 'sha256:' + hash.digest('hex')
+}
+function numberId(value) {
+ assert.ok(Number.isSafeInteger(Number(value)) && Number(value) > 0, 'Invalid GitHub ID or run attempt')
+ return Number(value)
+}
+function gh(...args) {
+ return execFileSync('gh', args, { encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 })
+}
+function api(path) {
+ return JSON.parse(gh('api', 'repos/' + process.env.GITHUB_REPOSITORY + '/' + path))
+}
+async function tagIdentity(tag, sha) {
+ assert.match(tag, /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)
+ assert.match(sha, /^[a-f0-9]{40}$/)
+ assert.equal(api('commits/refs%2Ftags%2F' + tag).sha, sha, 'Release tag moved')
+}
+function artifactIndex(runId) {
+ const pages = JSON.parse(
+ gh(
+ 'api',
+ '--paginate',
+ '--slurp',
+ 'repos/' + process.env.GITHUB_REPOSITORY + '/actions/runs/' + numberId(runId) + '/artifacts?per_page=100',
+ ),
+ )
+ return new Map(
+ pages
+ .flatMap((page) => page.artifacts)
+ .filter((item) => !item.expired)
+ .map((item) => [item.name, item.id]),
+ )
+}
+function cArchiveName(tag, target) {
+ return 'boxlite-c-' + tag + '-' + target + '.tar.gz'
+}
+async function archiveSources(tag, platforms) {
+ const version = tag.slice(1)
+ const names = new Map()
+ const required = (group, files) => names.set(group, { required: files, accepts: (name) => files.includes(name) })
+ const runtimes = ['install.sh', 'install.sh.sha256', 'SHA256SUMS']
+ const packages = ['boxlite-ai-boxlite-' + version + '.tgz']
+ for (const { target, rust_target, os } of platforms) {
+ const runtime = 'boxlite-runtime-' + tag + '-' + target + '.tar.gz'
+ const cli = 'boxlite-cli-' + tag + '-' + rust_target + '.tar.gz'
+ runtimes.push(runtime, runtime + '.sha256', cli, cli + '.sha256')
+ packages.push('boxlite-ai-boxlite-' + target + '-' + version + '.tgz')
+ required('c-sdk-' + target, [cArchiveName(tag, target)])
+ names.set('wheels-' + os, {
+ required: [],
+ accepts: (name) => name.startsWith('boxlite-' + version + '-') && name.endsWith('.whl'),
+ })
+ }
+ required('runtime-distribution', runtimes)
+ required('node-packages', packages)
+ const runner = 'boxlite-runner-' + tag + '-linux-amd64.tar.gz'
+ required('runner-linux-amd64', [runner, runner + '.sha256'])
+ return names
+}
+function verifyOrigin(source, sha, run, attempt) {
+ assert.equal(source.sha, sha)
+ assert.equal(source.run, run)
+ assert.ok(numberId(source.attempt) <= attempt)
+}
+
+export function linuxClients(tag) {
+ const version = tag.slice(1)
+ return {
+ 'cli-linux-x64-gnu': ['boxlite-cli-' + tag + '-x86_64-unknown-linux-gnu.tar.gz'],
+ 'c-sdk-linux-x64-gnu': ['boxlite-c-' + tag + '-linux-x64-gnu.tar.gz'],
+ 'wheels-ubuntu-latest': ['boxlite-' + version + '-cp312-cp312-manylinux_2_28_x86_64.whl'],
+ 'npm-linux-x64-gnu': [
+ 'boxlite-ai-boxlite-' + version + '.tgz',
+ 'boxlite-ai-boxlite-linux-x64-gnu-' + version + '.tgz',
+ ],
+ }
+}
+
+// A run can be retried with a mix of reused and rebuilt jobs. Compare the actual
+// accepted client bytes and deployment pins before certifying the complete distribution.
+export function verifyAcceptedDistribution(candidate, acceptance, pins) {
+ for (const key of ['tag', 'sha', 'run']) assert.equal(candidate[key], acceptance[key])
+ for (const key of ['tag', 'sha', 'images', 'runner']) assert.deepEqual(candidate[key], pins[key])
+ for (const name of Object.values(linuxClients(candidate.tag)).flat()) {
+ assert.match(acceptance.clients[name], digestPattern)
+ assert.equal(candidate.assets[name]?.digest, acceptance.clients[name], 'Release differs from dev E2E: ' + name)
+ }
+}
+
+async function clientArtifactIds(tag) {
+ const groups = Object.keys(linuxClients(tag))
+ const run = numberId(process.env.GITHUB_RUN_ID)
+ const attempt = numberId(process.env.GITHUB_RUN_ATTEMPT)
+ const deadline = Date.now() + 120 * 60_000
+ const producers = ['Build Runtime (linux-x64-gnu)', 'Build (linux-x64-gnu)', 'Build wheels on ubuntu-latest']
+ while (Date.now() < deadline) {
+ const jobs = JSON.parse(
+ gh(
+ 'api',
+ '--paginate',
+ '--slurp',
+ 'repos/' +
+ process.env.GITHUB_REPOSITORY +
+ '/actions/runs/' +
+ run +
+ '/attempts/' +
+ attempt +
+ '/jobs?per_page=100',
+ ),
+ ).flatMap((page) => page.jobs)
+ const index = artifactIndex(run)
+ const missing = groups.filter((group) => !index.has(group))
+ const linuxJobs = jobs.filter((job) => producers.some((name) => job.name.endsWith(' / ' + name)))
+ const failed = linuxJobs.find((job) => ['failure', 'cancelled', 'timed_out'].includes(job.conclusion))
+ assert.ok(!failed, 'Linux client build failed: ' + failed?.name)
+ if (!missing.length && !linuxJobs.some((job) => job.status !== 'completed'))
+ return groups.map((group) => numberId(index.get(group))).join(',')
+ console.error('Waiting for Linux release clients: ' + (missing.join(', ') || 'producer completion'))
+ await delay(30_000)
+ }
+ throw new Error('Timed out waiting for Linux client artifacts from this run')
+}
+
+async function prepareClients(candidate, directory) {
+ const files = linuxClients(candidate.tag)
+ const clients = {}
+ for (const [group, names] of Object.entries(files)) {
+ const source = join(directory, group)
+ verifyOrigin(
+ await readJson(join(source, 'producer.json')),
+ candidate.sha,
+ candidate.run,
+ numberId(process.env.GITHUB_RUN_ATTEMPT),
+ )
+ for (const name of names) {
+ await copyFile(join(source, name), join(bundle, name))
+ clients[name] = await fileDigest(join(bundle, name))
+ }
+ }
+ const [cli] = files['cli-linux-x64-gnu']
+ await writeFile(join(bundle, cli + '.sha256'), clients[cli].slice(7) + ' ' + cli + '\n')
+ await writeFile(join(bundle, 'tested-clients.json'), JSON.stringify(clients))
+}
+
+async function stage(mode, component) {
+ const { TAG: tag, SHA: sha, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT } = process.env
+ await tagIdentity(tag, sha)
+ const run = numberId(GITHUB_RUN_ID)
+ const attempt = numberId(GITHUB_RUN_ATTEMPT)
+ const index = artifactIndex(run)
+ const deploymentOnly = mode === 'deployment'
+ const groups = deploymentOnly ? [] : await archiveSources(tag, (await readJson('.github/ci-config.json')).platforms)
+ const assets = {}
+ const producers = {}
+ async function origin(group) {
+ const dir = join(raw, group)
+ const source = await readJson(join(dir, 'producer.json'))
+ verifyOrigin(source, sha, run, attempt)
+ producers[group] = { id: numberId(index.get(group)), attempt: source.attempt }
+ return dir
+ }
+ await mkdir(bundle)
+ for (const [group, contract] of groups) {
+ if (component && !group.startsWith(component)) continue
+ const dir = await origin(group)
+ const files = (await readdir(dir, { withFileTypes: true })).filter(({ name }) => name !== 'producer.json')
+ assert.ok(files.length, 'Empty artifact ' + group)
+ for (const name of contract.required)
+ assert.ok(
+ files.some((item) => item.name === name),
+ 'Missing ' + name,
+ )
+ for (const item of files) {
+ const name = item.name
+ assert.ok(
+ item.isFile() && assetName.test(name) && contract.accepts(name) && !Object.hasOwn(assets, name),
+ 'Unexpected asset ' + name,
+ )
+ const path = join(dir, name)
+ assert.ok((await stat(path)).size > 0, 'Empty file ' + name)
+ assets[name] = { digest: await fileDigest(path), group }
+ await copyFile(path, join(bundle, name))
+ }
+ }
+ const candidate = { tag, sha, run, attempt, producers, assets }
+ if (mode === 'component' && component !== 'runner-linux-amd64') {
+ assert.ok(Object.keys(assets).length, 'No files for selected component')
+ } else {
+ const images = {}
+ const expectedImages = JSON.parse(process.env.IMAGES)
+ for (const image of expectedImages) {
+ assert.match(image, /^[a-z][a-z0-9-]*$/)
+ const dir = await origin('ghcr-' + image)
+ const [entry] = await readJson(join(dir, 'image.json'))
+ assert.equal(entry.artifact, image)
+ assert.match(entry.digest, digestPattern)
+ images[image] = entry.digest
+ }
+ const runner = await readJson(join(await origin('ghcr-runner'), 'runner.json'))
+ assert.match(runner.manifest, digestPattern)
+ assert.match(runner.archive, digestPattern)
+ if (!deploymentOnly) assert.equal(runner.archive, assets['boxlite-runner-' + tag + '-linux-amd64.tar.gz'].digest)
+ Object.assign(candidate, { images, runner })
+ }
+ await writeFile(join(bundle, metadata), JSON.stringify(candidate, null, 2) + '\n')
+ return candidate
+}
+export async function verifyCandidate(directory, { tag, sha, fingerprint }) {
+ const path = join(directory, metadata)
+ assert.match(fingerprint, digestPattern)
+ assert.equal(await fileDigest(path), fingerprint, 'Unrecognized release candidate')
+ const candidate = await readJson(path)
+ assert.equal(candidate.tag, tag)
+ assert.equal(candidate.sha, sha)
+ for (const [name, { digest }] of Object.entries(candidate.assets)) {
+ assert.ok(assetName.test(name))
+ assert.equal(await fileDigest(join(directory, name)), digest, 'Changed release asset ' + name)
+ }
+ return candidate
+}
+function releaseAssets(releaseId) {
+ return JSON.parse(
+ gh(
+ 'api',
+ '--paginate',
+ '--slurp',
+ 'repos/' + process.env.GITHUB_REPOSITORY + '/releases/' + numberId(releaseId) + '/assets?per_page=100',
+ ),
+ ).flat()
+}
+async function verifyPublicCArchives(tag, releaseId) {
+ const release = api('releases/' + numberId(releaseId))
+ assert.equal(release.tag_name, tag, 'Unexpected product release')
+ assert.equal(release.draft, false, 'Publish the GitHub Release before tagging the Go module')
+ const assets = new Map(releaseAssets(releaseId).map(asset => [asset.name, asset]))
+ const { platforms } = await readJson('.github/ci-config.json')
+ assert.ok(platforms.length, 'The C SDK platform matrix is empty')
+ for (const { target } of platforms) {
+ const name = cArchiveName(tag, target)
+ const asset = assets.get(name)
+ assert.ok(asset?.state === 'uploaded' && asset.size > 0, 'Missing public C SDK archive: ' + name)
+ const url = 'https://github.com/' + process.env.GITHUB_REPOSITORY + '/releases/download/' + tag + '/' + name
+ const response = await fetch(url, { signal: AbortSignal.timeout(300_000) })
+ assert.equal(response.status, 200, 'Anonymous C SDK download failed: ' + name)
+ const hash = createHash('sha256')
+ for await (const chunk of response.body) hash.update(chunk)
+ assert.equal('sha256:' + hash.digest('hex'), asset.digest, 'Public C SDK digest mismatch: ' + name)
+ }
+}
+async function publishFiles(candidate, id, scope, finalize = false) {
+ const release = api('releases/' + numberId(id))
+ assert.equal(release.tag_name, candidate.tag)
+ if (!scope && !finalize) assert.equal(release.draft, true, 'Release must be a draft during normal asset publication')
+ const files = Object.fromEntries(
+ Object.entries(candidate.assets).filter(([, { group }]) => !scope || group.startsWith(scope)),
+ )
+ assert.ok(Object.keys(files).length, 'No files for requested component')
+ if (!scope) files[metadata] = { digest: await fileDigest(join(bundle, metadata)) }
+ const uploadedAssets = () => new Map(releaseAssets(id).map((entry) => [entry.name, entry]))
+ if (!finalize) {
+ const existing = uploadedAssets()
+ const missing = []
+ for (const [name, { digest }] of Object.entries(files)) {
+ if (existing.has(name))
+ assert.equal(existing.get(name).digest, digest, 'Release already holds different bytes for ' + name)
+ else missing.push(name)
+ }
+ for (const name of missing)
+ gh('release', 'upload', candidate.tag, join(bundle, name), '--repo', process.env.GITHUB_REPOSITORY)
+ }
+ const uploaded = uploadedAssets()
+ for (const [name, { digest }] of Object.entries(files)) {
+ assert.equal(uploaded.get(name)?.state, 'uploaded', 'Incomplete upload ' + name)
+ assert.equal(uploaded.get(name)?.digest, digest, 'Uploaded asset differs from candidate: ' + name)
+ }
+ if (finalize && release.draft)
+ gh(
+ 'api',
+ '--method',
+ 'PATCH',
+ 'repos/' + process.env.GITHUB_REPOSITORY + '/releases/' + numberId(id),
+ '-F',
+ 'draft=false',
+ '-F',
+ 'prerelease=false',
+ )
+}
+async function main(command) {
+ const { TAG: tag, SHA: sha, CANDIDATE_DIGEST: fingerprint, RELEASE_ID } = process.env
+ if (command === 'verify-public-c') return verifyPublicCArchives(tag, RELEASE_ID)
+ if (command === 'client-ids') {
+ await tagIdentity(tag, sha)
+ console.log(await clientArtifactIds(tag))
+ return
+ }
+ if (['stage', 'deployment', 'component'].includes(command)) {
+ const group = command === 'component' ? process.env.COMPONENT_GROUP : ''
+ if (command === 'component')
+ assert.ok(['runtime-distribution', 'wheels-', 'node-packages', 'c-sdk-', 'runner-linux-amd64'].includes(group), 'Unknown component group')
+ await stage(command, group)
+ console.log(await fileDigest(join(bundle, metadata)))
+ return
+ }
+ const candidate = await verifyCandidate(bundle, { tag, sha, fingerprint })
+ if (command === 'verify') return
+ if (command === 'clients') return prepareClients(candidate, process.env.CLIENT_ARTIFACT_DIR)
+ if (command === 'check-acceptance') {
+ const acceptance = await readJson(process.env.ACCEPTANCE_FILE)
+ assert.equal(acceptance.digest, process.env.DEPLOYMENT_DIGEST)
+ assert.equal(acceptance.candidate, numberId(process.env.DEPLOYMENT_ID))
+ assert.equal(acceptance.attempt, numberId(process.env.ACCEPTED_ATTEMPT))
+ return verifyAcceptedDistribution(candidate, acceptance, JSON.parse(process.env.DEPLOYMENT_PINS))
+ }
+ await tagIdentity(tag, sha)
+ if (command === 'attach') return publishFiles(candidate, RELEASE_ID, process.env.REPAIR_GROUP)
+ if (command === 'finalize') return publishFiles(candidate, RELEASE_ID, undefined, true)
+ throw new Error('Unknown release candidate operation ' + command)
+}
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main(process.argv[2])
diff --git a/apps/infra/scripts/release-pipeline.mjs b/apps/infra/scripts/release-pipeline.mjs
index 51a5187de..d356059a2 100644
--- a/apps/infra/scripts/release-pipeline.mjs
+++ b/apps/infra/scripts/release-pipeline.mjs
@@ -9,18 +9,10 @@ import { fileURLToPath } from 'node:url'
const VERSION = /^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/
const HOUR = 60 * 60 * 1000
const clock = { now: Date.now, wait: sleep }
-const output = (name, value) => {
- if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, name + '=' + value + '\n')
-}
const id = (value) => {
if (!Number.isSafeInteger(value) || value < 1) throw new Error('GitHub returned an invalid run or release ID')
return value
}
-const timestamp = (value) => {
- const time = typeof value === 'string' ? Date.parse(value) : NaN
- if (!Number.isFinite(time)) throw new Error('GitHub returned unavailable workflow attempt timing')
- return time
-}
const repository = (value) => {
if (
!/^[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+$/.test(value) ||
@@ -68,68 +60,40 @@ export const slackWebhook = (value) => {
return url.href
}
-async function githubRequest(repo, token, request, path, body) {
- const method = body === undefined ? 'GET' : 'POST'
- let response
- try {
- response = await request('https://api.github.com/repos/' + repo + path, {
- method,
- headers: {
- Authorization: 'Bearer ' + token,
- Accept: 'application/vnd.github+json',
- 'Content-Type': 'application/json',
- 'X-GitHub-Api-Version': '2026-03-10',
- },
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
- redirect: 'error',
- signal: AbortSignal.timeout(30_000),
- })
- } catch {
- throw new Error(
- method === 'POST' ? 'Dispatch outcome unknown; inspect GitHub before retrying' : 'GitHub read failed',
- )
- }
- if (!response.ok) {
- throw new Error(
- 'GitHub ' +
- method +
- ' failed: HTTP ' +
- response.status +
- (method === 'POST' && response.status >= 500 ? '; dispatch outcome unknown, inspect before retrying' : ''),
- )
- }
- try {
- const result = await response.json()
- if (result === null || typeof result !== 'object') throw new Error('Invalid JSON document')
- return result
- } catch {
- throw new Error(
- method === 'POST'
- ? 'Dispatch outcome unknown: no readable run ID; inspect before retrying'
- : 'Malformed GitHub JSON response',
- )
- }
+async function githubRequest(repo, token, request, path) {
+ const response = await request('https://api.github.com/repos/' + repo + path, {
+ method: 'GET',
+ headers: {
+ Authorization: 'Bearer ' + token,
+ Accept: 'application/vnd.github+json',
+ 'X-GitHub-Api-Version': '2026-03-10',
+ },
+ redirect: 'error',
+ signal: AbortSignal.timeout(30_000),
+ }).catch(() => {
+ throw new Error('GitHub read failed: ' + path)
+ })
+ if (!response.ok) throw new Error('GitHub GET ' + path + ' failed: HTTP ' + response.status)
+ const result = await response.json().catch(() => null)
+ if (result === null || typeof result !== 'object') throw new Error('Malformed GitHub JSON response')
+ return result
}
export class ReleasePipeline {
#repo
#requiredAssets
#tag
- #sha
#api
#timer
- #record
#log
- constructor({ repo, tag, sha, token, request = fetch, timer = clock, record = output, log = console.log }) {
+ constructor({ repo, tag, token, request = fetch, timer = clock, log = console.log }) {
this.#repo = repository(repo)
this.#requiredAssets = releaseAssets(tag)
if (!token) throw new Error('GH_TOKEN is required')
this.#tag = tag
- this.#sha = sha
- this.#api = (path, body) => githubRequest(this.#repo, token, request, path, body)
+ this.#api = (path) => githubRequest(this.#repo, token, request, path)
this.#timer = timer
- this.#record = record
this.#log = log
}
@@ -173,208 +137,59 @@ export class ReleasePipeline {
() => 'release assets: ' + missing.join(', '),
)
}
-
- async #assertTag() {
- if (!/^[0-9a-f]{40}$/.test(this.#sha ?? ''))
- throw new Error('The publisher must supply its resolved release commit')
- const commit = await this.#api('/commits/' + encodeURIComponent('refs/tags/' + this.#tag))
- if (commit.sha !== this.#sha) throw new Error('Release tag moved after publication; refusing downstream dispatch')
- }
-
- async #dispatch(workflow, inputs, name) {
- await this.#assertTag()
- const result = await this.#api('/actions/workflows/' + workflow + '/dispatches', { ref: 'main', inputs })
- let runId
- try {
- runId = id(result?.workflow_run_id)
- } catch {
- throw new Error('Dispatch outcome unknown: no valid run ID; inspect GitHub before retrying')
- }
- this.#record(name + '_run_id', runId)
- this.#log(name + ': https://github.com/' + this.#repo + '/actions/runs/' + runId)
- return runId
- }
-
- async #completed(runId, name, timeout) {
- return this.#poll(
- async () => {
- const run = await this.#api('/actions/runs/' + runId)
- if (run.id !== runId || typeof run.status !== 'string')
- throw new Error('GitHub returned an unexpected workflow run')
- if (run.status !== 'completed') return undefined
- const conclusion = /^[a-z_]+$/.test(run.conclusion ?? '') ? run.conclusion : 'unknown'
- this.#record(name + '_result', conclusion)
- if (conclusion !== 'success') throw new Error(name + ' run ' + runId + ' ended with ' + conclusion)
- return run
- },
- timeout,
- () => name + ' run ' + runId,
- )
- }
-
- async #undisturbed(dev, e2e) {
- const start = timestamp(dev.updated_at)
- const end = timestamp(e2e.updated_at)
- if (end < start) throw new Error('GitHub returned an invalid validation interval')
- if (!Number.isSafeInteger(dev.run_attempt) || dev.run_attempt < 1 || dev.run_attempt > 50) {
- throw new Error('Deployment attempt history cannot be verified')
- }
- const check = (run) => {
- const started = timestamp(run.run_started_at)
- const updated = timestamp(run.updated_at)
- if (started > end || (run.status === 'completed' && updated < start)) return
- throw new Error('Dev validation overlapped another or unidentified apply: run ' + run.id)
- }
- // Inspect attempts, including failed/cancelled applies and reruns of old run IDs.
- for (let page = 1; page <= 5; page++) {
- const result = await this.#api(
- '/actions/workflows/mdeploy-all.yml/runs?event=workflow_dispatch&per_page=100&page=' + page,
- )
- if (!Array.isArray(result.workflow_runs)) throw new Error('Malformed deployment history')
- for (const run of result.workflow_runs) {
- const ownRun = id(run.id) === dev.id
- if (ownRun && run.run_attempt === dev.run_attempt) continue
- if (/^preview (dev|stage|prod) ·/.test(run.display_title) || /^deploy (stage|prod) ·/.test(run.display_title))
- continue
- if (timestamp(run.created_at) > end || (run.status === 'completed' && timestamp(run.updated_at) < start))
- continue
- if (!Number.isSafeInteger(run.run_attempt) || run.run_attempt < 1 || run.run_attempt > 50) {
- throw new Error('Deployment attempt history cannot be verified')
- }
- if (run.run_attempt === 1) check(run)
- else
- for (let attempt = 1; attempt <= run.run_attempt; attempt++) {
- if (ownRun && attempt === dev.run_attempt) continue
- check(await this.#api('/actions/runs/' + run.id + '/attempts/' + attempt))
- }
- }
- if (result.workflow_runs.length < 100) return
- }
- throw new Error('Deployment history was truncated; refusing a prod request')
- }
-
- async run(notifyDev) {
- const inputs = { stage: 'dev', components: 'api+runner', ref: this.#tag, apply: true, confirm: true }
- this.#record('phase', 'dev_dispatch')
- const devId = await this.#dispatch('mdeploy-all.yml', inputs, 'dev')
- this.#record('phase', 'dev_wait')
- if (notifyDev) {
- try {
- await notifyDev(devId)
- } catch {
- this.#log(
- '::warning::Dev approval notice failed. Follow https://github.com/' + this.#repo + '/actions/runs/' + devId,
- )
- }
- }
- const dev = await this.#completed(devId, 'dev', 3 * HOUR)
- this.#record('phase', 'e2e_dispatch')
- const e2eId = await this.#dispatch('e2e-cloud.yml', { stage: 'dev', tag: this.#tag }, 'e2e')
- this.#record('phase', 'e2e_wait')
- const e2e = await this.#completed(e2eId, 'e2e', HOUR)
- this.#record('phase', 'history')
- await this.#undisturbed(dev, e2e)
- this.#record('phase', 'prod_reviewers')
- const environment = await this.#api('/environments/prod')
- if (
- !Array.isArray(environment.protection_rules) ||
- !environment.protection_rules.some(
- (rule) => rule.type === 'required_reviewers' && Array.isArray(rule.reviewers) && rule.reviewers.length > 0,
- )
- ) {
- throw new Error('Prod must have required Environment reviewers before a prod run can be created')
- }
- // Creation fixes inputs; GitHub Environment approval remains a separate human action.
- this.#record('phase', 'prod_dispatch')
- await this.#dispatch('mdeploy-all.yml', { ...inputs, stage: 'prod' }, 'prod')
- }
}
-const reviewButton = (repo, runId, environment) => ({
+const runButton = (repo, runId, label) => ({
type: 'actions',
elements: [
{
type: 'button',
style: 'primary',
- text: { type: 'plain_text', text: 'Review ' + environment + ' deployment' },
+ text: { type: 'plain_text', text: label },
url: 'https://github.com/' + repository(repo) + '/actions/runs/' + id(Number(runId)),
},
],
})
-const releasePhases = {
- dev_dispatch: ['dev', 'Dev deployment dispatch'],
- dev_wait: ['dev', 'Dev deployment'],
- e2e_dispatch: ['dev', 'E2E dispatch'],
- e2e_wait: ['dev', 'E2E cloud'],
- history: ['dev', 'Dev validation history'],
- prod_reviewers: ['prod', 'Prod reviewer verification'],
- prod_dispatch: ['prod', 'Prod deployment dispatch'],
-}
-
-const stoppedPhase = (results) => {
- for (const [job, label] of [
- ['resolve', 'Release ref resolution'],
- ['publish', 'Image publication'],
- ['assets', 'Release assets'],
- ]) {
- if (results[job]?.result && results[job].result !== 'success') return ['Pre-deployment', label]
- }
- return (
- releasePhases[results.pipeline?.outputs?.phase] ?? ['Release', 'Release orchestration (last phase unavailable)']
- )
-}
-
export const releaseReport = ({ repo, tag, runId, results }) => {
- repository(repo)
- const source = 'https://github.com/' + repo
- const pipeline = results.pipeline ?? {}
- const outputs = pipeline.outputs ?? {}
- const link = (value, label) =>
- /^[1-9][0-9]*$/.test(String(value ?? '')) ? '<' + source + '/actions/runs/' + value + '|' + label + '>' : label
- const success = pipeline.result === 'success' && /^[1-9][0-9]*$/.test(outputs.prod_run_id ?? '')
const release = VERSION.test(tag) ? tag : '(invalid release tag)'
- const [environment, phase] = success ? ['prod', 'Prod deployment approval'] : stoppedPhase(results)
- const interrupted = Object.values(results).some((job) => job.result === 'cancelled')
- const outcome = interrupted ? 'interrupted' : 'failed'
- const title = success
- ? release + ': dev verified; prod review requested'
- : release + ': release pipeline ' + outcome + ' at ' + phase
const rows = [
- ['Publication', results.publish?.result ?? 'not started'],
- ['Release assets', results.assets?.result ?? 'not started'],
- ['Dev deployment', link(outputs.dev_run_id, outputs.dev_result ?? 'not completed')],
- ['E2E cloud', link(outputs.e2e_run_id, outputs.e2e_result ?? 'not completed')],
- ['Validation / prod request', pipeline.result ?? 'not started'],
- ]
+ ['Release ref', results.resolve?.result],
+ ...Object.entries(results).filter(([job]) => job.startsWith('build-')).map(([job, outcome]) => [job, outcome.result]),
+ ['Image publication', results.publish?.result],
+ ...(results['publish-runner'] ? [['Runner publication', results['publish-runner'].result]] : []),
+ ['Release assets', results.distribution?.result],
+ ].map(([label, result]) => [label, result ?? 'not started'])
+ if (results.dev && results.dev.result !== 'skipped') {
+ const e2e = results.dev.outputs?.e2e_result
+ if (!e2e || e2e === 'skipped') rows.push(['Dev deployment and acceptance', results.dev.result])
+ if (e2e) rows.push(['E2E cloud', e2e])
+ }
+ for (const [job, label] of Object.entries({
+ attach: 'Draft attachments', pypi: 'PyPI', npm: 'npm', 'tag-go-module': 'Go module tag',
+ finalize: 'GitHub Release', publish_crates: 'crates.io',
+ })) {
+ if (results[job]) rows.push([label, results[job].result])
+ }
+ const stopped = rows.find(([, result]) => ['failure', 'cancelled'].includes(result)) ??
+ rows.find(([, result]) => result !== 'success')
+ const phase = stopped?.[0] ?? 'Release'
+ const title = release + ': ' + phase + ' — ' + (stopped?.[1] ?? 'stopped')
const blocks = [
{ type: 'header', text: { type: 'plain_text', text: title } },
- { type: 'section', fields: rows.map(([name, value]) => ({ type: 'mrkdwn', text: '*' + name + '*\n' + value })) },
- { type: 'section', text: { type: 'mrkdwn', text: link(runId, 'Release pipeline logs') } },
- ]
- if (success) {
- blocks.push({
+ ...Array.from({ length: Math.ceil(rows.length / 10) }, (_, i) => ({
type: 'section',
- text: {
- type: 'mrkdwn',
- text:
- 'Prod inputs: stage=prod, ref=' +
- release +
- ', components=api+runner, apply=true, confirm=true. Review and approve in GitHub.',
- },
- })
- blocks.push(reviewButton(repo, outputs.prod_run_id, 'prod'))
- }
+ fields: rows.slice(i * 10, i * 10 + 10).map(([key, value]) => ({ type: 'plain_text', text: key + '\n' + value })),
+ })),
+ runButton(repo, runId, 'View run logs'),
+ ]
const summary =
'## ' +
title +
'\n\n| Stage | Result |\n| --- | --- |\n' +
- rows
- .map(([name, value]) => '| ' + name + ' | ' + value.replace(/<([^>|]+)\|([^>]+)>/g, '[$2]($1)') + ' |')
- .join('\n') +
- '\n' +
- (success ? '\nProd run: ' + source + '/actions/runs/' + outputs.prod_run_id + '\n' : '')
- return { payload: { text: title, blocks }, summary, environment, phase }
+ rows.map(([key, value]) => '| ' + key + ' | ' + value + ' |').join('\n') +
+ '\n'
+ return { payload: { text: title, blocks }, summary, environment: 'dev', phase }
}
export const sendSlack = async (webhook, payload, request = fetch) => {
@@ -429,7 +244,7 @@ function notifyApproval(runId, environment, phase, title) {
text: title,
blocks: [
{ type: 'header', text: { type: 'plain_text', text: title } },
- reviewButton(process.env.GITHUB_REPOSITORY, runId, environment),
+ runButton(process.env.GITHUB_REPOSITORY, runId, 'Review ' + environment + ' deployment'),
],
},
})
@@ -446,29 +261,45 @@ if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1
})
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, report.summary)
await sendRunSlack(report)
+ } else if (process.argv[2] === 'result') {
+ const {
+ DEPLOY_ENVIRONMENT: environment,
+ DEPLOY_RESULT: result,
+ DEPLOY_REF: ref,
+ GITHUB_REPOSITORY: repo,
+ GITHUB_RUN_ID: runId,
+ } = process.env
+ const title = environment + ' deployment: ' + result
+ await sendRunSlack({
+ environment,
+ phase: 'Deployment result',
+ payload: {
+ text: title,
+ blocks: [
+ { type: 'header', text: { type: 'plain_text', text: title } },
+ { type: 'section', text: { type: 'plain_text', text: 'Ref: ' + ref } },
+ runButton(repo, runId, result === 'failure' ? 'View run logs' : 'View deployment run'),
+ ],
+ },
+ })
} else if (process.argv[2] === 'approval') {
- const { DEPLOY_ENVIRONMENT, APPROVAL_PHASE, GITHUB_RUN_ID } = process.env
+ const { DEPLOY_ENVIRONMENT, APPROVAL_PHASE, GITHUB_RUN_ID, ACCEPTED_TAG } = process.env
+ const title = ACCEPTED_TAG
+ ? ACCEPTED_TAG + ': dev E2E passed · review prod deployment'
+ : 'Deployment review requested'
try {
- await notifyApproval(GITHUB_RUN_ID, DEPLOY_ENVIRONMENT, APPROVAL_PHASE, 'Deployment review requested')
+ await notifyApproval(GITHUB_RUN_ID, DEPLOY_ENVIRONMENT, APPROVAL_PHASE, title)
} catch {
console.warn('::warning::Deployment approval notice failed. Review this run in GitHub.')
}
- } else {
- const pipeline = new ReleasePipeline({
+ } else if (process.argv[2] === 'assets') {
+ if (process.env.SLACK_WEBHOOK_URL) slackWebhook(process.env.SLACK_WEBHOOK_URL)
+ await new ReleasePipeline({
repo: process.env.GITHUB_REPOSITORY,
tag: process.env.TAG,
- sha: process.env.RELEASE_SHA,
token: process.env.GH_TOKEN,
- })
- if (process.argv[2] === 'assets') {
- if (process.env.SLACK_WEBHOOK_URL) slackWebhook(process.env.SLACK_WEBHOOK_URL)
- await pipeline.waitForAssets()
- } else if (process.argv[2] === 'run') {
- await pipeline.run((devId) =>
- notifyApproval(devId, 'dev', 'Dev deployment approval', process.env.TAG + ': dev deployment dispatched'),
- )
- } else throw new Error('Expected assets, run, report, or approval')
- }
+ }).waitForAssets()
+ } else throw new Error('Expected assets, approval, result or report')
} catch (error) {
console.error(error instanceof Error ? error.message : 'Release pipeline failed')
process.exitCode = 1
diff --git a/apps/infra/scripts/release-pipeline.test.mjs b/apps/infra/scripts/release-pipeline.test.mjs
index d4c865d8c..a868decfe 100644
--- a/apps/infra/scripts/release-pipeline.test.mjs
+++ b/apps/infra/scripts/release-pipeline.test.mjs
@@ -13,38 +13,17 @@ const snapshot = JSON.parse(readFileSync(new URL('./fixtures/release-v0.13.1-ass
const repo = 'boxlite-ai/boxlite'
const displayTitle = 'deploy dev · <@requested_by> · <!channel> & review'
const tag = snapshot.tag_name
-const sha = '6c5855a654beb3ba952faceb9665b5c563770859'
const webhook = 'https://hooks.slack.com/services/Tfixture/Bfixture/private-fixture-token'
const root = new URL('../../../', import.meta.url)
-const workflow = load(readFileSync(new URL('.github/workflows/mbuild-release.yml', root), 'utf8'))
const e2eWorkflow = load(readFileSync(new URL('.github/workflows/e2e-cloud.yml', root), 'utf8'))
-const run = (runId, values = {}) => ({
- id: runId,
- run_attempt: 1,
- status: 'completed',
- conclusion: 'success',
- display_title: 'deploy dev · ' + tag + ' · api+runner',
- created_at: '2026-11-17T07:00:00Z',
- run_started_at: '2026-11-17T07:00:00Z',
- updated_at: '2026-11-17T07:10:00Z',
- ...values,
-})
const json = (value, status = 200) => new Response(JSON.stringify(value), { status })
const harness = (options = {}) => {
const calls = [],
- records = {},
logs = [],
waits = []
let now = 0,
assetReads = 0
- const dev = run(101, options.dev)
- const e2e = run(202, {
- created_at: '2026-11-17T07:11:00Z',
- run_started_at: '2026-11-17T07:11:00Z',
- updated_at: '2026-11-17T07:20:00Z',
- ...options.e2e,
- })
const request = async (url, init) => {
const req = new Request(url, init)
const path = new URL(req.url).pathname + new URL(req.url).search
@@ -58,36 +37,13 @@ const harness = (options = {}) => {
calls.push(call)
const overridden = options.respond?.(call)
if (overridden) return overridden
- if (path.includes('/commits/')) return json({ sha: options.sha ?? sha })
if (path.includes('/releases/tags/')) return json(snapshot)
if (path.includes('/assets?')) return json(options.assets?.(++assetReads, path) ?? snapshot.assets)
- if (req.method === 'POST' && path.endsWith('/dispatches')) {
- return json({ workflow_run_id: path.includes('e2e-cloud') ? 202 : call.body.inputs.stage === 'prod' ? 303 : 101 })
- }
- if (path.endsWith('/actions/runs/101')) return json(options.devRead?.() ?? dev)
- if (path.endsWith('/actions/runs/202')) return json(e2e)
- if (path.includes('/attempts/')) {
- const attempt = Number(path.split('/').at(-1))
- return json(options.attempts?.[attempt])
- }
- if (path.includes('/mdeploy-all.yml/runs?')) {
- const page = Number(new URL(req.url).searchParams.get('page'))
- return json({ workflow_runs: options.history?.(page) ?? [dev, ...(options.others ?? [])] })
- }
- if (path.endsWith('/environments/prod')) {
- return json({
- protection_rules:
- options.reviewers === false
- ? []
- : [{ type: 'required_reviewers', reviewers: [{ type: 'User', reviewer: { id: 1 } }] }],
- })
- }
throw new Error('Unexpected test request: ' + path)
}
const client = new ReleasePipeline({
repo,
tag,
- sha,
token: 'fixture-token',
request,
timer: {
@@ -97,12 +53,9 @@ const harness = (options = {}) => {
now += options.advance ?? delay
},
},
- record: (name, value) => {
- records[name] = String(value)
- },
log: (message) => logs.push(message),
})
- return { client, calls, records, logs, waits, dev, e2e }
+ return { client, calls, logs, waits }
}
const cliHarness = (t) => {
@@ -121,9 +74,6 @@ const cliHarness = (t) => {
" if (address.hostname === 'hooks.slack.com') return new Response('ok', { status: Number(process.env.SLACK_TEST_STATUS || 200) })",
" if (address.pathname.endsWith('/actions/runs/10')) return Response.json({ id: 10, display_title: process.env.TEST_TITLE }, { status: Number(process.env.TITLE_TEST_STATUS || 200) })",
" if (address.hostname !== 'api.github.com') throw new Error('Unexpected test host')",
- " if (init.method === 'POST' && address.pathname.endsWith('/dispatches')) {",
- ' return Response.json({ workflow_run_id: body.inputs.stage === "prod" ? 303 : body.inputs.tag ? 202 : 101 })',
- ' }',
' const value = responses[address.pathname]',
" if (value === undefined) throw new Error('Unexpected test endpoint')",
' return Response.json(value)',
@@ -134,13 +84,6 @@ const cliHarness = (t) => {
const responses = {
[prefix + '/releases/tags/' + tag]: snapshot,
[prefix + '/releases/' + snapshot.id + '/assets']: snapshot.assets,
- [prefix + '/commits/' + encodeURIComponent('refs/tags/' + tag)]: { sha },
- [prefix + '/actions/runs/101']: run(101),
- [prefix + '/actions/runs/202']: run(202, { updated_at: '2026-11-17T07:20:00Z' }),
- [prefix + '/actions/workflows/mdeploy-all.yml/runs']: { workflow_runs: [run(101)] },
- [prefix + '/environments/prod']: {
- protection_rules: [{ type: 'required_reviewers', reviewers: [{ type: 'User', reviewer: { id: 1 } }] }],
- },
}
return (command, overrides = {}) => {
const output = join(directory, 'output')
@@ -163,7 +106,6 @@ const cliHarness = (t) => {
GITHUB_OUTPUT: output,
GITHUB_STEP_SUMMARY: summary,
TAG: tag,
- RELEASE_SHA: sha,
GH_TOKEN: 'fixture-token',
SLACK_WEBHOOK_URL: webhook,
RELEASE_RESULTS: '{}',
@@ -182,108 +124,6 @@ const cliHarness = (t) => {
}
}
-test('workflow CLI waits for assets, records child runs, and reports their prod approval link', (t) => {
- const cli = cliHarness(t)
- const assets = cli('assets')
- assert.equal(assets.status, 0, assets.stderr)
- assert.equal(assets.requests.length, 2)
- const pipeline = cli('run')
- assert.equal(pipeline.status, 0, pipeline.stderr)
- const outputs = Object.fromEntries(
- pipeline.output
- .trim()
- .split('\n')
- .map((line) => line.split('=')),
- )
- assert.deepEqual(outputs, {
- dev_run_id: '101',
- dev_result: 'success',
- e2e_run_id: '202',
- e2e_result: 'success',
- prod_run_id: '303',
- phase: 'prod_dispatch',
- })
- const dispatches = pipeline.requests.filter((request) => request.url.endsWith('/dispatches'))
- assert.equal(dispatches.length, 3)
- for (const request of dispatches) assert.equal(request.body.inputs.ref ?? request.body.inputs.tag, tag)
- const notices = pipeline.requests.filter((request) => request.url === webhook)
- assert.equal(notices.length, 1)
- const dev = notices[0]
- assert.ok(pipeline.requests.indexOf(dev) > pipeline.requests.indexOf(dispatches[0]))
- assert.ok(pipeline.requests.indexOf(dev) < pipeline.requests.findIndex((r) => r.url.endsWith('/actions/runs/101')))
- assert.equal(dev.body.blocks.at(-1).elements[0].url, 'https://github.com/' + repo + '/actions/runs/101')
- const report = cli('report', {
- RELEASE_RESULTS: JSON.stringify({ pipeline: { result: 'success', outputs } }),
- })
- assert.equal(report.status, 0, report.stderr)
- assert.match(report.summary, /Prod run: https:\/\/github.com\/boxlite-ai\/boxlite\/actions\/runs\/303/)
- const final = report.requests.find((r) => r.url === webhook)
- for (const [message, environment] of [
- [dev.body, 'dev'],
- [final.body, 'prod'],
- ]) {
- const fields = message.blocks.flatMap((b) => b.fields ?? []).filter((f) => f.type === 'plain_text')
- for (const value of [displayTitle, 'mbuild-release', 'github-actor', environment]) {
- assert.ok(
- fields.some((f) => f.text.endsWith('\n' + value)),
- value,
- )
- }
- assert.ok(fields.some((f) => f.text.startsWith('Phase\n') && f.text.length > 6))
- assert.ok(!JSON.stringify(message.blocks.filter((b) => !b.fields)).includes('<!channel>'))
- }
- const actions = final.body.blocks.find((block) => block.type === 'actions')
- assert.equal(actions.elements[0].url, 'https://github.com/' + repo + '/actions/runs/' + outputs.prod_run_id)
-})
-
-test('workflow CLI rejects invalid configuration without network calls and preserves a failed report summary', (t) => {
- const cli = cliHarness(t)
- for (const [command, overrides, error] of [
- ['assets', { SLACK_WEBHOOK_URL: 'malformed' }, /SLACK_WEBHOOK_URL/],
- ['unknown', {}, /Expected assets, run, report, or approval/],
- ['run', { TAG: 'main' }, /TAG must be/],
- ['run', { GH_TOKEN: '' }, /GH_TOKEN is required/],
- ['report', { SLACK_WEBHOOK_URL: 'malformed' }, /SLACK_WEBHOOK_URL/],
- ]) {
- const result = cli(command, overrides)
- assert.equal(result.status, 1, result.stderr)
- assert.match(result.stderr, error)
- assert.equal(result.requests.length, 0)
- if (command === 'report') assert.match(result.summary, /release pipeline failed/)
- }
-})
-
-test('missing release webhook preserves asset checks, all dispatches and the final summary', (t) => {
- const cli = cliHarness(t)
- for (const secret of [undefined, '']) {
- for (const command of ['assets', 'run', 'report']) {
- const result = cli(command, { SLACK_WEBHOOK_URL: secret })
- assert.equal(result.status, 0, result.stderr)
- assert.ok(result.requests.every((r) => r.url.startsWith('https://api.github.com/')))
- if (command === 'assets') assert.ok(result.requests.some((r) => r.url.includes('/assets?')))
- if (command === 'run') assert.match(result.output, /prod_run_id=303/)
- if (command === 'report') assert.match(result.summary, /Release assets/)
- }
- }
-})
-
-test('a failed notice or title lookup still follows the dispatched child exactly once', (t) => {
- const cli = cliHarness(t)
- for (const overrides of [{ SLACK_TEST_STATUS: '503' }, { TITLE_TEST_STATUS: '403' }]) {
- const result = cli('run', overrides)
- assert.equal(result.status, 0, result.stderr)
- assert.match(result.stdout + result.stderr, /::warning::.*101/)
- assert.doesNotMatch(result.stdout + result.stderr, /private-fixture-token/)
- assert.equal(result.requests.filter((r) => r.url === webhook).length, overrides.SLACK_TEST_STATUS ? 1 : 0)
- assert.equal(
- result.requests.filter((r) => r.url.endsWith('/mdeploy-all.yml/dispatches') && r.body.inputs.stage === 'dev')
- .length,
- 1,
- )
- assert.match(result.output, /prod_run_id=303/)
- }
-})
-
test('deployment CLI identifies the sender, approval batch and current run', (t) => {
const cli = cliHarness(t)
const env = {
@@ -304,21 +144,6 @@ test('deployment CLI identifies the sender, approval batch and current run', (t)
assert.deepEqual(disabled.requests, [])
})
-test('failed and cancelled reports name the interrupted phase without prompting for approval', () => {
- for (const [results, phase] of [
- [{ resolve: { result: 'failure' } }, 'Release ref resolution'],
- [{ publish: { result: 'failure' }, assets: { result: 'skipped' } }, 'Image publication'],
- [{ assets: { result: 'cancelled' } }, 'Release assets'],
- [{ pipeline: { result: 'failure', outputs: { phase: 'history' } } }, 'Dev validation history'],
- [{ pipeline: { result: 'cancelled', outputs: { phase: 'e2e_wait' } } }, 'E2E cloud'],
- [{ pipeline: { result: 'failure', outputs: { phase: 'prod_reviewers' } } }, 'Prod reviewer verification'],
- ]) {
- const { payload, summary } = releaseReport({ repo, tag, runId: '10', results })
- assert.ok(payload.text.includes(phase) && summary.includes(phase))
- assert.ok(!payload.blocks.some((b) => b.type === 'actions'))
- }
-})
-
test('required assets agree with the real Release snapshot and production consumers', () => {
const required = releaseAssets(tag)
assert.ok(
@@ -327,16 +152,16 @@ test('required assets agree with the real Release snapshot and production consum
)
const runner = runnerArtifactFor({ selector: { kind: 'release', version: tag.slice(1) } })
assert.ok(required.includes(runner.tarballName))
- assert.ok(required.includes(new URL(runner.checksumUrl).pathname.split('/').at(-1)))
+ assert.ok(required.includes(runner.tarballName + '.sha256'))
const installer = readFileSync(new URL('scripts/ci/install-e2e-release.sh', root), 'utf8')
const python = e2eWorkflow.jobs.e2e.steps.find((step) => step.name === 'Setup Python for release wheel').with[
'python-version'
]
const variables = { tag, version: tag.slice(1), abi: 'cp' + python.replace('.', '') }
const downloads = [...installer.matchAll(/^\s*(?:wheel|package|platform|archive)="([^"]+)"/gm)].map((match) =>
- match[1].replace(/\$\{(\w+)\}/g, (_, name) => variables[name]),
+ match[1].replace(/\$\{(\w+)\}|\$(tag)\b/g, (_, name, bare) => variables[name ?? bare]),
)
- assert.equal(downloads.length, 4)
+ assert.equal(downloads.length, 5)
for (const name of downloads) assert.ok(required.includes(name), name)
})
@@ -384,251 +209,11 @@ test('asset authentication and malformed responses are failures, not absence', a
}
})
-test('full pipeline dispatches exact child IDs and preserves the release across dev, E2E and prod', async () => {
- let reads = 0
- const h = harness({
- devRead: () => (++reads === 1 ? run(101, { status: 'in_progress', conclusion: null }) : run(101)),
- })
- await h.client.run()
- const posts = h.calls.filter((call) => call.method === 'POST')
- assert.deepEqual(
- posts.map((call) => call.body),
- [
- { ref: 'main', inputs: { stage: 'dev', components: 'api+runner', ref: tag, apply: true, confirm: true } },
- { ref: 'main', inputs: { stage: 'dev', tag } },
- { ref: 'main', inputs: { stage: 'prod', components: 'api+runner', ref: tag, apply: true, confirm: true } },
- ],
- )
- assert.deepEqual(h.records, {
- dev_run_id: '101',
- dev_result: 'success',
- e2e_run_id: '202',
- e2e_result: 'success',
- prod_run_id: '303',
- phase: 'prod_dispatch',
- })
- assert.equal(h.waits.length, 1)
- assert.ok(!h.calls.some((call) => call.path.endsWith('/actions/runs/303')))
- assert.ok(!h.calls.some((call) => call.path.includes('pending_deployments')))
- assert.ok(
- h.calls.every((call) => call.headers.get('X-GitHub-Api-Version') === '2026-03-10' && call.redirect === 'error'),
- )
- const envRead = h.calls.findIndex((call) => call.path.endsWith('/environments/prod'))
- assert.ok(envRead > h.calls.findIndex((call) => call.path.endsWith('/actions/runs/202')))
- assert.ok(envRead < h.calls.indexOf(posts[2]))
-})
-
-test('failed and cancelled dev runs stop before E2E or prod dispatch', async () => {
- for (const conclusion of ['failure', 'cancelled', 'timed_out']) {
- const h = harness({ dev: { conclusion } })
- await assert.rejects(h.client.run(), /dev run 101 ended/)
- assert.equal(h.calls.filter((call) => call.method === 'POST').length, 1)
- assert.equal(h.records.dev_run_id, '101')
- assert.equal(h.records.dev_result, conclusion)
- assert.equal(h.records.phase, 'dev_wait')
- }
-})
-
-test('failed E2E never requests a prod run', async () => {
- const h = harness({ e2e: { conclusion: 'failure' } })
- await assert.rejects(h.client.run(), /e2e run 202 ended/)
- assert.equal(h.calls.filter((call) => call.method === 'POST').length, 2)
- assert.equal(h.records.e2e_run_id, '202')
- assert.equal(h.records.prod_run_id, undefined)
-})
-
-test('deployment and E2E deadlines stop dispatching without cancelling children', async () => {
- for (const [options, name, expectedPosts] of [
- [{ dev: { status: 'waiting', conclusion: null }, advance: 3 * 60 * 60 * 1000 }, 'dev', 1],
- [{ e2e: { status: 'in_progress', conclusion: null }, advance: 60 * 60 * 1000 }, 'e2e', 2],
- ]) {
- const h = harness(options)
- await assert.rejects(h.client.run(), new RegExp('Timed out waiting for ' + name + ' run'))
- assert.equal(h.calls.filter((call) => call.method === 'POST').length, expectedPosts)
- assert.equal(h.records.prod_run_id, undefined)
- assert.ok(h.records[name + '_run_id'])
- assert.equal(h.waits.length, 1)
- assert.ok(!h.calls.some((call) => call.path.endsWith('/cancel')))
- }
-})
-
-test('uncertain dispatch responses are not retried or replaced with the latest run', async () => {
- for (const response of [new Response(null, { status: 204 }), json({ workflow_run_id: 0 }), json({}, 503)]) {
- const h = harness({ respond: (call) => (call.method === 'POST' ? response.clone() : undefined) })
- let notified = false
- await assert.rejects(
- h.client.run(() => {
- notified = true
- }),
- /unknown|valid run ID/,
- )
- assert.equal(notified, false)
- assert.equal(h.calls.filter((call) => call.method === 'POST').length, 1)
- assert.ok(!h.calls.some((call) => call.path.includes('/runs?')))
- }
-})
-
-test('tag movement before downstream dispatch is rejected', async () => {
- const h = harness({ sha: 'a'.repeat(40) })
- await assert.rejects(h.client.run(), /tag moved/)
- assert.ok(!h.calls.some((call) => call.method === 'POST'))
-})
-
-test('prod creation requires a reviewer rule and readable Environment configuration', async () => {
- for (const options of [
- { reviewers: false },
- { respond: (call) => (call.path.endsWith('/environments/prod') ? json({}, 403) : undefined) },
- ]) {
- const h = harness(options)
- await assert.rejects(h.client.run(), /reviewers|HTTP 403/)
- assert.equal(h.calls.filter((call) => call.method === 'POST').length, 2)
- assert.equal(h.records.prod_run_id, undefined)
- }
-})
-
-test('failed and cancelled overlapping dev applies invalidate acceptance', async () => {
- for (const conclusion of ['success', 'failure', 'cancelled']) {
- const h = harness({ others: [run(99, { conclusion, updated_at: '2026-11-17T07:15:00Z' })] })
- await assert.rejects(h.client.run(), /overlapped/)
- assert.equal(h.records.prod_run_id, undefined)
- }
-})
-
-test('reruns are checked by attempt timing even when the run was created earlier', async () => {
- const previous = run(99, {
- created_at: '2026-10-01T07:00:00Z',
- run_started_at: '2026-11-17T07:15:00Z',
- updated_at: '2026-11-17T07:18:00Z',
- run_attempt: 2,
- })
- const h = harness({
- others: [previous],
- attempts: {
- 1: { ...previous, run_started_at: '2026-10-01T07:00:00Z', updated_at: '2026-10-01T07:10:00Z' },
- 2: previous,
- },
- })
- await assert.rejects(h.client.run(), /overlapped/)
- assert.ok(h.calls.some((call) => call.path.endsWith('/actions/runs/99/attempts/2')))
-})
-
-test('missing attempt timing and truncated history fail closed', async () => {
- const unknown = harness({ others: [run(99, { run_started_at: null, updated_at: '2026-11-17T07:15:00Z' })] })
- await assert.rejects(unknown.client.run(), /attempt timing/)
- const truncated = harness({
- history: () => Array.from({ length: 100 }, (_, index) => run(1000 + index, { updated_at: '2026-11-16T07:10:00Z' })),
- })
- await assert.rejects(truncated.client.run(), /truncated/)
- assert.equal(truncated.records.prod_run_id, undefined)
-})
-
-test('a manual rerun of this pipeline dev run also invalidates its validation interval', async () => {
- const rerun = run(101, {
- run_attempt: 2,
- run_started_at: '2026-11-17T07:15:00Z',
- updated_at: '2026-11-17T07:18:00Z',
- })
- const h = harness({
- history: () => [rerun],
- attempts: { 1: run(101), 2: rerun },
- })
- await assert.rejects(h.client.run(), /overlapped/)
- assert.equal(h.records.prod_run_id, undefined)
-})
-
test('null release responses are classified as malformed API data', async () => {
const h = harness({ respond: (call) => (call.path.includes('/releases/tags/') ? json(null) : undefined) })
await assert.rejects(h.client.waitForAssets(), /Malformed GitHub JSON/)
})
-test('previews, manual prod requests and completed earlier applies do not invalidate dev acceptance', async () => {
- const h = harness({
- others: [
- run(99, {
- display_title: 'preview dev · ' + tag + ' · api',
- updated_at: '2026-11-17T07:15:00Z',
- run_started_at: null,
- }),
- run(98, { display_title: 'deploy prod · ' + tag + ' · api', status: 'waiting', run_started_at: null }),
- run(97, { updated_at: '2026-11-17T07:09:59Z' }),
- ],
- })
- await h.client.run()
- assert.equal(h.records.prod_run_id, '303')
-})
-
-test('workflow build-only gates preserve publication and disable every downstream job', () => {
- assert.deepEqual(Object.keys(workflow.on.workflow_dispatch.inputs).sort(), ['build-only', 'command', 'tag'])
- assert.deepEqual(workflow.on.workflow_dispatch.inputs['build-only'], {
- description: 'Build and upload only; skip deployment, E2E and Slack reporting',
- required: true,
- default: false,
- type: 'boolean',
- })
- for (const name of ['publish', 'assets', 'pipeline', 'report']) {
- const expression = workflow.jobs[name].if.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
- const evaluate = new Function('inputs', 'github', 'always', 'return (' + expression + ')')
- for (const buildOnly of [true, false]) {
- assert.equal(
- evaluate({ command: 'publish', 'build-only': buildOnly }, { ref: 'refs/heads/main' }, () => true),
- name === 'publish' || !buildOnly,
- name,
- )
- }
- }
- assert.deepEqual(workflow.jobs.pipeline.permissions, { contents: 'read', actions: 'write' })
- assert.equal(workflow.jobs.pipeline.concurrency.group, 'mbuild-release-dev-validation')
- assert.equal(workflow.jobs.pipeline.concurrency['cancel-in-progress'], false)
-})
-
-test('reports contain exact run links and expose prod approval only after a successful pipeline', () => {
- const results = {
- publish: { result: 'success' },
- assets: { result: 'success' },
- pipeline: {
- result: 'success',
- outputs: {
- dev_run_id: '101',
- dev_result: 'success',
- e2e_run_id: '202',
- e2e_result: 'success',
- prod_run_id: '303',
- },
- },
- }
- const report = releaseReport({ repo, tag, runId: '10', results })
- assert.match(report.payload.text, /prod review requested/)
- assert.equal(
- report.payload.blocks.find((block) => block.type === 'actions').elements[0].url,
- 'https://github.com/boxlite-ai/boxlite/actions/runs/303',
- )
- assert.match(report.summary, /\[success\]\(https:\/\/github.com\/boxlite-ai\/boxlite\/actions\/runs\/202\)/)
- assert.ok(!report.summary.includes('<https:'))
- results.pipeline.result = 'failure'
- const failed = releaseReport({ repo, tag, runId: '10', results })
- assert.ok(!failed.payload.blocks.some((block) => block.type === 'actions'))
- assert.match(failed.payload.text, /failed/)
-})
-
-test('reports keep each prod request URL distinct across several validated releases', () => {
- for (const [release, runId] of [
- ['v0.13.1', '303'],
- ['v0.13.2', '404'],
- ['v0.13.3', '505'],
- ]) {
- const report = releaseReport({
- repo,
- tag: release,
- runId: '10',
- results: { pipeline: { result: 'success', outputs: { prod_run_id: runId } } },
- })
- assert.ok(
- report.payload.blocks.some((block) => block.type === 'actions' && block.elements[0].url.endsWith('/' + runId)),
- )
- assert.ok(report.payload.blocks.some((block) => block.text?.text?.includes('ref=' + release)))
- }
-})
-
test('Slack payloads are JSON, while HTTP and transport failures do not expose webhook secrets', async () => {
const payload = releaseReport({ repo, tag, runId: '10', results: {} }).payload
await sendSlack(webhook, payload, async (url, init) => {
@@ -662,3 +247,77 @@ test('Slack payloads are JSON, while HTTP and transport failures do not expose w
assert.throws(() => slackWebhook(value), /SLACK_WEBHOOK_URL/)
}
})
+
+test('prod review combines dev E2E success with the approval button; failed acceptance has its own report', (t) => {
+ const cli = cliHarness(t)
+ const approval = cli('approval', {
+ DEPLOY_ENVIRONMENT: 'prod',
+ APPROVAL_PHASE: 'Release deployment approval',
+ ACCEPTED_TAG: tag,
+ })
+ const messages = approval.requests.filter((req) => req.url === webhook)
+ assert.equal(messages.length, 1)
+ assert.match(messages[0].body.text, /dev E2E passed/i)
+ assert.ok(messages[0].body.text.includes(tag))
+ const button = messages[0].body.blocks.at(-1).elements[0]
+ assert.equal(button.text.text, 'Review prod deployment')
+ assert.equal(button.url, 'https://github.com/' + repo + '/actions/runs/10')
+ for (const outcome of ['failure', 'cancelled', 'skipped']) {
+ const results = {
+ resolve: { result: 'success' },
+ publish: { result: 'success' },
+ dev: { result: 'failure', outputs: { e2e_result: outcome } },
+ }
+ const response = cli('report', { RELEASE_RESULTS: JSON.stringify(results) })
+ assert.equal(response.status, 0, response.stderr)
+ assert.ok(response.summary.includes('| E2E cloud | ' + outcome + ' |'))
+ const message = response.requests.find((req) => req.url === webhook).body
+ assert.equal(message.blocks.at(-1).elements[0].url, 'https://github.com/' + repo + '/actions/runs/10')
+ assert.equal(message.blocks.at(-1).elements[0].text.text, 'View run logs')
+ assert.ok(message.blocks.some((block) => block.fields?.some((field) => field.text === 'E2E cloud\n' + outcome)))
+ }
+ const preflight = cli('report', {
+ RELEASE_RESULTS: JSON.stringify({
+ resolve: { result: 'success' },
+ publish: { result: 'success' },
+ distribution: { result: 'skipped' },
+ dev: { result: 'failure' },
+ }),
+ })
+ assert.match(preflight.summary, /Dev deployment and acceptance \| failure/)
+ const preflightButton = preflight.requests.find((r) => r.url === webhook).body.blocks.at(-1).elements[0]
+ assert.equal(preflightButton.text.text, 'View run logs')
+ assert.equal(preflightButton.url, 'https://github.com/' + repo + '/actions/runs/10')
+ const missing = cli('report', { SLACK_WEBHOOK_URL: '' })
+ assert.equal(missing.status, 0)
+ assert.deepEqual(missing.requests, [])
+ const failed = cli('report', { SLACK_TEST_STATUS: '503' })
+ assert.equal(failed.status, 1)
+ assert.match(failed.summary, /Release assets/)
+})
+
+test('deployment success and failure notifications link to the run and render the ref as plain text', (t) => {
+ const cli = cliHarness(t)
+ for (const result of ['success', 'failure']) {
+ const response = cli('result', { DEPLOY_ENVIRONMENT: 'stage', DEPLOY_REF: '#123', DEPLOY_RESULT: result })
+ assert.equal(response.status, 0, response.stderr)
+ const message = response.requests.find((req) => req.url === webhook).body
+ assert.equal(
+ message.blocks.at(-1).elements[0].text.text,
+ result === 'failure' ? 'View run logs' : 'View deployment run',
+ )
+ assert.equal(message.text, 'stage deployment: ' + result)
+ assert.deepEqual(message.blocks.at(-2).text, { type: 'plain_text', text: 'Ref: #123' })
+ assert.equal(message.blocks.at(-1).elements[0].url, 'https://github.com/' + repo + '/actions/runs/10')
+ }
+})
+
+test('asset preflight rejects an invalid webhook before reading GitHub and works without Slack', (t) => {
+ const cli = cliHarness(t)
+ const invalid = cli('assets', { SLACK_WEBHOOK_URL: 'malformed' })
+ assert.equal(invalid.status, 1)
+ assert.deepEqual(invalid.requests, [])
+ const assets = cli('assets', { SLACK_WEBHOOK_URL: '' })
+ assert.equal(assets.status, 0, assets.stderr)
+ assert.equal(assets.requests.length, 2)
+})
diff --git a/apps/infra/scripts/release-selection.mjs b/apps/infra/scripts/release-selection.mjs
new file mode 100644
index 000000000..3d7ba1bf2
--- /dev/null
+++ b/apps/infra/scripts/release-selection.mjs
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 BoxLite AI
+
+import assert from 'node:assert/strict'
+import { appendFileSync } from 'node:fs'
+import { pathToFileURL } from 'node:url'
+
+const groups = {
+ runtime: 'runtime-distribution',
+ wheels: 'wheels-',
+ node: 'node-packages',
+ c: 'c-sdk-',
+ go: '',
+ runner: 'runner-linux-amd64',
+}
+
+export function selectRelease(command, buildOnly, candidate, source) {
+ if (command === 'publish') {
+ assert.ok(!candidate && !source, 'A full release requires its product tag')
+ return { mode: buildOnly ? 'ghcr' : 'release', builds: buildOnly ? ['c', 'runner'] : Object.keys(groups), group: '', producer: '' }
+ }
+ const match = /^(publish|repair)-(runtime|wheels|node|c|go|runner)$/.exec(command)
+ assert.ok(match, 'Unknown component command')
+ const [, operation, component] = match
+ const group = groups[component]
+ if (operation === 'repair') {
+ assert.ok(['runtime', 'wheels', 'node', 'c'].includes(component) && !buildOnly && !source && /^[1-9]\d*$/.test(candidate),
+ 'Repair requires a candidate ID, a supported component and build-only=false')
+ return { mode: 'repair', builds: [], group, producer: '' }
+ }
+ assert.ok(!candidate && (buildOnly || !source), 'Only standalone builds accept a source ref')
+ const builds = ['go', 'runner'].includes(component) ? ['c', component] : [component]
+ const producer = component === 'runner' ? 'publish-runner' : 'build-' + component
+ return { mode: buildOnly ? 'build' : 'component', builds, group, producer }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const { COMMAND, BUILD_ONLY, CANDIDATE, SOURCE, GITHUB_OUTPUT } = process.env
+ const selection = selectRelease(COMMAND, BUILD_ONLY === 'true', CANDIDATE, SOURCE)
+ for (const [key, value] of Object.entries(selection))
+ appendFileSync(GITHUB_OUTPUT, key + '=' + (Array.isArray(value) ? JSON.stringify(value) : value) + '\n')
+}
diff --git a/apps/infra/scripts/release-workflow.test.mjs b/apps/infra/scripts/release-workflow.test.mjs
new file mode 100644
index 000000000..e6a481146
--- /dev/null
+++ b/apps/infra/scripts/release-workflow.test.mjs
@@ -0,0 +1,627 @@
+import assert from 'node:assert/strict'
+import { execFileSync, spawnSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import test from 'node:test'
+import { data, Evaluator, Lexer, Parser } from '@actions/expressions'
+import { load } from 'js-yaml'
+import { selectRelease } from './release-selection.mjs'
+
+const readWorkflow = (name) =>
+ load(readFileSync(new URL('../../../.github/workflows/' + name + '.yml', import.meta.url), 'utf8'))
+const release = readWorkflow('mbuild-release')
+const rollout = readWorkflow('mdeploy-all')
+
+test('release deployment is a native dependency in the publisher run', () => {
+ const calls = Object.values(release.jobs).filter((job) => job.uses === './.github/workflows/mdeploy-all.yml')
+ assert.deepEqual(
+ calls.map((job) => job.with.stage).sort(),
+ ['dev', 'prod'],
+ 'release dispatches deployment outside its workflow run',
+ )
+ assert.ok(release.jobs.dev.needs.includes('publish-runner'))
+ assert.ok(release.jobs.prod.needs.includes('dev'))
+ assert.equal(rollout.jobs.e2e.uses, './.github/workflows/e2e-cloud.yml')
+ assert.ok(rollout.jobs.e2e.needs.includes('plan'))
+ assert.equal(rollout.jobs.report, undefined, 'successful acceptance must not allocate a report runner')
+})
+
+test('release dev approval uses only the release webhook', () => {
+ const inputs = { stage: 'dev', apply: true, release_sha: 'a'.repeat(40) }
+ const notices = rollout.jobs.resolve.steps.filter((s) => s.run?.endsWith('release-pipeline.mjs approval'))
+ const selected = notices.filter((s) => new Function('inputs', 'return ' + s.if)(inputs))
+ assert.deepEqual(
+ selected.map((s) => s.env.SLACK_WEBHOOK_URL),
+ ['$' + '{{ secrets.SLACK_WEBHOOK_URL }}'],
+ )
+})
+
+const expression = (value) => value.replace(/^\$\{\{\s*|\s*\}\}$/g, '')
+
+test('release caller routes the pinned C SDK build to its qualified runner', () => {
+ const sha = 'a'.repeat(40)
+ const caller = release.jobs['build-c']
+ const callee = readWorkflow('build-c').jobs.build
+ const platforms = JSON.parse(readFileSync(new URL('../../../.github/ci-config.json', import.meta.url))).platforms
+ function evaluate(value, context) {
+ const tokens = new Lexer(expression(value)).lex().tokens
+ const ast = new Parser(tokens, Object.keys(context), []).parse()
+ return new Evaluator(ast, JSON.parse(JSON.stringify(context), data.reviver)).evaluate().value
+ }
+ for (const [command, buildOnly, source, linuxX64] of [
+ ['publish', false, '', 'boxlite-4vcpu-16gbmem-64gbdisk'],
+ ['publish', true, '', 'ubuntu-latest'],
+ ['publish-c', true, 'topic', 'ubuntu-latest'],
+ ['publish-c', false, '', 'ubuntu-latest'],
+ ['publish-runner', false, '', 'ubuntu-latest'],
+ ]) {
+ const { mode } = selectRelease(command, buildOnly, '', source)
+ const context = { inputs: { command, 'build-only': buildOnly }, needs: { resolve: { outputs: { sha, mode } } } }
+ const inputs = Object.fromEntries(Object.entries(caller.with).map(([key, value]) => [key, evaluate(value, context)]))
+ assert.equal(inputs.ref, sha, 'runner selection must preserve the resolved source commit')
+ for (const { os, target } of platforms) {
+ const actual = evaluate(callee['runs-on'], { inputs, matrix: { os } })
+ assert.equal(actual, target === 'linux-x64-gnu' ? linuxX64 : os, command + ' ' + mode + ' ' + target)
+ }
+ }
+})
+
+test('standalone and release applies choose exactly one channel, including an unset release webhook', () => {
+ const job = rollout.jobs.result
+ const steps = job.steps.filter((step) => step.run?.endsWith('release-pipeline.mjs result'))
+ for (const step of steps) {
+ assert.match(
+ expression(step.env.SLACK_WEBHOOK_URL),
+ /^secrets\.(SLACK_WEBHOOK_URL|SLACK_DEV_DEPLOYMENT_WEBHOOK_URL)$/,
+ 'each result step must read one named secret',
+ )
+ }
+ const channel = (inputs, secrets) => {
+ const selected = steps.filter((step) => new Function('inputs', 'return ' + expression(step.if))(inputs))
+ assert.equal(selected.length, 1)
+ return new Function('secrets', 'return ' + expression(selected[0].env.SLACK_WEBHOOK_URL))(secrets)
+ }
+ const secrets = { SLACK_WEBHOOK_URL: 'release', SLACK_DEV_DEPLOYMENT_WEBHOOK_URL: 'dev' }
+ for (const [stage, sha, expected] of [
+ ['dev', '', 'dev'],
+ ['stage', '', 'dev'],
+ ['prod', '', 'release'],
+ ['dev', 'sha', 'release'],
+ ['prod', 'sha', 'release'],
+ ]) {
+ assert.equal(channel({ stage, release_sha: sha }, secrets), expected)
+ }
+ assert.equal(channel({ stage: 'dev', release_sha: 'sha' }, { ...secrets, SLACK_WEBHOOK_URL: '' }), '')
+ assert.match(rollout.jobs.result.if, /inputs\.apply/)
+ assert.equal(release.jobs.dev.secrets.SLACK_DEV_DEPLOYMENT_WEBHOOK_URL, undefined)
+ const outcome = new Function('needs', 'return ' + expression(job.env.DEPLOY_RESULT))
+ for (const [version, plan, deploy, expected] of [
+ ['v1.2.3', 'success', 'skipped', 'success'],
+ ['', 'success', 'failure', 'failure'],
+ ['', 'success', 'success', 'success'],
+ ['v1.2.3', 'failure', 'skipped', 'failure'],
+ ]) {
+ assert.equal(
+ outcome({
+ resolve: { result: 'success', outputs: { version } },
+ plan: { result: plan },
+ deploy: { result: deploy },
+ }),
+ expected,
+ )
+ }
+})
+
+test('release admission checks caller, tag, reviewers and deployment attempt before production', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'release-call-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ writeFileSync(join(dir, 'gh'), '#!/bin/sh\nprintf "%s\\n" "$REVIEWERS"\nexit "${GH_EXIT:-0}"\n', { mode: 0o755 })
+ const guard = rollout.jobs.resolve.steps.find((step) => step.name === 'Validate release caller and published commit')
+ const repo = 'boxlite-ai/boxlite'
+ const base = {
+ PATH: dir + ':' + process.env.PATH,
+ GITHUB_REPOSITORY: repo,
+ GITHUB_REF: 'refs/heads/main',
+ GITHUB_WORKFLOW_REF: repo + '/.github/workflows/mbuild-release.yml@refs/heads/main',
+ RESOLVED: 'a'.repeat(40),
+ RELEASE_SHA: 'a'.repeat(40),
+ VERSION: 'v1.2.3',
+ STAGE: 'prod',
+ ACCEPTED_ATTEMPT: '2',
+ GITHUB_RUN_ATTEMPT: '2',
+ REVIEWERS: JSON.stringify({ protection_rules: [{ type: 'required_reviewers', reviewers: [{ type: 'User' }] }] }),
+ }
+ const run = (script, extra) => spawnSync('bash', ['-c', script], { env: { ...base, ...extra } }).status
+ assert.equal(run(guard.run, {}), 0)
+ for (const overrides of [
+ { GITHUB_WORKFLOW_REF: 'unexpected' },
+ { RESOLVED: 'b'.repeat(40) },
+ { VERSION: '' },
+ { STAGE: 'stage' },
+ { REVIEWERS: '{"protection_rules":[]}' },
+ { GH_EXIT: '1' },
+ ])
+ assert.notEqual(run(guard.run, overrides), 0)
+ assert.equal(run(guard.run, { STAGE: 'dev', ACCEPTED_ATTEMPT: '', GH_EXIT: '1' }), 0)
+ const cloud = readWorkflow('e2e-cloud')
+ const e2eGuard = cloud.jobs.e2e.steps.find((step) => step.env?.DEPLOYMENT_ATTEMPT)
+ for (const [attempt, sha, expected] of [
+ ['2', base.RELEASE_SHA, 0],
+ ['1', base.RELEASE_SHA, 1],
+ ['2', 'b'.repeat(40), 1],
+ ]) {
+ assert.equal(
+ run(e2eGuard.run, {
+ DEPLOYMENT_ATTEMPT: attempt,
+ REVIEWERS: sha,
+ RELEASE_TAG: base.VERSION,
+ GITHUB_OUTPUT: join(dir, 'outputs'),
+ }),
+ expected,
+ )
+ }
+ const checkout = cloud.jobs.e2e.steps.find(
+ (step) => step.name === 'Checkout release SDK sources for subdomain clients',
+ )
+ assert.equal(
+ checkout.env?.RELEASE_SDK_SHA,
+ '${{ steps.release_commit.outputs.sha }}',
+ 'release SDK checkout must use the verified commit',
+ )
+ const outputs = join(dir, 'standalone-outputs')
+ const standalone = { DEPLOYMENT_ATTEMPT: '', RELEASE_SHA: '', RELEASE_TAG: base.VERSION, GITHUB_OUTPUT: outputs }
+ assert.notEqual(run(e2eGuard.run, { ...standalone, REVIEWERS: base.VERSION }), 0)
+ assert.equal(run(e2eGuard.run, { ...standalone, REVIEWERS: base.RELEASE_SHA }), 0)
+ assert.equal(readFileSync(outputs, 'utf8'), 'sha=' + base.RELEASE_SHA + '\n')
+})
+
+test('prod may retry a previous attempt only with the exact dev acceptance receipt', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'prod-retry-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ writeFileSync(
+ join(dir, 'gh'),
+ '#!/bin/bash\nset -eu\nmkdir -p "${@: -1}"\ncp "$RECEIPT" "${@: -1}/acceptance.json"\n',
+ { mode: 0o755 },
+ )
+ const sha = 'a'.repeat(40),
+ digest = 'sha256:' + 'b'.repeat(64)
+ const accepted = { run: 44, attempt: 1, candidate: 77, digest, sha, tag: 'v1.2.3' }
+ const env = {
+ ...process.env,
+ PATH: dir + ':' + process.env.PATH,
+ RUNNER_TEMP: dir,
+ RECEIPT: join(dir, 'receipt'),
+ GITHUB_RUN_ATTEMPT: '2',
+ GITHUB_RUN_ID: '44',
+ GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
+ ACCEPTED_ATTEMPT: '1',
+ CANDIDATE: '77',
+ DIGEST: digest,
+ TAG: accepted.tag,
+ SHA: sha,
+ }
+ for (const job of [rollout.jobs.plan, rollout.jobs.resolve]) {
+ const guard = job.steps.find((step) => step.name === 'Verify dev acceptance for the production candidate')
+ for (const [changed, expected] of [
+ [{}, 0],
+ [{ candidate: 78 }, 1],
+ [{ digest: 'sha256:' + 'c'.repeat(64) }, 1],
+ [{ sha: 'd'.repeat(40) }, 1],
+ [{ run: 45 }, 1],
+ [{ attempt: 3 }, 1],
+ [{ tag: 'v1.2.4' }, 1],
+ ]) {
+ writeFileSync(env.RECEIPT, JSON.stringify({ ...accepted, ...changed }))
+ const result = spawnSync('bash', ['-c', guard.run], { env, encoding: 'utf8' })
+ assert.equal(result.status === 0, expected === 0, 'receipt ' + JSON.stringify(changed) + ' ' + result.stderr)
+ }
+ }
+})
+
+test('npm preflights all packages before publishing and verifies missing packages in order', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'boxlite-npm-publication-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const tag = 'v1.2.3'
+ const platform = '@boxlite-ai/[email protected]'
+ const main = '@boxlite-ai/[email protected]'
+ const record = join(dir, 'published')
+ mkdirSync(join(dir, 'package'))
+ writeFileSync(record, '')
+ for (const id of [platform, main]) {
+ const name = id.slice(0, id.lastIndexOf('@'))
+ const file = name.slice(1).replace('/', '-') + '-1.2.3.tgz'
+ writeFileSync(join(dir, 'package', 'package.json'), JSON.stringify({ name, version: '1.2.3' }))
+ execFileSync('tar', ['-czf', file, 'package/package.json'], { cwd: dir })
+ }
+ writeFileSync(join(dir, 'npm'), [
+ '#!/bin/bash',
+ 'set -euo pipefail',
+ 'case "$1" in',
+ ' view)',
+ ' entry="$RUNNER_TEMP/${2##*/}.integrity"',
+ ' if [[ ! -f "$entry" ]]; then echo "npm error code E404" >&2; exit 1; fi',
+ ' if [[ "${4:-}" == --json ]]; then jq -Rs . < "$entry"; else cat "$entry"; fi ;;',
+ ' publish)',
+ " id=$(tar -xOzf \"$2\" package/package.json | jq -r '.name + \"@\" + .version')",
+ ' echo "$id" >> "$RUNNER_TEMP/published"',
+ ' digest=$(openssl dgst -sha512 -binary "$2" | openssl base64 -A)',
+ ' printf %s "${CORRUPT:-sha512-$digest}" > "$RUNNER_TEMP/${id##*/}.integrity" ;;',
+ ' *) exit 2 ;;',
+ 'esac',
+ ].join('\n'), { mode: 0o755 })
+ const script = release.jobs.npm.steps.find(step => step.name === 'Publish platform packages before the main package').run
+ const publish = (extra = {}) => spawnSync('bash', ['-ec', script], {
+ cwd: dir, encoding: 'utf8',
+ env: { ...process.env, PATH: dir + ':' + process.env.PATH, RELEASE_ASSET_DIR: dir, RUNNER_TEMP: dir, TAG: tag, ...extra },
+ })
+ const mainEntry = join(dir, '[email protected]')
+ writeFileSync(mainEntry, 'sha512-conflict')
+ assert.notEqual(publish().status, 0, 'existing main package conflicts')
+ assert.equal(readFileSync(record, 'utf8'), '', 'a later conflict must block even the first platform upload')
+ rmSync(mainEntry)
+ const first = publish()
+ assert.equal(first.status, 0, first.stderr)
+ assert.deepEqual(readFileSync(record, 'utf8').trim().split('\n'), [platform, main])
+ writeFileSync(record, '')
+ const retry = publish()
+ assert.equal(retry.status, 0, retry.stderr)
+ assert.equal(readFileSync(record, 'utf8'), '', 'matching packages must be reused')
+ rmSync(mainEntry)
+ assert.notEqual(publish({ CORRUPT: 'sha512-wrong' }).status, 0, 'the registry must report the uploaded digest')
+ assert.equal(readFileSync(record, 'utf8').trim(), main)
+})
+
+test('PyPI publication rejects conflicting wheels before the upload action can run', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'pypi-preflight-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const steps = release.jobs.pypi.steps
+ const source = join(dir, 'source'),
+ filename = 'boxlite-1.2.3-py3-none-any.whl'
+ mkdirSync(source)
+ writeFileSync(join(source, filename), 'accepted')
+ writeFileSync(
+ join(dir, 'curl'),
+ '#!/bin/bash\nset -eu\nwhile [[ $# -gt 0 ]]; do if [[ "$1" == "-o" ]]; then cp "$DATA" "$2"; shift; fi; shift; done\nprintf %s "$STATUS"\n',
+ { mode: 0o755 },
+ )
+ const env = {
+ ...process.env,
+ PATH: dir + ':' + process.env.PATH,
+ TAG: 'v1.2.3',
+ RELEASE_ASSET_DIR: source,
+ DATA: join(dir, 'pypi-response'),
+ }
+ const select = steps.findIndex((step) => step.name === 'Select accepted wheels')
+ const upload = steps.findIndex((step) => step.uses?.startsWith('pypa/'))
+ const repo = new URL('../../../', import.meta.url).pathname.replace(/\/$/, '')
+ const before = steps
+ .slice(select, upload)
+ .map((step) => step.run)
+ .join('\n')
+ .replaceAll('scripts/release/', repo + '/scripts/release/')
+ const after = steps[upload + 1].run.replaceAll('scripts/release/', repo + '/scripts/release/')
+ function check(script, status, sha) {
+ writeFileSync(env.DATA, JSON.stringify({ urls: sha ? [{ filename, digests: { sha256: sha } }] : [] }))
+ return spawnSync('bash', ['-ec', script], { cwd: dir, env: { ...env, STATUS: status }, encoding: 'utf8' }).status
+ }
+ const hash = execFileSync('shasum', ['-a', '256', join(source, filename)], { encoding: 'utf8' }).split(' ')[0]
+ for (const [status, sha, allowed, complete] of [
+ ['200', '0'.repeat(64), false, false],
+ ['200', hash, true, true],
+ ['404', '', true, false],
+ ['500', '', false, false],
+ ['200', '', true, false],
+ ]) {
+ rmSync(join(dir, 'dist'), { recursive: true, force: true })
+ assert.equal(check(before, status, sha) === 0, allowed, 'before publisher ' + status + ' ' + sha)
+ assert.equal(check(after, status, sha) === 0, complete, 'after publisher ' + status + ' ' + sha)
+ }
+})
+
+test('build-only never enters deployment, checks, or reporting; failed E2E cannot stamp acceptance', () => {
+ for (const id of ['distribution', 'dev', 'prod']) assert.match(release.jobs[id].if, /needs\.resolve\.outputs\.mode == 'release'/)
+ assert.match(release.jobs.report.if, /!inputs\['build-only'\]/)
+ assert.equal(rollout.concurrency.group, 'mdeploy-all-${{ inputs.stage }}')
+ assert.notEqual(release.concurrency.group, rollout.concurrency.group)
+ const outputs = rollout.on.workflow_call.outputs
+ const stamp = new Function('jobs', 'return ' + expression(outputs.accepted_attempt.value))
+ for (const result of ['failure', 'cancelled', 'skipped', 'success']) {
+ assert.equal(
+ stamp({
+ plan: { result: 'success', outputs: { deployment_attempt: '2' } },
+ e2e: { outputs: { release_result: result } },
+ }),
+ result === 'success' ? '2' : '',
+ )
+ }
+ assert.equal(outputs.e2e_result.value, '${{ jobs.e2e.outputs.release_result }}')
+ const cloud = readWorkflow('e2e-cloud')
+ assert.equal(cloud.on.workflow_call.outputs.release_result.value, '${{ jobs.e2e.outputs.release_result }}')
+ assert.equal(cloud.jobs.e2e.outputs.release_result, '${{ steps.acceptance.outputs.result }}')
+ const summary = cloud.jobs.e2e.steps.at(-1)
+ assert.equal(summary.id, 'acceptance')
+ assert.equal(summary.if, 'always() && inputs.deployment_attempt')
+ assert.equal(summary.env.E2E_RESULT, '${{ job.status }}')
+ assert.match(release.jobs.report.if, /contains\(needs\.\*\.result, 'failure'\)/)
+ assert.match(release.jobs.report.if, /contains\(needs\.\*\.result, 'cancelled'\)/)
+ for (const job of ['dev','attach','finalize','pypi','npm','publish_crates']) assert.ok(release.jobs.report.needs.includes(job))
+ assert.match(release.jobs.prod.if, /needs\.dev\.outputs\.accepted_attempt != ''/)
+})
+
+test('only a prod approval after dev acceptance carries the E2E success', () => {
+ const notice = rollout.jobs.resolve.steps.find((step) => step.name === 'Notify release reviewers')
+ assert.ok(notice.env.ACCEPTED_TAG, 'prod approval must include the accepted tag')
+ const accepted = new Function('inputs', 'return ' + expression(notice.env.ACCEPTED_TAG))
+ for (const [stage, attempt, expected] of [
+ ['dev', '', ''],
+ ['prod', '', ''],
+ ['prod', '2', 'v1.2.3'],
+ ]) {
+ assert.equal(accepted({ stage, accepted_attempt: attempt, ref: 'v1.2.3' }), expected)
+ }
+})
+
+test('the cloud suite cannot write the default branch cache', () => {
+ const cloud = readWorkflow('e2e-cloud')
+ assert.ok(
+ ['read', 'none'].includes(cloud.jobs.e2e['cache-mode'] || cloud['cache-mode']),
+ 'E2E needs a read-only cache',
+ )
+})
+
+test('release SDK worktree uses the verified commit even when the remote has advanced', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'cloud-sdk-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const git = (...args) =>
+ execFileSync('git', args, { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
+ git('init', '-q', 'source')
+ const commit = (text) =>
+ git(
+ '-C',
+ 'source',
+ '-c',
+ 'user.name=Test',
+ '-c',
+ '-c',
+ 'commit.gpgsign=false',
+ '-c',
+ 'core.hooksPath=/dev/null',
+ 'commit',
+ '-q',
+ '--allow-empty',
+ '-m',
+ text,
+ )
+ commit('published')
+ const sha = git('-C', 'source', 'rev-parse', 'HEAD')
+ commit('later change')
+ git('init', '-q', 'suite')
+ const step = readWorkflow('e2e-cloud').jobs.e2e.steps.find(
+ (s) => s.name === 'Checkout release SDK sources for subdomain clients',
+ )
+ assert.ok(step.run, 'the suite should share its Git object store with the release SDK worktree')
+ const run = (ref) =>
+ spawnSync('bash', ['-c', step.run], {
+ cwd: join(dir, 'suite'),
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ RELEASE_SDK_SHA: ref,
+ GIT_CONFIG_COUNT: '1',
+ GIT_CONFIG_KEY_0: 'url.file://' + join(dir, 'source') + '.insteadOf',
+ GIT_CONFIG_VALUE_0: 'https://github.com/boxlite-ai/boxlite.git',
+ },
+ })
+ const missing = run('0'.repeat(40))
+ assert.notEqual(missing.status, 0)
+ const result = run(sha)
+ assert.equal(result.status, 0, result.stderr)
+ assert.equal(git('-C', 'suite/target/e2e-release', 'rev-parse', 'HEAD'), sha)
+ const common = (path) => git('-C', path, 'rev-parse', '--path-format=absolute', '--git-common-dir')
+ assert.equal(common('suite/target/e2e-release'), common('suite'))
+})
+
+test('component repairs use the accepted candidate and package publishers stay in the entry workflow', () => {
+ const commands = release.on.workflow_dispatch.inputs.command.options
+ assert.deepEqual(commands.filter((name) => name.startsWith('repair-')), ['repair-runtime', 'repair-wheels', 'repair-node', 'repair-c'])
+ const locate = release.jobs['accepted-candidate']
+ const receipt = locate.steps.find((step) => step.id === 'receipt').run
+ assert.match(receipt, /head_branch == "main"/)
+ assert.match(receipt, /dev-accepted-\$ID/)
+ assert.match(receipt, /\.candidate == \$id and \.run == \$run/)
+ const attach = release.jobs.attach
+ assert.ok(attach.needs.includes('accepted-candidate'))
+ for (const [job, command] of [['npm','repair-node'],['pypi','repair-wheels']]) {
+ const publisher=release.jobs[job]
+ assert.ok(publisher.needs.includes('attach'))
+ assert.equal(publisher.permissions['id-token'],'write')
+ assert.ok(publisher.if.includes(command))
+ const input=publisher.steps.find((step)=>step.uses==='./.github/actions/release-candidate').with
+ assert.equal(input.run,'${{ needs.attach.outputs.run }}')
+ assert.equal(input.id,'${{ needs.attach.outputs.candidate }}')
+ assert.equal(input.digest,'${{ needs.attach.outputs.digest }}')
+ }
+ assert.ok(release.jobs.publish_crates.needs.includes('finalize'))
+ assert.ok(release.jobs.finalize.if.includes("inputs.command == 'publish'"))
+})
+
+test('GHCR pins unlock dev and dev acceptance independently unlocks prod and publication', () => {
+ const jobs = release.jobs
+ assert.deepEqual(jobs.dev.needs, ['resolve', 'publish', 'publish-runner'], 'dev must prepare as soon as GHCR producers finish')
+ assert.equal(jobs.check, undefined)
+ const prepare = rollout.jobs.resolve
+ const validate = prepare.steps.findIndex((step) => step.run?.includes('release-candidate.mjs deployment'))
+ const upload = prepare.steps.findIndex((step) => step.with?.name?.startsWith('deployment-candidate-'))
+ const approve = prepare.steps.findIndex((step) => step.name === 'Notify release reviewers')
+ const download = prepare.steps.findIndex((step) => step.with?.pattern === 'ghcr-*')
+ assert.ok(download >= 0 && download < validate && validate < upload && upload < approve)
+ for (const index of [download, validate, upload]) {
+ const stageCandidate = new Function('inputs', 'return ' + prepare.steps[index].if)
+ assert.ok(stageCandidate({ stage: 'dev', release_sha: 'release-commit' }))
+ assert.ok(!stageCandidate({ stage: 'prod', release_sha: 'release-commit' }))
+ assert.ok(!stageCandidate({ stage: 'dev' }))
+ }
+ for (const key of ['candidate_id', 'candidate_digest', 'registry_digests']) {
+ assert.equal(rollout.on.workflow_call.outputs[key].value, '$' + '{{ jobs.resolve.outputs.' + key + ' }}')
+ assert.equal(jobs.prod.with[key], '$' + '{{ needs.dev.outputs.' + key + ' }}')
+ }
+ for (const key of ['candidate_id', 'candidate_digest']) {
+ assert.equal(rollout.jobs.e2e.with[key], '$' + '{{ needs.resolve.outputs.' + key + ' }}')
+ }
+ assert.equal(jobs.dev.with.release_images, '$' + '{{ needs.resolve.outputs.artifacts }}')
+ assert.equal(prepare.steps[validate].env.IMAGES, '$' + '{{ inputs.release_images }}')
+ assert.deepEqual(jobs.prod.needs, ['resolve', 'dev'], 'prod waits for release finalization')
+ assert.ok(jobs.attach.needs.includes('dev'))
+ assert.ok(jobs.attach.needs.includes('distribution'))
+ assert.ok(jobs.attach.needs.includes('build-go'))
+ assert.ok(!jobs.attach.needs.includes('prod'))
+ assert.ok(jobs.publish_crates.needs.includes('finalize'))
+})
+
+test('Go tag stays unpublished until every C SDK can be downloaded anonymously for this public release', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'go-public-c-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const root = new URL('../../../', import.meta.url)
+ const tag = 'v1.2.3'
+ const goRef = 'refs/tags/sdks/go/' + tag
+ const git = (...args) => execFileSync('git', args, { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
+ git('init', '--bare', 'origin.git')
+ git('init')
+ git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgSign=false', 'commit', '--allow-empty', '-m', 'source')
+ const sha = git('rev-parse', 'HEAD')
+ git('remote', 'add', 'origin', join(dir, 'origin.git'))
+ git('push', 'origin', sha + ':refs/tags/' + tag)
+ for (const path of ['apps/infra/scripts/release-candidate.mjs', '.github/ci-config.json']) {
+ mkdirSync(dirname(join(dir, path)), { recursive: true })
+ copyFileSync(new URL(path, root), join(dir, path))
+ }
+
+ const targets = JSON.parse(readFileSync(new URL('.github/ci-config.json', root))).platforms
+ const assets = targets.map(({ target }) => {
+ const name = 'boxlite-c-' + tag + '-' + target + '.tar.gz'
+ return { name, size: name.length, state: 'uploaded', digest: 'sha256:' + createHash('sha256').update(name).digest('hex') }
+ })
+ writeFileSync(join(dir, 'gh'), [
+ '#!/bin/sh',
+ 'case "$*" in',
+ ' "api repos/boxlite-ai/boxlite/releases/123") cat "$FIXTURE/release.json" ;;',
+ ' *"/releases/123/assets?per_page=100") cat "$FIXTURE/assets.json" ;;',
+ ' *) exit 2 ;;',
+ 'esac',
+ ].join('\n'), { mode: 0o755 })
+ writeFileSync(join(dir, 'public-fetch.mjs'), `
+ globalThis.fetch = async (url, options) => {
+ const request = new Request(url, options)
+ const base = 'https://github.com/boxlite-ai/boxlite/releases/download/v1.2.3/'
+ if (!request.url.startsWith(base) || request.method !== 'GET' || request.headers.has('authorization')) throw Error('unexpected request')
+ const name = request.url.slice(base.length)
+ if (name === process.env.UNAVAILABLE) return new Response(null, { status: 404 })
+ return new Response(name === process.env.CORRUPT ? 'wrong bytes' : name)
+ }
+ `)
+ const steps = release.jobs['tag-go-module'].steps.filter(step => step.run).map(step => step.run)
+ function publish({ draft = false, files = assets, ...extra } = {}) {
+ writeFileSync(join(dir, 'release.json'), JSON.stringify({ tag_name: tag, draft }))
+ writeFileSync(join(dir, 'assets.json'), JSON.stringify([files]))
+ return spawnSync('bash', ['-ec', steps.join('\n')], { cwd: dir, encoding: 'utf8',
+ env: { ...process.env, FIXTURE: dir, PATH: dir + ':' + process.env.PATH, GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
+ TAG: tag, RELEASE_TAG: tag, RELEASE_ID: '123', C_SHA: sha, NODE_OPTIONS: '--import=' + join(dir, 'public-fetch.mjs'), ...extra },
+ })
+ }
+ for (const [reason, options] of [
+ ['draft', { draft: true }], ['missing asset', { files: assets.slice(1) }],
+ ['anonymous 404', { UNAVAILABLE: assets.at(-1).name }], ['wrong bytes', { CORRUPT: assets[0].name }],
+ ]) {
+ const result = publish(options)
+ assert.equal(git('ls-remote', '--refs', 'origin', goRef), '', 'Go tag was pushed for ' + reason)
+ assert.notEqual(result.status, 0, reason)
+ }
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const result = publish()
+ assert.equal(result.status, 0, result.stderr)
+ assert.equal(git('ls-remote', '--refs', 'origin', goRef), sha + '\t' + goRef)
+ }
+})
+
+test('publication gates accept a skipped optional ancestor and require successful direct prerequisites', () => {
+ for (const [id, prerequisites, commands] of [
+ ['npm', ['attach'], ['publish', 'publish-node', 'repair-node']],
+ ['pypi', ['attach'], ['publish', 'publish-wheels', 'repair-wheels']],
+ ['tag-go-module', ['finalize'], ['publish', 'publish-go']],
+ ['finalize', ['npm', 'pypi', 'attach'], ['publish']],
+ ['publish_crates', ['finalize'], ['publish', 'publish-runtime']],
+ ]) {
+ const condition = expression(release.jobs[id].if)
+ const evaluate = new Function('github', 'inputs', 'needs', 'cancelled', 'contains', 'fromJSON',
+ 'return ' + condition.replace(/needs\.([\w]+-[\w-]+)/g, "needs['$1']"))
+ const needs = Object.fromEntries(release.jobs[id].needs.map((name) => [name, { result: 'success' }]))
+ needs.resolve.outputs = { public_release: 'true' }
+ const selected = (command, cancelled = false, ref = 'refs/heads/main') => {
+ // GitHub implicitly adds success() when the condition omits a status function.
+ if (!/\b(success|failure|always|cancelled)\(/.test(condition)) return false
+ return evaluate({ ref }, { command }, needs, () => cancelled, (a, b) => a.includes(b), JSON.parse)
+ }
+ for (const command of release.on.workflow_dispatch.inputs.command.options) {
+ assert.equal(selected(command), commands.includes(command), id + ' on ' + command)
+ }
+ for (const name of prerequisites) {
+ needs[name] ??= { result: 'success' }
+ for (const result of ['skipped', 'failure', 'cancelled']) {
+ needs[name].result = result
+ assert.equal(selected('publish'), false, id + ' after ' + name + ' ' + result)
+ }
+ needs[name].result = 'success'
+ }
+ assert.equal(selected('publish', true), false)
+ assert.equal(selected('publish', false, 'refs/heads/topic'), false)
+ }
+})
+
+test('single components select their producers and bypass rollout, including with skipped sibling jobs', () => {
+ for (const [component, group] of Object.entries({ runtime: 'runtime-distribution', wheels: 'wheels-', node: 'node-packages', c: 'c-sdk-', go: '', runner: 'runner-linux-amd64' })) {
+ const command = 'publish-' + component
+ for (const buildOnly of [true, false]) {
+ const selection = selectRelease(command, buildOnly, '', '')
+ assert.equal(selection.group, group)
+ const needs = Object.fromEntries(Object.keys(release.jobs).map(id => [id, { result: 'skipped', outputs: {} }]))
+ needs.resolve = { result: 'success', outputs: { ...selection, builds: JSON.stringify(selection.builds) } }
+ const allows = id => {
+ const job = release.jobs[id]
+ const deps = [job.needs || []].flat()
+ const condition = expression(job.if).replaceAll('needs.*.result', 'results').replace(/needs\.([\w]+-[\w-]+)/g, "needs['$1']")
+ const statuses = deps.map(dep => needs[dep].result)
+ if (!condition.includes('cancelled()') && statuses.some(result => result !== 'success')) return false
+ const evaluate = new Function('needs','results','inputs','github','contains','fromJSON','cancelled','return ' + condition)
+ return Boolean(evaluate(needs, statuses, { command, 'build-only': buildOnly }, { ref: 'refs/heads/main' }, (a,b) => a.includes(b), JSON.parse, () => false))
+ }
+ const enabled = []
+ for (const id of ['build-runtime','build-wheels','build-node','build-c','build-go','build-runner-binary','publish','publish-runner','distribution','accepted-candidate','dev','attach','npm','pypi','prod','finalize','tag-go-module','publish_crates']) {
+ if (allows(id)) { enabled.push(id); needs[id].result = 'success' }
+ }
+ const expected = ['go','runner'].includes(component) ? ['build-c'] : []
+ expected.push(component === 'runner' ? 'build-runner-binary' : 'build-' + component)
+ if (!buildOnly) {
+ if (component === 'runner') expected.push('publish-runner')
+ if (group) expected.push('distribution','attach')
+ if (component === 'node') expected.push('npm')
+ if (component === 'wheels') expected.push('pypi')
+ if (component === 'go') expected.push('tag-go-module')
+ }
+ assert.deepEqual(enabled, expected, command + ' build-only=' + buildOnly)
+ if (!buildOnly && group) {
+ needs[selection.producer].result = 'failure'
+ assert.equal(allows('distribution'), false, 'failed ' + component + ' must block publication')
+ }
+ if (!buildOnly && component === 'runtime') {
+ needs.resolve.outputs.public_release = 'true'
+ assert.equal(allows('publish_crates'), true)
+ }
+ }
+ }
+ assert.throws(() => selectRelease('publish-c', false, '', 'feature'))
+ assert.throws(() => selectRelease('repair-node', false, '', ''))
+ assert.throws(() => selectRelease('publish-runner', false, '3', ''))
+})
diff --git a/apps/infra/scripts/runtime-attachment.test.mjs b/apps/infra/scripts/runtime-attachment.test.mjs
new file mode 100644
index 000000000..1f404380e
--- /dev/null
+++ b/apps/infra/scripts/runtime-attachment.test.mjs
@@ -0,0 +1,89 @@
+import assert from 'node:assert/strict'
+import { createHash } from 'node:crypto'
+import { spawnSync } from 'node:child_process'
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import test from 'node:test'
+import { load } from 'js-yaml'
+
+const digest = (data) => 'sha256:' + createHash('sha256').update(data).digest('hex')
+test('publishing a runtime includes each sidecar once and resumes without replacing it', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'release-upload-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ const bundle = join(dir, 'dist')
+ mkdirSync(bundle)
+ const files = ['boxlite-runtime-v1.2.3-linux.tar.gz', 'boxlite-cli-v1.2.3-linux.tar.gz', 'install.sh']
+ const names = [...files, ...files.map((f) => f + '.sha256'), 'SHA256SUMS']
+ const assets = {}
+ for (const name of names) {
+ writeFileSync(join(bundle, name), name)
+ assets[name] = { group: 'runtime-distribution', digest: digest(name) }
+ }
+ const tag = 'v1.2.3'
+ const sha = 'a'.repeat(40)
+ const receipt = JSON.stringify({ tag, sha, assets })
+ writeFileSync(join(bundle, 'release-candidate.json'), receipt)
+ const gh = join(dir, 'gh')
+ writeFileSync(join(dir, 'uploads'), '')
+ writeFileSync(
+ gh,
+ `#!/usr/bin/env node
+const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
+const args=process.argv.slice(2), ledger=process.env.LEDGER;
+if(args.includes('PATCH')) {if(!args.includes('draft=false')||!args.includes('prerelease=false'))process.exit(10); fs.appendFileSync(ledger+'.patch','P'); fs.writeFileSync(ledger+'.public','1'); process.exit(9)}
+else if(args[0]==='release' && args[1]==='upload') fs.appendFileSync(ledger,path.basename(args[3])+'\\n');
+else if(args.at(-1).endsWith('/assets?per_page=100')) console.log(JSON.stringify([fs.readFileSync(ledger,'utf8').split('\\n').filter(Boolean).map(name=>({name,state:'uploaded',digest:'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(process.env.RELEASE_ASSET_DIR,name))).digest('hex')}))]));
+else if(args.at(-1).includes('/commits/')) console.log(JSON.stringify({sha:process.env.SHA}));
+else if(args.at(-1).endsWith('/releases/1')) console.log(JSON.stringify({tag_name:process.env.TAG,draft:!fs.existsSync(ledger+'.public')}));
+else process.exit(9);
+`,
+ { mode: 0o755 },
+ )
+ const env = {
+ ...process.env,
+ PATH: dir + ':' + process.env.PATH,
+ RELEASE_ASSET_DIR: bundle,
+ TAG: tag,
+ SHA: sha,
+ CANDIDATE_DIGEST: digest(receipt),
+ RELEASE_ID: '1',
+ GITHUB_REPOSITORY: 'boxlite-ai/boxlite',
+ LEDGER: join(dir, 'uploads'),
+ }
+ const code = new URL('./release-candidate.mjs', import.meta.url)
+ for (const scope of ['', '', 'runtime-distribution']) {
+ const r = spawnSync(process.execPath, [resolve(code.pathname), 'attach'], {
+ cwd: dir,
+ env: { ...env, REPAIR_GROUP: scope },
+ encoding: 'utf8',
+ })
+ assert.equal(r.status, 0, r.stderr)
+ }
+ assert.deepEqual(
+ readFileSync(env.LEDGER, 'utf8').trim().split('\n').sort(),
+ [...names, 'release-candidate.json'].sort(),
+ )
+ const workflow = load(readFileSync(new URL('../../../.github/workflows/mbuild-release.yml', import.meta.url), 'utf8'))
+ const finalize = workflow.jobs.finalize.steps
+ .at(-1)
+ .run.replace('apps/infra/scripts/release-candidate.mjs', JSON.stringify(code.pathname))
+ const run = () => spawnSync('bash', ['-ec', finalize], { cwd: dir, env, encoding: 'utf8' })
+ assert.notEqual(run().status, 0, 'simulate a lost response to the publication request')
+ assert.equal(readFileSync(env.LEDGER + '.public', 'utf8'), '1')
+ let result = run()
+ assert.equal(result.status, 0, result.stderr)
+ assert.equal(readFileSync(env.LEDGER + '.patch', 'utf8'), 'P', 'retry must only verify the public release')
+ assert.deepEqual(
+ readFileSync(env.LEDGER, 'utf8').trim().split('\n').sort(),
+ [...names, 'release-candidate.json'].sort(),
+ )
+ writeFileSync(env.LEDGER, names.join('\n') + '\n')
+ result = run()
+ assert.notEqual(result.status, 0, 'incomplete public release must fail')
+ assert.equal(
+ readFileSync(env.LEDGER, 'utf8').trim().split('\n').length,
+ names.length,
+ 'public release must be read-only',
+ )
+})
diff --git a/scripts/ci/install-e2e-release.sh b/scripts/ci/install-e2e-release.sh
index 5b0c06987..5af81619c 100644
--- a/scripts/ci/install-e2e-release.sh
+++ b/scripts/ci/install-e2e-release.sh
@@ -14,6 +14,10 @@ case "$component" in
esac
if [[ "$component" == validate ]]; then
+ if [[ -n "${RELEASE_ASSET_DIR:-}" ]]; then
+ jq -e --arg tag "$tag" '.tag == $tag' "$RELEASE_ASSET_DIR/release-candidate.json" >/dev/null
+ exit 0
+ fi
published=$(gh release view "$tag" --repo boxlite-ai/boxlite \
--json tagName,isDraft --jq 'select(.isDraft == false) | .tagName')
[[ "$published" == "$tag" ]] || { echo "release $tag is not published" >&2; exit 1; }
@@ -25,6 +29,10 @@ scratch=$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/e2e-release.XXXXXX")
trap 'rm -rf "$scratch"' EXIT
version=${tag#v}
download() {
+ if [[ -n "${RELEASE_ASSET_DIR:-}" ]]; then
+ cp -- "$RELEASE_ASSET_DIR/$1" "$scratch/$1"
+ return
+ fi
gh release download "$tag" --repo boxlite-ai/boxlite --pattern "$1" --dir "$scratch"
}
@@ -58,9 +66,18 @@ case "$component" in
)
;;
cli)
- download install.sh
install_dir="$root/target/e2e-bin"
- BOXLITE_VERSION="$tag" BOXLITE_INSTALL_DIR="$install_dir" sh "$scratch/install.sh"
+ if [[ -n "${RELEASE_ASSET_DIR:-}" ]]; then
+ archive="boxlite-cli-$tag-x86_64-unknown-linux-gnu.tar.gz"
+ download "$archive"
+ download "$archive.sha256"
+ (cd "$scratch" && sha256sum --check --strict "$archive.sha256")
+ mkdir -p "$install_dir"
+ tar xzf "$scratch/$archive" -C "$install_dir" boxlite
+ else
+ download install.sh
+ BOXLITE_VERSION="$tag" BOXLITE_INSTALL_DIR="$install_dir" sh "$scratch/install.sh"
+ fi
"$install_dir/boxlite" --version
echo "$install_dir" >> "${GITHUB_PATH:?GITHUB_PATH is required}"
;;
diff --git a/scripts/release/test_install.sh b/scripts/release/test_install.sh
index d4da3ce7a..991b53b09 100755
--- a/scripts/release/test_install.sh
+++ b/scripts/release/test_install.sh
@@ -135,14 +135,14 @@ if ! awk '
exit 1
fi
-# Structural test: release upload must ship install.sh.sha256 too, otherwise
-# the sidecar exists in CI but never reaches the release page.
+# The complete runtime distribution, including the verified installer sidecar,
+# must enter the candidate that acceptance and publication share.
if ! awk '
- /^ - name: Upload to release/ { in_block = 1; next }
+ /^ - name: Stage release files/ { in_block = 1; next }
in_block && /^ - name: / { exit }
in_block { print }
-' "$workflow" | grep -E 'dist/install\.sh\.sha256' >/dev/null; then
- echo "FAIL: release upload does not include dist/install.sh.sha256" >&2
+' "$workflow" | grep -Eq '^ path: dist/$'; then
+ echo "FAIL: runtime distribution does not stage the verified dist directory" >&2
exit 1
fi
diff --git a/scripts/release/verify-pypi-wheels.sh b/scripts/release/verify-pypi-wheels.sh
new file mode 100644
index 000000000..2c4350ecd
--- /dev/null
+++ b/scripts/release/verify-pypi-wheels.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: AGPL-3.0-only
+set -euo pipefail
+mode=${1:?expected before or after}
+[[ "$mode" == before || "$mode" == after ]]
+[[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]
+index=$(mktemp)
+trap 'rm -f "$index"' EXIT
+status=$(curl -sS --retry 5 --retry-all-errors -o "$index" -w '%{http_code}' "https://pypi.org/pypi/boxlite/${TAG#v}/json")
+if [[ "$status" == 404 && "$mode" == before ]]; then exit 0; fi
+[[ "$status" == 200 ]] || { echo "PyPI lookup for $TAG returned HTTP $status" >&2; exit 1; }
+jq -e '.urls | type == "array"' "$index" >/dev/null
+for wheel in dist/*.whl; do
+ sha=$(sha256sum "$wheel" | cut -d' ' -f1)
+ jq -e --arg name "${wheel##*/}" --arg sha "$sha" --arg mode "$mode" '
+ [.urls[] | select(.filename == $name)] |
+ if length == 0 then $mode == "before" else all(.[]; .digests.sha256 == $sha) end' "$index" >/dev/null ||
+ { echo "PyPI has a missing or conflicting accepted wheel: ${wheel##*/}" >&2; exit 1; }
+done
diff --git a/tests/scripts/test_e2e_release.py b/tests/scripts/test_e2e_release.py
index 7f518f5f2..c5fae1da7 100644
--- a/tests/scripts/test_e2e_release.py
+++ b/tests/scripts/test_e2e_release.py
@@ -102,6 +102,18 @@ class ReleaseInstallTest(unittest.TestCase):
self.assertIn("stable vX.Y.Z", result.stderr)
self.assertEqual(calls, [])
+ def test_draft_acceptance_installs_the_staged_wheel(self):
+ abi = f"cp{sys.version_info.major}{sys.version_info.minor}"
+ wheel = self.assets / f"boxlite-0.13.1-{abi}-{abi}-manylinux_2_28_x86_64.whl"
+ wheel.write_bytes(b"candidate wheel")
+ result, calls = self.run_install("python", RELEASE_ASSET_DIR=str(self.assets), FAIL_TOOL="gh")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual([call["tool"] for call in calls], ["pip"])
+ wheel.unlink()
+ result, calls = self.run_install("python", RELEASE_ASSET_DIR=str(self.assets))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual([call["tool"] for call in calls], ["pip"])
+
def test_validates_exact_published_release_and_propagates_lookup_failure(self):
result, calls = self.run_install("validate")
self.assertEqual(result.returncode, 0, result.stderr)