diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 9d2eddc75..b54256d44 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -95,6 +95,8 @@ All stable kinds (`patch`, `minor`, `major`) are computed off the latest *stable **Safety guarantees:** - Stable releases are refused if the new version isn't strictly greater than the latest published stable. This is the only rule `electron-updater` actually needs — it compares semver within the `latest` channel, so a regressing stable is the one thing that breaks auto-update for fresh installs. +- Complete RC draft releases created by the release workflow are published before cutting a new tag, so a GitHub queue failure in the final publish job can be resumed safely. +- If the latest RC tag exists but is still draft-only or missing its GitHub Release, the workflow resumes that tag before cutting the next RC. This keeps retries from leaving multiple unpublished draft releases behind. - Off-main releases (when `ref` is not the tip of `main`) only push the tag. `main` is never mutated from a non-main ref, so you can safely release an older commit without polluting history. - When `ref` is the tip of `main`, the version-bump commit is fast-forwarded onto `main` so local `package.json` stays in sync with what's shipped. diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index 5128f74d0..4851157bc 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -16,7 +16,7 @@ name: Cut Release # 5. Write package.json, commit (detached), tag, push tag. # 6. If ref was the tip of origin/main, fast-forward main to include the # version-bump commit so developers see the right version locally. -# 7. Invoke release.yml to build and publish artifacts. +# 7. Build and publish artifacts from the tag. on: workflow_dispatch: @@ -61,7 +61,7 @@ jobs: timeout-minutes: 15 outputs: tag: ${{ steps.tag.outputs.tag || steps.version.outputs.recovered_tag }} - should_release: ${{ steps.window.outputs.allowed == 'true' && steps.existing.outputs.already_ran != 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) }} + should_release: ${{ steps.tag.outputs.tag != '' || steps.version.outputs.recovered_tag != '' }} steps: - name: Checkout ref uses: actions/checkout@v4 @@ -174,9 +174,21 @@ jobs: echo "Already ran this slot: ${{ steps.existing.outputs.already_ran }}" echo "Reason: ${{ steps.existing.outputs.reason }}" + - name: Publish complete release-cut RC drafts from prior runs + id: publish_drafts + # Why: this must run even when the current slot already cut a tag; a + # later cron retry may be the first chance to unstick a complete RC draft. + if: steps.window.outputs.allowed == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node config/scripts/publish-complete-draft-releases.mjs + - name: Compute next version id: version - if: steps.window.outputs.allowed == 'true' && steps.existing.outputs.already_ran != 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) + # Why: if an RC run only had complete drafts to publish, stop there + # instead of immediately cutting another RC after the recovered one. + # Stable dispatches should still cut the requested stable release. + if: steps.window.outputs.allowed == 'true' && steps.existing.outputs.already_ran != 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) && !((github.event_name == 'schedule' || inputs.kind == 'rc') && steps.publish_drafts.outputs.published_count != '0' && steps.publish_drafts.outputs.skipped_count == '0') env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} KIND: ${{ github.event_name == 'schedule' && 'rc' || inputs.kind }} @@ -238,22 +250,50 @@ jobs: ' "$(strip_pre "$1")" "$2" } - next_rc_in_series() { - # Given a base version, find the highest existing -rc.N for it - # and return base-rc.(N+1). If none exists, base-rc.0. + highest_rc_for_base() { local base="$1" - local highest - highest="$(git tag --list "v${base}-rc.*" \ + git tag --list "v${base}-rc.*" \ | sed -E "s/^v${base//./\\.}-rc\.//" \ | sort -n \ - | tail -n 1 || true)" - if [[ -z "$highest" ]]; then - echo "${base}-rc.0" + | tail -n 1 || true + } + + release_draft_state() { + # Prints: true, false, or missing. + local tag="$1" + local state_file="$RUNNER_TEMP/release-state-${tag//[^A-Za-z0-9_.-]/_}" + if gh release view "$tag" \ + --repo "$GITHUB_REPOSITORY" \ + --json isDraft \ + --jq '.isDraft' >"$state_file" 2>/dev/null; then + cat "$state_file" else - echo "${base}-rc.$((highest + 1))" + echo "missing" fi } + recover_unpublished_tag() { + local tag="$1" + local reason="$2" + local release_state + release_state="$(release_draft_state "$tag")" + case "$release_state" in + missing|true) + echo "::warning::Tag $tag already exists but has no published release ($reason) - recovering by re-dispatching the release build against the existing tag." + echo "recovered_tag=$tag" >>"$GITHUB_OUTPUT" + echo "recovered=true" >>"$GITHUB_OUTPUT" + exit 0 + ;; + false) + return 1 + ;; + *) + echo "::error::Unexpected release state for $tag: $release_state" >&2 + exit 1 + ;; + esac + } + # Fresh repo fallback so the math below never divides by zero. if [[ -z "$latest_stable" ]]; then latest_stable="0.0.0" @@ -270,7 +310,18 @@ jobs: # that class of bug; minor/major RCs are cut by running # that stable kind first. base="$(bump "$latest_stable" patch)" - new="$(next_rc_in_series "$base")" + highest_rc="$(highest_rc_for_base "$base")" + if [[ -z "$highest_rc" ]]; then + new="${base}-rc.0" + else + existing_rc_tag="v${base}-rc.${highest_rc}" + # Why: a failed or GitHub-stuck run can leave the highest RC + # tag attached to a draft/missing release. Resume that tag so + # retries finish the intended release instead of piling up + # vX.Y.Z-rc.N+1 drafts. + recover_unpublished_tag "$existing_rc_tag" "latest RC in series" || true + new="${base}-rc.$((highest_rc + 1))" + fi ;; patch|minor|major) new="$(bump "$latest_stable" "$KIND")" @@ -289,7 +340,7 @@ jobs: # Orphan-tag recovery. # # Why: if a previous cut pushed the tag but was cancelled (or the - # dependent release.yml job otherwise failed to start) before the + # dependent release build jobs otherwise failed to start) before the # GitHub Release was published, the tag now exists on the remote # but "latest stable" still points at the prior version. Every # subsequent patch cut then recomputes the same version and dies @@ -301,7 +352,7 @@ jobs: # Recovery policy: if the tag exists AND no GitHub release has # been published for it (draft-or-absent both count as "not # shipped"), treat this as a resumable state: emit the existing - # tag as the job output so the downstream release.yml job runs + # tag as the job output so the downstream release build jobs run # against it and finishes what the earlier attempt started. The # bump/commit/push steps are skipped in that case — there is # nothing to bump; the tag is already on the remote. @@ -310,32 +361,10 @@ jobs: # already exist — that's a real conflict (someone tagged manually # over a shipped version) and needs human attention. if git rev-parse "v$new" >/dev/null 2>&1; then - # Why: use the REST API, not `gh release view`. `gh api` returns - # `true`/`false` for a real release, while a 404 means the tag is - # orphaned and can be safely re-dispatched. Capture failures - # explicitly so the 404 payload never leaks into the state check. - release_state="missing" - if gh api \ - "repos/$GITHUB_REPOSITORY/releases/tags/v$new" \ - --jq '.draft' >"$RUNNER_TEMP/release-state" 2>/dev/null; then - release_state="$(cat "$RUNNER_TEMP/release-state")" - fi - case "$release_state" in - missing|true) - echo "::warning::Tag v$new already exists but no published release is attached — recovering by re-dispatching release.yml against the existing tag." - echo "recovered_tag=v$new" >>"$GITHUB_OUTPUT" - echo "recovered=true" >>"$GITHUB_OUTPUT" - exit 0 - ;; - false) - echo "::error::Tag v$new already exists and has a published release. Refusing to re-cut over a shipped version." >&2 - exit 1 - ;; - *) - echo "::error::Unexpected release state for v$new: $release_state" >&2 - exit 1 - ;; - esac + recover_unpublished_tag "v$new" "tag collision" || { + echo "::error::Tag v$new already exists and has a published release. Refusing to re-cut over a shipped version." >&2 + exit 1 + } fi echo "version=$new" >>"$GITHUB_OUTPUT" @@ -680,6 +709,9 @@ jobs: - name: Build app run: pnpm build:release env: + # Why: Vite's web build crossed Node's default old-space ceiling on + # the macOS release runner, leaving v1.4.2-rc.8 as an incomplete draft. + NODE_OPTIONS: --max-old-space-size=4096 ORCA_BUILD_IDENTITY: ${{ steps.tag-classify.outputs.identity }} ORCA_POSTHOG_WRITE_KEY: ${{ secrets.ORCA_POSTHOG_WRITE_KEY }} diff --git a/config/scripts/publish-complete-draft-releases.mjs b/config/scripts/publish-complete-draft-releases.mjs new file mode 100644 index 000000000..68af1d87c --- /dev/null +++ b/config/scripts/publish-complete-draft-releases.mjs @@ -0,0 +1,133 @@ +#!/usr/bin/env node + +import { appendFileSync } from 'node:fs' +import { pathToFileURL } from 'node:url' +import { verifyRequiredReleaseAssets } from './verify-release-required-assets.mjs' + +const API_VERSION = '2022-11-28' +const RELEASE_CUT_AUTHOR = 'github-actions[bot]' +const DESKTOP_RC_TAG_PATTERN = /^v[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+$/ + +export function isReleaseCutDraft(release) { + return ( + release?.draft === true && + release?.author?.login === RELEASE_CUT_AUTHOR && + typeof release?.tag_name === 'string' && + DESKTOP_RC_TAG_PATTERN.test(release.tag_name) + ) +} + +function isRcTag(tag) { + return tag.includes('-rc.') +} + +async function githubJson(fetchImpl, url, token, options = {}) { + const res = await fetchImpl(url, { + ...options, + headers: { + Accept: 'application/vnd.github+json', + Authorization: `Bearer ${token}`, + 'X-GitHub-Api-Version': API_VERSION, + ...options.headers + } + }) + if (!res.ok) { + const body = await res.text().catch(() => '') + throw new Error(`GitHub request failed ${res.status} ${res.statusText}: ${body.slice(0, 300)}`) + } + return res.json() +} + +async function fetchReleases(repo, token, fetchImpl) { + const releases = await githubJson( + fetchImpl, + `https://api.github.com/repos/${repo}/releases?per_page=100`, + token + ) + if (!Array.isArray(releases)) { + throw new Error(`GitHub releases response for ${repo} was not an array`) + } + return releases +} + +export async function publishCompleteDraftReleases({ + repo, + token, + fetchImpl = fetch, + verifyReleaseAssets = verifyRequiredReleaseAssets, + log = console.log +}) { + if (!repo) { + throw new Error('repo is required') + } + if (!token) { + throw new Error('token is required') + } + + const releases = await fetchReleases(repo, token, fetchImpl) + const candidates = releases + .filter(isReleaseCutDraft) + .sort((a, b) => new Date(a.created_at ?? 0).getTime() - new Date(b.created_at ?? 0).getTime()) + + const published = [] + const skipped = [] + + for (const release of candidates) { + const tag = release.tag_name + try { + await verifyReleaseAssets({ repo, tag, token }) + } catch (error) { + const reason = error instanceof Error ? error.message.split('\n')[0] : String(error) + skipped.push({ tag, reason }) + log(`Skipping incomplete RC draft release ${tag}: ${reason}`) + continue + } + + // Why: only release-cut-authored RC drafts with a complete asset set are + // resumed here; incomplete drafts stay private for the normal rebuild path. + await githubJson(fetchImpl, `https://api.github.com/repos/${repo}/releases/${release.id}`, token, { + method: 'PATCH', + body: JSON.stringify({ + draft: false, + prerelease: isRcTag(tag) + }) + }) + published.push(tag) + log(`Published complete RC draft release ${tag}`) + } + + if (published.length === 0 && skipped.length === 0) { + log('No complete release-cut RC drafts to publish.') + } + + return { published, skipped } +} + +export function writeGithubOutputs({ published, skipped }, outputPath = process.env.GITHUB_OUTPUT) { + if (!outputPath) { + return + } + appendFileSync( + outputPath, + `${[ + `published_count=${published.length}`, + `skipped_count=${skipped.length}`, + `published_tags=${published.join(',')}`, + `skipped_tags=${skipped.map((item) => item.tag).join(',')}` + ].join('\n')}\n` + ) +} + +async function main() { + const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN + const repo = process.env.GITHUB_REPOSITORY || 'stablyai/orca' + const result = await publishCompleteDraftReleases({ repo, token }) + writeGithubOutputs(result) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + console.error(error.message) + process.exit(1) + }) +} diff --git a/config/scripts/publish-complete-draft-releases.test.mjs b/config/scripts/publish-complete-draft-releases.test.mjs new file mode 100644 index 000000000..589f5475b --- /dev/null +++ b/config/scripts/publish-complete-draft-releases.test.mjs @@ -0,0 +1,136 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { + isReleaseCutDraft, + publishCompleteDraftReleases, + writeGithubOutputs +} from './publish-complete-draft-releases.mjs' + +function jsonResponse(body, init = {}) { + return { + ok: init.ok ?? true, + status: init.status ?? 200, + statusText: init.statusText ?? 'OK', + json: vi.fn(async () => body), + text: vi.fn(async () => (typeof body === 'string' ? body : JSON.stringify(body))) + } +} + +describe('isReleaseCutDraft', () => { + it('only accepts bot-authored desktop draft releases', () => { + expect( + isReleaseCutDraft({ + draft: true, + tag_name: 'v1.4.2-rc.7', + author: { login: 'github-actions[bot]' } + }) + ).toBe(true) + expect( + isReleaseCutDraft({ + draft: true, + tag_name: 'mobile-v0.0.7', + author: { login: 'github-actions[bot]' } + }) + ).toBe(false) + expect( + isReleaseCutDraft({ + draft: true, + tag_name: 'v1.4.2', + author: { login: 'github-actions[bot]' } + }) + ).toBe(false) + expect( + isReleaseCutDraft({ + draft: false, + tag_name: 'v1.4.2', + author: { login: 'github-actions[bot]' } + }) + ).toBe(false) + }) +}) + +describe('publishCompleteDraftReleases', () => { + it('publishes complete release-cut drafts and skips incomplete ones', async () => { + const fetchImpl = vi + .fn() + .mockResolvedValueOnce( + jsonResponse([ + { + id: 7, + draft: true, + tag_name: 'v1.4.2-rc.7', + created_at: '2026-05-15T07:31:19Z', + author: { login: 'github-actions[bot]' } + }, + { + id: 8, + draft: true, + tag_name: 'v1.4.2-rc.8', + created_at: '2026-05-15T10:51:57Z', + author: { login: 'github-actions[bot]' } + } + ]) + ) + .mockResolvedValueOnce(jsonResponse({ tag_name: 'v1.4.2-rc.7', draft: false })) + const verifyReleaseAssets = vi.fn(async ({ tag }) => { + if (tag === 'v1.4.2-rc.8') { + throw new Error('Release v1.4.2-rc.8 is missing required assets.') + } + }) + const log = vi.fn() + + const result = await publishCompleteDraftReleases({ + repo: 'stablyai/orca', + token: 'token', + fetchImpl, + verifyReleaseAssets, + log + }) + + expect(result).toEqual({ + published: ['v1.4.2-rc.7'], + skipped: [ + { + tag: 'v1.4.2-rc.8', + reason: 'Release v1.4.2-rc.8 is missing required assets.' + } + ] + }) + expect(fetchImpl).toHaveBeenLastCalledWith( + 'https://api.github.com/repos/stablyai/orca/releases/7', + expect.objectContaining({ + method: 'PATCH', + body: JSON.stringify({ draft: false, prerelease: true }) + }) + ) + }) +}) + +describe('writeGithubOutputs', () => { + it('writes count outputs for workflow conditions', () => { + const dir = mkdtempSync(join(tmpdir(), 'orca-release-outputs-')) + const outputPath = join(dir, 'output') + try { + writeGithubOutputs( + { + published: ['v1.4.2-rc.7'], + skipped: [{ tag: 'v1.4.2-rc.8', reason: 'missing assets' }] + }, + outputPath + ) + + expect(readFileSync(outputPath, 'utf8')).toBe( + `${[ + 'published_count=1', + 'skipped_count=1', + 'published_tags=v1.4.2-rc.7', + 'skipped_tags=v1.4.2-rc.8' + ].join('\n')}\n` + ) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/config/vitest.config.ts b/config/vitest.config.ts index bee38dc32..13711cebd 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -10,6 +10,6 @@ export default defineConfig({ }, test: { environment: 'node', - include: ['src/**/*.test.ts', 'src/**/*.test.tsx'] + include: ['src/**/*.test.ts', 'src/**/*.test.tsx', 'config/scripts/**/*.test.mjs'] } })