Skip to content

AI-native design editor. Open-source Figma alternative.

ci: unify verified release builds (#711)

Danila Poyarkovc4a3dae2a44b
diff --git a/.github/actions/setup-bun/README.md b/.github/actions/setup-bun/README.md
new file mode 100644
index 000000000..2746d4069
--- /dev/null
+++ b/.github/actions/setup-bun/README.md
@@ -0,0 +1,24 @@
+# Bun workspace setup and release caching
+
+This action installs the manifest-selected Bun version, restores its package download cache, and always runs `bun install`. It does not cache `node_modules` or skip frozen-lockfile installation on a cache hit.
+
+- `cache-scope` separates independent workflow groups; the default is `workspace`.
+- Keys include the runner OS and host architecture, not the cross-compilation target, plus `bun.lock`. Fallbacks preserve scope, OS and architecture.
+- `cache-save: 'false'` makes a consumer restore-only. A writer saves immediately after successful installation, using the restore action's primary key, only on an exact-key miss. No dependency cache post-step runs after a long build.
+- The desktop matrix designates one writer per host platform. The macOS Intel cross-build and Windows ARM64 cross-build are readers; package publication also reads the desktop Linux cache. This assumes both macOS entries use the same host architecture, as configured with `macos-latest`; revisit writer selection if runner labels change.
+- Bun executable caching is disabled explicitly. Dependency caching remains enabled, avoiding a separate executable cache upload lifecycle.
+
+Rust release caching uses `desktop -> target`: `target` is relative to the Cargo workspace. The Rust action retains compiler/environment keys and the explicit target key; different target artifacts must not be mixed.
+
+## Limits
+
+GitHub isolates caches by ref. One release tag cannot restore another tag's caches. The corrected Rust path benefits retries and compatible caches from the default branch, but does not alone make every future release warm. To seed caches for later tags, manually run the existing Build workflow on `master` with the same toolchain/targets. That dispatch does not publish npm packages or create a tagged release; it does run the full desktop build matrix. This change does not schedule or launch such a warm-up automatically.
+
+Other callers retain the default writer behavior. Concurrent writers in the general `workspace` scope may still race; the single-writer policy here is specifically for the desktop release matrix, not a repository-wide cache scheduler.
+
+## Upstream references
+
+- [Rust cache workspace and key configuration](https://github.com/Swatinem/rust-cache#example-usage).
+- [setup-bun inputs, including executable caching](https://github.com/oven-sh/setup-bun#inputs).
+- [Restore-only cache action](https://github.com/actions/cache/blob/main/restore/README.md).
+- [GitHub cache scope restrictions](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching#restrictions-for-accessing-a-cache).
diff --git a/.github/actions/setup-bun/action.yml b/.github/actions/setup-bun/action.yml
index 62d362bec..694c5acd0 100644
--- a/.github/actions/setup-bun/action.yml
+++ b/.github/actions/setup-bun/action.yml
@@ -12,6 +12,15 @@ inputs:
required: false
default: 'false'
+ cache-save:
+ description: Save the dependency cache; set false for other jobs sharing the same cache key.
+ required: false
+ default: 'true'
+ cache-scope:
+ description: Separate dependency caches for independently running workflow groups.
+ required: false
+ default: workspace
+
runs:
using: composite
steps:
@@ -24,13 +33,24 @@ runs:
head -c 4 tests/fixtures/material3.fig | xxd
- uses: oven-sh/setup-bun@v2
+ with:
+ # Avoid a second cache/upload lifecycle for the small Bun executable.
+ no-cache: true
- - uses: actions/cache@v6
+ - uses: actions/cache/restore@v6
+ id: dependencies
with:
path: ~/.bun/install/cache
- key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
- restore-keys: bun-${{ runner.os }}-
+ key: bun-${{ inputs.cache-scope }}-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('bun.lock') }}
+ restore-keys: bun-${{ inputs.cache-scope }}-${{ runner.os }}-${{ runner.arch }}-
- name: Install dependencies
shell: bash
run: bun install ${{ inputs.install-args }}
+
+ - name: Save dependency cache
+ if: inputs.cache-save == 'true' && steps.dependencies.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v6
+ with:
+ path: ~/.bun/install/cache
+ key: ${{ steps.dependencies.outputs.cache-primary-key }}
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 0b6f492fb..aff8ee1dc 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -2,75 +2,166 @@ name: Build
on:
workflow_dispatch:
+ inputs:
+ tag:
+ description: Existing stable release tag to rebuild without moving it (vX.Y.Z).
+ required: true
+ type: string
push:
tags:
- 'v*'
permissions:
- contents: write
- id-token: write
+ contents: read
+
+concurrency:
+ group: release-${{ inputs.tag || github.ref_name }}
+ cancel-in-progress: false
+
+env:
+ WORKFLOW_COMMIT: ${{ github.workflow_sha }}
jobs:
- build:
+ plan:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ tag: ${{ steps.release.outputs.tag }}
+ version: ${{ steps.release.outputs.version }}
+ source: ${{ steps.release.outputs.source }}
+ matrix: ${{ steps.release.outputs.matrix }}
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.workflow_sha }}
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: ./.github/actions/setup-bun
+ - id: release
+ name: Resolve immutable source and native matrix
+ env:
+ RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
+ run: bun tools/release-packages/src/native/resolve.ts
+
+ frontend:
+ needs: plan
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ outputs:
+ sha256: ${{ steps.frontend.outputs.sha256 }}
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ needs.plan.outputs.source }}
+ persist-credentials: false
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.workflow_sha }}
+ path: .pipeline
+ persist-credentials: false
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 24.x
+ - uses: ./.pipeline/.github/actions/setup-bun
+ with:
+ cache-scope: desktop
+ - name: Install pinned workflow tooling
+ run: bun install --cwd .pipeline --frozen-lockfile
+ - name: Build shared desktop frontend and package outputs
+ run: |
+ bun run generate:icons --target desktop
+ bun run generate:tauri-menu
+ bun run build
+ - name: Prepare and validate npm tarballs
+ run: |
+ bun .pipeline/tools/release-packages/src/cli.ts prepare
+ bun .pipeline/tools/release-packages/src/cli.ts pack
+ - name: Extract exact release notes
+ env:
+ RELEASE_VERSION: ${{ needs.plan.outputs.version }}
+ run: bun .pipeline/tools/release-packages/src/extract-release-notes.ts "$RELEASE_VERSION" release-notes.md
+ - name: Archive platform-independent native inputs
+ id: frontend
+ run: |
+ tar -cf frontend.tar dist desktop/icons desktop/generated
+ echo "sha256=$(sha256sum frontend.tar | cut -d ' ' -f 1)" >> "$GITHUB_OUTPUT"
+ - uses: actions/upload-artifact@v7
+ with:
+ name: release-frontend
+ path: |
+ frontend.tar
+ release-notes.md
+ if-no-files-found: error
+ compression-level: 0
+ - uses: actions/upload-artifact@v7
+ with:
+ name: release-npm
+ path: .npm-packages/*.tgz
+ include-hidden-files: true
+ if-no-files-found: error
+ compression-level: 0
+
+ native:
+ needs: [plan, frontend]
strategy:
fail-fast: false
- matrix:
- include:
- - platform: macos-latest
- target: aarch64-apple-darwin
- label: macos-arm64
- - platform: macos-latest
- target: x86_64-apple-darwin
- label: macos-x64
- - platform: windows-latest
- target: x86_64-pc-windows-msvc
- label: windows-x64
- - platform: windows-latest
- target: aarch64-pc-windows-msvc
- label: windows-arm64
- - platform: ubuntu-22.04
- target: x86_64-unknown-linux-gnu
- label: linux-x64
-
+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
runs-on: ${{ matrix.platform }}
+ timeout-minutes: 40
+ env:
+ RELEASE_TAG: ${{ needs.plan.outputs.tag }}
+ SOURCE_COMMIT: ${{ needs.plan.outputs.source }}
+ FRONTEND_SHA256: ${{ needs.frontend.outputs.sha256 }}
+ RELEASE_TARGET: ${{ matrix.target }}
steps:
- uses: actions/checkout@v7
-
+ with:
+ ref: ${{ needs.plan.outputs.source }}
+ persist-credentials: false
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.workflow_sha }}
+ path: .pipeline
+ persist-credentials: false
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 24.x
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
-
- uses: Swatinem/rust-cache@v2
with:
- workspaces: desktop/src-tauri -> target
+ workspaces: desktop -> target
key: ${{ matrix.target }}
-
- - name: Install dependencies (Linux)
- if: startsWith(matrix.platform, 'ubuntu')
+ - name: Install native dependencies on Linux
+ if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
-
- - uses: ./.github/actions/setup-bun
-
- - name: Extract release notes
- if: startsWith(github.ref, 'refs/tags/v')
- id: changelog
- shell: bash
+ - uses: ./.pipeline/.github/actions/setup-bun
+ with:
+ cache-scope: desktop
+ cache-save: ${{ matrix.saveBunCache && runner.os != 'Linux' }}
+ - name: Install pinned workflow tooling
+ run: bun install --cwd .pipeline --frozen-lockfile
+ - uses: actions/download-artifact@v8
+ with:
+ name: release-frontend
+ - name: Verify shared inputs and disable only the redundant build hook
+ run: bun .pipeline/tools/release-packages/src/native/frontend.ts
+ - name: Extract shared frontend, icons and menu
+ run: tar -xf frontend.tar
+ - name: Verify Node and Tauri startup
+ timeout-minutes: 1
run: |
- VERSION="${GITHUB_REF_NAME#v}"
- NOTES_FILE="$RUNNER_TEMP/release-notes.md"
- bun tools/release-packages/src/extract-release-notes.ts "$VERSION" "$NOTES_FILE"
- EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
- echo "release_notes<<$EOF" >> "$GITHUB_OUTPUT"
- cat "$NOTES_FILE" >> "$GITHUB_OUTPUT"
- echo "$EOF" >> "$GITHUB_OUTPUT"
-
- - name: Build Tauri
+ node --version
+ node node_modules/@tauri-apps/cli/tauri.js --version
+ - name: Build and sign native bundles (no release uploads)
+ id: tauri
+ timeout-minutes: 30
uses: tauri-apps/tauri-action@v0
env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY || '' }}
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD || '' }}
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
@@ -78,40 +169,86 @@ jobs:
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
with:
- tauriScript: bunx tauri
- args: --target ${{ matrix.target }}
- tagName: ${{ startsWith(github.ref, 'refs/tags/v') && github.ref_name || '' }}
- releaseName: ${{ startsWith(github.ref, 'refs/tags/v') && github.ref_name || '' }}
- releaseBody: ${{ steps.changelog.outputs.release_notes }}
- releaseDraft: true
- uploadUpdaterJson: true
- uploadUpdaterSignatures: true
+ tauriScript: node node_modules/@tauri-apps/cli/tauri.js
+ args: --target ${{ matrix.target }} --config "${{ github.workspace }}/release-build-config.json" --verbose
+ retryAttempts: 0
+ - name: Collect only reported bundles and signatures
+ env:
+ TAURI_ARTIFACT_PATHS: ${{ steps.tauri.outputs.artifactPaths }}
+ run: bun .pipeline/tools/release-packages/src/native/collect.ts
+ - uses: actions/upload-artifact@v7
+ with:
+ name: native-${{ matrix.target }}
+ path: native-output/*
+ if-no-files-found: error
+ compression-level: 0
- publish-npm:
- if: startsWith(github.ref, 'refs/tags/v')
- needs: build
+ publish:
+ needs: [plan, frontend, native]
runs-on: ubuntu-latest
+ timeout-minutes: 25
permissions:
- contents: read
+ contents: write
id-token: write
+ attestations: write
+ env:
+ RELEASE_TAG: ${{ needs.plan.outputs.tag }}
+ SOURCE_COMMIT: ${{ needs.plan.outputs.source }}
+ FRONTEND_SHA256: ${{ needs.frontend.outputs.sha256 }}
+ GH_TOKEN: ${{ github.token }}
steps:
- uses: actions/checkout@v7
-
+ with:
+ ref: ${{ needs.plan.outputs.source }}
+ persist-credentials: false
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.workflow_sha }}
+ path: .pipeline
+ persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: 24.x
registry-url: https://registry.npmjs.org/
-
- - uses: ./.github/actions/setup-bun
-
- - name: Build packages for publish
- run: bun tools/release-packages/src/cli.ts build
-
- - name: Prepare publish directories
- run: bun tools/release-packages/src/cli.ts prepare
-
- - name: Pack and validate packages for publish
- run: bun tools/release-packages/src/cli.ts pack
-
- - name: Publish verified packages to npm
- run: bun tools/release-packages/src/cli.ts publish
+ - uses: ./.pipeline/.github/actions/setup-bun
+ with:
+ cache-scope: desktop
+ cache-save: 'false'
+ - name: Install pinned workflow tooling
+ run: bun install --cwd .pipeline --frozen-lockfile
+ - uses: actions/download-artifact@v8
+ with:
+ name: release-frontend
+ - uses: actions/download-artifact@v8
+ with:
+ name: release-npm
+ path: .npm-packages
+ - uses: actions/download-artifact@v8
+ with:
+ pattern: native-*
+ path: native-artifacts
+ - name: Install signature verifier
+ run: sudo apt-get update && sudo apt-get install -y minisign
+ - name: Verify all targets, digests and updater signatures
+ run: bun .pipeline/tools/release-packages/src/native/assemble.ts
+ - name: Refuse published releases or moved tags
+ run: bun .pipeline/tools/release-packages/src/native/publish.ts check
+ - name: Attest the complete binary set and source/workflow manifest
+ id: provenance
+ uses: actions/attest@v4
+ with:
+ subject-path: release-output/*
+ - name: Verify attestations against the pinned workflow
+ env:
+ ATTESTATION_BUNDLE: ${{ steps.provenance.outputs.bundle-path }}
+ run: |
+ for artifact in release-output/*; do
+ gh attestation verify "$artifact" --bundle "$ATTESTATION_BUNDLE" \
+ --repo "$GITHUB_REPOSITORY" \
+ --signer-workflow "$GITHUB_REPOSITORY/.github/workflows/build.yml" \
+ --signer-digest "$WORKFLOW_COMMIT" --deny-self-hosted-runners
+ done
+ - name: Publish verified npm artifacts with provenance
+ run: bun .pipeline/tools/release-packages/src/cli.ts publish
+ - name: Replace and verify the entire draft asset set
+ run: bun .pipeline/tools/release-packages/src/native/publish.ts upload
diff --git a/AGENTS.md b/AGENTS.md
index 1f1077caa..1071683fe 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -89,7 +89,7 @@ Browser tests use the canonical `playwright.config.ts`; do not create task-speci
For releases, update versions in the root and publishable package manifests plus `desktop/tauri.conf.json` and `desktop/Cargo.toml`; move `Unreleased` into `## x.y.z — YYYY-MM-DD`; commit `Release vX.Y.Z`; then tag and push `vX.Y.Z`.
-`.github/workflows/build.yml` is the source of truth: `v*` tags build signed desktop artifacts, create a draft release from the exact changelog section, upload updater files, and publish the public workspace packages discovered by `tools/package-artifacts/src/catalog.ts`. Bun source exports require the complete `src` directory in package contents; Node exports continue to use `dist`. Release preparation must preserve resolution maps. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks—do not publish package directories manually. Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title/body and artifacts, then publish it; `homebrew.yml` updates the cask on publication.
+`.github/workflows/build.yml` is the source of truth: `v*` tags (or dispatches for an immutable stable tag) build shared frontend/package outputs once, build signed desktop artifacts in parallel, verify and attest one complete same-run artifact set, publish npm packages, and replace the draft release assets using the exact changelog section. Native release policy and recovery rules live in `tools/release-packages/README.md`; workflow and application source commits are recorded separately. Public workspace packages are discovered by the package-artifacts catalog. Bun source exports require the complete `src` directory in package contents; Node exports continue to use `dist`. Release preparation must preserve resolution maps. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks—do not publish package directories manually. Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title/body and artifacts, then publish it; `homebrew.yml` updates the cask on publication.
App/docs production workflows run on `v*` tags or `workflow_dispatch`, not ordinary `master` pushes. `ci.yml` and `heavy-tests.yml` define validation gates.
diff --git a/bun.lock b/bun.lock
index 6f7091d45..88044f094 100644
--- a/bun.lock
+++ b/bun.lock
@@ -445,6 +445,8 @@
"@open-pencil/package-artifacts": "workspace:*",
"@open-pencil/package-quality-tools": "workspace:*",
"citty": "^0.1.6",
+ "es-toolkit": "^1.51.0",
+ "valibot": "^1.4.2",
},
},
"tools/visual-oracles": {
diff --git a/tools/release-packages/README.md b/tools/release-packages/README.md
new file mode 100644
index 000000000..853894c1d
--- /dev/null
+++ b/tools/release-packages/README.md
@@ -0,0 +1,41 @@
+# Release packages and native artifacts
+
+`src/workflow.ts` owns npm release policy and reuses package-artifacts/package-quality mechanics. `src/native/` owns desktop release orchestration. Cross-directory imports within this package use `#release/*`; sibling modules remain relative.
+
+## Canonical release workflow
+
+`.github/workflows/build.yml` runs on a new stable tag, or through `workflow_dispatch` with an existing `vX.Y.Z` tag. A dispatch uses the selected workflow revision but builds the immutable application commit resolved from that tag. The source must be an ancestor of `origin/master`.
+
+1. **Plan:** resolve the source commit and generate the native matrix from `native/catalog.ts`.
+2. **Frontend:** build packages and the desktop frontend once; prepare and pack npm archives without rebuilding. Archive `dist`, desktop icons, and generated menus together and record its SHA-256.
+3. **Native:** five independent jobs check out that same source, verify and extract the shared inputs, then build through Node's Tauri CLI launcher. A generated config sets only `build.beforeBuildCommand` to `null`; the checked-in local build hook is unchanged. No native job uploads release assets.
+4. **Publish:** require the complete matrix with identical source/workflow/run/attempt/frontend identity. Verify file inventories, hashes, every updater signature, and exact source changelog notes. Generate the updater JSON, source/workflow manifest, and checksums; attest and verify the complete output set. Verify npm consumers and publish the original tarballs with npm provenance. Replace every expected draft asset, then download and verify all uploaded bytes.
+
+Workflow tooling is checked out separately in `.pipeline` and installed from its own frozen lockfile where it runs. Application dependency installation and builds remain owned by the tagged checkout; rebuilding an older tag must not accidentally execute its older release orchestration. Dependency installation is not frontend/package compilation.
+
+The workflow leaves the GitHub Release **draft**. After successful verification, publish it with the exact tagged changelog body and publish any accompanying security advisory separately. Never move a release tag to repair CI.
+
+## Artifact policy and provenance
+
+`native/catalog.ts` is OpenPencil's required asset/naming policy, not a replacement for Tauri artifact discovery. Collection consumes `tauri-action`'s `artifactPaths` output and refuses missing, duplicate, unexpected, empty, or escaping files. The macOS `.app` directory is ignored in favor of its required signed archive. Stable architecture-qualified macOS archive names are preserved.
+
+GitHub's default provenance identifies the **workflow execution revision**, which can differ from the tagged application source in a manual rebuild. The independently attested `release-manifest.json` records both commits, the workflow run/attempt, shared frontend digest, target file digests, and npm tarball digests. Do not describe the default workflow provenance alone as proof of the application's checked-out source. npm also emits its own provenance from the same workflow execution; the signed manifest binds its exact tarballs to the application source.
+
+Verify downloaded release files with:
+
+```sh
+gh attestation verify release-manifest.json --repo open-pencil/open-pencil \
+ --signer-workflow open-pencil/open-pencil/.github/workflows/build.yml \
+ --deny-self-hosted-runners
+sha256sum --check SHA256SUMS
+```
+
+Each release asset, including `SHA256SUMS`, also has its own attestation. For a pinned audit, pass the independently obtained workflow commit to `--signer-digest`; compare the attested manifest's source commit with the immutable tag. Do not treat an unverified manifest as trusted configuration.
+
+## Failure and recovery
+
+- There are explicit job/build/startup/command deadlines. Native builds do not silently retry or upload partial release outputs.
+- Missing or mixed matrix identities stop publication. Rerun **all jobs**, not only failed jobs, to obtain a single new run-attempt identity.
+- Existing published GitHub releases, moved tags, unexpected draft assets, or already-published npm versions stop preflight. Already-published npm versions require an explicit provenance/recovery review; they are never silently mixed with this run.
+- npm publication and GitHub multi-asset uploads are not atomic. A mid-publication failure requires review; the draft is not automatically published or deleted. A failed upload can leave a partial draft, not a successful canonical release.
+- Caches improve repeat installs/builds but do not establish provenance. Their scope and writer limits are documented in `.github/actions/setup-bun/README.md`.
diff --git a/tools/release-packages/package.json b/tools/release-packages/package.json
index fc3fcf452..e942e2483 100644
--- a/tools/release-packages/package.json
+++ b/tools/release-packages/package.json
@@ -2,6 +2,9 @@
"name": "@open-pencil/release-packages",
"private": true,
"type": "module",
+ "imports": {
+ "#release/*": "./src/*.ts"
+ },
"scripts": {
"check-changelog": "bun src/check-changelog.ts",
"build": "bun src/cli.ts build",
@@ -13,6 +16,8 @@
"dependencies": {
"@open-pencil/package-artifacts": "workspace:*",
"@open-pencil/package-quality-tools": "workspace:*",
- "citty": "^0.1.6"
+ "citty": "^0.1.6",
+ "es-toolkit": "^1.51.0",
+ "valibot": "^1.4.2"
}
}
diff --git a/tools/release-packages/src/native/artifacts.ts b/tools/release-packages/src/native/artifacts.ts
new file mode 100644
index 000000000..125cb9383
--- /dev/null
+++ b/tools/release-packages/src/native/artifacts.ts
@@ -0,0 +1,56 @@
+import { realpath, stat } from 'node:fs/promises'
+import { basename, isAbsolute, relative, resolve, sep } from 'node:path'
+
+import * as v from 'valibot'
+
+import type { DesktopAsset } from './catalog.ts'
+
+export interface ReportedAsset {
+ source: string
+ name: string
+}
+
+/** Consume tauri-action's artifactPaths output, never search for plausible build files. */
+export async function resolveReportedAssets(
+ input: unknown,
+ expected: readonly DesktopAsset[],
+ root: string
+): Promise<ReportedAsset[]> {
+ const paths = v.parse(v.array(v.string()), input)
+ const sourceRoot = await realpath(root)
+ const wanted = new Map<string, string>()
+
+ for (const asset of expected) {
+ wanted.set(asset.source, asset.name)
+
+ if (asset.signed) wanted.set(`${asset.source}.sig`, `${asset.name}.sig`)
+ }
+
+ const found = new Map<string, ReportedAsset>()
+
+ for (const path of paths) {
+ const source = await realpath(resolve(sourceRoot, path))
+ const local = relative(sourceRoot, source)
+
+ if (isAbsolute(local) || local === '..' || local.startsWith(`..${sep}`)) {
+ throw new Error('Reported artifact escapes source checkout')
+ }
+
+ const info = await stat(source)
+ // tauri-action also reports the macOS .app directory. Its signed archive is required below.
+ if (info.isDirectory() && source.endsWith('.app')) continue
+ if (!info.isFile()) throw new Error(`Not an artifact file: ${path}`)
+
+ const name = wanted.get(basename(source))
+ if (!name) throw new Error(`Unexpected reported artifact: ${path}`)
+ if (found.has(name)) throw new Error(`Duplicate reported artifact: ${name}`)
+ if (info.size === 0) throw new Error(`Empty reported artifact: ${name}`)
+
+ found.set(name, { source, name })
+ }
+
+ const missing = [...wanted.values()].filter((name) => !found.has(name))
+ if (missing.length > 0) throw new Error(`Missing reported artifacts: ${missing.join(', ')}`)
+
+ return [...found.values()]
+}
diff --git a/tools/release-packages/src/native/assemble.ts b/tools/release-packages/src/native/assemble.ts
new file mode 100644
index 000000000..48c2bd096
--- /dev/null
+++ b/tools/release-packages/src/native/assemble.ts
@@ -0,0 +1,125 @@
+import { copyFile, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { readReleaseNotes } from '#release/release-notes'
+import { isEqual } from 'es-toolkit'
+import * as v from 'valibot'
+
+import { desktopAssets } from './catalog.ts'
+import { releaseCommands } from './commands.ts'
+import { createReleaseContext } from './context.ts'
+import { digestFile, validateTargetManifests } from './manifest.ts'
+
+const { identity, repository, version, paths } = createReleaseContext()
+const { verifySignature } = releaseCommands(paths.root)
+
+const directories = (await readdir(paths.nativeArtifacts)).sort()
+const manifests = validateTargetManifests(
+ await Promise.all(
+ directories.map(async (directory) =>
+ JSON.parse(await readFile(join(paths.nativeArtifacts, directory, 'manifest.json'), 'utf8'))
+ )
+ ),
+ identity
+)
+
+const notes = await readFile(paths.notes, 'utf8')
+const sourceNotes = await readReleaseNotes(join(paths.root, 'CHANGELOG.md'), version)
+if (notes !== sourceNotes) throw new Error('Release notes do not match the source changelog')
+const config = v.parse(
+ v.object({ plugins: v.object({ updater: v.object({ pubkey: v.string() }) }) }),
+ JSON.parse(await readFile(paths.tauriConfig, 'utf8'))
+)
+
+const temporary = await mkdtemp(join(tmpdir(), 'open-pencil-signatures-'))
+const output = paths.output
+await rm(output, { recursive: true, force: true })
+await mkdir(output, { recursive: true })
+
+const platforms: Record<string, { signature: string; url: string }> = {}
+
+try {
+ const publicKey = join(temporary, 'key.pub')
+ await writeFile(publicKey, Buffer.from(config.plugins.updater.pubkey, 'base64'))
+
+ for (const [index, manifest] of manifests.entries()) {
+ const directory = directories[index]
+ if (!directory) throw new Error('Missing artifact directory')
+
+ const source = join(paths.nativeArtifacts, directory)
+ const actualNames = (await readdir(source)).filter((name) => name !== 'manifest.json').sort()
+ const expectedNames = manifest.files.map((file) => file.name).sort()
+
+ if (!isEqual(actualNames, expectedNames)) {
+ throw new Error(`Unexpected files in ${directory}`)
+ }
+
+ for (const file of manifest.files) {
+ const path = join(source, file.name)
+ const actual = await digestFile(path)
+
+ if (actual.sha256 !== file.sha256 || actual.size !== file.size) {
+ throw new Error(`Corrupt artifact: ${file.name}`)
+ }
+
+ await copyFile(path, join(output, file.name))
+ }
+
+ for (const asset of desktopAssets(manifest.target, version)) {
+ if (!asset.signed) continue
+
+ const signature = (await readFile(join(source, `${asset.name}.sig`), 'utf8')).trim()
+ const decoded = join(temporary, `${asset.name}.minisig`)
+ await writeFile(decoded, Buffer.from(signature, 'base64'))
+ await verifySignature(join(source, asset.name), publicKey, decoded)
+
+ for (const platform of asset.updaterKeys) {
+ if (platforms[platform]) throw new Error(`Duplicate updater platform: ${platform}`)
+ platforms[platform] = {
+ signature,
+ url: `https://github.com/${repository}/releases/download/${identity.tag}/${asset.name}`
+ }
+ }
+ }
+ }
+} finally {
+ await rm(temporary, { recursive: true, force: true })
+}
+
+const pubDate = new Date().toISOString()
+await writeFile(
+ join(output, 'latest.json'),
+ JSON.stringify({ version, notes, pub_date: pubDate, platforms }, null, 2)
+)
+
+const packageFiles = (await readdir(paths.packages)).filter((name) => name.endsWith('.tgz')).sort()
+if (packageFiles.length === 0) throw new Error('Missing npm artifacts')
+
+const packages = await Promise.all(
+ packageFiles.map(async (name) => ({ name, ...(await digestFile(join(paths.packages, name))) }))
+)
+await writeFile(
+ join(output, 'release-manifest.json'),
+ JSON.stringify(
+ {
+ ...identity,
+ repository,
+ workflow: `${repository}/.github/workflows/build.yml@${identity.workflowCommit}`,
+ run: `https://github.com/${repository}/actions/runs/${identity.runId}/attempts/${identity.runAttempt}`,
+ targets: manifests,
+ packages
+ },
+ null,
+ 2
+ )
+)
+
+const checksums = await Promise.all(
+ (await readdir(output))
+ .sort()
+ .map(async (name) => `${(await digestFile(join(output, name))).sha256} ${name}`)
+)
+
+await writeFile(join(output, 'SHA256SUMS'), `${checksums.join('\n')}\n`)
+console.log(`Verified all ${manifests.length} native targets and updater signatures`)
diff --git a/tools/release-packages/src/native/catalog.ts b/tools/release-packages/src/native/catalog.ts
new file mode 100644
index 000000000..ec94ed0af
--- /dev/null
+++ b/tools/release-packages/src/native/catalog.ts
@@ -0,0 +1,107 @@
+import { releaseVersion } from './context.ts'
+
+export const desktopBuilds = [
+ {
+ target: 'aarch64-apple-darwin',
+ platform: 'macos-latest',
+ label: 'macos-arm64',
+ saveBunCache: true
+ },
+ {
+ target: 'x86_64-apple-darwin',
+ platform: 'macos-latest',
+ label: 'macos-x64',
+ saveBunCache: false
+ },
+ {
+ target: 'x86_64-pc-windows-msvc',
+ platform: 'windows-latest',
+ label: 'windows-x64',
+ saveBunCache: true
+ },
+ {
+ target: 'aarch64-pc-windows-msvc',
+ platform: 'windows-latest',
+ label: 'windows-arm64',
+ saveBunCache: false
+ },
+ {
+ target: 'x86_64-unknown-linux-gnu',
+ platform: 'ubuntu-22.04',
+ label: 'linux-x64',
+ saveBunCache: true
+ }
+] as const
+
+export const desktopTargets = desktopBuilds.map((build) => build.target)
+
+export type DesktopTarget = (typeof desktopTargets)[number]
+
+export interface DesktopAsset {
+ source: string
+ name: string
+ updaterKeys: string[]
+ signed: boolean
+}
+
+/** Required OpenPencil release outputs, not a discovery or packaging implementation. */
+export function desktopAssets(target: DesktopTarget, version: string): DesktopAsset[] {
+ releaseVersion(`v${version}`)
+
+ if (target.endsWith('apple-darwin')) {
+ const arch = target.startsWith('aarch64') ? 'aarch64' : 'x64'
+ const platform = arch === 'x64' ? 'darwin-x86_64' : 'darwin-aarch64'
+ return [
+ {
+ source: `OpenPencil_${version}_${arch}.dmg`,
+ name: `OpenPencil_${version}_${arch}.dmg`,
+ updaterKeys: [],
+ signed: false
+ },
+ {
+ source: 'OpenPencil.app.tar.gz',
+ name: `OpenPencil_${arch}.app.tar.gz`,
+ updaterKeys: [platform, `${platform}-app`],
+ signed: true
+ }
+ ]
+ }
+ if (target.endsWith('windows-msvc')) {
+ const arch = target.startsWith('aarch64') ? 'arm64' : 'x64'
+ const platform = target.startsWith('aarch64') ? 'windows-aarch64' : 'windows-x86_64'
+ return [
+ {
+ source: `OpenPencil_${version}_${arch}-setup.exe`,
+ name: `OpenPencil_${version}_${arch}-setup.exe`,
+ updaterKeys: [`${platform}-nsis`],
+ signed: true
+ },
+ {
+ source: `OpenPencil_${version}_${arch}_en-US.msi`,
+ name: `OpenPencil_${version}_${arch}_en-US.msi`,
+ updaterKeys: [platform, `${platform}-msi`],
+ signed: true
+ }
+ ]
+ }
+ return [
+ {
+ source: `OpenPencil_${version}_amd64.AppImage`,
+ name: `OpenPencil_${version}_amd64.AppImage`,
+ updaterKeys: ['linux-x86_64', 'linux-x86_64-appimage'],
+ signed: true
+ },
+ {
+ source: `OpenPencil_${version}_amd64.deb`,
+ name: `OpenPencil_${version}_amd64.deb`,
+ updaterKeys: ['linux-x86_64-deb'],
+ signed: true
+ },
+ {
+ source: `OpenPencil-${version}-1.x86_64.rpm`,
+ name: `OpenPencil-${version}-1.x86_64.rpm`,
+ updaterKeys: ['linux-x86_64-rpm'],
+ signed: true
+ }
+ ]
+}
diff --git a/tools/release-packages/src/native/collect.ts b/tools/release-packages/src/native/collect.ts
new file mode 100644
index 000000000..e91c07763
--- /dev/null
+++ b/tools/release-packages/src/native/collect.ts
@@ -0,0 +1,31 @@
+import { copyFile, mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+import * as v from 'valibot'
+
+import { resolveReportedAssets } from './artifacts.ts'
+import { desktopAssets, desktopTargets } from './catalog.ts'
+import { createReleaseContext } from './context.ts'
+import { digestFile, targetManifestSchema } from './manifest.ts'
+
+const { identity, paths, version } = createReleaseContext()
+const target = v.parse(v.picklist(desktopTargets), process.env.RELEASE_TARGET)
+const reported = JSON.parse(process.env.TAURI_ARTIFACT_PATHS ?? 'null')
+const assets = await resolveReportedAssets(reported, desktopAssets(target, version), paths.root)
+
+await mkdir(paths.nativeOutput, { recursive: true })
+
+for (const asset of assets) {
+ await copyFile(asset.source, join(paths.nativeOutput, asset.name))
+}
+
+const files = await Promise.all(
+ assets.map(async ({ name }) => ({
+ name,
+ ...(await digestFile(join(paths.nativeOutput, name)))
+ }))
+)
+const manifest = v.parse(targetManifestSchema, { ...identity, target, files })
+
+await writeFile(join(paths.nativeOutput, 'manifest.json'), JSON.stringify(manifest, null, 2))
+console.log(`Collected ${files.length} reported files for ${target}`)
diff --git a/tools/release-packages/src/native/commands.ts b/tools/release-packages/src/native/commands.ts
new file mode 100644
index 000000000..e0b0b05d0
--- /dev/null
+++ b/tools/release-packages/src/native/commands.ts
@@ -0,0 +1,31 @@
+import { runCommand } from '@open-pencil/package-artifacts'
+
+const METADATA_TIMEOUT_MS = 60_000
+export const ARTIFACT_TRANSFER_TIMEOUT_MS = 15 * 60_000
+
+/** Release-specific command defaults; shared tooling owns spawning and diagnostics. */
+export function releaseCommands(cwd: string, execute = runCommand) {
+ async function git(...args: string[]): Promise<string> {
+ const result = await execute({ command: 'git', args, cwd, timeoutMs: METADATA_TIMEOUT_MS })
+
+ return result.stdout.trim()
+ }
+
+ async function github(args: string[], timeoutMs = METADATA_TIMEOUT_MS): Promise<string> {
+ const result = await execute({ command: 'gh', args, cwd, timeoutMs })
+
+ return result.stdout
+ }
+
+ async function verifySignature(artifact: string, publicKey: string, signature: string) {
+ await execute({
+ command: 'minisign',
+ args: ['-Vm', artifact, '-p', publicKey, '-x', signature],
+ cwd,
+ output: 'inherit',
+ timeoutMs: METADATA_TIMEOUT_MS
+ })
+ }
+
+ return { git, github, verifySignature }
+}
diff --git a/tools/release-packages/src/native/context.ts b/tools/release-packages/src/native/context.ts
new file mode 100644
index 000000000..15c445513
--- /dev/null
+++ b/tools/release-packages/src/native/context.ts
@@ -0,0 +1,59 @@
+import { join, resolve } from 'node:path'
+
+import { releasePaths as packageReleasePaths } from '#release/workflow'
+import * as v from 'valibot'
+
+export const releaseTagSchema = v.pipe(v.string(), v.regex(/^v\d+\.\d+\.\d+$/))
+export const commitSchema = v.pipe(v.string(), v.regex(/^[a-f0-9]{40}$/))
+export const sha256Schema = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/))
+
+export const identitySchema = v.object({
+ tag: releaseTagSchema,
+ sourceCommit: commitSchema,
+ workflowCommit: commitSchema,
+ runId: v.pipe(v.string(), v.regex(/^\d+$/)),
+ runAttempt: v.pipe(v.string(), v.regex(/^\d+$/)),
+ frontendSha256: sha256Schema
+})
+
+export type ReleaseIdentity = v.InferOutput<typeof identitySchema>
+
+export function releaseVersion(tag: string): string {
+ return v.parse(releaseTagSchema, tag).slice(1)
+}
+
+export function desktopReleasePaths(root: string) {
+ const absoluteRoot = resolve(root)
+
+ return {
+ root: absoluteRoot,
+ nativeOutput: join(absoluteRoot, 'native-output'),
+ nativeArtifacts: join(absoluteRoot, 'native-artifacts'),
+ output: join(absoluteRoot, 'release-output'),
+ packages: packageReleasePaths(absoluteRoot).artifacts,
+ notes: join(absoluteRoot, 'release-notes.md'),
+ tauriConfig: join(absoluteRoot, 'desktop', 'tauri.conf.json')
+ }
+}
+
+export function createReleaseContext(env: NodeJS.ProcessEnv = process.env, root = process.cwd()) {
+ const identity = v.parse(identitySchema, {
+ tag: env.RELEASE_TAG,
+ sourceCommit: env.SOURCE_COMMIT,
+ workflowCommit: env.WORKFLOW_COMMIT,
+ runId: env.GITHUB_RUN_ID,
+ runAttempt: env.GITHUB_RUN_ATTEMPT,
+ frontendSha256: env.FRONTEND_SHA256
+ })
+ const repository = v.parse(
+ v.pipe(v.string(), v.regex(/^[\w.-]+\/[\w.-]+$/)),
+ env.GITHUB_REPOSITORY
+ )
+
+ return {
+ identity,
+ repository,
+ version: releaseVersion(identity.tag),
+ paths: desktopReleasePaths(root)
+ }
+}
diff --git a/tools/release-packages/src/native/draft.ts b/tools/release-packages/src/native/draft.ts
new file mode 100644
index 000000000..a06ce8814
--- /dev/null
+++ b/tools/release-packages/src/native/draft.ts
@@ -0,0 +1,32 @@
+import * as v from 'valibot'
+
+import type { ReleaseIdentity } from './context.ts'
+
+export const releaseSchema = v.object({
+ id: v.number(),
+ tag_name: v.string(),
+ draft: v.boolean(),
+ assets: v.array(v.object({ name: v.string() }))
+})
+
+export function assertDraftReplacement(
+ release: v.InferOutput<typeof releaseSchema> | undefined,
+ names: string[],
+ actualCommit: string,
+ identity: ReleaseIdentity
+): void {
+ if (release && !release.draft) throw new Error('Refusing to replace a published release')
+ if (actualCommit !== identity.sourceCommit)
+ throw new Error('Release tag changed during the build')
+
+ if (!names.includes('release-manifest.json') || !names.includes('SHA256SUMS')) {
+ throw new Error('Missing release manifest')
+ }
+
+ const unexpected = release?.assets.filter((asset) => !names.includes(asset.name)) ?? []
+ if (unexpected.length > 0) {
+ throw new Error(
+ `Refusing to remove unexpected draft assets: ${unexpected.map((asset) => asset.name).join(', ')}`
+ )
+ }
+}
diff --git a/tools/release-packages/src/native/frontend.ts b/tools/release-packages/src/native/frontend.ts
new file mode 100644
index 000000000..aa4eb7a68
--- /dev/null
+++ b/tools/release-packages/src/native/frontend.ts
@@ -0,0 +1,32 @@
+import { writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+import { readPackageManifest } from '@open-pencil/package-artifacts'
+
+import { releaseCommands } from './commands.ts'
+import { createReleaseContext } from './context.ts'
+import { digestFile } from './manifest.ts'
+
+/** CI-only override; the checked-in local Tauri build remains self-contained. */
+export async function prepareSharedFrontend(
+ context: ReturnType<typeof createReleaseContext>,
+ commands = releaseCommands(context.paths.root)
+): Promise<void> {
+ const { identity, version, paths } = context
+ const source = await commands.git('rev-parse', 'HEAD')
+ const manifest = await readPackageManifest(join(paths.root, 'package.json'))
+ const archive = await digestFile(join(paths.root, 'frontend.tar'))
+
+ if (source !== identity.sourceCommit) throw new Error('Unexpected source checkout')
+ if (manifest.version !== version) throw new Error('Source version does not match release tag')
+ if (archive.sha256 !== identity.frontendSha256) throw new Error('Shared frontend digest mismatch')
+
+ await writeFile(
+ join(paths.root, 'release-build-config.json'),
+ JSON.stringify({ build: { beforeBuildCommand: null } })
+ )
+}
+
+if (import.meta.main) {
+ await prepareSharedFrontend(createReleaseContext())
+}
diff --git a/tools/release-packages/src/native/manifest.ts b/tools/release-packages/src/native/manifest.ts
new file mode 100644
index 000000000..9131fa8b3
--- /dev/null
+++ b/tools/release-packages/src/native/manifest.ts
@@ -0,0 +1,60 @@
+import { createHash } from 'node:crypto'
+import { readFile } from 'node:fs/promises'
+
+import { isEqual, pick } from 'es-toolkit'
+import * as v from 'valibot'
+
+import { desktopAssets, desktopTargets } from './catalog.ts'
+import { identitySchema, releaseVersion, sha256Schema, type ReleaseIdentity } from './context.ts'
+export const artifactSchema = v.object({
+ name: v.pipe(v.string(), v.regex(/^[A-Za-z0-9_.-]+$/)),
+ sha256: sha256Schema,
+ size: v.pipe(v.number(), v.integer(), v.minValue(1))
+})
+export const targetManifestSchema = v.object({
+ ...identitySchema.entries,
+ target: v.picklist(desktopTargets),
+ files: v.array(artifactSchema)
+})
+const identityKeys = v.keyof(identitySchema).options
+
+export type TargetManifest = v.InferOutput<typeof targetManifestSchema>
+
+export async function digestFile(path: string): Promise<{ sha256: string; size: number }> {
+ const bytes = await readFile(path)
+ return { sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.byteLength }
+}
+
+export function validateTargetManifests(
+ input: unknown[],
+ identity: ReleaseIdentity
+): TargetManifest[] {
+ const manifests = input.map((entry) => v.parse(targetManifestSchema, entry))
+ if (manifests.length !== desktopTargets.length) throw new Error('Incomplete native matrix')
+
+ const seenTargets = new Set<string>()
+ const seenFiles = new Set<string>()
+
+ for (const manifest of manifests) {
+ if (!isEqual(pick(manifest, identityKeys), identity)) {
+ throw new Error('Mismatched release identity')
+ }
+
+ if (seenTargets.has(manifest.target)) throw new Error('Duplicate native target')
+ seenTargets.add(manifest.target)
+
+ const expected = desktopAssets(manifest.target, releaseVersion(identity.tag))
+ .flatMap((asset) => (asset.signed ? [asset.name, `${asset.name}.sig`] : [asset.name]))
+ .sort()
+ const actual = manifest.files.map((file) => file.name).sort()
+
+ if (!isEqual(expected, actual)) throw new Error(`Invalid assets for ${manifest.target}`)
+
+ for (const name of actual) {
+ if (seenFiles.has(name)) throw new Error(`Duplicate release filename: ${name}`)
+ seenFiles.add(name)
+ }
+ }
+
+ return manifests
+}
diff --git a/tools/release-packages/src/native/publish.ts b/tools/release-packages/src/native/publish.ts
new file mode 100644
index 000000000..9536023e6
--- /dev/null
+++ b/tools/release-packages/src/native/publish.ts
@@ -0,0 +1,127 @@
+import { mkdtemp, readdir, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { createPublicationPlan } from '#release/workflow'
+import { isEqual } from 'es-toolkit'
+import * as v from 'valibot'
+
+import { ARTIFACT_TRANSFER_TIMEOUT_MS, releaseCommands } from './commands.ts'
+import { createReleaseContext } from './context.ts'
+import { assertDraftReplacement, releaseSchema } from './draft.ts'
+import { digestFile } from './manifest.ts'
+
+const { identity, repository, paths } = createReleaseContext()
+const { git, github } = releaseCommands(paths.root)
+
+const releases = v
+ .parse(
+ v.array(v.array(releaseSchema)),
+ JSON.parse(await github(['api', '--paginate', '--slurp', `repos/${repository}/releases`]))
+ )
+ .flat()
+const release = releases.find((entry) => entry.tag_name === identity.tag)
+
+// Re-fetch the tag and peel annotated tags before any registry/release mutation.
+await git('fetch', 'origin', `refs/tags/${identity.tag}`)
+const actualCommit = await git('rev-parse', 'FETCH_HEAD^{commit}')
+const names = (await readdir(paths.output)).sort()
+assertDraftReplacement(release, names, actualCommit, identity)
+
+if (process.argv[2] === 'check') {
+ const plan = await createPublicationPlan(paths.root)
+ const published = plan.filter((entry) => entry.status === 'published')
+ if (published.length > 0) {
+ throw new Error('Release already has published npm packages; review provenance before recovery')
+ }
+
+ console.log('Draft, unpublished npm versions and immutable tag verified before publication')
+ process.exit(0)
+}
+
+if (process.argv[2] !== 'upload') throw new Error('Expected check or upload')
+
+if (!release) {
+ await github([
+ 'release',
+ 'create',
+ identity.tag,
+ '--repo',
+ repository,
+ '--draft',
+ '--verify-tag',
+ '--title',
+ identity.tag,
+ '--notes-file',
+ paths.notes
+ ])
+} else {
+ await github([
+ 'release',
+ 'edit',
+ identity.tag,
+ '--repo',
+ repository,
+ '--title',
+ identity.tag,
+ '--notes-file',
+ paths.notes
+ ])
+}
+
+// Every asset is replaced, never skipped merely because its name already exists.
+// GitHub has no atomic multi-asset upload. The release remains draft on failure.
+await github(
+ [
+ 'release',
+ 'upload',
+ identity.tag,
+ ...names.map((name) => join(paths.output, name)),
+ '--repo',
+ repository,
+ '--clobber'
+ ],
+ ARTIFACT_TRANSFER_TIMEOUT_MS
+)
+
+const remote = v.parse(
+ v.object({ isDraft: v.boolean(), assets: v.array(v.object({ name: v.string() })) }),
+ JSON.parse(
+ await github([
+ 'release',
+ 'view',
+ identity.tag,
+ '--repo',
+ repository,
+ '--json',
+ 'isDraft,assets'
+ ])
+ )
+)
+const remoteNames = remote.assets.map((asset) => asset.name).sort()
+
+if (!remote.isDraft || !isEqual(remoteNames, names)) {
+ throw new Error('Uploaded asset set mismatch')
+}
+
+const temporary = await mkdtemp(join(tmpdir(), 'open-pencil-release-verify-'))
+
+try {
+ await github(
+ ['release', 'download', identity.tag, '--repo', repository, '--dir', temporary],
+ ARTIFACT_TRANSFER_TIMEOUT_MS
+ )
+
+ for (const name of names) {
+ if (
+ (await digestFile(join(temporary, name))).sha256 !==
+ (await digestFile(join(paths.output, name))).sha256
+ ) {
+ throw new Error(`Uploaded digest mismatch: ${name}`)
+ }
+ }
+} finally {
+ await rm(temporary, { recursive: true, force: true })
+}
+
+console.log(`Draft ${identity.tag} contains only the verified assets from this run`)
diff --git a/tools/release-packages/src/native/resolve.ts b/tools/release-packages/src/native/resolve.ts
new file mode 100644
index 000000000..718a68111
--- /dev/null
+++ b/tools/release-packages/src/native/resolve.ts
@@ -0,0 +1,34 @@
+import { appendFile } from 'node:fs/promises'
+
+import * as v from 'valibot'
+
+import { desktopBuilds } from './catalog.ts'
+import { releaseCommands } from './commands.ts'
+import { commitSchema, releaseVersion } from './context.ts'
+
+const tag = process.env.RELEASE_TAG ?? ''
+const version = releaseVersion(tag)
+const { git } = releaseCommands(process.cwd())
+const sourceCommit = v.parse(
+ commitSchema,
+ await git('rev-parse', '--verify', `refs/tags/${tag}^{commit}`)
+)
+
+// Release signing/publishing never checks out a caller-supplied arbitrary branch.
+await git('merge-base', '--is-ancestor', sourceCommit, 'origin/master')
+
+const output = process.env.GITHUB_OUTPUT
+if (!output) throw new Error('Missing GITHUB_OUTPUT')
+
+await appendFile(
+ output,
+ [
+ `tag=${tag}`,
+ `version=${version}`,
+ `source=${sourceCommit}`,
+ `matrix=${JSON.stringify({ include: desktopBuilds })}`,
+ ''
+ ].join('\n')
+)
+
+console.log(`Release ${tag}: source ${sourceCommit}; workflow ${process.env.WORKFLOW_COMMIT}`)
diff --git a/tools/release-packages/tests/changelog.test.ts b/tools/release-packages/tests/changelog.test.ts
index 1f8231691..46c720c3e 100644
--- a/tools/release-packages/tests/changelog.test.ts
+++ b/tools/release-packages/tests/changelog.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { validateChangelog } from '../src/changelog'
+import { validateChangelog } from '#release/changelog'
const validChangelog = `# Changelog
diff --git a/tools/release-packages/tests/native/artifacts.test.ts b/tools/release-packages/tests/native/artifacts.test.ts
new file mode 100644
index 000000000..3a03ec725
--- /dev/null
+++ b/tools/release-packages/tests/native/artifacts.test.ts
@@ -0,0 +1,83 @@
+import { expect, test } from 'bun:test'
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { resolveReportedAssets } from '#release/native/artifacts'
+import { desktopAssets } from '#release/native/catalog'
+
+const expected = desktopAssets('aarch64-apple-darwin', '0.15.0')
+
+async function withArtifacts(run: (root: string, reported: string[]) => Promise<void>) {
+ const root = await mkdtemp(join(tmpdir(), 'release-artifacts-'))
+
+ try {
+ const reported: string[] = []
+
+ for (const asset of expected) {
+ for (const name of asset.signed ? [asset.source, `${asset.source}.sig`] : [asset.source]) {
+ const path = join(root, name)
+ await writeFile(path, 'fixture')
+ reported.push(path)
+ }
+ }
+
+ await run(root, reported)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+}
+
+test('uses reported paths and retains the stable macOS archive name', () =>
+ withArtifacts(async (root, reported) => {
+ const app = join(root, 'OpenPencil.app')
+ await mkdir(app)
+ await writeFile(join(root, 'unrelated-file.dmg'), 'not reported')
+
+ const assets = await resolveReportedAssets([...reported, app], expected, root)
+
+ expect(assets.map((asset) => asset.name).sort()).toEqual([
+ 'OpenPencil_0.15.0_aarch64.dmg',
+ 'OpenPencil_aarch64.app.tar.gz',
+ 'OpenPencil_aarch64.app.tar.gz.sig'
+ ])
+ }))
+
+test('does not discover an existing signature missing from the action output', () =>
+ withArtifacts(async (root, reported) => {
+ await expect(
+ resolveReportedAssets(
+ reported.filter((path) => !path.endsWith('.sig')),
+ expected,
+ root
+ )
+ ).rejects.toThrow('Missing reported artifacts')
+ }))
+
+test('rejects duplicate reports', () =>
+ withArtifacts(async (root, reported) => {
+ await expect(resolveReportedAssets([...reported, ...reported], expected, root)).rejects.toThrow(
+ 'Duplicate reported artifact'
+ )
+ }))
+
+test('rejects additional reported files', () =>
+ withArtifacts(async (root, reported) => {
+ const extra = join(root, 'unexpected.exe')
+ await writeFile(extra, 'fixture')
+
+ await expect(resolveReportedAssets([...reported, extra], expected, root)).rejects.toThrow(
+ 'Unexpected reported artifact'
+ )
+ }))
+
+test('rejects symlink escapes', () =>
+ withArtifacts(async (root, reported) => {
+ const source = join(root, 'source')
+ await mkdir(source)
+ await symlink(reported[0] ?? '', join(source, 'outside.dmg'))
+
+ await expect(
+ resolveReportedAssets([join(source, 'outside.dmg')], expected, source)
+ ).rejects.toThrow('escapes source checkout')
+ }))
diff --git a/tools/release-packages/tests/native/context.test.ts b/tools/release-packages/tests/native/context.test.ts
new file mode 100644
index 000000000..9da919edf
--- /dev/null
+++ b/tools/release-packages/tests/native/context.test.ts
@@ -0,0 +1,79 @@
+import { expect, test } from 'bun:test'
+import { resolve } from 'node:path'
+
+import { desktopBuilds, desktopTargets } from '#release/native/catalog'
+import { ARTIFACT_TRANSFER_TIMEOUT_MS, releaseCommands } from '#release/native/commands'
+import { createReleaseContext, releaseVersion } from '#release/native/context'
+import { releasePaths } from '#release/workflow'
+
+import type { CommandRequest } from '@open-pencil/package-artifacts'
+
+const environment = {
+ RELEASE_TAG: 'v0.15.0',
+ SOURCE_COMMIT: 'a'.repeat(40),
+ WORKFLOW_COMMIT: 'b'.repeat(40),
+ GITHUB_RUN_ID: '123',
+ GITHUB_RUN_ATTEMPT: '1',
+ FRONTEND_SHA256: 'c'.repeat(64),
+ GITHUB_REPOSITORY: 'open-pencil/open-pencil'
+}
+
+test('one context owns release identity and reuses existing npm paths', () => {
+ const root = resolve('fixture')
+ const context = createReleaseContext(environment, root)
+
+ expect(context.version).toBe('0.15.0')
+ expect(context.paths.packages).toBe(releasePaths(root).artifacts)
+ expect(context.paths.notes).toBe(resolve(root, 'release-notes.md'))
+ expect(context.identity.sourceCommit).toBe(environment.SOURCE_COMMIT)
+})
+
+test.each(['master', '--help', 'v0.15.0/other', 'v0.15.0\n', 'v0.15'])(
+ 'rejects invalid release tag %s',
+ (tag) => {
+ expect(() => releaseVersion(tag)).toThrow()
+ }
+)
+
+test('matrix metadata and target validation share the same catalog', () => {
+ expect(desktopTargets).toEqual(desktopBuilds.map((build) => build.target))
+ expect(new Set(desktopTargets).size).toBe(desktopTargets.length)
+
+ for (const platform of new Set(desktopBuilds.map((build) => build.platform))) {
+ expect(
+ desktopBuilds.filter((build) => build.platform === platform && build.saveBunCache)
+ ).toHaveLength(1)
+ }
+})
+
+test('command adapters delegate argument arrays and deadlines to shared tooling', async () => {
+ const requests: CommandRequest[] = []
+ const cwd = resolve('fixture')
+ const commands = releaseCommands(cwd, async (request) => {
+ requests.push(request)
+ return { stdout: 'output\n', stderr: '' }
+ })
+
+ expect(await commands.git('rev-parse', 'HEAD')).toBe('output')
+ expect(await commands.github(['release', 'view', 'v0.15.0'])).toBe('output\n')
+ await commands.github(['release', 'download', 'v0.15.0'], ARTIFACT_TRANSFER_TIMEOUT_MS)
+ await commands.verifySignature('asset with spaces', 'key.pub', 'asset.sig')
+
+ expect(requests).toEqual([
+ { command: 'git', args: ['rev-parse', 'HEAD'], cwd, timeoutMs: 60_000 },
+ { command: 'gh', args: ['release', 'view', 'v0.15.0'], cwd, timeoutMs: 60_000 },
+ {
+ command: 'gh',
+ args: ['release', 'download', 'v0.15.0'],
+ cwd,
+ timeoutMs: ARTIFACT_TRANSFER_TIMEOUT_MS
+ },
+ {
+ command: 'minisign',
+ args: ['-Vm', 'asset with spaces', '-p', 'key.pub', '-x', 'asset.sig'],
+ cwd,
+ output: 'inherit',
+ timeoutMs: 60_000
+ }
+ ])
+})
diff --git a/tools/release-packages/tests/native/draft.test.ts b/tools/release-packages/tests/native/draft.test.ts
new file mode 100644
index 000000000..17e766cbe
--- /dev/null
+++ b/tools/release-packages/tests/native/draft.test.ts
@@ -0,0 +1,52 @@
+import { expect, test } from 'bun:test'
+
+import type { ReleaseIdentity } from '#release/native/context'
+import { assertDraftReplacement } from '#release/native/draft'
+
+const identity: ReleaseIdentity = {
+ tag: 'v0.15.0',
+ sourceCommit: 'a'.repeat(40),
+ workflowCommit: 'b'.repeat(40),
+ runId: '123',
+ runAttempt: '1',
+ frontendSha256: 'c'.repeat(64)
+}
+const names = ['release-manifest.json', 'SHA256SUMS', 'installer.exe']
+const draft = { id: 123, tag_name: identity.tag, draft: true, assets: [{ name: 'installer.exe' }] }
+
+test('permits creating a draft or replacing its known assets', () => {
+ expect(() =>
+ assertDraftReplacement(undefined, names, identity.sourceCommit, identity)
+ ).not.toThrow()
+ expect(() => assertDraftReplacement(draft, names, identity.sourceCommit, identity)).not.toThrow()
+})
+
+test('refuses to modify a published release', () => {
+ expect(() =>
+ assertDraftReplacement({ ...draft, draft: false }, names, identity.sourceCommit, identity)
+ ).toThrow('published release')
+})
+
+test('refuses a tag moved after artifact construction', () => {
+ expect(() => assertDraftReplacement(draft, names, 'd'.repeat(40), identity)).toThrow(
+ 'tag changed'
+ )
+})
+
+test('refuses to silently delete unexpected draft assets', () => {
+ const unexpected = { ...draft, assets: [{ name: 'unrelated.zip' }] }
+ expect(() => assertDraftReplacement(unexpected, names, identity.sourceCommit, identity)).toThrow(
+ 'unexpected draft assets'
+ )
+})
+
+test.each(['release-manifest.json', 'SHA256SUMS'])('requires %s before publication', (missing) => {
+ expect(() =>
+ assertDraftReplacement(
+ draft,
+ names.filter((name) => name !== missing),
+ identity.sourceCommit,
+ identity
+ )
+ ).toThrow('Missing release manifest')
+})
diff --git a/tools/release-packages/tests/native/frontend.test.ts b/tools/release-packages/tests/native/frontend.test.ts
new file mode 100644
index 000000000..c30f3ab7e
--- /dev/null
+++ b/tools/release-packages/tests/native/frontend.test.ts
@@ -0,0 +1,65 @@
+import { expect, test } from 'bun:test'
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { releaseCommands } from '#release/native/commands'
+import { desktopReleasePaths } from '#release/native/context'
+import { prepareSharedFrontend } from '#release/native/frontend'
+import { digestFile } from '#release/native/manifest'
+
+test.each(['valid', 'source', 'version', 'digest'])(
+ 'shared frontend validation: %s',
+ async (scenario) => {
+ const root = await mkdtemp(join(tmpdir(), 'release-frontend-'))
+
+ try {
+ const archive = join(root, 'frontend.tar')
+ await writeFile(archive, 'shared frontend fixture')
+ await writeFile(
+ join(root, 'package.json'),
+ JSON.stringify({
+ name: 'open-pencil',
+ version: scenario === 'version' ? '0.14.0' : '0.15.0'
+ })
+ )
+
+ const sourceCommit = 'a'.repeat(40)
+ const identity = {
+ tag: 'v0.15.0',
+ sourceCommit,
+ workflowCommit: 'b'.repeat(40),
+ runId: '123',
+ runAttempt: '1',
+ frontendSha256: (await digestFile(archive)).sha256
+ }
+ const context = {
+ identity,
+ repository: 'open-pencil/open-pencil',
+ version: '0.15.0',
+ paths: desktopReleasePaths(root)
+ }
+ const commands = releaseCommands(root, async () => ({
+ stdout: scenario === 'source' ? 'c'.repeat(40) : sourceCommit,
+ stderr: ''
+ }))
+
+ if (scenario === 'digest') await writeFile(archive, 'changed archive')
+
+ const operation = prepareSharedFrontend(context, commands)
+ const config = join(root, 'release-build-config.json')
+
+ if (scenario === 'valid') {
+ await operation
+ expect(JSON.parse(await readFile(config, 'utf8'))).toEqual({
+ build: { beforeBuildCommand: null }
+ })
+ } else {
+ await expect(operation).rejects.toThrow()
+ expect(await Bun.file(config).exists()).toBe(false)
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ }
+)
diff --git a/tools/release-packages/tests/native/manifest.test.ts b/tools/release-packages/tests/native/manifest.test.ts
new file mode 100644
index 000000000..09234be80
--- /dev/null
+++ b/tools/release-packages/tests/native/manifest.test.ts
@@ -0,0 +1,71 @@
+import { expect, test } from 'bun:test'
+
+import { desktopAssets, desktopTargets } from '#release/native/catalog'
+import { releaseVersion, type ReleaseIdentity } from '#release/native/context'
+import { validateTargetManifests, type TargetManifest } from '#release/native/manifest'
+
+const identity: ReleaseIdentity = {
+ tag: 'v0.15.0',
+ sourceCommit: 'a'.repeat(40),
+ workflowCommit: 'b'.repeat(40),
+ runId: '123',
+ runAttempt: '1',
+ frontendSha256: 'c'.repeat(64)
+}
+
+function manifests(): TargetManifest[] {
+ return desktopTargets.map((target) => ({
+ ...identity,
+ target,
+ files: desktopAssets(target, releaseVersion(identity.tag))
+ .flatMap((asset) => (asset.signed ? [asset.name, `${asset.name}.sig`] : [asset.name]))
+ .map((name) => ({ name, sha256: 'd'.repeat(64), size: 100 }))
+ }))
+}
+
+test('accepts the complete release set regardless of file order', () => {
+ const input = manifests().map((manifest) => ({ ...manifest, files: manifest.files.toReversed() }))
+
+ expect(validateTargetManifests(input, identity)).toHaveLength(desktopTargets.length)
+})
+
+test.each([
+ { ...identity, sourceCommit: 'e'.repeat(40) },
+ { ...identity, workflowCommit: 'e'.repeat(40) },
+ { ...identity, frontendSha256: 'e'.repeat(64) },
+ { ...identity, tag: 'v0.15.1' },
+ { ...identity, runId: '124' },
+ { ...identity, runAttempt: '2' }
+])('rejects mixed release identity %#', (other) => {
+ expect(() => validateTargetManifests(manifests(), other)).toThrow('Mismatched release identity')
+})
+
+test('rejects duplicate targets even with a complete matrix count', () => {
+ const input = manifests()
+ const first = input[0]
+ if (!first) throw new Error('Missing fixture')
+
+ input[1] = structuredClone(first)
+
+ expect(() => validateTargetManifests(input, identity)).toThrow('Duplicate native target')
+})
+
+test('rejects duplicate filenames instead of treating arrays as sets', () => {
+ const input = manifests()
+ const first = input[0]
+ const file = first?.files[0]
+ if (!first || !file) throw new Error('Missing fixture')
+
+ first.files.push({ ...file })
+
+ expect(() => validateTargetManifests(input, identity)).toThrow('Invalid assets')
+})
+
+test('rejects missing updater signatures', () => {
+ const input = manifests().map((manifest) => ({
+ ...manifest,
+ files: manifest.files.filter((file) => !file.name.endsWith('.sig'))
+ }))
+
+ expect(() => validateTargetManifests(input, identity)).toThrow('Invalid assets')
+})
diff --git a/tools/release-packages/tests/publication.test.ts b/tools/release-packages/tests/publication.test.ts
index 3e6c50e1d..679b0e9d2 100644
--- a/tools/release-packages/tests/publication.test.ts
+++ b/tools/release-packages/tests/publication.test.ts
@@ -4,7 +4,7 @@ import {
publishReleasePackages,
type PublicationOperations,
type PublicationPlanEntry
-} from '../src/workflow'
+} from '#release/workflow'
function fixture() {
const plan: PublicationPlanEntry[] = ['one', 'two'].map((name) => ({
diff --git a/tools/release-packages/tests/publish-dirs.test.ts b/tools/release-packages/tests/publish-dirs.test.ts
index 0bf335f70..a40fee778 100644
--- a/tools/release-packages/tests/publish-dirs.test.ts
+++ b/tools/release-packages/tests/publish-dirs.test.ts
@@ -7,7 +7,7 @@ import {
discoverPublishPackages,
preparePublishDirectories,
publishPackageJSON
-} from '../src/publish-dirs'
+} from '#release/publish-dirs'
async function fixtureRoot() {
const root = join(tmpdir(), `open-pencil-release-packages-${crypto.randomUUID()}`)
diff --git a/tools/release-packages/tests/release-notes.test.ts b/tools/release-packages/tests/release-notes.test.ts
index b2f3975a5..07fc6f762 100644
--- a/tools/release-packages/tests/release-notes.test.ts
+++ b/tools/release-packages/tests/release-notes.test.ts
@@ -3,7 +3,7 @@ import { mkdir, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { readReleaseNotes } from '../src/release-notes'
+import { readReleaseNotes } from '#release/release-notes'
const changelog = `# Changelog
diff --git a/tools/release-packages/tests/workflow.test.ts b/tools/release-packages/tests/workflow.test.ts
index d19c58ce3..150461252 100644
--- a/tools/release-packages/tests/workflow.test.ts
+++ b/tools/release-packages/tests/workflow.test.ts
@@ -10,7 +10,7 @@ import {
prepareReleasePackages,
releasePaths,
validatePublicationArtifacts
-} from '../src/workflow'
+} from '#release/workflow'
async function createWorkspace() {
const root = join(tmpdir(), `open-pencil-release-workflow-${crypto.randomUUID()}`)