Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

ci: publish architecture-specific APKs in nightly releases

Amruth Pillai00751846650d
diff --git a/.agents/docs/container-publishing.md b/.agents/docs/container-publishing.md
index c568005f3..7e56350fa 100644
--- a/.agents/docs/container-publishing.md
+++ b/.agents/docs/container-publishing.md
@@ -34,6 +34,55 @@ builds. An older build still publishes its SHA and timestamped nightly aliases,
the current main HEAD updates the moving `nightly` alias. Architecture-specific build
outputs use `sha-<full-commit>-amd64` and `sha-<full-commit>-arm64`.
+### Nightly Android APKs and GitHub releases
+
+Every push to `main` also builds signed Android APKs for `arm64-v8a`, `armeabi-v7a`,
+and `x86_64`, the three ABIs supported by the pinned Forme native binaries. There is
+no daily schedule: "nightly" means each main push, matching the Docker publishing mode.
+Manual canaries and stable promotions do not build these APKs or create nightly releases.
+
+The `mobile-apk` matrix uses Expo Prebuild, Gradle, and the existing Fastlane Android
+build lane on CI runners with Node 24, pnpm, Ruby, Java 17, Android SDK, and the pinned
+Forme NDK. Each build selects one ABI, loads the preview EAS environment, and embeds
+the preview update channel through `MOBILE_UPDATE_CHANNEL`. Signing uses the existing
+Android upload keystore from Actions secrets, matching the manual native release
+workflow. Nightlies use version code 1 without allocating store build numbers. Each
+APK's signature, ABI, and embedded Forme library are checked before upload. Workflow
+artifacts are retained for 14 days.
+
+After all three APK builds and Docker publishing succeed, `nightly-release` creates
+`nightly-<workflow-run-id>` at that push's full SHA. Each push gets its own prerelease,
+including builds superseded by a newer main push. Prereleases never replace the latest
+stable release or trigger production promotion. Each release contains all three APKs,
+`SHA256SUMS`, and `CHANGELOG.md`; release assets outlive workflow artifact retention.
+The changelog includes full commit messages from `before..after`, deduplicated merged
+main PR titles/descriptions, comparison/build links, and the matching SHA Docker image.
+It reads local Git history rather than the push payload's potentially truncated commit
+list. A newly created main branch includes only its head commit. Very long changelogs
+are attached in full, with a shortened release description linking to the attachment.
+
+Required setup: retain `EXPO_TOKEN` and the four `ANDROID_KEYSTORE_*`/`ANDROID_KEY_*`
+Actions secrets described in [mobile CI](./mobile-ci.md). The release job uses
+`GITHUB_TOKEN` with `contents: write` and `pull-requests: read`;
+repository rules must allow the `nightly-*` tags. No signing keys are stored in GitHub
+artifacts or releases. Missing credentials fail APK publishing without undoing Docker
+publishing. A failed upload leaves a draft release; rerunning the same workflow replaces
+only that draft's assets and publishes it once complete. Already published releases are
+left unchanged on reruns, supporting immutable releases.
+
+These APKs use package `me.rxresu` and the preview update channel. The Android upload
+certificate can differ from Play App Signing, preventing upgrades between Play and
+GitHub installations. Back up local drafts before switching distributions. Add the
+upload signing certificate's SHA-256 fingerprint to `MOBILE_ANDROID_CERT_SHA256` on
+the backend when enabling verified App Links for sideloaded builds; retain the Play
+fingerprint. Keep the same upload key across nightly builds so sideloaded installs remain
+upgradable. See [mobile release handoff](./mobile-release-handoff.md#nightly-android-downloads).
+
+References: [Expo local production builds](https://docs.expo.dev/guides/local-app-production/) and
+[GitHub release API](https://docs.github.com/en/rest/releases/releases#create-a-release).
+
+### Stable promotions
+
Release tags must be `vMAJOR.MINOR.PATCH`, optionally with a prerelease suffix, and match
`package.json` at the tagged commit. Promotion resolves that commit's GHCR
`sha-<full-commit>` image, validates both architectures, and copies the complete image index
diff --git a/.agents/docs/mobile-ci.md b/.agents/docs/mobile-ci.md
index f96f2f3d7..56feec3ed 100644
--- a/.agents/docs/mobile-ci.md
+++ b/.agents/docs/mobile-ci.md
@@ -94,8 +94,9 @@ paths are manual, and signing is limited to `main`.
`fingerprint.json`, available source maps, and iOS symbols. Raw build logs are not
uploaded because toolchains can include environment values in them. Download the
fingerprint and keep it with the store release record before the 14-day Actions
- retention expires. Binaries stay in workflow artifacts; no GitHub Release assets
- or public sideload distribution are created.
+ retention expires. Store binaries stay in workflow artifacts. Separately, each main
+ push builds Android APKs for public sideloading through the same Fastlane build
+ lane; see [nightly downloads](./mobile-release-handoff.md#nightly-android-downloads).
4. Dispatch with **upload** enabled when ready. Upload jobs start only after every
selected platform built successfully, then pass the `mobile-store` environment gate.
They publish the exact signed artifacts from that run. Android creates a **completed
@@ -118,7 +119,8 @@ Apple resources. Renew certificates/profiles before expiry and update Actions se
## OTA compatibility and observability
The update URL, EAS project and fingerprint policy remain unchanged. The production
-channel is explicitly embedded through `updates.requestHeaders`; setting a channel in
+channel is explicitly embedded through `updates.requestHeaders`; nightly APK builds
+select `preview` with `MOBILE_UPDATE_CHANNEL`. Setting a channel in
`eas.json` alone does not configure a build produced outside EAS Build. Build numbers
are excluded from Expo's normalized config fingerprint. Native project output and
generated Forme binaries remain excluded through `fingerprint.config.js`; reviewed
diff --git a/.agents/docs/mobile-release-handoff.md b/.agents/docs/mobile-release-handoff.md
index cd4160fc5..87e89bef1 100644
--- a/.agents/docs/mobile-release-handoff.md
+++ b/.agents/docs/mobile-release-handoff.md
@@ -164,7 +164,32 @@ binaries and deploy the backend first.
7. Run the [signed-device test matrix](#signed-device-test-matrix) on the store-installed builds before promoting to production.
8. Confirm that a later OTA update reaches the new binary, because its fingerprint and runtime version changed.
-Distribution is store-only. No IPA, AAB, or APK is attached to GitHub Releases. An IPA cannot be installed outside the App Store or TestFlight, and an AAB cannot be installed directly. A sideloaded APK would need a separate build profile and signing key. It could not upgrade a Play install or be upgraded by one, so users would lose local drafts on switching. Its certificate fingerprint would also need adding to `MOBILE_ANDROID_CERT_SHA256` for App Links and native sign-in to work.
+Stable distribution uses the App Store and Play Store. IPA and AAB files are not attached to GitHub Releases. Nightly Android APKs are published separately for sideloading as described below; they do not replace store builds or store review.
+
+### Nightly Android downloads
+
+Every push to `main` builds signed APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64`
+with Expo Prebuild, Gradle, and the existing Fastlane Android build lane. Builds use
+the Android upload keystore already stored in Actions secrets; `EXPO_TOKEN` loads
+the preview environment. `MOBILE_UPDATE_CHANNEL=preview` embeds the preview update
+channel. Nightlies use version code 1 without allocating store build numbers.
+
+Once all APKs and the matching Docker image succeed, CI publishes a GitHub prerelease
+named `nightly-<workflow-run-id>` at that exact main commit. It contains the three
+APKs, SHA-256 checksums, and a changelog of that push's full commit messages and merged
+PR descriptions. Each push is preserved even when builds finish out of order. Stable
+release aliases and production OTA publishing follow their existing promotion flow.
+
+The APKs retain package `me.rxresu`. Their upload signing certificate may differ from
+Play App Signing, so they cannot necessarily upgrade a Play installation or be
+upgraded by one. Back up local drafts before uninstalling to switch distributions.
+Retain the same upload signing key for future APK updates. For verified App Links,
+add its certificate fingerprint to the backend's `MOBILE_ANDROID_CERT_SHA256` list
+alongside the Play fingerprint; do not replace the Play fingerprint. Test native
+sign-in on an actual sideloaded build before advertising it as verified.
+
+See [container publishing](./container-publishing.md#nightly-android-apks-and-github-releases)
+for artifact retention, draft recovery, runner tools, and release permissions.
## Native artifacts and signing
diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml
index 849a4fc30..8f953307b 100644
--- a/.github/workflows/docker-build.yml
+++ b/.github/workflows/docker-build.yml
@@ -174,6 +174,169 @@ jobs:
if-no-files-found: error
retention-days: 1
+ mobile-apk:
+ needs: mode
+ if: ${{ needs.mode.outputs.nightly == 'true' }}
+ strategy:
+ fail-fast: false
+ matrix:
+ abi: [arm64-v8a, armeabi-v7a, x86_64]
+ runs-on: ${{ vars.USE_BLACKSMITH == 'true' && 'blacksmith-32vcpu-ubuntu-2404' || 'ubuntu-latest' }}
+ timeout-minutes: 60
+ permissions:
+ contents: read
+ env:
+ CI: "1"
+ EXPO_NO_TELEMETRY: "1"
+ FASTLANE_SKIP_UPDATE_CHECK: "1"
+ FASTLANE_HIDE_CHANGELOG: "1"
+ FASTLANE_OPT_OUT_USAGE: "1"
+ BUNDLE_GEMFILE: ${{ github.workspace }}/tooling/mobile/Gemfile
+ MOBILE_UPDATE_CHANNEL: preview
+ MOBILE_BUILD_NUMBER: "1"
+
+ steps:
+ - name: Check Android signing credentials
+ env:
+ EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
+ ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
+ ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
+ ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
+ ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
+ run: |
+ for name in EXPO_TOKEN ANDROID_KEYSTORE_BASE64 ANDROID_KEYSTORE_PASSWORD ANDROID_KEY_ALIAS ANDROID_KEY_PASSWORD; do
+ if [[ -z "${!name}" ]]; then
+ echo "::error::Missing Actions secret: $name"
+ exit 1
+ fi
+ done
+
+ - name: Checkout Repository
+ if: ${{ vars.USE_BLACKSMITH != 'true' }}
+ uses: actions/checkout@v7
+ with: &checkout-mobile-apk
+ ref: ${{ github.sha }}
+ persist-credentials: false
+
+ - name: Checkout Repository (Blacksmith)
+ if: ${{ vars.USE_BLACKSMITH == 'true' }}
+ uses: useblacksmith/checkout@v1
+ with: *checkout-mobile-apk
+
+ - name: Install pnpm
+ uses: pnpm/action-setup@v6
+
+ - name: Setup Node
+ uses: actions/setup-node@v7
+ with:
+ node-version-file: .nvmrc
+ cache: pnpm
+
+ - name: Setup Java
+ uses: actions/setup-java@v5
+ with:
+ distribution: temurin
+ java-version: "17"
+
+ - name: Setup Ruby and Fastlane
+ uses: ruby/setup-ruby@v1
+ with:
+ ruby-version: "3.3"
+ bundler-cache: true
+ working-directory: tooling/mobile
+
+ - name: Check Android build and signing behavior
+ run: ruby tooling/mobile/build_test.rb
+
+ - name: Setup Android SDK and Forme NDK
+ uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4.0.4
+ with:
+ packages: platform-tools platforms;android-37 build-tools;37.0.0 ndk;27.1.12297006 ndk;28.2.13676358 cmake;3.22.1
+
+ - name: Install Dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Setup EAS
+ uses: expo/expo-github-action@v9
+ with:
+ eas-version: 25.2.0
+ token: ${{ secrets.EXPO_TOKEN }}
+
+ - name: Build signed architecture APK
+ working-directory: apps/mobile
+ env:
+ ABI: ${{ matrix.abi }}
+ ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
+ ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
+ ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
+ ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
+ run: |
+ node ../../packages/forme-native/scripts/fetch-prebuilt.mjs --platform android
+ eas env:exec preview --non-interactive \
+ 'pnpm exec expo prebuild --platform android --clean --no-install && cd ../../tooling/mobile && bundle exec fastlane android build abi:"$ABI"'
+
+ - name: Verify APK signature and architecture
+ env:
+ ABI: ${{ matrix.abi }}
+ run: |
+ set -euo pipefail
+ apk="$RUNNER_TEMP/mobile-release/reactive-resume-$ABI.apk"
+ "$ANDROID_HOME/build-tools/37.0.0/apksigner" verify --verbose --print-certs "$apk"
+ abis=$(unzip -Z1 "$apk" | awk -F/ '/^lib\/[^/]+\/.*\.so$/ {print $2}' | sort -u)
+ [[ "$abis" == "$ABI" ]]
+ unzip -Z1 "$apk" > "$RUNNER_TEMP/apk-entries.txt"
+ grep -Fx "lib/$ABI/libforme_native.so" "$RUNNER_TEMP/apk-entries.txt"
+
+ - name: Upload APK
+ uses: actions/upload-artifact@v7
+ with:
+ name: nightly-apk-${{ matrix.abi }}
+ path: ${{ runner.temp }}/mobile-release/*.apk
+ if-no-files-found: error
+ retention-days: 14
+
+ nightly-release:
+ needs: [mode, merge, mobile-apk]
+ if: ${{ needs.mode.outputs.nightly == 'true' }}
+ runs-on: ${{ vars.USE_BLACKSMITH == 'true' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-latest' }}
+ timeout-minutes: 10
+ permissions:
+ contents: write
+ pull-requests: read
+
+ steps:
+ - name: Checkout Repository
+ if: ${{ vars.USE_BLACKSMITH != 'true' }}
+ uses: actions/checkout@v7
+ with: &checkout-nightly-release
+ ref: ${{ github.sha }}
+ fetch-depth: 0
+ persist-credentials: false
+
+ - name: Checkout Repository (Blacksmith)
+ if: ${{ vars.USE_BLACKSMITH == 'true' }}
+ uses: useblacksmith/checkout@v1
+ with: *checkout-nightly-release
+
+ - name: Setup Node
+ uses: actions/setup-node@v7
+ with:
+ node-version-file: .nvmrc
+
+ - name: Download architecture APKs
+ uses: actions/download-artifact@v8
+ with:
+ pattern: nightly-apk-*
+ path: ${{ runner.temp }}/apks
+ merge-multiple: true
+
+ - name: Publish nightly release with changelog
+ uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
+ with:
+ script: |
+ const { publishNightly } = await import(`${process.env.GITHUB_WORKSPACE}/tooling/releases/nightly.mjs`);
+ await publishNightly({ github, context, artifactDir: `${process.env.RUNNER_TEMP}/apks` });
+
merge:
# Release runs skip build; failed builds must never publish partial indexes.
if: ${{ !cancelled() && needs.mode.result == 'success' && (needs.build.result == 'success' || needs.build.result == 'skipped') }}
diff --git a/.github/workflows/mobile-release.yml b/.github/workflows/mobile-release.yml
index a5773fb9f..a8c2f4ec8 100644
--- a/.github/workflows/mobile-release.yml
+++ b/.github/workflows/mobile-release.yml
@@ -100,7 +100,9 @@ jobs:
bundler-cache: true
working-directory: tooling/mobile
- name: Check signing file handling
- run: bundle exec ruby tooling/mobile/signing_test.rb
+ run: |
+ bundle exec ruby tooling/mobile/signing_test.rb
+ ruby tooling/mobile/build_test.rb
- name: Check beta distribution targets
run: ruby tooling/mobile/distribution_test.rb
- uses: actions/setup-java@v5
diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts
index b70c1ebaf..befa2437e 100644
--- a/apps/mobile/app.config.ts
+++ b/apps/mobile/app.config.ts
@@ -14,7 +14,7 @@ const config: ExpoConfig = {
runtimeVersion: { policy: "fingerprint" },
updates: {
url: "https://u.expo.dev/5830280e-e1ba-45b7-b9c9-ba048fa3bd4d",
- requestHeaders: { "expo-channel-name": "production" },
+ requestHeaders: { "expo-channel-name": process.env.MOBILE_UPDATE_CHANNEL ?? "production" },
checkAutomatically: "ON_LOAD",
fallbackToCacheTimeout: 0,
},
diff --git a/tooling/mobile/build_test.rb b/tooling/mobile/build_test.rb
new file mode 100644
index 000000000..cd1a274d8
--- /dev/null
+++ b/tooling/mobile/build_test.rb
@@ -0,0 +1,83 @@
+require "tmpdir"
+
+# Exercise the real build lane while replacing only Gradle and the Fastlane DSL.
+class AndroidBuildContract
+ attr_reader :gradle_options, :keystore_path
+
+ def initialize
+ @lanes = {}
+ instance_eval(File.read(File.join(__dir__, "fastlane/Fastfile")), File.join(__dir__, "fastlane/Fastfile"))
+ end
+
+ def desc(_description); end
+
+ def platform(name)
+ @platform = name
+ yield
+ end
+
+ def lane(name, &block)
+ @lanes[[@platform, name]] = block
+ end
+
+ def build(options = {})
+ instance_exec(options, &@lanes.fetch([:android, :build]))
+ end
+
+ def gradle(**options)
+ @gradle_options = options
+ @keystore_path = options.fetch(:properties).fetch("android.injected.signing.store.file")
+ raise "Missing keystore" unless File.binread(@keystore_path) == "fixture"
+ raise "Keystore permissions" unless File.stat(@keystore_path).mode & 0777 == 0600
+ File.write(File.join(ENV.fetch("RUNNER_TEMP"), "fixture.apk"), "signed APK")
+ File.write(File.join(ENV.fetch("RUNNER_TEMP"), "fixture.aab"), "signed AAB")
+ end
+
+ def lane_context
+ {
+ SharedValues::GRADLE_APK_OUTPUT_PATH => File.join(ENV.fetch("RUNNER_TEMP"), "fixture.apk"),
+ SharedValues::GRADLE_AAB_OUTPUT_PATH => File.join(ENV.fetch("RUNNER_TEMP"), "fixture.aab")
+ }
+ end
+end
+
+module SharedValues
+ GRADLE_APK_OUTPUT_PATH = :apk
+ GRADLE_AAB_OUTPUT_PATH = :aab
+end
+
+module UI
+ def self.user_error!(message)
+ raise message
+ end
+end
+
+Dir.mktmpdir do |directory|
+ ENV.update(
+ "RUNNER_TEMP" => directory,
+ "ANDROID_KEYSTORE_BASE64" => "Zml4dHVyZQ==",
+ "ANDROID_KEYSTORE_PASSWORD" => "fixture-store",
+ "ANDROID_KEY_ALIAS" => "fixture-alias",
+ "ANDROID_KEY_PASSWORD" => "fixture-key"
+ )
+ contract = AndroidBuildContract.new
+ [nil, "arm64-v8a", "armeabi-v7a", "x86_64"].each do |abi|
+ contract.build(abi ? { abi: abi } : {})
+ options = contract.gradle_options
+ raise "Wrong Gradle task" unless options[:task] == (abi ? "assemble" : "bundle")
+ raise "Wrong ABI filter" unless options[:properties]["reactNativeArchitectures"] == abi
+ raise "Signing command exposed" unless options[:print_command] == false
+ raise "Keystore leaked" if File.exist?(contract.keystore_path)
+ name = abi ? "reactive-resume-#{abi}.apk" : "ReactiveResume.aab"
+ expected = abi ? "signed APK" : "signed AAB"
+ raise "Wrong artifact" unless File.read(File.join(directory, "mobile-release", name)) == expected
+ end
+ begin
+ contract.build(abi: "invalid")
+ raise "Invalid ABI accepted"
+ rescue RuntimeError => error
+ raise unless error.message == "Unsupported Android ABI"
+ end
+end
+
+puts "Android build contract passed: store AAB, three nightly APK ABIs, signing cleanup, invalid ABI rejection."
diff --git a/tooling/mobile/fastlane/Fastfile b/tooling/mobile/fastlane/Fastfile
index 817b99da7..bc1c916ed 100644
--- a/tooling/mobile/fastlane/Fastfile
+++ b/tooling/mobile/fastlane/Fastfile
@@ -14,23 +14,27 @@ def secret_file(directory, name, value, base64: false)
end
platform :android do
- desc "Build a signed production App Bundle"
- lane :build do
+ desc "Build a signed production App Bundle, or a nightly APK for the requested ABI"
+ lane :build do |options|
+ abi = options[:abi]
+ UI.user_error!("Unsupported Android ABI") if abi && !%w[arm64-v8a armeabi-v7a x86_64].include?(abi)
FileUtils.mkdir_p(OUTPUT)
Dir.mktmpdir("android-signing-", ENV.fetch("RUNNER_TEMP")) do |directory|
keystore = secret_file(directory, "upload.jks", ENV.fetch("ANDROID_KEYSTORE_BASE64"), base64: true)
gradle(
project_dir: File.join(MOBILE, "android"),
- task: "bundle", build_type: "Release", flags: "--no-daemon",
+ task: abi ? "assemble" : "bundle", build_type: "Release", flags: "--no-daemon",
print_command: false,
properties: {
"android.injected.signing.store.file" => keystore,
"android.injected.signing.store.password" => ENV.fetch("ANDROID_KEYSTORE_PASSWORD"),
"android.injected.signing.key.alias" => ENV.fetch("ANDROID_KEY_ALIAS"),
"android.injected.signing.key.password" => ENV.fetch("ANDROID_KEY_PASSWORD")
- }
+ }.merge(abi ? { "reactNativeArchitectures" => abi } : {})
)
- FileUtils.cp(lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH], File.join(OUTPUT, "ReactiveResume.aab"))
+ source = lane_context[abi ? SharedValues::GRADLE_APK_OUTPUT_PATH : SharedValues::GRADLE_AAB_OUTPUT_PATH]
+ name = abi ? "reactive-resume-#{abi}.apk" : "ReactiveResume.aab"
+ FileUtils.cp(source, File.join(OUTPUT, name))
maps = File.join(MOBILE, "android/app/build/generated/sourcemaps/react/release")
FileUtils.cp_r(maps, File.join(OUTPUT, "sourcemaps")) if Dir.exist?(maps)
end
diff --git a/tooling/releases/nightly.mjs b/tooling/releases/nightly.mjs
new file mode 100644
index 000000000..3093e9501
--- /dev/null
+++ b/tooling/releases/nightly.mjs
@@ -0,0 +1,151 @@
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+export const androidAbis = ["arm64-v8a", "armeabi-v7a", "x86_64"];
+
+export function getPushCommits({ before, sha, cwd = process.cwd() }) {
+ if (!/^[a-f0-9]{40}$/.test(sha) || !/^[a-f0-9]{40}$/.test(before)) {
+ throw new Error("Expected full commit SHAs from a push event");
+ }
+ const git = (...args) => execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).trim();
+ // A newly created main branch has no previous tip. Include its head rather than the entire repository history.
+ const range = /^0+$/.test(before) ? ["--max-count=1", sha] : [`${before}..${sha}`];
+ return git("rev-list", "--reverse", ...range, "--")
+ .split("\n")
+ .filter(Boolean)
+ .map((commit) => ({ sha: commit, message: git("show", "-s", "--format=%B", commit, "--") }));
+}
+
+export async function buildChangelog({ github, repo, commits, sha, before, serverUrl, runId }) {
+ const url = `${serverUrl}/${repo.owner}/${repo.repo}`;
+ const pulls = new Map();
+ for (const commit of commits) {
+ const associated = await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, {
+ ...repo,
+ commit_sha: commit.sha,
+ per_page: 100,
+ });
+ for (const pull of associated) {
+ if (pull.merged_at && pull.base.ref === "main") pulls.set(pull.number, pull);
+ }
+ }
+ const lines = [
+ `Nightly build of [\`${sha}\`](${url}/commit/${sha}) from main.`,
+ `[Build logs](${url}/actions/runs/${runId}) · Docker: \`ghcr.io/${repo.owner.toLowerCase()}/${repo.repo.toLowerCase()}:sha-${sha}\``,
+ "",
+ "## Android downloads",
+ "",
+ "Choose the APK matching your device: arm64-v8a (64-bit ARM), armeabi-v7a (32-bit ARM), or x86_64 (64-bit Intel/AMD). Verify downloads against SHA256SUMS.",
+ "",
+ "APKs use the existing Android upload signing key and the preview update channel. Play Store installs may use a different signing key and cannot be upgraded with these APKs. Back up local drafts before switching distributions.",
+ "",
+ "## Commits in this push",
+ "",
+ ];
+ if (!/^0+$/.test(before)) lines.push(`[Compare changes](${url}/compare/${before}...${sha})`, "");
+ for (const commit of commits) {
+ lines.push(`### [\`${commit.sha.slice(0, 7)}\`](${url}/commit/${commit.sha})`, "");
+ lines.push(...commit.message.split("\n").map((line) => `> ${line}`), "");
+ }
+ lines.push("## Pull request summaries", "");
+ if (pulls.size === 0) lines.push("No merged pull requests associated with these commits.", "");
+ for (const pull of pulls.values()) {
+ const title = pull.title.replace(/[\r\n]/g, " ").replace(/[\\`*_[\]<>]/g, "\\$&");
+ lines.push(
+ `### [#${pull.number}](${pull.html_url}) ${title}`,
+ "",
+ pull.body?.trim() || "No description provided.",
+ "",
+ );
+ }
+ return lines.join("\n");
+}
+
+export async function publishNightly({ github, context, artifactDir, sourceDir = process.cwd() }) {
+ if (context.eventName !== "push" || context.ref !== "refs/heads/main") {
+ throw new Error("Nightly releases require a push to main");
+ }
+ const repo = context.repo;
+ const sha = context.sha;
+ const tag = `nightly-${context.runId}`;
+ const names = androidAbis.map((abi) => `reactive-resume-${abi}.apk`);
+ // Read every required artifact before creating a release; partial matrices must never publish.
+ const apks = await Promise.all(names.map((name) => readFile(join(artifactDir, name))));
+ if (apks.some((apk) => apk.length === 0)) throw new Error("Empty APK artifact");
+ const checksums = apks
+ .map((apk, index) => `${createHash("sha256").update(apk).digest("hex")} ${names[index]}\n`)
+ .join("");
+ await writeFile(join(artifactDir, "SHA256SUMS"), checksums);
+
+ let release;
+ try {
+ release = (await github.rest.repos.getReleaseByTag({ ...repo, tag })).data;
+ } catch (error) {
+ if (error.status !== 404) throw error;
+ }
+ if (release) {
+ if (release.target_commitish !== sha || !release.prerelease)
+ throw new Error("Existing release does not match build");
+ // Published assets stay immutable on reruns, including repositories enforcing release immutability.
+ if (!release.draft) return release.html_url;
+ }
+
+ const before = context.payload.before;
+ const commits = getPushCommits({ before, sha, cwd: sourceDir });
+ const changelog = await buildChangelog({
+ github,
+ repo,
+ commits,
+ sha,
+ before,
+ serverUrl: context.serverUrl,
+ runId: context.runId,
+ });
+ await writeFile(join(artifactDir, "CHANGELOG.md"), changelog);
+ const body =
+ changelog.length <= 60_000
+ ? changelog
+ : `${changelog.slice(0, 59_000)}\n\n[Full changelog](${context.serverUrl}/${repo.owner}/${repo.repo}/releases/download/${tag}/CHANGELOG.md)`;
+ if (!release) {
+ release = (
+ await github.rest.repos.createRelease({
+ ...repo,
+ tag_name: tag,
+ target_commitish: sha,
+ name: `Nightly ${tag.slice("nightly-".length)} (${sha.slice(0, 7)})`,
+ body,
+ draft: true,
+ prerelease: true,
+ make_latest: "false",
+ })
+ ).data;
+ }
+ // A failed upload leaves a recoverable draft. Reruns replace only assets on that draft.
+ const assets = await github.paginate(github.rest.repos.listReleaseAssets, {
+ ...repo,
+ release_id: release.id,
+ per_page: 100,
+ });
+ for (const name of [...names, "SHA256SUMS", "CHANGELOG.md"]) {
+ const existing = assets.find((asset) => asset.name === name);
+ if (existing) await github.rest.repos.deleteReleaseAsset({ ...repo, asset_id: existing.id });
+ await github.rest.repos.uploadReleaseAsset({
+ ...repo,
+ release_id: release.id,
+ name,
+ headers: { "content-type": name.endsWith(".apk") ? "application/vnd.android.package-archive" : "text/plain" },
+ data: await readFile(join(artifactDir, name)),
+ });
+ }
+ const published = await github.rest.repos.updateRelease({
+ ...repo,
+ release_id: release.id,
+ body,
+ draft: false,
+ prerelease: true,
+ make_latest: "false",
+ });
+ return published.data.html_url;
+}
diff --git a/tooling/releases/nightly.test.mjs b/tooling/releases/nightly.test.mjs
new file mode 100644
index 000000000..7f1098022
--- /dev/null
+++ b/tooling/releases/nightly.test.mjs
@@ -0,0 +1,210 @@
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it, vi } from "vite-plus/test";
+import { androidAbis, buildChangelog, getPushCommits, publishNightly } from "./nightly.mjs";
+
+const directories = [];
+afterEach(async () => {
+ await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })));
+});
+
+async function temporaryDirectory() {
+ const directory = await mkdtemp(join(tmpdir(), "nightly-release-"));
+ directories.push(directory);
+ return directory;
+}
+
+async function repository() {
+ const cwd = await temporaryDirectory();
+ const git = (...args) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
+ git("init", "--quiet");
+ git("config", "user.name", "Release Test");
+ git("config", "user.email", "[email protected]");
+ const commit = (message) => {
+ git("-c", "commit.gpgsign=false", "commit", "--quiet", "--allow-empty", "-m", message);
+ return git("rev-parse", "HEAD");
+ };
+ const before = commit("existing history");
+ return { cwd, before, commit };
+}
+
+function githubFixture() {
+ const repos = {
+ listPullRequestsAssociatedWithCommit: vi.fn(async () => ({ data: [] })),
+ getReleaseByTag: vi.fn(async () => {
+ throw Object.assign(new Error("Not found"), { status: 404 });
+ }),
+ createRelease: vi.fn(async (input) => ({ data: { id: 17, ...input } })),
+ listReleaseAssets: vi.fn(async () => ({ data: [] })),
+ deleteReleaseAsset: vi.fn(async () => ({})),
+ uploadReleaseAsset: vi.fn(async () => ({})),
+ updateRelease: vi.fn(async () => ({
+ data: { html_url: "https://github.com/example/resume/releases/tag/nightly-42" },
+ })),
+ };
+ return { rest: { repos }, paginate: vi.fn(async (method, input) => (await method(input)).data) };
+}
+
+async function publishingFixture() {
+ const source = await repository();
+ const sha = source.commit("fix: export\n\nPreserve all fonts.");
+ const artifactDir = await temporaryDirectory();
+ for (const abi of androidAbis) await writeFile(join(artifactDir, `reactive-resume-${abi}.apk`), `signed ${abi}`);
+ const context = {
+ eventName: "push",
+ ref: "refs/heads/main",
+ repo: { owner: "example", repo: "resume" },
+ sha,
+ runId: 42,
+ serverUrl: "https://github.com",
+ payload: { before: source.before },
+ };
+ return { github: githubFixture(), context, artifactDir, sourceDir: source.cwd };
+}
+
+it("reads the complete push from Git, including bodies and more than 20 commits", async () => {
+ const source = await repository();
+ const shas = Array.from({ length: 25 }, (_, index) =>
+ source.commit(`fix: change ${index}\n\nDetailed message ${index}`),
+ );
+ const sha = shas.at(-1);
+ const commits = getPushCommits({ before: source.before, sha, cwd: source.cwd });
+ expect(commits.map((commit) => commit.sha)).toEqual(shas);
+ expect(commits.at(-1).message).toBe("fix: change 24\n\nDetailed message 24");
+ expect(getPushCommits({ before: "0".repeat(40), sha, cwd: source.cwd })).toEqual([commits.at(-1)]);
+ expect(() => getPushCommits({ before: source.before, sha: "--all", cwd: source.cwd })).toThrow("full commit SHAs");
+});
+
+it("includes commit bodies and deduplicated merged main PR summaries, without executing their text", async () => {
+ const github = githubFixture();
+ const pull = {
+ number: 12,
+ title: "fix: PDF [export]",
+ html_url: "https://github.com/example/resume/pull/12",
+ body: "## Summary\n\nPreserve fonts. Literal `$(echo unsafe)` remains text.",
+ merged_at: "2026-10-22T00:00:00Z",
+ base: { ref: "main" },
+ };
+ github.rest.repos.listPullRequestsAssociatedWithCommit.mockResolvedValue({
+ data: [pull, { ...pull, number: 13, merged_at: null }, { ...pull, number: 14, base: { ref: "other" } }],
+ });
+ const body = await buildChangelog({
+ github,
+ repo: { owner: "example", repo: "resume" },
+ commits: [
+ { sha: "a".repeat(40), message: "fix: fonts\n\nFull body" },
+ { sha: "b".repeat(40), message: "fix: layout" },
+ ],
+ sha: "b".repeat(40),
+ before: "c".repeat(40),
+ serverUrl: "https://github.com",
+ runId: 42,
+ });
+ expect(body).toContain("> fix: fonts\n> \n> Full body");
+ expect(body).toContain(pull.body);
+ expect(body.match(/### \[#12\]/g)).toHaveLength(1);
+ expect(body).not.toContain("### [#13]");
+ expect(body).not.toContain("### [#14]");
+ expect(github.paginate).toHaveBeenCalledTimes(2);
+});
+
+it("stages all APKs, checksums and full changelog before publishing a prerelease at the exact SHA", async () => {
+ const fixture = await publishingFixture();
+ const repos = fixture.github.rest.repos;
+ await publishNightly(fixture);
+ expect(repos.createRelease).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tag_name: "nightly-42",
+ target_commitish: fixture.context.sha,
+ draft: true,
+ prerelease: true,
+ make_latest: "false",
+ }),
+ );
+ expect(repos.uploadReleaseAsset.mock.calls.map(([input]) => input.name)).toEqual([
+ ...androidAbis.map((abi) => `reactive-resume-${abi}.apk`),
+ "SHA256SUMS",
+ "CHANGELOG.md",
+ ]);
+ const checksum = createHash("sha256").update("signed arm64-v8a").digest("hex");
+ expect(await readFile(join(fixture.artifactDir, "SHA256SUMS"), "utf8")).toContain(
+ `${checksum} reactive-resume-arm64-v8a.apk\n`,
+ );
+ expect(await readFile(join(fixture.artifactDir, "CHANGELOG.md"), "utf8")).toContain("Preserve all fonts.");
+ expect(repos.updateRelease).toHaveBeenCalledWith(
+ expect.objectContaining({ draft: false, prerelease: true, make_latest: "false" }),
+ );
+ expect(repos.updateRelease.mock.invocationCallOrder[0]).toBeGreaterThan(
+ repos.uploadReleaseAsset.mock.invocationCallOrder.at(-1),
+ );
+});
+
+it("withholds publishing after upload failure, then resumes the same draft on rerun", async () => {
+ const fixture = await publishingFixture();
+ const repos = fixture.github.rest.repos;
+ repos.uploadReleaseAsset.mockRejectedValueOnce(new Error("Upload failed"));
+ await expect(publishNightly(fixture)).rejects.toThrow("Upload failed");
+ expect(repos.updateRelease).not.toHaveBeenCalled();
+ repos.getReleaseByTag.mockResolvedValue({
+ data: { id: 17, target_commitish: fixture.context.sha, prerelease: true, draft: true },
+ });
+ repos.listReleaseAssets.mockResolvedValue({ data: [{ id: 9, name: "reactive-resume-arm64-v8a.apk" }] });
+ await publishNightly(fixture);
+ expect(repos.createRelease).toHaveBeenCalledTimes(1);
+ expect(repos.deleteReleaseAsset).toHaveBeenCalledWith(expect.objectContaining({ asset_id: 9 }));
+ expect(repos.updateRelease).toHaveBeenCalledTimes(1);
+});
+
+it("leaves an already published release and its assets untouched on rerun", async () => {
+ const fixture = await publishingFixture();
+ const repos = fixture.github.rest.repos;
+ repos.getReleaseByTag.mockResolvedValue({
+ data: { id: 17, target_commitish: fixture.context.sha, prerelease: true, draft: false, html_url: "existing" },
+ });
+ expect(await publishNightly(fixture)).toBe("existing");
+ expect(repos.createRelease).not.toHaveBeenCalled();
+ expect(repos.uploadReleaseAsset).not.toHaveBeenCalled();
+ expect(repos.updateRelease).not.toHaveBeenCalled();
+});
+
+it("attaches oversized changelogs in full while keeping the release description within API limits", async () => {
+ const fixture = await publishingFixture();
+ const summary = "Detailed PR summary. ".repeat(4000);
+ const repos = fixture.github.rest.repos;
+ repos.listPullRequestsAssociatedWithCommit.mockResolvedValue({
+ data: [
+ {
+ number: 12,
+ title: "Large change",
+ body: summary,
+ html_url: "https://github.com/example/resume/pull/12",
+ merged_at: "2026-10-22",
+ base: { ref: "main" },
+ },
+ ],
+ });
+ await publishNightly(fixture);
+ expect(repos.createRelease.mock.calls[0][0].body.length).toBeLessThan(60_000);
+ expect(repos.createRelease.mock.calls[0][0].body).toContain("/nightly-42/CHANGELOG.md");
+ expect(await readFile(join(fixture.artifactDir, "CHANGELOG.md"), "utf8")).toContain(summary.trim());
+});
+
+it("fails on release API authorization errors instead of treating them as missing releases", async () => {
+ const fixture = await publishingFixture();
+ const repos = fixture.github.rest.repos;
+ repos.getReleaseByTag.mockRejectedValue(Object.assign(new Error("Forbidden"), { status: 403 }));
+ await expect(publishNightly(fixture)).rejects.toThrow("Forbidden");
+ expect(repos.createRelease).not.toHaveBeenCalled();
+});
+
+it("rejects incomplete APK matrices and non-main events before creating a release", async () => {
+ const fixture = await publishingFixture();
+ await rm(join(fixture.artifactDir, "reactive-resume-x86_64.apk"));
+ await expect(publishNightly(fixture)).rejects.toThrow("ENOENT");
+ fixture.context.ref = "refs/heads/other";
+ await expect(publishNightly(fixture)).rejects.toThrow("push to main");
+ expect(fixture.github.rest.repos.createRelease).not.toHaveBeenCalled();
+});