🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🔨 chore(desktop): pin Stable release source combinations (#22015)
Innei1c08e91e9418
diff --git a/.agents/skills/version-release/SKILL.md b/.agents/skills/version-release/SKILL.mdindex 4f586a6c1e4..031607e35dc 100644--- a/.agents/skills/version-release/SKILL.md+++ b/.agents/skills/version-release/SKILL.md@@ -86,6 +86,7 @@ Before creating the release branch, verify the source branch:Pick the right reference and follow it end-to-end:+- **Desktop Stable sources** (Cloud selection, hotfix baselines, rebuild/import) → [references/desktop-stable-sources.md](references/desktop-stable-sources.md). For release branches and PRs, also read the relevant Minor or Patch workflow below.- **Minor release** → `references/minor-release.md`- **Patch release** (weekly / hotfix / model launch / DB migration) → `references/patch-release-scenarios.md`- **Writing the PR body / release notes** (any release type) → `references/release-notes-style.md`diff --git a/.agents/skills/version-release/references/desktop-stable-sources.md b/.agents/skills/version-release/references/desktop-stable-sources.mdnew file mode 100644index 00000000000..6cf72f6a631--- /dev/null+++ b/.agents/skills/version-release/references/desktop-stable-sources.md@@ -0,0 +1,31 @@+# Desktop Stable Sources++Use this reference for Cloud selection, delivered hotfix baselines, rebuilds and historical imports. For patch branch and PR steps, see [Patch Release Scenarios](./patch-release-scenarios.md).++Stable desktop releases bind OSS and Cloud in the Release asset `desktop-sources.v1.json`. A matching `desktop-published.v1.json` proves the version completed the required delivery stages. A tag or a green job alone is not a delivered hotfix baseline.++| Path | Cloud selection |+| ------------------------------------------------- | ----------------------------------------------------------------------------------- |+| Weekly / explicit ordinary release, first attempt | Resolve Cloud HEAD once and save it before building. |+| Rebuild the same version | Read its existing source record; never choose HEAD again. |+| Hotfix, model-only patch, or targeted migration | Explicitly inherit a delivered base version, with optional documented Cloud repair. |+| Historical version with no record | Import a verified full Cloud SHA and original run/attempt before rebuilding. |++For a hotfix, use `bun run hotfix:branch --base v2.2.21` (the example version must already be delivered). Omit `--base` to select interactively from delivered versions. `--cloud-ref <full-SHA> --reason <repair>` records a Cloud fix on the new version. The script includes the selected base, full Cloud SHA and base-record hash in machine-readable PR metadata.++For an existing manual/Agent-created PR, generate that metadata using the installed GitHub CLI authentication, append the emitted HTML comment unchanged to the PR body, and keep its readable source summary alongside it:++```bash+GITHUB_REPOSITORY=lobehub/lobehub BASE_VERSION=2.2.21 \+ GH_TOKEN="$(gh auth token)" node .github/scripts/desktopReleaseCli.mjs hotfix-intent+```++The **Desktop Release Sources** PR check validates the base's delivery proof, hash and main ancestry. If main includes undelivered product changes, stop and choose the appropriate release path. After merge, auto-tag binds the same intent to the actual PR number, merge SHA and PR base SHA, and passes it to Stable. Automatic and manual hotfix entry points verify that merged PR and its base again. Do not infer the baseline from a patch number or let a missing record fall back to current Cloud HEAD.++Manual `release_mode=hotfix` resumes a Release with that bound intent; optional `base_version`, `cloud_ref` and repair reason inputs must match it. It cannot create a new hotfix intent or bypass PR validation. An older Release without metadata uses explicit historical import instead. For both ordinary and hotfix releases, only attempt 1 may create a missing source record; a later attempt must reuse an existing record or recover explicitly.++To rebuild an older version, run the repaired **Release Desktop Stable** workflow from a ref containing the current release tooling. Select `release_mode=rebuild`, target `version`, and `source_ref=v<version>`; the latter must resolve to that version's tag SHA. Keep both upload-skip inputs enabled for a dry-run. `release_mode=import` is a separate metadata-only operation: supply `cloud_ref`, `evidence_run_id` and `evidence_run_attempt`; it records sources without building or publishing installers. An import does not create delivery proof.++Current Core OTA and Canary/Beta source selection are outside this Stable change. Existing runs use their original workflow code; start a new manual run to use repaired tooling.++For a historical import, inspect that run attempt's logs or diagnostic `cloudRef` and verify it equals the supplied Cloud SHA. The resolver validates the run/attempt and OSS SHA; the operator supplies the verified Cloud evidence. If delivery proof is missing, do not hand-author it: complete the required build/publication checks through the pinned-source pipeline before selecting that version as a delivered hotfix base.diff --git a/.agents/skills/version-release/references/patch-release-scenarios.md b/.agents/skills/version-release/references/patch-release-scenarios.mdindex e32e297d8e7..51077f3be51 100644--- a/.agents/skills/version-release/references/patch-release-scenarios.md+++ b/.agents/skills/version-release/references/patch-release-scenarios.md@@ -2,6 +2,8 @@All Patch Release scenarios automatically bump the patch version (e.g. 2.1.31 → 2.1.32). PR titles do not need to include a version number.+For Desktop Stable releases, read [Desktop Stable Sources](./desktop-stable-sources.md) for Cloud selection, delivered baselines, PR metadata, rebuilds and historical imports.+---## 1. Weekly Release (canary → main)@@ -62,7 +64,7 @@ git checkout -b hotfix/v{version}-{short-hash}git push -u origin hotfix/v{version}-{short-hash}```-2. **Create PR to main** with a gitmoji prefix title (e.g. `🐛 fix: description`)+2. **Select a delivered desktop baseline and create PR to main** with a gitmoji prefix title (e.g. `🐛 fix: description`). Prefer `hotfix:branch --base` or add the generated metadata from [Desktop Stable Sources](./desktop-stable-sources.md); branch name alone does not pin Cloud.3. **Write a short hotfix changelog** — See `changelog-example/hotfix.md`. Keep it minimal: scope line, 1-3 fix bullets (symptom + fix in one sentence), upgrade note, owner. No long root-cause section — that lives in the commit message.- **Hotfix owner**: Use the actual PR author (retrieve via `gh pr view <number> --json author --jq '.author.login'`), never hardcode a username.@@ -74,7 +76,7 @@ git push -u origin hotfix/v{version}-{short-hash}### Script```bash-bun run hotfix:branch+bun run hotfix:branch --base v2.2.21```---@@ -87,7 +89,7 @@ New AI model or provider support, typically contributed via community PRs.- Community contributors submit PRs with titles like `✨ feat: add xxx model` or `💄 style: support xxx models`- These PR title prefixes (`feat` / `style`) are in the auto-tag trigger list-- No special branch naming or manual release steps required — merging the PR triggers auto patch +1+- No special branch naming is required. A main-targeted model patch carries the delivered desktop baseline metadata from [Desktop Stable Sources](./desktop-stable-sources.md); merging still triggers auto patch +1.### When an agent is involved@@ -119,6 +121,8 @@ git push -u origin release/db-migration-{name}3. **Create PR to main** with the migration changelog as the PR body+ Add the generated desktop baseline metadata from [Desktop Stable Sources](./desktop-stable-sources.md). A `release/db-migration-*` branch is a targeted patch, not a weekly release selecting latest Cloud.+```bashgh pr create \--title "👷 build: {migration description}" \diff --git a/.github/actions/desktop-build-setup/action.yml b/.github/actions/desktop-build-setup/action.ymlindex 830159bd906..e1fcb51f154 100644--- a/.github/actions/desktop-build-setup/action.yml+++ b/.github/actions/desktop-build-setup/action.yml@@ -7,8 +7,7 @@ inputs:required: truecloud-repository:description: >-- Overlay repository (owner/name) for commercial desktop builds — pass the- OVERLAY_REPOSITORY repository variable; deliberately no hardcoded default.+ Overlay repository (owner/name) for commercial desktop builds — pass the OVERLAY_REPOSITORY repository variable; deliberately no hardcoded default.required: falsedefault: ''cloud-ref:@@ -19,10 +18,25 @@ inputs:description: GitHub token with permission to read the Cloud repositoryrequired: falsedefault: ''+ require-pinned-cloud:+ description: Require a full Cloud SHA and token for a commercial Stable build+ default: 'false'runs:using: compositesteps:+ - name: Validate pinned Stable sources+ shell: bash+ env:+ REQUIRE_PINNED_CLOUD: ${{ inputs.require-pinned-cloud }}+ CLOUD_REF: ${{ inputs.cloud-ref }}+ CLOUD_TOKEN: ${{ inputs.cloud-token }}+ run: |+ set -euo pipefail+ if [ "$REQUIRE_PINNED_CLOUD" = true ]; then+ [ -n "$CLOUD_TOKEN" ] || { echo '::error::Stable requires a Cloud read token'; exit 1; }+ [[ "$CLOUD_REF" =~ ^[0-9a-f]{40}$ ]] || { echo '::error::Stable requires a full pinned Cloud SHA'; exit 1; }+ fi- name: Setup environmentuses: ./.github/actions/setup-envwith:@@ -37,6 +51,7 @@ runs:CLOUD_REPOSITORY: ${{ inputs.cloud-repository }}CLOUD_ROOT: ${{ github.workspace }}/..CLOUD_TOKEN: ${{ inputs.cloud-token }}+ REQUIRE_PINNED_CLOUD: ${{ inputs.require-pinned-cloud }}run: |set -euo pipefail# Fail loudly rather than silently shipping an OSS-only commercial build.@@ -56,6 +71,10 @@ runs:firesolved_cloud_ref="$(git -C "$cloud_checkout" rev-parse HEAD)"+ if [ "$REQUIRE_PINNED_CLOUD" = true ] && [ "$resolved_cloud_ref" != "$CLOUD_REF" ]; then+ echo '::error::Resolved Cloud SHA differs from the pinned release sources'+ exit 1+ fiecho "CLOUD_REF=$resolved_cloud_ref" >> "$GITHUB_ENV"node <<'NODE'diff --git a/.github/actions/desktop-publish-s3/action.yml b/.github/actions/desktop-publish-s3/action.ymlindex 22be5d9eafb..8fe0abd9bbe 100644--- a/.github/actions/desktop-publish-s3/action.yml+++ b/.github/actions/desktop-publish-s3/action.yml@@ -33,6 +33,14 @@ inputs:required: falsedefault: 'true'+outputs:+ core-published:+ description: Whether the versioned Core update was uploaded+ value: ${{ steps.base.outputs.published }}+ installers-published:+ description: Whether installer files and manifests were uploaded+ value: ${{ steps.installers.outputs.published }}+runs:using: compositesteps:@@ -121,6 +129,7 @@ runs:VERSION: ${{ inputs.version }}run: |set -euo pipefail+ echo "published=false" >> "$GITHUB_OUTPUT"if [ -z "$S3_BUCKET" ]; thenecho "⚠️ S3 bucket is not configured, skipping S3 upload"exit 0@@ -189,6 +198,7 @@ runs:doneecho ""+ echo "published=true" >> "$GITHUB_OUTPUT"echo "✅ S3 upload completed!"echo ""echo "📋 Files in s3://$S3_BUCKET/$CHANNEL/:"diff --git a/.github/actions/desktop-publish-sparkle/action.yml b/.github/actions/desktop-publish-sparkle/action.ymlindex 9d5e5f44e35..bbc1e863d77 100644--- a/.github/actions/desktop-publish-sparkle/action.yml+++ b/.github/actions/desktop-publish-sparkle/action.yml@@ -53,6 +53,11 @@ inputs:required: falsedefault: ''+outputs:+ published:+ description: Whether the appcast generation and upload step completed+ value: ${{ steps.publish.outputs.published }}+runs:using: compositesteps:@@ -113,6 +118,7 @@ runs:echo "SPARKLE_HISTORY_SCRIPT=$PKG_DIR/package/native/scripts/appcast-history.py" >> "$GITHUB_ENV"- name: Generate, sign and upload appcasts (EdDSA key lives only on a RAM disk)+ id: publishif: steps.gate.outputs.enabled == 'true'shell: bashenv:@@ -155,3 +161,4 @@ runs:--history-script "$SPARKLE_HISTORY_SCRIPT" \--delta-bases "$DELTA_BASES" \--delta-history "$DELTA_HISTORY"+ echo "published=true" >> "$GITHUB_OUTPUT"diff --git a/.github/scripts/desktopReleaseCli.mjs b/.github/scripts/desktopReleaseCli.mjsnew file mode 100644index 00000000000..8f7b027a09d--- /dev/null+++ b/.github/scripts/desktopReleaseCli.mjs@@ -0,0 +1,219 @@+import { execFile } from 'node:child_process';+import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++import { createGithubStore } from './desktopReleaseGithub.mjs';+import {+ formatIntent,+ stripIntent,+ validatePrIntent,+ validateReleaseIntent,+} from './desktopReleaseIntent.mjs';+import {+ deliveredBaseline,+ normalizeVersion,+ recordPublication,+ resolveSources,+ sourcesHash,+} from './desktopReleaseSources.mjs';++export function storeFromEnv(env) {+ return createGithubStore({+ apiUrl: env.GITHUB_API_URL,+ repository: env.GITHUB_REPOSITORY,+ token: env.GH_TOKEN || env.GITHUB_TOKEN,+ cloudRepository: env.CLOUD_REPOSITORY,+ cloudToken: env.CLOUD_TOKEN,+ });+}++async function output(env, values) {+ if (env.GITHUB_OUTPUT)+ await appendFile(+ env.GITHUB_OUTPUT,+ Object.entries(values)+ .map(([key, value]) => `${key}=${value}\n`)+ .join(''),+ );+ console.log(JSON.stringify(values));+}++export async function runReleaseCli(command, env = process.env) {+ if (command === 'verify-checkout') {+ const actual = (await promisify(execFile)('git', ['rev-parse', 'HEAD'])).stdout.trim();+ if (actual !== env.RELEASE_OSS_SHA) throw new Error('Product source SHA mismatch');+ await mkdir('desktop-ota-diagnostics', { recursive: true });+ await writeFile(+ 'desktop-ota-diagnostics/sources.json',+ `${JSON.stringify(+ {+ ossSha: actual,+ cloudSha: env.CLOUD_REF,+ sourcesHash: env.SOURCES_HASH,+ toolingSha: env.DESKTOP_TOOLING_SHA,+ runId: env.GITHUB_RUN_ID,+ runAttempt: env.GITHUB_RUN_ATTEMPT,+ },+ null,+ 2,+ )}\n`,+ );+ return;+ }+ const store = storeFromEnv(env);+ if (command === 'check-pr' || command === 'prepare-release') {+ const event = JSON.parse(await readFile(env.GITHUB_EVENT_PATH, 'utf8'));+ const pr = event.pull_request;+ if (!pr) throw new Error('A pull request event is required');+ const intent = await validatePrIntent(pr, store);+ if (command === 'check-pr') {+ await output(env, { release_mode: intent?.mode || 'none' });+ return;+ }+ if (!intent) throw new Error('This PR has no desktop release intent');+ const bound = {+ ...intent,+ mergeSha: pr.merge_commit_sha,+ prNumber: pr.number,+ ...(intent.mode === 'hotfix' && { prBaseSha: pr.base.sha }),+ };+ const file = path.join(env.RUNNER_TEMP, 'desktop-release-body.md');+ await writeFile(+ file,+ `## Release v${normalizeVersion(env.RELEASE_VERSION)}\n\nFrom PR #${pr.number}: ${pr.html_url}\n\n${stripIntent(pr.body || '')}\n\n${formatIntent(bound)}\n`,+ );+ await output(env, { body_file: file });+ return;+ }+ if (command === 'list') {+ console.log(JSON.stringify(await store.listDelivered()));+ return;+ }+ if (command === 'baseline') {+ console.log(JSON.stringify(await deliveredBaseline(store, env.BASE_VERSION)));+ return;+ }+ if (command === 'hotfix-intent') {+ const baseline = await deliveredBaseline(store, env.BASE_VERSION);+ const cloudSha = env.CLOUD_REF || baseline.cloudSha;+ if (cloudSha !== baseline.cloudSha && !env.CLOUD_OVERRIDE_REASON?.trim())+ throw new Error('A different Cloud SHA needs a repair reason');+ console.log(+ formatIntent({+ schemaVersion: 1,+ mode: 'hotfix',+ baseVersion: baseline.version,+ cloudSha,+ baseSourcesHash: sourcesHash(baseline),+ ...(env.CLOUD_OVERRIDE_REASON && { overrideReason: env.CLOUD_OVERRIDE_REASON }),+ }),+ );+ return;+ }+ const version = normalizeVersion(env.RELEASE_VERSION);+ if (command === 'publish') {+ const outcomes = JSON.parse(env.PUBLICATION_OUTCOMES || '{}');+ if (env.CORE_PUBLISHED !== 'true' || env.INSTALLERS_PUBLISHED !== 'true')+ outcomes.s3 = 'skipped';+ if (env.SPARKLE_PUBLISHED !== 'true') outcomes.sparkle = 'skipped';+ const platforms = JSON.parse(env.BUILT_PLATFORMS || '[]');+ if (+ env.RELEASE_DRY_RUN !== 'true' &&+ ['build', 'github', 's3', 'sparkle'].every((stage) => outcomes[stage] === 'success')+ )+ await store.assertInstallerAssets(version);+ const receipt = await recordPublication(+ {+ version,+ sourcesHash: env.SOURCES_HASH,+ runId: env.GITHUB_RUN_ID,+ publishedAt: new Date().toISOString(),+ outcomes,+ platforms,+ dryRun: env.RELEASE_DRY_RUN === 'true',+ },+ store,+ );+ await output(env, { published: receipt !== null });+ return;+ }+ if (command !== 'resolve') throw new Error(`Unknown release command: ${command}`);+ // Resolve through the commits API so annotated tags are peeled as well.+ const targetRelease = await store.release(version);+ const tagSha = await store.resolveCommit(`v${version}`);+ const ossSha = env.SOURCE_REF ? await store.resolveCommit(env.SOURCE_REF) : tagSha;+ if (ossSha !== tagSha)+ throw new Error(+ 'source_ref does not match the target tag; a version input cannot relabel other product sources',+ );+ let mode = env.RELEASE_MODE || 'rebuild';+ let intent;+ if (mode === 'auto') {+ const event = JSON.parse(await readFile(env.GITHUB_EVENT_PATH, 'utf8'));+ if (env.GITHUB_EVENT_NAME !== 'release' || event.action !== 'published')+ throw new Error('Automatic source initialization requires a published release event');+ intent = validateReleaseIntent(event.release?.body || '', ossSha);+ mode = intent?.mode || 'rebuild';+ }+ if (mode === 'hotfix') {+ intent ||= validateReleaseIntent(targetRelease.body || '', ossSha);+ if (intent?.mode !== 'hotfix')+ throw new Error('Hotfix requires bound release intent metadata from its merged PR');+ if (+ (env.BASE_VERSION && normalizeVersion(env.BASE_VERSION) !== intent.baseVersion) ||+ (env.CLOUD_REF && env.CLOUD_REF !== intent.cloudSha) ||+ (env.BASE_SOURCES_HASH && env.BASE_SOURCES_HASH !== intent.baseSourcesHash) ||+ (env.CLOUD_OVERRIDE_REASON && env.CLOUD_OVERRIDE_REASON.trim() !== intent.overrideReason)+ )+ throw new Error('Manual hotfix inputs conflict with the bound release intent');+ const baseline = await deliveredBaseline(store, intent.baseVersion, intent.baseSourcesHash);+ await store.assertReleasePr(intent);+ await store.assertHotfixBase(baseline, intent.prBaseSha);+ }+ const result = await resolveSources(+ {+ version,+ ossSha,+ mode,+ firstRelease: intent?.mode === 'initialize' || env.FIRST_RELEASE === 'true',+ write: env.WRITE_SOURCES === 'true',+ cloudSha: intent?.cloudSha || env.CLOUD_REF || undefined,+ baseVersion: intent?.baseVersion || env.BASE_VERSION || undefined,+ baseSourcesHash: intent?.baseSourcesHash || env.BASE_SOURCES_HASH || undefined,+ overrideReason: intent?.overrideReason || env.CLOUD_OVERRIDE_REASON || undefined,+ evidence: {+ runId: mode === 'import' ? env.EVIDENCE_RUN_ID : env.GITHUB_RUN_ID,+ runAttempt: Number(mode === 'import' ? env.EVIDENCE_RUN_ATTEMPT : env.GITHUB_RUN_ATTEMPT),+ },+ },+ {+ store,+ latestCloud: store.latestCloud,+ assertCloudCommit: store.assertCloudCommit,+ assertImportEvidence: store.assertImportEvidence,+ },+ );+ const dir = env.RUNNER_TEMP || process.cwd();+ await mkdir(dir, { recursive: true });+ await writeFile(+ path.join(dir, 'desktop-release-sources.json'),+ `${JSON.stringify(result.sources, null, 2)}\n`,+ );+ await output(env, {+ oss_sha: result.sources.ossSha,+ cloud_sha: result.sources.cloudSha,+ sources_hash: result.hash,+ persisted: result.persisted,+ build_required: mode !== 'import',+ version,+ });+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ runReleaseCli(process.argv[2]).catch((error) => {+ console.error(error.message);+ process.exitCode = 1;+ });+}diff --git a/.github/scripts/desktopReleaseCli.test.mjs b/.github/scripts/desktopReleaseCli.test.mjsnew file mode 100644index 00000000000..04180627d36--- /dev/null+++ b/.github/scripts/desktopReleaseCli.test.mjs@@ -0,0 +1,383 @@+import assert from 'node:assert/strict';+import { execFile } from 'node:child_process';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++import { createGithubStore } from './desktopReleaseGithub.mjs';+import { formatIntent, parseIntent } from './desktopReleaseIntent.mjs';+import { recordPublication, sourcesHash, stablePlatforms } from './desktopReleaseSources.mjs';+import {+ fixtureCloud,+ fixtureNextOss,+ fixtureOss,+ fixtureSources,+ startGithubFixture,+} from './desktopReleaseTestUtils.mjs';++const exec = promisify(execFile);+const cli = fileURLToPath(new URL('./desktopReleaseCli.mjs', import.meta.url));++async function fixture(t) {+ const github = await startGithubFixture();+ const root = await mkdtemp(path.join(os.tmpdir(), 'desktop-release-cli-'));+ t.after(async () => {+ await github.close();+ await rm(root, { recursive: true, force: true });+ });+ const env = {+ ...process.env,+ GITHUB_REPOSITORY: 'example/lobehub',+ GITHUB_API_URL: github.apiUrl,+ GH_TOKEN: 'oss-test-token',+ CLOUD_REPOSITORY: 'example/cloud',+ CLOUD_TOKEN: 'cloud-test-token',+ RELEASE_VERSION: '2.2.21',+ RELEASE_MODE: 'rebuild',+ SOURCE_REF: 'v2.2.21',+ GITHUB_RUN_ID: '40841847688',+ GITHUB_RUN_ATTEMPT: '3',+ GITHUB_OUTPUT: path.join(root, 'outputs'),+ RUNNER_TEMP: root,+ WRITE_SOURCES: 'false',+ };+ return {+ github,+ root,+ env,+ run: (overrides = {}, command = 'resolve') =>+ exec(process.execPath, [cli, command], { env: { ...env, ...overrides }, cwd: root }),+ };+}++test('the real CLI rebuilds the old product ref with its saved Cloud', async (t) => {+ const { github, env, run } = await fixture(t);+ github.addAsset('2.2.21', 'desktop-sources.v1.json', JSON.stringify(fixtureSources));+ github.state.rejectHead = true;+ await run();+ const output = await readFile(env.GITHUB_OUTPUT, 'utf8');+ assert.match(output, new RegExp(`oss_sha=${fixtureOss}`));+ assert.match(output, new RegExp(`cloud_sha=${fixtureCloud}`));+ assert.match(output, /persisted=true/);+});++test('a missing lock makes the CLI fail without querying current Cloud HEAD', async (t) => {+ const { github, run } = await fixture(t);+ github.state.rejectHead = true;+ await assert.rejects(run(), (error) => /Missing source record/.test(error.stderr));+});++test('a version input cannot relabel latest main as an older source tag', async (t) => {+ const { github, run } = await fixture(t);+ github.addAsset('2.2.21', 'desktop-sources.v1.json', JSON.stringify(fixtureSources));+ await assert.rejects(run({ SOURCE_REF: 'main' }), (error) =>+ /source_ref|target tag/i.test(error.stderr),+ );+});++test('an explicit import records the original run but does not publish delivery proof', async (t) => {+ const { github, run } = await fixture(t);+ await run({+ RELEASE_MODE: 'import',+ CLOUD_REF: fixtureCloud,+ EVIDENCE_RUN_ID: '40841847688',+ EVIDENCE_RUN_ATTEMPT: '1',+ WRITE_SOURCES: 'true',+ });+ const names = github.releases.get('2.2.21').assets.map((asset) => asset.name);+ assert.deepEqual(names, ['desktop-sources.v1.json']);+ const asset = [...github.assets.values()].find((entry) => entry.name === names[0]);+ const record = JSON.parse(asset.content);+ assert.equal(record.selection, 'historical-import');+ assert.equal(record.evidence.runAttempt, 1);+});++test('a dry-run ordinary candidate does not add a Release asset', async (t) => {+ const { github, run } = await fixture(t);+ await run({ RELEASE_MODE: 'initialize', FIRST_RELEASE: 'true', GITHUB_RUN_ATTEMPT: '1' });+ assert.equal(github.releases.get('2.2.21').assets.length, 0);+});++test('prepare-release binds weekly intent once and automatic source resolution consumes it', async (t) => {+ const { github, root, run } = await fixture(t);+ const eventPath = path.join(root, 'event.json');+ await writeFile(+ eventPath,+ JSON.stringify({+ pull_request: {+ number: 22000,+ title: '🚀 release: 20261031',+ body: 'Release notes',+ html_url: 'https://example.test/pull/22000',+ head: { ref: 'release/weekly-20261031' },+ base: { ref: 'main', sha: fixtureOss },+ merge_commit_sha: fixtureOss,+ },+ }),+ );+ await run({ GITHUB_EVENT_PATH: eventPath }, 'prepare-release');+ const body = await readFile(path.join(root, 'desktop-release-body.md'), 'utf8');+ assert.deepEqual(parseIntent(body), {+ schemaVersion: 1,+ mode: 'initialize',+ mergeSha: fixtureOss,+ prNumber: 22000,+ });+ await writeFile(eventPath, JSON.stringify({ action: 'published', release: { body } }));+ await run({+ GITHUB_EVENT_PATH: eventPath,+ GITHUB_EVENT_NAME: 'release',+ RELEASE_MODE: 'auto',+ WRITE_SOURCES: 'true',+ GITHUB_RUN_ATTEMPT: '1',+ });+ assert.equal(github.releases.get('2.2.21').assets.length, 1);+});++test('a release intent for a different merge cannot initialize sources', async (t) => {+ const { github, root, run } = await fixture(t);+ const eventPath = path.join(root, 'event.json');+ await writeFile(+ eventPath,+ JSON.stringify({+ action: 'published',+ release: {+ body: formatIntent({+ schemaVersion: 1,+ mode: 'initialize',+ mergeSha: '1'.repeat(40),+ prNumber: 22000,+ }),+ },+ }),+ );+ await assert.rejects(+ run({+ GITHUB_EVENT_PATH: eventPath,+ GITHUB_EVENT_NAME: 'release',+ RELEASE_MODE: 'auto',+ WRITE_SOURCES: 'true',+ GITHUB_RUN_ATTEMPT: '1',+ }),+ (error) => /mismatch/.test(error.stderr),+ );+ assert.equal(github.releases.get('2.2.21').assets.length, 0);+});++test('successful jobs that skipped actual uploads cannot produce delivery proof', async (t) => {+ const { github, run } = await fixture(t);+ github.addAsset('2.2.21', 'desktop-sources.v1.json', JSON.stringify(fixtureSources));+ await run(+ {+ SOURCES_HASH: sourcesHash(fixtureSources),+ BUILT_PLATFORMS: JSON.stringify(stablePlatforms),+ PUBLICATION_OUTCOMES: JSON.stringify({+ build: 'success',+ github: 'success',+ s3: 'success',+ sparkle: 'success',+ }),+ CORE_PUBLISHED: 'false',+ INSTALLERS_PUBLISHED: 'true',+ SPARKLE_PUBLISHED: 'true',+ },+ 'publish',+ );+ assert.equal(+ github.releases+ .get('2.2.21')+ .assets.some((asset) => asset.name === 'desktop-published.v1.json'),+ false,+ );+});++test('delivery proof requires public installer assets as well as completed upload stages', async (t) => {+ const { github, run } = await fixture(t);+ github.addAsset('2.2.21', 'desktop-sources.v1.json', JSON.stringify(fixtureSources));+ const env = {+ SOURCES_HASH: sourcesHash(fixtureSources),+ BUILT_PLATFORMS: JSON.stringify(stablePlatforms),+ PUBLICATION_OUTCOMES: JSON.stringify({+ build: 'success',+ github: 'success',+ s3: 'success',+ sparkle: 'success',+ }),+ CORE_PUBLISHED: 'true',+ INSTALLERS_PUBLISHED: 'true',+ SPARKLE_PUBLISHED: 'true',+ };+ await assert.rejects(run(env, 'publish'), (error) => /installer|asset/i.test(error.stderr));+ for (const name of [+ 'latest.yml',+ 'latest-linux.yml',+ 'latest-mac-arm64.yml',+ 'latest-mac-x64.yml',+ 'LobeHub-2.2.21-arm64.dmg',+ 'LobeHub-2.2.21-x64.dmg',+ 'LobeHub-2.2.21-setup.exe',+ 'LobeHub-2.2.21.AppImage',+ ])+ github.addAsset('2.2.21', name, 'fixture bytes');+ await run(env, 'publish');+ assert.equal(+ github.releases+ .get('2.2.21')+ .assets.some((asset) => asset.name === 'desktop-published.v1.json'),+ true,+ );+});++test('operators can generate pinned hotfix metadata for an existing manually created PR', async (t) => {+ const { github, run } = await fixture(t);+ const store = createGithubStore(github.options);+ await store.createSources('2.2.21', fixtureSources);+ await assert.rejects(run({ BASE_VERSION: '2.2.21' }, 'hotfix-intent'));+ await recordPublication(+ {+ version: '2.2.21',+ sourcesHash: sourcesHash(fixtureSources),+ runId: '40841847688',+ publishedAt: '2026-10-31T12:00:00Z',+ platforms: stablePlatforms,+ outcomes: { build: 'success', github: 'success', s3: 'success', sparkle: 'success' },+ },+ store,+ );+ const result = await run({ BASE_VERSION: '2.2.21' }, 'hotfix-intent');+ const intent = parseIntent(result.stdout);+ assert.equal(intent.mode, 'hotfix');+ assert.equal(intent.cloudSha, fixtureCloud);+ assert.equal(intent.baseSourcesHash, sourcesHash(fixtureSources));+});++async function hotfixFixture(t) {+ const context = await fixture(t);+ const { github, root } = context;+ const store = createGithubStore(github.options);+ await store.createSources('2.2.21', fixtureSources);+ await recordPublication(+ {+ version: '2.2.21',+ sourcesHash: sourcesHash(fixtureSources),+ runId: '40841847688',+ publishedAt: '2026-10-31T12:00:00Z',+ platforms: stablePlatforms,+ outcomes: { build: 'success', github: 'success', s3: 'success', sparkle: 'success' },+ },+ store,+ );+ const intent = {+ schemaVersion: 1,+ mode: 'hotfix',+ baseVersion: '2.2.21',+ cloudSha: fixtureCloud,+ baseSourcesHash: sourcesHash(fixtureSources),+ mergeSha: fixtureNextOss,+ prNumber: 22000,+ prBaseSha: fixtureCloud,+ };+ // Raw transport, so the test does not depend on the production formatter preserving the base SHA.+ const body = `<!-- desktop-release-request ${JSON.stringify(intent)} -->`;+ github.releases.get('2.2.22').body = body;+ github.state.pullRequest = {+ number: 22000,+ merged: true,+ merge_commit_sha: fixtureNextOss,+ base: { ref: 'main', sha: fixtureCloud },+ };+ const eventPath = path.join(root, 'event.json');+ await writeFile(eventPath, JSON.stringify({ action: 'published', release: { body } }));+ const input = {+ RELEASE_VERSION: '2.2.22',+ SOURCE_REF: 'v2.2.22',+ BASE_VERSION: '2.2.21',+ WRITE_SOURCES: 'true',+ GITHUB_RUN_ATTEMPT: '1',+ };+ return { ...context, input, eventPath };+}++test('manual hotfix rejects undelivered product changes in the actual merged PR base', async (t) => {+ const { github, input, run } = await hotfixFixture(t);+ github.state.comparison = {+ status: 'ahead',+ total_commits: 1,+ files: [{ filename: 'src/features/CanvasStorage/useCanvasStorage.ts' }],+ };+ await assert.rejects(run({ ...input, RELEASE_MODE: 'hotfix' }), (error) =>+ /product changes|baseline/i.test(error.stderr),+ );+ assert.equal(github.releases.get('2.2.22').assets.length, 0);+ github.state.comparison.files = [{ filename: '.github/workflows/release-desktop-stable.yml' }];+ await run({ ...input, RELEASE_MODE: 'hotfix' });+ assert.equal(github.releases.get('2.2.22').assets.length, 1);+});++test('manual hotfix cannot invent a PR identity or change a bound baseline', async (t) => {+ const { github, input, run } = await hotfixFixture(t);+ github.state.pullRequest.merge_commit_sha = fixtureOss;+ await assert.rejects(run({ ...input, RELEASE_MODE: 'hotfix' }), (error) =>+ /PR|identity|merge/i.test(error.stderr),+ );+ github.state.pullRequest.merge_commit_sha = fixtureNextOss;+ github.state.pullRequest.base.sha = fixtureOss;+ await assert.rejects(run({ ...input, RELEASE_MODE: 'hotfix' }), (error) =>+ /PR|identity|base/i.test(error.stderr),+ );+ github.state.pullRequest.base.sha = fixtureCloud;+ github.state.comparison = { status: 'ahead', total_commits: 1, files: [] };+ await assert.rejects(run({ ...input, RELEASE_MODE: 'hotfix', BASE_VERSION: '2.2.20' }), (error) =>+ /conflict|mismatch/i.test(error.stderr),+ );+ github.releases.get('2.2.22').body = '';+ await assert.rejects(run({ ...input, RELEASE_MODE: 'hotfix' }), (error) =>+ /intent|metadata/i.test(error.stderr),+ );+ assert.equal(github.releases.get('2.2.22').assets.length, 0);+});++test('prepare-release binds the validated hotfix request to its actual PR base', async (t) => {+ const { github, root, run, eventPath } = await hotfixFixture(t);+ const bound = parseIntent(github.releases.get('2.2.22').body);+ const { mergeSha, prNumber, prBaseSha, ...request } = bound;+ github.state.comparison = { status: 'ahead', total_commits: 1, files: [] };+ await writeFile(+ eventPath,+ JSON.stringify({+ pull_request: {+ ...github.state.pullRequest,+ title: '🐛 fix: targeted repair',+ head: { ref: 'hotfix/a-repair' },+ html_url: 'https://example.test/pull/22000',+ body: formatIntent(request),+ },+ }),+ );+ await run({ GITHUB_EVENT_PATH: eventPath, RELEASE_VERSION: '2.2.22' }, 'prepare-release');+ const body = await readFile(path.join(root, 'desktop-release-body.md'), 'utf8');+ assert.equal(parseIntent(body).mergeSha, mergeSha);+ assert.equal(parseIntent(body).prNumber, prNumber);+ assert.equal(parseIntent(body).prBaseSha, prBaseSha);+});++test('automatic hotfix reruns cannot initialize missing locks but can reuse the first attempt', async (t) => {+ const { github, input, eventPath, run } = await hotfixFixture(t);+ github.state.comparison = { status: 'ahead', total_commits: 1, files: [] };+ const automatic = {+ ...input,+ RELEASE_MODE: 'auto',+ GITHUB_EVENT_NAME: 'release',+ GITHUB_EVENT_PATH: eventPath,+ };+ await assert.rejects(run({ ...automatic, GITHUB_RUN_ATTEMPT: '2' }), (error) =>+ /missing|initial|first|import/i.test(error.stderr),+ );+ assert.equal(github.releases.get('2.2.22').assets.length, 0);+ await run(automatic);+ await run({ ...automatic, GITHUB_RUN_ATTEMPT: '2' });+ assert.equal(github.releases.get('2.2.22').assets.length, 1);+});diff --git a/.github/scripts/desktopReleaseGithub.mjs b/.github/scripts/desktopReleaseGithub.mjsnew file mode 100644index 00000000000..0fed177ce66--- /dev/null+++ b/.github/scripts/desktopReleaseGithub.mjs@@ -0,0 +1,234 @@+import {+ assertSha,+ deliveredBaseline,+ normalizeVersion,+ publicationAssetName,+ sourceAssetName,+} from './desktopReleaseSources.mjs';++const repositoryPath = (value) => {+ if (typeof value !== 'string' || !/^[\w.-]+\/[\w.-]+$/.test(value))+ throw new Error('A GitHub owner/repository is required');+ return `repos/${value}`;+};++export function createGithubStore(options) {+ const apiUrl = (options.apiUrl || 'https://api.github.com').replace(/\/$/, '');+ const root = repositoryPath(options.repository);+ const releaseCache = new Map();++ async function request(route, { token = options.token, accept, ...init } = {}) {+ const url = route.startsWith('http') ? route : `${apiUrl}/${route}`;+ const response = await fetch(url, {+ ...init,+ headers: {+ 'Accept': accept || 'application/vnd.github+json',+ 'X-GitHub-Api-Version': '2026-03-10',+ 'User-Agent': 'lobehub-desktop-release',+ ...(token && { Authorization: `Bearer ${token}` }),+ ...init.headers,+ },+ });+ if (!response.ok) {+ const error = new Error(+ `GitHub request failed (${response.status}): ${new URL(url).pathname}`,+ );+ error.status = response.status;+ try {+ error.details = await response.json();+ } catch {+ /* Non-JSON errors retain their HTTP status. */+ }+ throw error;+ }+ return response;+ }++ async function release(version, required = true) {+ const normalized = normalizeVersion(version);+ if (releaseCache.has(normalized)) return releaseCache.get(normalized);+ try {+ const result = await (await request(`${root}/releases/tags/v${normalized}`)).json();+ if (result.tag_name !== `v${normalized}`) throw new Error('Release tag mismatch');+ releaseCache.set(normalized, result);+ return result;+ } catch (error) {+ if (!required && error.status === 404) return null;+ throw error;+ }+ }++ async function listAssets(version) {+ const target = await release(version, false);+ if (!target) return [];+ const assets = [];+ for (let page = 1; ; page++) {+ const batch = await (+ await request(`${root}/releases/${target.id}/assets?per_page=100&page=${page}`)+ ).json();+ if (!Array.isArray(batch)) throw new Error('Invalid GitHub asset list');+ assets.push(...batch);+ if (batch.length < 100) return assets;+ }+ }++ async function readAsset(version, name) {+ const matches = (await listAssets(version)).filter((asset) => asset.name === name);+ if (matches.length > 1) throw new Error(`Duplicate release asset: ${name}`);+ if (!matches.length) return null;+ if (matches[0].state !== 'uploaded') throw new Error(`Release asset is not ready: ${name}`);+ const response = await request(`${root}/releases/assets/${matches[0].id}`, {+ accept: 'application/octet-stream',+ });+ try {+ return JSON.parse(await response.text());+ } catch {+ throw new Error(`Invalid JSON in release asset ${name}`);+ }+ }++ async function createAsset(version, name, value) {+ if (!options.token)+ throw new Error('A repository write token is required to save release metadata');+ const target = await release(version);+ const url = new URL(target.upload_url.replace(/\{.*$/, ''));+ const allowed =+ new URL(apiUrl).hostname === 'api.github.com'+ ? 'https://uploads.github.com'+ : new URL(apiUrl).origin;+ if (url.origin !== allowed) throw new Error('Unexpected GitHub upload origin');+ url.searchParams.set('name', name);+ try {+ await request(url.href, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: `${JSON.stringify(value, null, 2)}\n`,+ });+ return true;+ } catch (error) {+ if (+ error.status === 422 &&+ error.details?.errors?.some((entry) => entry.code === 'already_exists')+ )+ return false;+ throw error;+ }+ }++ async function resolveCommit(ref) {+ if (typeof ref !== 'string' || !ref || ref.length > 250)+ throw new Error('A source_ref is required');+ const commit = await (await request(`${root}/commits/${encodeURIComponent(ref)}`)).json();+ return assertSha(commit.sha, 'Resolved OSS');+ }++ async function cloudCommit(ref) {+ if (!options.cloudToken) throw new Error('A Cloud read token is required');+ const cloud = repositoryPath(options.cloudRepository);+ const commit = await (+ await request(`${cloud}/commits/${encodeURIComponent(ref)}`, { token: options.cloudToken })+ ).json();+ return assertSha(commit.sha, 'Resolved Cloud');+ }++ const store = {+ release,+ listAssets,+ resolveCommit,+ readSources: (version) => readAsset(version, sourceAssetName),+ createSources: (version, record) => createAsset(version, sourceAssetName, record),+ readPublication: (version) => readAsset(version, publicationAssetName),+ createPublication: (version, receipt) => createAsset(version, publicationAssetName, receipt),+ latestCloud: () => cloudCommit('HEAD'),+ async assertInstallerAssets(version) {+ const target = await release(version);+ if (target.draft || target.prerelease)+ throw new Error('Installer release is not publicly published');+ const assets = (await listAssets(version)).filter(+ (asset) => asset.state === 'uploaded' && asset.size > 0,+ );+ const names = assets.map((asset) => asset.name);+ for (const name of [+ 'latest.yml',+ 'latest-linux.yml',+ 'latest-mac-arm64.yml',+ 'latest-mac-x64.yml',+ ])+ if (!names.includes(name)) throw new Error(`Missing installer manifest asset: ${name}`);+ for (const suffix of [+ `-${version}-arm64.dmg`,+ `-${version}-x64.dmg`,+ `-${version}-setup.exe`,+ `-${version}.AppImage`,+ ])+ if (!names.some((name) => name.endsWith(suffix)))+ throw new Error(`Missing installer asset: ${suffix}`);+ },+ async assertCloudCommit(sha) {+ if ((await cloudCommit(assertSha(sha, 'Cloud'))) !== sha)+ throw new Error('Cloud commit SHA mismatch');+ },+ async assertImportEvidence({ ossSha, evidence }) {+ const run = await (+ await request(`${root}/actions/runs/${evidence.runId}/attempts/${evidence.runAttempt}`)+ ).json();+ if (+ String(run.id) !== evidence.runId ||+ run.head_sha !== ossSha ||+ run.run_attempt !== evidence.runAttempt+ )+ throw new Error('Historical run evidence SHA/attempt mismatch');+ },+ async listDelivered() {+ const delivered = [];+ for (let page = 1; page <= 10 && delivered.length < 20; page++) {+ const batch = await (await request(`${root}/releases?per_page=100&page=${page}`)).json();+ for (const entry of batch) {+ if (entry.draft || entry.prerelease || !/^v\d+\.\d+\.\d+$/.test(entry.tag_name)) continue;+ const version = normalizeVersion(entry.tag_name);+ releaseCache.set(version, entry);+ if (!(await store.readSources(version)) || !(await store.readPublication(version)))+ continue;+ delivered.push(await deliveredBaseline(store, version));+ if (delivered.length === 20) break;+ }+ if (batch.length < 100) break;+ }+ return delivered;+ },+ async assertReleasePr(intent) {+ const pr = await (await request(`${root}/pulls/${intent.prNumber}`)).json();+ if (+ pr.number !== intent.prNumber ||+ pr.merged !== true ||+ pr.merge_commit_sha !== intent.mergeSha ||+ pr.base?.ref !== 'main' ||+ pr.base.sha !== intent.prBaseSha+ )+ throw new Error('Release intent does not match the actual merged PR identity/base');+ },+ async assertHotfixBase(sources, baseSha) {+ assertSha(baseSha, 'PR base');+ if (sources.ossSha === baseSha) return;+ const comparison = await (+ await request(`${root}/compare/${sources.ossSha}...${baseSha}`)+ ).json();+ if (+ comparison.status !== 'ahead' ||+ comparison.total_commits > 250 ||+ !Array.isArray(comparison.files) ||+ comparison.files.length >= 300 ||+ comparison.files.some(+ (file) =>+ !/^(?:\.github\/(?:actions|scripts|workflows)\/|docs\/|scripts\/(?:hotfixWorkflow|releaseWorkflow)\/)/.test(+ file.filename,+ ),+ )+ )+ throw new Error(+ 'main contains product changes outside the selected delivered baseline; choose the correct release path',+ );+ },+ };+ return store;+}diff --git a/.github/scripts/desktopReleaseGithub.test.mjs b/.github/scripts/desktopReleaseGithub.test.mjsnew file mode 100644index 00000000000..3b48c0b49bc--- /dev/null+++ b/.github/scripts/desktopReleaseGithub.test.mjs@@ -0,0 +1,101 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';++import { createGithubStore } from './desktopReleaseGithub.mjs';+import { recordPublication, sourcesHash, stablePlatforms } from './desktopReleaseSources.mjs';+import {+ fixtureCloud,+ fixtureOss,+ fixtureSources,+ startGithubFixture,+} from './desktopReleaseTestUtils.mjs';++test('GitHub assets preserve the first source record without clobbering', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ const store = createGithubStore(github.options);+ assert.equal(await store.createSources('2.2.21', fixtureSources), true);+ assert.equal(+ await store.createSources('2.2.21', { ...fixtureSources, cloudSha: '0'.repeat(40) }),+ false,+ );+ assert.deepEqual(await store.readSources('2.2.21'), fixtureSources);+});++test('asset lookup follows pagination and reads JSON via its asset ID', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ for (let i = 0; i < 100; i++) github.addAsset('2.2.21', `other-${i}.txt`, 'unrelated');+ github.addAsset('2.2.21', 'desktop-sources.v1.json', JSON.stringify(fixtureSources));+ assert.deepEqual(await createGithubStore(github.options).readSources('2.2.21'), fixtureSources);+});++test('only a genuinely missing asset returns null; API failures and corrupt JSON reject', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ const store = createGithubStore(github.options);+ assert.equal(await store.readSources('2.2.21'), null);+ github.state.error = 403;+ await assert.rejects(store.readSources('2.2.21'), /403/);+ github.state.error = null;+ github.addAsset('2.2.21', 'desktop-sources.v1.json', '{broken');+ await assert.rejects(store.readSources('2.2.21'), /JSON|invalid/i);+});++test('a missing download after asset discovery fails rather than reinitializing', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ const asset = github.addAsset('2.2.21', 'desktop-sources.v1.json', '{}');+ github.assets.delete(asset.id);+ await assert.rejects(createGithubStore(github.options).readSources('2.2.21'), /404/);+});++test('commit resolution peels source tags and Cloud requests use their read token', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ const store = createGithubStore(github.options);+ assert.equal(await store.resolveCommit('v2.2.21'), fixtureOss);+ await store.assertCloudCommit(fixtureCloud);+ await assert.rejects(+ createGithubStore({ ...github.options, cloudToken: 'wrong' }).assertCloudCommit(fixtureCloud),+ /403/,+ );+});++test('historical evidence must identify the actual OSS run and attempt', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ const store = createGithubStore(github.options);+ await store.assertImportEvidence({ ossSha: fixtureOss, evidence: fixtureSources.evidence });+ await assert.rejects(+ store.assertImportEvidence({ ossSha: '0'.repeat(40), evidence: fixtureSources.evidence }),+ /evidence|mismatch/i,+ );+ await assert.rejects(+ store.assertImportEvidence({+ ossSha: fixtureOss,+ evidence: { ...fixtureSources.evidence, runAttempt: 3 },+ }),+ /attempt|evidence/i,+ );+});++test('baseline listing includes only releases with matching successful publication proof', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ const store = createGithubStore(github.options);+ await store.createSources('2.2.21', fixtureSources);+ assert.deepEqual(await store.listDelivered(), []);+ await recordPublication(+ {+ version: '2.2.21',+ sourcesHash: sourcesHash(fixtureSources),+ runId: '40841847688',+ publishedAt: '2026-10-31T12:00:00Z',+ platforms: stablePlatforms,+ outcomes: { build: 'success', github: 'success', s3: 'success', sparkle: 'success' },+ },+ store,+ );+ assert.deepEqual(await store.listDelivered(), [fixtureSources]);+});diff --git a/.github/scripts/desktopReleaseIntent.mjs b/.github/scripts/desktopReleaseIntent.mjsnew file mode 100644index 00000000000..5aef29ef7a6--- /dev/null+++ b/.github/scripts/desktopReleaseIntent.mjs@@ -0,0 +1,107 @@+import {+ assertSha,+ deliveredBaseline,+ normalizeVersion,+ sourcesHash,+} from './desktopReleaseSources.mjs';++const marker = /<!-- desktop-release-request ([\s\S]*?)-->/g;++function validateIntent(value) {+ if (!value || value.schemaVersion !== 1 || !['initialize', 'hotfix'].includes(value.mode))+ throw new Error('Invalid desktop release intent metadata');+ const intent = { schemaVersion: 1, mode: value.mode };+ if (value.mode === 'hotfix') {+ intent.baseVersion = normalizeVersion(value.baseVersion);+ intent.cloudSha = assertSha(value.cloudSha, 'Hotfix Cloud');+ if (!/^[a-f0-9]{64}$/.test(value.baseSourcesHash || ''))+ throw new Error('Hotfix metadata requires the baseline source hash');+ intent.baseSourcesHash = value.baseSourcesHash;+ if (value.overrideReason !== undefined) {+ if (+ typeof value.overrideReason !== 'string' ||+ !value.overrideReason.trim() ||+ value.overrideReason.length > 500+ )+ throw new Error('Invalid Cloud repair reason');+ intent.overrideReason = value.overrideReason.trim();+ }+ } else if (value.baseVersion || value.cloudSha) {+ throw new Error('Ordinary initialization cannot carry a hotfix baseline');+ }+ if (+ value.mergeSha !== undefined ||+ value.prNumber !== undefined ||+ value.prBaseSha !== undefined+ ) {+ intent.mergeSha = assertSha(value.mergeSha, 'Release merge');+ if (!Number.isSafeInteger(value.prNumber) || value.prNumber < 1)+ throw new Error('Release intent requires its PR number');+ intent.prNumber = value.prNumber;+ if (value.mode === 'hotfix') intent.prBaseSha = assertSha(value.prBaseSha, 'Release PR base');+ }+ return intent;+}++export function parseIntent(body = '') {+ const matches = [...body.matchAll(marker)];+ if (!matches.length) {+ if (body.includes('desktop-release-request'))+ throw new Error('Malformed desktop release metadata');+ return null;+ }+ if (matches.length !== 1)+ throw new Error('Only one desktop release intent is allowed; duplicate metadata');+ return validateIntent(JSON.parse(matches[0][1]));+}++export function formatIntent(value) {+ const json = JSON.stringify(validateIntent(value))+ .replaceAll('<', '\\u003c')+ .replaceAll('>', '\\u003e');+ return `<!-- desktop-release-request ${json} -->`;+}++export function stripIntent(body = '') {+ return body.replaceAll(marker, '').trim();+}++export function requestFromPr(pr) {+ const head = pr.head?.ref || '';+ const title = pr.title || '';+ const ordinary =+ head.startsWith('release/weekly-') || /^🚀\s+release:\s*v\d+\.\d+\.\d+$/.test(title);+ const candidate =+ ordinary ||+ /^(?:hotfix|release)\//.test(head) ||+ /^(?:(?:💄|✨|🐛|♻️|🩹|👷)\s*)?(?:style|feat|fix|refactor|hotfix|build)(?:\([^)]*\))?:/i.test(+ title,+ );+ if (!candidate) return null;+ const intent = parseIntent(pr.body || '');+ if (intent?.mergeSha)+ throw new Error('PR metadata must not preassign the release merge identity');+ if (ordinary) return intent || { schemaVersion: 1, mode: 'initialize' };+ if (!intent || intent.mode !== 'hotfix')+ throw new Error(+ 'Targeted main patches need hotfix intent metadata with an explicitly delivered base; use hotfix:branch --base',+ );+ return intent;+}++export async function validatePrIntent(pr, store) {+ const intent = requestFromPr(pr);+ if (!intent || intent.mode === 'initialize') return intent;+ const baseline = await deliveredBaseline(store, intent.baseVersion, intent.baseSourcesHash);+ if (intent.cloudSha !== baseline.cloudSha && !intent.overrideReason)+ throw new Error('A different Cloud SHA needs a repair reason');+ await store.assertHotfixBase(baseline, pr.base.sha);+ return { ...intent, baseSourcesHash: sourcesHash(baseline) };+}++export function validateReleaseIntent(body, ossSha) {+ const intent = parseIntent(body);+ if (!intent) return null;+ if (intent.mergeSha !== ossSha) throw new Error('Release intent merge SHA mismatch');+ return intent;+}diff --git a/.github/scripts/desktopReleaseIntent.test.mjs b/.github/scripts/desktopReleaseIntent.test.mjsnew file mode 100644index 00000000000..89798dfa104--- /dev/null+++ b/.github/scripts/desktopReleaseIntent.test.mjs@@ -0,0 +1,142 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';++import { createGithubStore } from './desktopReleaseGithub.mjs';+import {+ formatIntent,+ parseIntent,+ requestFromPr,+ validatePrIntent,+ validateReleaseIntent,+} from './desktopReleaseIntent.mjs';+import { recordPublication, sourcesHash, stablePlatforms } from './desktopReleaseSources.mjs';+import {+ fixtureCloud,+ fixtureNextOss,+ fixtureOss,+ fixtureSources,+ startGithubFixture,+} from './desktopReleaseTestUtils.mjs';++const hotfix = {+ schemaVersion: 1,+ mode: 'hotfix',+ baseVersion: '2.2.21',+ cloudSha: fixtureCloud,+ baseSourcesHash: sourcesHash(fixtureSources),+};+const pr = (overrides = {}) => ({+ number: 22000,+ title: '🐛 fix: a targeted repair',+ body: formatIntent(hotfix),+ head: { ref: 'hotfix/a-repair' },+ base: { ref: 'main', sha: fixtureOss },+ ...overrides,+});++async function delivered(t) {+ const github = await startGithubFixture();+ t.after(github.close);+ const store = createGithubStore(github.options);+ await store.createSources('2.2.21', fixtureSources);+ await recordPublication(+ {+ version: '2.2.21',+ sourcesHash: sourcesHash(fixtureSources),+ runId: '40841847688',+ publishedAt: '2026-10-31T12:00:00Z',+ platforms: stablePlatforms,+ outcomes: { build: 'success', github: 'success', s3: 'success', sparkle: 'success' },+ },+ store,+ );+ return { github, store };+}++test('weekly releases select ordinary initialization but targeted patches need explicit metadata', () => {+ assert.equal(+ requestFromPr(pr({ head: { ref: 'release/weekly-20261031' }, body: '' })).mode,+ 'initialize',+ );+ assert.equal(+ requestFromPr(+ pr({ title: '🔨 chore: repair tooling', head: { ref: 'chore/tools' }, body: '' }),+ ),+ null,+ );+ assert.throws(() => requestFromPr(pr({ body: '' })), /metadata|base|intent/i);+ assert.throws(+ () => requestFromPr(pr({ body: formatIntent({ schemaVersion: 1, mode: 'initialize' }) })),+ /weekly|ordinary|hotfix/i,+ );+});++test('a PR keeps the exact chosen hotfix baseline and rejects duplicate metadata', () => {+ assert.deepEqual(requestFromPr(pr()), hotfix);+ assert.throws(+ () => parseIntent(`${formatIntent(hotfix)}\n${formatIntent(hotfix)}`),+ /duplicate|one/i,+ );+});++test('structured metadata safely round-trips a Cloud repair reason containing HTML delimiters', () => {+ const value = { ...hotfix, overrideReason: 'repair --> <script>example</script>' };+ assert.deepEqual(parseIntent(formatIntent(value)), value);+});++test('merged release metadata is bound to the actual target OSS commit', () => {+ const value = { ...hotfix, mergeSha: fixtureNextOss, prNumber: 22000, prBaseSha: fixtureOss };+ assert.deepEqual(validateReleaseIntent(formatIntent(value), fixtureNextOss), value);+ assert.throws(+ () => validateReleaseIntent(formatIntent(value), fixtureOss),+ /SHA|commit|mismatch/i,+ );+});++test('a hotfix PR validates the delivered record and cannot use an unpublished base', async (t) => {+ const { github, store } = await delivered(t);+ assert.deepEqual(await validatePrIntent(pr(), store), hotfix);+ github.releases.get('2.2.21').assets = github.releases+ .get('2.2.21')+ .assets.filter((asset) => asset.name !== 'desktop-published.v1.json');+ await assert.rejects(validatePrIntent(pr(), store), /published|delivered/i);+});++test('a changed hotfix baseline hash is rejected before merging', async (t) => {+ const { store } = await delivered(t);+ await assert.rejects(+ validatePrIntent(+ pr({ body: formatIntent({ ...hotfix, baseSourcesHash: '0'.repeat(64) }) }),+ store,+ ),+ /hash/i,+ );+});++test('a different Cloud SHA needs a recorded repair reason', async (t) => {+ const { store } = await delivered(t);+ const repair = { ...hotfix, cloudSha: '1'.repeat(40) };+ await assert.rejects(validatePrIntent(pr({ body: formatIntent(repair) }), store), /reason/i);+ assert.equal(+ (+ await validatePrIntent(+ pr({ body: formatIntent({ ...repair, overrideReason: 'Backport Cloud fix' }) }),+ store,+ )+ ).cloudSha,+ repair.cloudSha,+ );+});++test('main may advance with release tooling, but undistributed product changes block hotfix inheritance', async (t) => {+ const { github, store } = await delivered(t);+ const changed = pr({ base: { ref: 'main', sha: fixtureNextOss } });+ github.state.comparison = {+ status: 'ahead',+ total_commits: 1,+ files: [{ filename: '.github/scripts/desktopReleaseCli.mjs' }],+ };+ assert.equal((await validatePrIntent(changed, store)).baseVersion, '2.2.21');+ github.state.comparison.files = [{ filename: 'src/features/CanvasStorage/useCanvasStorage.ts' }];+ await assert.rejects(validatePrIntent(changed, store), /product changes|baseline/i);+});diff --git a/.github/scripts/desktopReleaseSources.mjs b/.github/scripts/desktopReleaseSources.mjsnew file mode 100644index 00000000000..9a4f97ab704--- /dev/null+++ b/.github/scripts/desktopReleaseSources.mjs@@ -0,0 +1,237 @@+import { createHash } from 'node:crypto';++export const sourceAssetName = 'desktop-sources.v1.json';+export const publicationAssetName = 'desktop-published.v1.json';+export const stablePlatforms = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'win32-x64'];++export function normalizeVersion(value) {+ if (+ typeof value !== 'string' ||+ !/^v?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(value)+ )+ throw new Error('A stable version such as 2.2.21 is required');+ return value.replace(/^v/, '');+}++export function assertSha(value, name = 'commit') {+ if (typeof value !== 'string' || !/^[a-f0-9]{40}$/.test(value))+ throw new Error(`${name} must be a full lowercase commit SHA`);+ return value;+}++const assertHash = (value) => {+ if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value))+ throw new Error('Invalid source record hash');+ return value;+};++const validateEvidence = (value) => {+ if (+ !value ||+ typeof value.runId !== 'string' ||+ !/^\d+$/.test(value.runId) ||+ !Number.isSafeInteger(value.runAttempt) ||+ value.runAttempt < 1+ )+ throw new Error('Source evidence requires a run ID and positive run attempt');+ return { runId: value.runId, runAttempt: value.runAttempt };+};++export function validateSources(value) {+ if (!value || value.schemaVersion !== 1 || value.channel !== 'stable')+ throw new Error('Unsupported stable source record schema/channel');+ if (!['latest', 'inherit', 'historical-import'].includes(value.selection))+ throw new Error('Invalid source selection');+ const record = {+ schemaVersion: 1,+ channel: 'stable',+ version: normalizeVersion(value.version),+ ossSha: assertSha(value.ossSha, 'OSS'),+ cloudSha: assertSha(value.cloudSha, 'Cloud'),+ selection: value.selection,+ baseVersion: value.baseVersion === null ? null : normalizeVersion(value.baseVersion),+ evidence: validateEvidence(value.evidence),+ };+ if (record.selection === 'inherit') {+ if (!record.baseVersion || record.baseVersion === record.version)+ throw new Error('A hotfix must reference a different base version');+ record.baseSourcesHash = assertHash(value.baseSourcesHash);+ if (value.overrideReason !== undefined) {+ if (+ typeof value.overrideReason !== 'string' ||+ !value.overrideReason.trim() ||+ value.overrideReason.length > 500+ )+ throw new Error('A Cloud override requires a concise reason');+ record.overrideReason = value.overrideReason.trim();+ }+ } else if (record.baseVersion !== null) {+ throw new Error('Only a hotfix may have a base version');+ }+ return record;+}++export function sourcesHash(record) {+ return createHash('sha256')+ .update(JSON.stringify(validateSources(record)))+ .digest('hex');+}++const assertIdentity = (record, input) => {+ if (record.version !== normalizeVersion(input.version) || record.ossSha !== input.ossSha)+ throw new Error('Source record version/OSS SHA mismatch');+ if (input.cloudSha && record.cloudSha !== input.cloudSha)+ throw new Error('Cloud SHA conflicts with the immutable source record');+ if (input.baseVersion && record.baseVersion !== normalizeVersion(input.baseVersion))+ throw new Error('Hotfix base version conflicts with the source record');+ if (input.baseSourcesHash && record.baseSourcesHash !== input.baseSourcesHash)+ throw new Error('Hotfix baseline hash conflicts with the source record');+};++export function validatePublication(value, sources) {+ if (+ !value ||+ value.schemaVersion !== 1 ||+ value.channel !== 'stable' ||+ normalizeVersion(value.version) !== sources.version ||+ value.sourcesHash !== sourcesHash(sources) ||+ value.ossSha !== sources.ossSha ||+ value.cloudSha !== sources.cloudSha ||+ !stablePlatforms.every((platform) => value.platforms?.includes(platform)) ||+ !['github', 's3', 'sparkle'].every((surface) => value.surfaces?.includes(surface)) ||+ typeof value.runId !== 'string' ||+ !/^\d+$/.test(value.runId) ||+ typeof value.publishedAt !== 'string' ||+ !Number.isFinite(Date.parse(value.publishedAt))+ )+ throw new Error('Publication proof is missing or does not match the source hash');+ return value;+}++export async function deliveredBaseline(store, version, expectedHash) {+ const normalized = normalizeVersion(version);+ const raw = await store.readSources(normalized);+ if (!raw) throw new Error(`Missing sources for baseline v${normalized}`);+ const sources = validateSources(raw);+ if (sources.version !== normalized) throw new Error('Baseline version mismatch');+ if (expectedHash && sourcesHash(sources) !== expectedHash)+ throw new Error('Baseline source hash mismatch');+ const receipt = await store.readPublication(normalized);+ if (!receipt) throw new Error(`Baseline v${normalized} has not been published/delivered`);+ validatePublication(receipt, sources);+ return sources;+}++// Storage has create-only semantics. A failed matrix never deletes this lock.+export async function resolveSources(input, dependencies) {+ const version = normalizeVersion(input.version);+ const ossSha = assertSha(input.ossSha, 'OSS');+ if (input.cloudSha) assertSha(input.cloudSha, 'Cloud');+ if (!['initialize', 'rebuild', 'hotfix', 'import'].includes(input.mode))+ throw new Error('An explicit release mode is required');+ const stored = await dependencies.store.readSources(version);+ if (stored !== null) {+ const sources = validateSources(stored);+ assertIdentity(sources, input);+ return { sources, hash: sourcesHash(sources), persisted: true };+ }+ if (input.mode === 'rebuild')+ throw new Error(`Missing source record for v${version}; use an explicit historical import`);++ const evidence = validateEvidence(input.evidence);+ if (input.mode !== 'import' && evidence.runAttempt !== 1)+ throw new Error(+ 'Missing source record: only the first attempt may initialize; use an explicit historical import',+ );+ let cloudSha;+ let selection;+ let baseVersion = null;+ let baseSourcesHash;+ let overrideReason;+ if (input.mode === 'initialize') {+ if (input.firstRelease !== true || evidence.runAttempt !== 1)+ throw new Error('Missing record: only the initial release attempt may initialize sources');+ if (input.cloudSha || input.baseVersion)+ throw new Error(+ 'Ordinary initialization selects Cloud HEAD; explicit sources require import/hotfix',+ );+ cloudSha = await dependencies.latestCloud();+ selection = 'latest';+ } else if (input.mode === 'hotfix') {+ const baseline = await deliveredBaseline(+ dependencies.store,+ input.baseVersion,+ input.baseSourcesHash,+ );+ baseVersion = baseline.version;+ if (baseVersion === version) throw new Error('A hotfix needs a new version');+ baseSourcesHash = sourcesHash(baseline);+ cloudSha = input.cloudSha || baseline.cloudSha;+ if (cloudSha !== baseline.cloudSha) {+ if (!input.overrideReason?.trim())+ throw new Error('A different Cloud SHA requires an override reason');+ overrideReason = input.overrideReason;+ }+ selection = 'inherit';+ } else {+ cloudSha = assertSha(input.cloudSha, 'Cloud');+ await dependencies.assertImportEvidence({ ...input, version, ossSha, evidence });+ selection = 'historical-import';+ }+ assertSha(cloudSha, 'Cloud');+ await dependencies.assertCloudCommit(cloudSha);+ const candidate = validateSources({+ schemaVersion: 1,+ channel: 'stable',+ version,+ ossSha,+ cloudSha,+ selection,+ baseVersion,+ evidence,+ ...(baseSourcesHash && { baseSourcesHash }),+ ...(overrideReason && { overrideReason }),+ });+ if (!input.write) return { sources: candidate, hash: sourcesHash(candidate), persisted: false };+ await dependencies.store.createSources(version, candidate);+ const winner = await dependencies.store.readSources(version);+ if (!winner) throw new Error('Source record was not persisted');+ const sources = validateSources(winner);+ assertIdentity(sources, { version, ossSha, cloudSha, baseVersion, baseSourcesHash });+ if (sources.selection !== selection || sources.overrideReason !== candidate.overrideReason)+ throw new Error('Concurrent source initialization conflict');+ return { sources, hash: sourcesHash(sources), persisted: true };+}++export async function recordPublication(input, store) {+ if (+ input.dryRun ||+ !stablePlatforms.every((platform) => input.platforms?.includes(platform)) ||+ !['build', 'github', 's3', 'sparkle'].every((stage) => input.outcomes?.[stage] === 'success')+ )+ return null;+ const raw = await store.readSources(normalizeVersion(input.version));+ if (!raw) throw new Error('Cannot publish proof without a source record');+ const sources = validateSources(raw);+ if (input.sourcesHash !== sourcesHash(sources)) throw new Error('Published source hash mismatch');+ const existing = await store.readPublication(sources.version);+ if (existing) return validatePublication(existing, sources);+ const receipt = validatePublication(+ {+ schemaVersion: 1,+ channel: 'stable',+ version: sources.version,+ sourcesHash: sourcesHash(sources),+ ossSha: sources.ossSha,+ cloudSha: sources.cloudSha,+ publishedAt: input.publishedAt,+ runId: input.runId,+ platforms: [...stablePlatforms],+ surfaces: ['github', 's3', 'sparkle'],+ },+ sources,+ );+ await store.createPublication(sources.version, receipt);+ const winner = await store.readPublication(sources.version);+ return validatePublication(winner, sources);+}diff --git a/.github/scripts/desktopReleaseSources.test.mjs b/.github/scripts/desktopReleaseSources.test.mjsnew file mode 100644index 00000000000..0a654eadf14--- /dev/null+++ b/.github/scripts/desktopReleaseSources.test.mjs@@ -0,0 +1,305 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';++import {+ recordPublication,+ resolveSources,+ sourcesHash,+ validateSources,+} from './desktopReleaseSources.mjs';++const ossSha = '483c4a343e437bf6e812b5f71a9a47ce7b5c7be4';+const cloudSha = 'bae4221819d5d3090a606610e6af3c28715749aa';+const nextCloud = '1df42564c5b35f21b24bcca164d71183b0619525';+const nextOss = '90659e0ed1327cd9bccb065d30b8edd09a8e9064';+const source = {+ schemaVersion: 1,+ channel: 'stable',+ version: '2.2.21',+ ossSha,+ cloudSha,+ selection: 'latest',+ baseVersion: null,+ evidence: { runId: '40841847688', runAttempt: 1 },+};+const outcomes = { build: 'success', github: 'success', s3: 'success', sparkle: 'success' };+const platforms = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'win32-x64'];++const memoryStore = () => {+ const sources = new Map();+ const publications = new Map();+ return {+ sources,+ publications,+ async readSources(version) {+ return sources.get(version) ?? null;+ },+ async createSources(version, record) {+ if (sources.has(version)) return false;+ sources.set(version, structuredClone(record));+ return true;+ },+ async readPublication(version) {+ return publications.get(version) ?? null;+ },+ async createPublication(version, receipt) {+ if (publications.has(version)) return false;+ publications.set(version, structuredClone(receipt));+ return true;+ },+ };+};+const request = (overrides = {}) => ({+ mode: 'initialize',+ version: '2.2.21',+ ossSha,+ evidence: { runId: '40841847688', runAttempt: 1 },+ firstRelease: true,+ write: true,+ ...overrides,+});+const dependencies = (store, overrides = {}) => ({+ store,+ latestCloud: async () => cloudSha,+ assertCloudCommit: async () => {},+ assertImportEvidence: async () => {},+ ...overrides,+});+const publish = (store, overrides = {}) =>+ recordPublication(+ {+ version: '2.2.21',+ sourcesHash: sourcesHash(source),+ runId: '40841847688',+ publishedAt: '2026-10-31T12:00:00.000Z',+ outcomes,+ platforms,+ ...overrides,+ },+ store,+ );++test('a rebuild uses the first Cloud after HEAD advances', async () => {+ const store = memoryStore();+ await resolveSources(request(), dependencies(store));+ const result = await resolveSources(+ request({ mode: 'rebuild', evidence: { runId: '40841847688', runAttempt: 3 } }),+ dependencies(store, { latestCloud: async () => nextCloud }),+ );+ assert.equal(result.sources.cloudSha, cloudSha);+ assert.equal(store.sources.get('2.2.21').evidence.runAttempt, 1);+});++test('a rerun cannot initialize a missing source lock', async () => {+ const store = memoryStore();+ await assert.rejects(+ resolveSources(+ request({ evidence: { runId: '40841847688', runAttempt: 2 } }),+ dependencies(store, { latestCloud: () => assert.fail('must not query HEAD') }),+ ),+ /initial|first|missing/i,+ );+ assert.equal(store.sources.size, 0);+});++test('a manual rebuild with no record fails without consulting HEAD', async () => {+ await assert.rejects(+ resolveSources(+ request({ mode: 'rebuild' }),+ dependencies(memoryStore(), { latestCloud: () => assert.fail('must not query HEAD') }),+ ),+ /missing/i,+ );+});++test('an existing lock rejects a different product SHA or Cloud override', async () => {+ const store = memoryStore();+ store.sources.set('2.2.21', source);+ for (const override of [{ ossSha: nextOss }, { cloudSha: nextCloud }]) {+ await assert.rejects(+ resolveSources(request({ mode: 'rebuild', ...override }), dependencies(store)),+ /conflict|mismatch/i,+ );+ }+ assert.deepEqual(store.sources.get('2.2.21'), source);+});++test('a corrupt or wrong-version source record never falls through to HEAD', async () => {+ for (const broken of [+ { ...source, cloudSha: 'main' },+ { ...source, version: '2.2.20' },+ ]) {+ const store = memoryStore();+ store.sources.set('2.2.21', broken);+ await assert.rejects(+ resolveSources(+ request(),+ dependencies(store, { latestCloud: () => assert.fail('must not query HEAD') }),+ ),+ /SHA|version|mismatch/i,+ );+ }+});++test('API failures propagate rather than being mistaken for a missing lock', async () => {+ const store = memoryStore();+ store.readSources = async () => {+ throw new Error('GitHub unavailable');+ };+ await assert.rejects(resolveSources(request(), dependencies(store)), /GitHub unavailable/);+});++test('a dry-run selects a candidate but does not persist a source record', async () => {+ const store = memoryStore();+ const result = await resolveSources(request({ write: false }), dependencies(store));+ assert.equal(result.sources.cloudSha, cloudSha);+ assert.equal(result.persisted, false);+ assert.equal(store.sources.size, 0);+});++test('a failed build leaves sources available but cannot become a hotfix baseline', async () => {+ const store = memoryStore();+ store.sources.set('2.2.21', source);+ assert.equal(await publish(store, { outcomes: { ...outcomes, build: 'failure' } }), null);+ assert.equal(store.sources.size, 1);+ await assert.rejects(+ resolveSources(+ request({ mode: 'hotfix', version: '2.2.22', ossSha: nextOss, baseVersion: '2.2.21' }),+ dependencies(store),+ ),+ /published|delivered/i,+ );+});++test('an OSS-only hotfix inherits the delivered baseline instead of latest Cloud', async () => {+ const store = memoryStore();+ store.sources.set('2.2.21', source);+ await publish(store);+ const result = await resolveSources(+ request({+ mode: 'hotfix',+ version: '2.2.22',+ ossSha: nextOss,+ baseVersion: 'v2.2.21',+ baseSourcesHash: sourcesHash(source),+ }),+ dependencies(store, { latestCloud: () => assert.fail('hotfix must not query HEAD') }),+ );+ assert.equal(result.sources.cloudSha, cloudSha);+ assert.equal(result.sources.ossSha, nextOss);+ assert.equal(result.sources.baseVersion, '2.2.21');+ assert.equal(result.sources.selection, 'inherit');+});++test('a hotfix refuses a changed baseline record or publication proof', async () => {+ const store = memoryStore();+ store.sources.set('2.2.21', source);+ await publish(store);+ store.sources.set('2.2.21', { ...source, cloudSha: nextCloud });+ await assert.rejects(+ resolveSources(+ request({+ mode: 'hotfix',+ version: '2.2.22',+ ossSha: nextOss,+ baseVersion: '2.2.21',+ baseSourcesHash: sourcesHash(source),+ }),+ dependencies(store),+ ),+ /hash|proof|mismatch/i,+ );+});++test('a hotfix Cloud repair needs a reason and is saved only on its new version', async () => {+ const store = memoryStore();+ store.sources.set('2.2.21', source);+ await publish(store);+ const input = request({+ mode: 'hotfix',+ version: '2.2.22',+ ossSha: nextOss,+ baseVersion: '2.2.21',+ cloudSha: nextCloud,+ });+ await assert.rejects(resolveSources(input, dependencies(store)), /reason/i);+ const result = await resolveSources(+ { ...input, overrideReason: 'Backport the Cloud fix' },+ dependencies(store),+ );+ assert.equal(result.sources.cloudSha, nextCloud);+ assert.equal(store.sources.get('2.2.21').cloudSha, cloudSha);+});++test('a historical import validates its run evidence before saving', async () => {+ const store = memoryStore();+ const input = request({ mode: 'import', cloudSha, firstRelease: false });+ await assert.rejects(+ resolveSources(+ input,+ dependencies(store, {+ assertImportEvidence: async () => {+ throw new Error('run SHA mismatch');+ },+ }),+ ),+ /run SHA mismatch/,+ );+ assert.equal(store.sources.size, 0);+ const result = await resolveSources(input, dependencies(store));+ assert.equal(result.sources.selection, 'historical-import');+ assert.equal(store.publications.size, 0);+});++test('a competing initializer cannot replace a different stored Cloud', async () => {+ const store = memoryStore();+ store.createSources = async () => {+ store.sources.set('2.2.21', { ...source, cloudSha: nextCloud });+ return false;+ };+ await assert.rejects(resolveSources(request(), dependencies(store)), /conflict/i);+ assert.equal(store.sources.get('2.2.21').cloudSha, nextCloud);+});++test('a competing initializer with identical sources reuses the winner', async () => {+ const store = memoryStore();+ store.createSources = async () => {+ store.sources.set('2.2.21', source);+ return false;+ };+ assert.deepEqual((await resolveSources(request(), dependencies(store))).sources, source);+});++test('partial, skipped or dry-run publication never creates delivery proof', async () => {+ for (const overrides of [+ { dryRun: true },+ { platforms: ['darwin-arm64'] },+ { outcomes: { ...outcomes, s3: 'skipped' } },+ { outcomes: { ...outcomes, sparkle: 'failure' } },+ { outcomes: { ...outcomes, github: 'cancelled' } },+ ]) {+ const store = memoryStore();+ store.sources.set('2.2.21', source);+ assert.equal(await publish(store, overrides), null);+ assert.equal(store.publications.size, 0);+ }+});++test('publication proof binds the exact source hash and is not overwritten by a rerun', async () => {+ const store = memoryStore();+ store.sources.set('2.2.21', source);+ await assert.rejects(publish(store, { sourcesHash: '0'.repeat(64) }), /hash|mismatch/i);+ const first = await publish(store);+ const second = await publish(store, { runId: 'later-run' });+ assert.equal(first.sourcesHash, sourcesHash(source));+ assert.deepEqual(first, second);+});++test('record hashes are stable across JSON property order and reject invalid identities', () => {+ assert.equal(+ sourcesHash({ ...source, version: '2.2.21' }),+ sourcesHash({ version: '2.2.21', ...source }),+ );+ assert.throws(() => validateSources({ ...source, channel: 'canary' }), /stable|channel/i);+ assert.throws(() => validateSources({ ...source, version: '2.2.22-canary.1' }), /version/i);+});diff --git a/.github/scripts/desktopReleaseTestUtils.mjs b/.github/scripts/desktopReleaseTestUtils.mjsnew file mode 100644index 00000000000..c1a2d1e1f59--- /dev/null+++ b/.github/scripts/desktopReleaseTestUtils.mjs@@ -0,0 +1,137 @@+import { createServer } from 'node:http';++export const fixtureOss = '483c4a343e437bf6e812b5f71a9a47ce7b5c7be4';+export const fixtureCloud = 'bae4221819d5d3090a606610e6af3c28715749aa';+export const fixtureNextOss = '90659e0ed1327cd9bccb065d30b8edd09a8e9064';+export const fixtureNextCloud = '1df42564c5b35f21b24bcca164d71183b0619525';+export const fixtureSources = {+ schemaVersion: 1,+ channel: 'stable',+ version: '2.2.21',+ ossSha: fixtureOss,+ cloudSha: fixtureCloud,+ selection: 'latest',+ baseVersion: null,+ evidence: { runId: '40841847688', runAttempt: 1 },+};++// A real HTTP boundary shared by the GitHub adapter and CLI process tests.+export async function startGithubFixture() {+ const releases = new Map();+ const assets = new Map();+ const commits = new Map([+ ['v2.2.21', fixtureOss],+ ['v2.2.22', fixtureNextOss],+ ['main', fixtureNextOss],+ ]);+ let serial = 100;+ const state = { cloud: fixtureNextCloud, error: null, rejectHead: false, intercept: null };+ const json = (response, status, value) => {+ response.writeHead(status, { 'Content-Type': 'application/json' });+ response.end(JSON.stringify(value));+ };+ const server = createServer(async (request, response) => {+ const url = new URL(request.url, 'http://localhost');+ if (state.intercept?.(request, response, url)) return;+ if (state.error) return json(response, state.error, { message: 'GitHub test error' });+ const route = url.pathname.replace('/repos/example/lobehub', '');+ if (url.pathname.startsWith('/repos/example/cloud/commits/')) {+ if (request.headers.authorization !== 'Bearer cloud-test-token')+ return json(response, 403, { message: 'wrong Cloud token' });+ const ref = url.pathname.split('/').pop();+ if (ref === 'HEAD' && state.rejectHead)+ return json(response, 500, { message: 'HEAD forbidden' });+ return json(response, 200, { sha: ref === 'HEAD' ? state.cloud : ref });+ }+ if (route.startsWith('/commits/')) {+ const sha = commits.get(decodeURIComponent(route.slice('/commits/'.length)));+ return json(response, sha ? 200 : 404, sha ? { sha } : { message: 'not found' });+ }+ if (route.startsWith('/actions/runs/'))+ return json(response, 200, { id: 40841847688, head_sha: fixtureOss, run_attempt: 1 });+ if (route === '/releases')+ return json(+ response,+ 200,+ [...releases.values()].map((release) => ({ ...release, assets: undefined })),+ );+ if (route.startsWith('/compare/'))+ return json(+ response,+ 200,+ state.comparison || { status: 'identical', total_commits: 0, files: [] },+ );+ if (route.startsWith('/releases/tags/')) {+ const release = releases.get(route.slice('/releases/tags/v'.length));+ return json(+ response,+ release ? 200 : 404,+ release ? { ...release, assets: undefined } : { message: 'not found' },+ );+ }+ if (route.startsWith('/releases/assets/')) {+ const asset = assets.get(Number(route.split('/').pop()));+ if (!asset) return json(response, 404, { message: 'not found' });+ response.writeHead(200, { 'Content-Type': 'application/octet-stream' });+ return response.end(asset.content);+ }+ const match = route.match(/^\/(?:uploads|releases)\/(\d+)\/assets$/);+ if (match) {+ const release = [...releases.values()].find((entry) => entry.id === Number(match[1]));+ if (!release) return json(response, 404, { message: 'not found' });+ if (request.method === 'POST') {+ const name = url.searchParams.get('name');+ if (release.assets.some((asset) => asset.name === name))+ return json(response, 422, { errors: [{ code: 'already_exists', field: 'name' }] });+ const chunks = [];+ for await (const chunk of request) chunks.push(chunk);+ const asset = addAsset(release.tag_name.slice(1), name, Buffer.concat(chunks).toString());+ return json(response, 201, asset);+ }+ const start = (Number(url.searchParams.get('page') || 1) - 1) * 100;+ return json(response, 200, release.assets.slice(start, start + 100));+ }+ if (route.startsWith('/pulls/')) {+ const pr = state.pullRequest;+ return json(response, pr ? 200 : 404, pr || { message: 'not found' });+ }+ return json(response, 404, { message: `Unknown fixture route ${route}` });+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ const apiUrl = `http://127.0.0.1:${server.address().port}`;+ function addRelease(version) {+ releases.set(version, {+ id: ++serial,+ tag_name: `v${version}`,+ draft: false,+ prerelease: false,+ upload_url: `${apiUrl}/repos/example/lobehub/uploads/${serial}/assets{?name,label}`,+ assets: [],+ });+ }+ function addAsset(version, name, content) {+ const asset = { id: ++serial, name, state: 'uploaded', size: Buffer.byteLength(content) };+ assets.set(asset.id, { ...asset, content });+ releases.get(version).assets.push(asset);+ return asset;+ }+ addRelease('2.2.21');+ addRelease('2.2.22');+ return {+ apiUrl,+ state,+ releases,+ commits,+ assets,+ addAsset,+ addRelease,+ options: {+ apiUrl,+ repository: 'example/lobehub',+ token: 'oss-test-token',+ cloudRepository: 'example/cloud',+ cloudToken: 'cloud-test-token',+ },+ close: () => new Promise((resolve) => server.close(resolve)),+ };+}diff --git a/.github/scripts/desktopReleaseWorkflow.test.mjs b/.github/scripts/desktopReleaseWorkflow.test.mjsnew file mode 100644index 00000000000..4b765d7f4f8--- /dev/null+++ b/.github/scripts/desktopReleaseWorkflow.test.mjs@@ -0,0 +1,196 @@+import assert from 'node:assert/strict';+import { execFile } from 'node:child_process';+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++import {+ fixtureCloud,+ fixtureNextCloud,+ fixtureSources,+ startGithubFixture,+} from './desktopReleaseTestUtils.mjs';++const exec = promisify(execFile);+const repository = fileURLToPath(new URL('../..', import.meta.url));+const workflow = await readFile(+ new URL('../workflows/release-desktop-stable.yml', import.meta.url),+ 'utf8',+);+const setup = await readFile(+ new URL('../actions/desktop-build-setup/action.yml', import.meta.url),+ 'utf8',+);++function shippedStep(source, name) {+ const section = source.split(`- name: ${name}\n`)[1]?.split(/\n *- (?:name:|uses:)/)[0];+ const block = section?.match(/^( +)run: \|\n/m);+ assert.ok(block, `shipped run step ${name} exists`);+ const indent = block[1].length + 2;+ const lines = [];+ for (const line of section.slice(block.index + block[0].length).split('\n')) {+ if (line.trim() && !line.startsWith(' '.repeat(indent))) break;+ lines.push(line.slice(indent));+ }+ return lines.join('\n').trimEnd();+}++test('the shipped Stable resolver reuses its old Cloud when the current HEAD has advanced', async (t) => {+ const github = await startGithubFixture();+ t.after(github.close);+ github.addAsset('2.2.21', 'desktop-sources.v1.json', JSON.stringify(fixtureSources));+ const root = await mkdtemp(path.join(os.tmpdir(), 'stable-resolver-'));+ t.after(() => rm(root, { recursive: true, force: true }));+ const output = path.join(root, 'outputs');+ // The original Bash resolver obtains B here. The repaired Node resolver reads A from GitHub.+ await exec(+ 'bash',+ [+ '-c',+ `git() { printf '%s\\tHEAD\\n' "$NEW_CLOUD"; }\n${shippedStep(workflow, 'Resolve Cloud revision')}`,+ ],+ {+ cwd: repository,+ env: {+ ...process.env,+ GITHUB_OUTPUT: output,+ RUNNER_TEMP: root,+ GITHUB_REPOSITORY: 'example/lobehub',+ GITHUB_API_URL: github.apiUrl,+ GH_TOKEN: 'oss-test-token',+ CLOUD_TOKEN: 'cloud-test-token',+ CLOUD_REPOSITORY: 'example/cloud',+ RELEASE_VERSION: '2.2.21',+ RELEASE_MODE: 'rebuild',+ SOURCE_REF: 'v2.2.21',+ GITHUB_RUN_ID: '40841847688',+ GITHUB_RUN_ATTEMPT: '3',+ WRITE_SOURCES: 'false',+ REQUESTED_CLOUD_REF: '',+ NEW_CLOUD: fixtureNextCloud,+ },+ },+ );+ const values = Object.fromEntries(+ (await readFile(output, 'utf8'))+ .trim()+ .split('\n')+ .map((line) => line.split('=')),+ );+ assert.equal(values.cloud_sha || values.cloud_ref, fixtureCloud);+});++test('the shipped setup refuses missing Stable Cloud credentials or an unpinned ref before installing', async () => {+ const script = shippedStep(setup, 'Validate pinned Stable sources');+ for (const overrides of [{ CLOUD_REF: '' }, { CLOUD_REF: 'main' }, { CLOUD_TOKEN: '' }]) {+ await assert.rejects(+ exec('bash', ['-c', script], {+ env: {+ ...process.env,+ REQUIRE_PINNED_CLOUD: 'true',+ CLOUD_REF: fixtureCloud,+ CLOUD_TOKEN: 'test-only',+ ...overrides,+ },+ }),+ );+ }+ await exec('bash', ['-c', script], {+ env: {+ ...process.env,+ REQUIRE_PINNED_CLOUD: 'true',+ CLOUD_REF: fixtureCloud,+ CLOUD_TOKEN: 'test-only',+ },+ });+});++test('the shipped source checkout guard validates the product SHA before restoring the new tooling', async (t) => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'stable-checkout-'));+ t.after(() => rm(root, { recursive: true, force: true }));+ const tools = path.join(root, 'tools');+ const product = path.join(root, 'product');+ const runner = path.join(root, 'runner');+ await mkdir(path.join(tools, '.github/scripts'), { recursive: true });+ await mkdir(product);+ await mkdir(runner);+ for (const name of [+ 'desktopReleaseSources.mjs',+ 'desktopReleaseGithub.mjs',+ 'desktopReleaseIntent.mjs',+ 'desktopReleaseCli.mjs',+ ])+ await copyFile(+ path.join(repository, '.github/scripts', name),+ path.join(tools, '.github/scripts', name),+ );+ await writeFile(path.join(tools, '.github/scripts/marker'), 'current tooling');+ await exec('git', ['init', tools]);+ await exec('git', ['-C', tools, 'add', '.github']);+ await exec('git', [+ '-C',+ tools,+ '-c',+ 'user.name=Release test',+ '-c',+ '[email protected]',+ '-c',+ 'commit.gpgsign=false',+ 'commit',+ '-m',+ 'tooling fixture',+ ]);+ await exec('git', ['init', product]);+ await writeFile(path.join(product, 'product.txt'), 'old application');+ await exec('git', ['-C', product, 'add', 'product.txt']);+ await exec('git', [+ '-C',+ product,+ '-c',+ 'user.name=Release test',+ '-c',+ '[email protected]',+ '-c',+ 'commit.gpgsign=false',+ 'commit',+ '-m',+ 'fixture',+ ]);+ const sha = (await exec('git', ['-C', product, 'rev-parse', 'HEAD'])).stdout.trim();+ // The preserve step runs in a tooling checkout; use a separate real product repository afterward.+ const env = {+ ...process.env,+ RUNNER_TEMP: runner,+ GITHUB_ENV: path.join(root, 'env'),+ RELEASE_OSS_SHA: sha,+ CLOUD_REF: fixtureCloud,+ SOURCES_HASH: 'a'.repeat(64),+ DESKTOP_TOOLING_SHA: 'b'.repeat(40),+ };+ await exec('bash', ['-c', shippedStep(workflow, 'Preserve release tooling')], {+ cwd: tools,+ env,+ });+ await exec('bash', ['-c', shippedStep(workflow, 'Verify product sources and restore tooling')], {+ cwd: product,+ env,+ });+ assert.equal(+ await readFile(path.join(product, '.github/scripts/marker'), 'utf8'),+ 'current tooling',+ );+ assert.equal(await readFile(path.join(product, 'product.txt'), 'utf8'), 'old application');+ const diagnostics = JSON.parse(+ await readFile(path.join(product, 'desktop-ota-diagnostics/sources.json'), 'utf8'),+ );+ assert.equal(diagnostics.ossSha, sha);+ await assert.rejects(+ exec('bash', ['-c', shippedStep(workflow, 'Verify product sources and restore tooling')], {+ cwd: product,+ env: { ...env, RELEASE_OSS_SHA: '0'.repeat(40) },+ }),+ );+});diff --git a/.github/scripts/hotfixWorkflow.test.mjs b/.github/scripts/hotfixWorkflow.test.mjsnew file mode 100644index 00000000000..ace44f4fe5a--- /dev/null+++ b/.github/scripts/hotfixWorkflow.test.mjs@@ -0,0 +1,24 @@+import assert from 'node:assert/strict';+import { execFile } from 'node:child_process';+import { mkdtemp, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { test } from 'node:test';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++const exec = promisify(execFile);++// Runs after setup/install: the operator CLI imports workspace prompt dependencies.+test('hotfix help explains explicit baseline selection without accessing Git or GitHub', async (t) => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'hotfix-help-'));+ t.after(() => rm(root, { recursive: true, force: true }));+ const script = fileURLToPath(new URL('../../scripts/hotfixWorkflow/index.ts', import.meta.url));+ const result = await exec(+ process.execPath,+ ['--disable-warning=MODULE_TYPELESS_PACKAGE_JSON', script, '--help'],+ { cwd: root },+ );+ assert.match(result.stdout, /--base/);+ assert.match(result.stdout, /--cloud-ref/);+});diff --git a/.github/workflows/auto-tag-release.yml b/.github/workflows/auto-tag-release.ymlindex e807215c752..4a6b270093e 100644--- a/.github/workflows/auto-tag-release.yml+++ b/.github/workflows/auto-tag-release.yml@@ -39,11 +39,11 @@ jobs:# Match "🚀 release: v{x.x.x}" format (strict semver: x.y.z with optional -prerelease or +build)if [[ "$PR_TITLE" =~ ^🚀[[:space:]]+release:[[:space:]]*v([0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?)$ ]]; thenVERSION="${BASH_REMATCH[1]}"- echo "version=$VERSION" >> $GITHUB_OUTPUT- echo "should_tag=true" >> $GITHUB_OUTPUT+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"+ echo "should_tag=true" >> "$GITHUB_OUTPUT"echo "✅ Detected release PR, version: v$VERSION"else- echo "should_tag=false" >> $GITHUB_OUTPUT+ echo "should_tag=false" >> "$GITHUB_OUTPUT"echo "⏭️ Not a release PR"fi@@ -59,17 +59,17 @@ jobs:# Priority 1: hotfix/* or release/* branch always triggers, ignore PR title gate.if [[ "$HEAD_REF" == hotfix/* ]] || [[ "$HEAD_REF" == release/* ]]; then- echo "should_tag=true" >> $GITHUB_OUTPUT+ echo "should_tag=true" >> "$GITHUB_OUTPUT"echo "✅ Detected auto-release PR from $HEAD_REF branch (title gate bypassed)"exit 0fi# Priority 2: fallback to PR title prefix gate (legacy behavior).if echo "$PR_TITLE" | grep -qiE '^(💄[[:space:]]*)?style(\(.+\))?:|^(✨[[:space:]]*)?feat(\(.+\))?:|^(🐛[[:space:]]*)?fix(\(.+\))?:|^(♻️[[:space:]]*)?refactor(\(.+\))?:|^((🐛|🩹)[[:space:]]*)?hotfix(\(.+\))?:|^(👷[[:space:]]*)?build(\(.+\))?:'; then- echo "should_tag=true" >> $GITHUB_OUTPUT+ echo "should_tag=true" >> "$GITHUB_OUTPUT"echo "✅ Detected patch PR from title prefix gate"else- echo "should_tag=false" >> $GITHUB_OUTPUT+ echo "should_tag=false" >> "$GITHUB_OUTPUT"echo "⏭️ Not a patch PR (neither hotfix/release branch nor style/feat/fix/refactor/hotfix/build title prefix)"fi@@ -101,16 +101,20 @@ jobs:- name: Set context (release)if: steps.release.outputs.should_tag == 'true'run: |- echo "SHOULD_TAG=true" >> $GITHUB_ENV- echo "KIND=release" >> $GITHUB_ENV- echo "VERSION=${{ steps.release.outputs.version }}" >> $GITHUB_ENV+ {+ echo "SHOULD_TAG=true"+ echo "KIND=release"+ echo "VERSION=${{ steps.release.outputs.version }}"+ } >> "$GITHUB_ENV"- name: Set context (patch)if: steps.patch.outputs.should_tag == 'true'run: |- echo "SHOULD_TAG=true" >> $GITHUB_ENV- echo "KIND=patch" >> $GITHUB_ENV- echo "VERSION=${{ steps.patch-version.outputs.version }}" >> $GITHUB_ENV+ {+ echo "SHOULD_TAG=true"+ echo "KIND=patch"+ echo "VERSION=${{ steps.patch-version.outputs.version }}"+ } >> "$GITHUB_ENV"- name: Check if tag already existsif: env.SHOULD_TAG == 'true'@@ -118,20 +122,29 @@ jobs:run: |VERSION="${{ env.VERSION }}"if git rev-parse "v$VERSION" >/dev/null 2>&1; then- echo "exists=true" >> $GITHUB_OUTPUT+ echo "exists=true" >> "$GITHUB_OUTPUT"echo "⚠️ Tag v$VERSION already exists"else- echo "exists=false" >> $GITHUB_OUTPUT+ echo "exists=false" >> "$GITHUB_OUTPUT"echo "✅ Tag v$VERSION does not exist, can create"fi+ - name: Validate and bind desktop release sources+ id: desktop-sources+ if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false' && !contains(env.VERSION, '-')+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ RELEASE_VERSION: ${{ env.VERSION }}+ run: node .github/scripts/desktopReleaseCli.mjs prepare-release+- name: Create GitHub Releaseif: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'- uses: softprops/action-gh-release@v1+ uses: softprops/action-gh-release@v3with:tag_name: v${{ env.VERSION }}target_commitish: ${{ github.event.pull_request.merge_commit_sha }}name: 🚀 Release v${{ env.VERSION }}+ body_path: ${{ steps.desktop-sources.outputs.body_file }}body: |## 📦 Release v${{ env.VERSION }}diff --git a/.github/workflows/desktop-release-request.yml b/.github/workflows/desktop-release-request.ymlnew file mode 100644index 00000000000..f493b448711--- /dev/null+++ b/.github/workflows/desktop-release-request.yml@@ -0,0 +1,32 @@+name: Desktop Release Sources++on:+ pull_request_target:+ types: [opened, edited, synchronize, reopened]+ branches: [main]++permissions:+ contents: read++concurrency:+ group: desktop-release-request-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ validate:+ name: Validate desktop release baseline+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ # Only trusted base scripts execute; PR text is data read from the event file.+ - uses: actions/checkout@v7+ with:+ ref: ${{ github.event.pull_request.base.sha }}+ sparse-checkout: .github/scripts+ - uses: actions/setup-node@v6+ with:+ node-version: '24.11.1'+ - name: Validate release intent+ env:+ GH_TOKEN: ${{ github.token }}+ run: node .github/scripts/desktopReleaseCli.mjs check-prdiff --git a/.github/workflows/release-desktop-stable.yml b/.github/workflows/release-desktop-stable.ymlindex 7af0656ce89..c332cb51b81 100644--- a/.github/workflows/release-desktop-stable.yml+++ b/.github/workflows/release-desktop-stable.yml@@ -30,10 +30,36 @@ on:required: truetype: stringcloud_ref:- description: 'Cloud commit SHA (40 lowercase hex characters); empty uses latest HEAD'+ description: 'Cloud SHA for import, or verify the SHA already bound in the hotfix Release'required: falsetype: stringdefault: ''+ release_mode:+ description: 'Rebuild pinned sources, resume a PR-bound hotfix, or import historical sources only'+ required: true+ type: choice+ options: [rebuild, hotfix, import]+ default: rebuild+ source_ref:+ description: 'Product source ref; defaults to the target version tag and must resolve to its SHA'+ type: string+ default: ''+ base_version:+ description: 'Optional verification of the delivered baseline already bound in the hotfix Release'+ type: string+ default: ''+ cloud_override_reason:+ description: 'Optional verification of the Cloud repair reason already bound in the hotfix Release'+ type: string+ default: ''+ evidence_run_id:+ description: 'Original build run ID for historical import'+ type: string+ default: ''+ evidence_run_attempt:+ description: 'Original build attempt for historical import'+ type: string+ default: ''build_mac:description: 'Build macOS (ARM64)'required: false@@ -81,13 +107,28 @@ jobs:check-stable:name: Check Release Versionruns-on: ubuntu-latest+ permissions:+ contents: write+ actions: read+ pull-requests: readoutputs:- cloud_ref: ${{ steps.cloud-ref.outputs.cloud_ref }}+ cloud_ref: ${{ steps.cloud-ref.outputs.cloud_sha }}+ oss_sha: ${{ steps.cloud-ref.outputs.oss_sha }}+ sources_hash: ${{ steps.cloud-ref.outputs.sources_hash }}+ build_required: ${{ steps.cloud-ref.outputs.build_required }}is_stable: ${{ steps.check.outputs.is_stable }}version: ${{ steps.check.outputs.version }}is_manual: ${{ steps.check.outputs.is_manual }}release_notes: ${{ steps.check.outputs.release_notes }}steps:+ - name: Checkout release tooling+ uses: actions/checkout@v7+ with:+ ref: ${{ github.workflow_sha }}+ - uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ package-manager-cache: false- name: Check release infoid: checkenv:@@ -98,34 +139,38 @@ jobs:# 手动触发: 使用输入的版本号version="${{ inputs.version }}"version="${version#v}"- echo "is_manual=true" >> $GITHUB_OUTPUT- echo "version=${version}" >> $GITHUB_OUTPUT- echo "release_notes=" >> $GITHUB_OUTPUT+ {+ echo "is_manual=true"+ echo "version=${version}"+ echo "release_notes="+ } >> "$GITHUB_OUTPUT"echo "🔧 Manual trigger: version=${version}"else# Release 触发: 从 tag 提取版本号version="${{ github.event.release.tag_name }}"version="${version#v}"- echo "is_manual=false" >> $GITHUB_OUTPUT- echo "version=${version}" >> $GITHUB_OUTPUT+ {+ echo "is_manual=false"+ echo "version=${version}"+ } >> "$GITHUB_OUTPUT"release_body="${RELEASE_BODY:-}"{echo "release_notes<<EOF"printf '%s\n' "$release_body"echo "EOF"- } >> $GITHUB_OUTPUT+ } >> "$GITHUB_OUTPUT"fi# 检查是否为 stable 版本 (不含任何 '-' 后缀)if [[ "$version" == *"-"* ]]; then- echo "is_stable=false" >> $GITHUB_OUTPUT+ echo "is_stable=false" >> "$GITHUB_OUTPUT"echo "⏭️ Skipping: $version is not a stable release"else- echo "is_stable=true" >> $GITHUB_OUTPUT+ echo "is_stable=true" >> "$GITHUB_OUTPUT"echo "✅ Stable release detected: $version"fi- # No checkout in this job, so the local overlay-token action is unavailable.+ # Restrict the Cloud token to the configured overlay repository.- name: Resolve overlay repositoryid: overlay-repoif: steps.check.outputs.is_stable == 'true'@@ -149,38 +194,40 @@ jobs:id: cloud-refif: steps.check.outputs.is_stable == 'true'env:- REQUESTED_CLOUD_REF: ${{ inputs.cloud_ref || '' }}+ GH_TOKEN: ${{ github.token }}+ RELEASE_VERSION: ${{ steps.check.outputs.version }}+ RELEASE_MODE: ${{ github.event_name == 'release' && 'auto' || inputs.release_mode }}+ SOURCE_REF: ${{ inputs.source_ref || '' }}+ CLOUD_REF: ${{ inputs.cloud_ref || '' }}+ BASE_VERSION: ${{ inputs.base_version || '' }}+ CLOUD_OVERRIDE_REASON: ${{ inputs.cloud_override_reason || '' }}+ EVIDENCE_RUN_ID: ${{ inputs.evidence_run_id || '' }}+ EVIDENCE_RUN_ATTEMPT: ${{ inputs.evidence_run_attempt || '' }}+ WRITE_SOURCES: ${{ github.event_name == 'release' || inputs.release_mode == 'import' || !inputs.skip_github_release || !inputs.skip_s3_upload }}CLOUD_REPOSITORY: ${{ vars.OVERLAY_REPOSITORY }}CLOUD_TOKEN: ${{ steps.overlay-token.outputs.token }}run: |- set -euo pipefail- : "${CLOUD_REPOSITORY:?OVERLAY_REPOSITORY repository variable is not set}"- if [ -n "$REQUESTED_CLOUD_REF" ]; then- if [[ ! "$REQUESTED_CLOUD_REF" =~ ^[0-9a-f]{40}$ ]]; then- echo "::error::cloud_ref must be a full 40-character lowercase commit SHA"- exit 1- fi- cloud_ref="$REQUESTED_CLOUD_REF"- else- # checkout persist-credentials extraheader would send GITHUB_TOKEN and 404 the private cloud repo- cloud_ref=$(git -c http.https://github.com/.extraheader= ls-remote "https://x-access-token:${CLOUD_TOKEN}@github.com/${CLOUD_REPOSITORY}.git" HEAD | cut -f1)- fi- if [[ ! "$cloud_ref" =~ ^[0-9a-f]{40}$ ]]; then- echo "Unable to resolve Cloud revision"- exit 1- fi- echo "cloud_ref=$cloud_ref" >> "$GITHUB_OUTPUT"+ node .github/scripts/desktopReleaseCli.mjs resolve++ - name: Preserve source selection diagnostics+ if: always()+ uses: actions/upload-artifact@v6+ with:+ name: desktop-sources-${{ github.run_id }}-${{ github.run_attempt }}+ path: ${{ runner.temp }}/desktop-release-sources.json+ if-no-files-found: ignore# ============================================# 配置构建矩阵 (检查自托管 Runner)# ============================================configure-build:needs: [check-stable]- if: needs.check-stable.outputs.is_stable == 'true'+ if: needs.check-stable.outputs.build_required == 'true'name: Configure Build Matrixruns-on: ubuntu-latestoutputs:matrix: ${{ steps.set-matrix.outputs.matrix }}+ complete_matrix: ${{ steps.set-matrix.outputs.complete_matrix }}steps:- name: Generate Matrixid: set-matrix@@ -213,21 +260,56 @@ jobs:fi# 输出- echo "matrix={\"include\":$static_matrix}" >> $GITHUB_OUTPUT+ count=$(jq 'length' <<< "$static_matrix")+ [ "$count" -gt 0 ] || { echo '::error::Select at least one build platform'; exit 1; }+ {+ echo "matrix={\"include\":$static_matrix}"+ echo "complete_matrix=$([ "$count" -eq 4 ] && echo true || echo false)"+ } >> "$GITHUB_OUTPUT"# ============================================# 多平台构建# ============================================build:needs: [check-stable, configure-build]- if: needs.check-stable.outputs.is_stable == 'true'+ if: needs.check-stable.outputs.build_required == 'true'name: Build Desktop Appruns-on: ${{ matrix.os }}strategy:fail-fast: falsematrix: ${{ fromJson(needs.configure-build.outputs.matrix) }}steps:- - uses: actions/checkout@v7+ - name: Checkout release tooling+ uses: actions/checkout@v7+ with:+ ref: ${{ github.workflow_sha }}++ - name: Preserve release tooling+ shell: bash+ run: |+ set -euo pipefail+ mkdir -p "$RUNNER_TEMP/desktop-release-tooling"+ cp -R .github "$RUNNER_TEMP/desktop-release-tooling/"+ tooling_sha="$(git rev-parse HEAD)"+ echo "DESKTOP_TOOLING_SHA=$tooling_sha" >> "$GITHUB_ENV"++ - name: Checkout product sources+ uses: actions/checkout@v7+ with:+ ref: ${{ needs.check-stable.outputs.oss_sha }}++ - name: Verify product sources and restore tooling+ shell: bash+ env:+ RELEASE_OSS_SHA: ${{ needs.check-stable.outputs.oss_sha }}+ CLOUD_REF: ${{ needs.check-stable.outputs.cloud_ref }}+ SOURCES_HASH: ${{ needs.check-stable.outputs.sources_hash }}+ run: |+ set -euo pipefail+ [ "$(git rev-parse HEAD)" = "$RELEASE_OSS_SHA" ] || { echo '::error::Product source SHA mismatch'; exit 1; }+ mkdir -p .github+ cp -R "$RUNNER_TEMP/desktop-release-tooling/.github/." .github/+ node .github/scripts/desktopReleaseCli.mjs verify-checkout- name: Create overlay tokenid: overlay-token@@ -245,6 +327,7 @@ jobs:cloud-repository: ${{ vars.OVERLAY_REPOSITORY }}cloud-token: ${{ steps.overlay-token.outputs.token }}node-version: ${{ env.NODE_VERSION }}+ require-pinned-cloud: 'true'- name: Resolve core seqid: core_seq@@ -367,6 +450,8 @@ jobs:steps:- name: Checkout repositoryuses: actions/checkout@v7+ with:+ ref: ${{ github.workflow_sha }}- name: Setup environmentuses: ./.github/actions/setup-env@@ -429,12 +514,12 @@ jobs:run: ls -R release- name: Upload to Release- uses: softprops/action-gh-release@v1+ uses: softprops/action-gh-release@v3with:# 手动触发时使用输入的版本号创建 tagtag_name: ${{ github.event_name == 'workflow_dispatch' && format('v{0}', needs.check-stable.outputs.version) || github.event.release.tag_name }}- # 手动触发时创建为 draft- draft: ${{ github.event_name == 'workflow_dispatch' }}+ # Source resolution already requires an existing release; do not unpublish it on a rebuild.+ draft: falsefiles: |release/stable*release/latest*@@ -456,6 +541,9 @@ jobs:needs: [merge-mac-files, check-stable]name: Publish to S3runs-on: ubuntu-latest+ outputs:+ core_published: ${{ steps.publish.outputs.core-published }}+ installers_published: ${{ steps.publish.outputs.installers-published }}# 手动触发时可选择跳过if: ${{ !(github.event_name == 'workflow_dispatch' && inputs.skip_s3_upload) }}steps:@@ -468,7 +556,9 @@ jobs:- uses: actions/checkout@v7with:token: ${{ steps.app-token.outputs.token }}+ ref: ${{ github.workflow_sha }}- uses: ./.github/actions/desktop-publish-s3+ id: publishwith:channel: stablecloud-ref: ${{ needs.check-stable.outputs.cloud_ref }}@@ -483,13 +573,18 @@ jobs:needs: [publish-s3, check-stable]name: Publish Sparkle Appcastruns-on: macos-15+ outputs:+ published: ${{ steps.publish.outputs.published }}steps:- uses: actions/checkout@v7+ with:+ ref: ${{ github.workflow_sha }}- uses: actions/setup-node@v6with:node-version: ${{ env.NODE_VERSION }}package-manager-cache: false- uses: ./.github/actions/desktop-publish-sparkle+ id: publishwith:channel: stableversion: ${{ needs.check-stable.outputs.version }}@@ -501,3 +596,31 @@ jobs:s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}s3-region: ${{ secrets.UPDATE_S3_REGION }}s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}++ record-delivery:+ name: Record successful desktop delivery+ needs: [check-stable, configure-build, build, publish-github, publish-s3, publish-sparkle]+ if: always() && needs.check-stable.outputs.build_required == 'true'+ runs-on: ubuntu-latest+ permissions:+ contents: write+ steps:+ - uses: actions/checkout@v7+ with:+ ref: ${{ github.workflow_sha }}+ - uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ package-manager-cache: false+ - name: Record publication proof+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_VERSION: ${{ needs.check-stable.outputs.version }}+ SOURCES_HASH: ${{ needs.check-stable.outputs.sources_hash }}+ CORE_PUBLISHED: ${{ needs.publish-s3.outputs.core_published }}+ INSTALLERS_PUBLISHED: ${{ needs.publish-s3.outputs.installers_published }}+ SPARKLE_PUBLISHED: ${{ needs.publish-sparkle.outputs.published }}+ RELEASE_DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && (inputs.skip_github_release || inputs.skip_s3_upload) }}+ BUILT_PLATFORMS: ${{ needs.configure-build.outputs.complete_matrix == 'true' && '["darwin-arm64","darwin-x64","linux-x64","win32-x64"]' || '[]' }}+ PUBLICATION_OUTCOMES: '{"build":"${{ needs.build.result }}","github":"${{ needs.publish-github.result }}","s3":"${{ needs.publish-s3.result }}","sparkle":"${{ needs.publish-sparkle.result }}"}'+ run: node .github/scripts/desktopReleaseCli.mjs publishdiff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex ca7cdc3b09e..2bdabbbbb3b 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -66,6 +66,7 @@ jobs:.github/scripts/size-gate-comment.test.cjs \.github/scripts/pr-admission-check.test.cjs \.github/scripts/mergeAllowBuilds.test.mjs \+ .github/scripts/desktopRelease*.test.mjs \.github/scripts/desktop-core-gate.test.mjs- name: Setup environment@@ -78,6 +79,9 @@ jobs:run: pnpm installworking-directory: apps/cli+ - name: Verify hotfix operator CLI+ run: node --test .github/scripts/hotfixWorkflow.test.mjs+- name: Test CLI build configuration, bundle and model-facing docsrun: bunx vitest run --config vitest.config.mts --silent='passed-only' tsdown.config.test.ts bundle.test.ts src/modelFacingDocs.test.tsworking-directory: apps/cli@@ -265,11 +269,7 @@ jobs:# new or cherry-picked changes (and conflict resolutions) on the branch# itself, so their PRs are the only place those changes get linted.ALINT_SKIP_REASON: >-- ${{- github.event_name == 'pull_request' && startsWith(github.head_ref, 'release/weekly-') && 'weekly release PR, whose changes were linted on their own PRs' ||- github.event_name == 'push' && github.ref == 'refs/heads/main' && 'push to main, whose changes were linted on their own PRs' ||- ''- }}+ ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'release/weekly-') && 'weekly release PR, whose changes were linted on their own PRs' || github.event_name == 'push' && github.ref == 'refs/heads/main' && 'push to main, whose changes were linted on their own PRs' || '' }}steps:- name: Checkoutdiff --git a/scripts/hotfixWorkflow/index.ts b/scripts/hotfixWorkflow/index.tsindex def3f9a907a..f66cdee5442 100644--- a/scripts/hotfixWorkflow/index.ts+++ b/scripts/hotfixWorkflow/index.ts@@ -1,13 +1,77 @@-import { execFileSync, execSync } from 'node:child_process';+import { execFile, execSync } from 'node:child_process';import * as fs from 'node:fs';-import * as path from 'node:path';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { parseArgs, promisify } from 'node:util';-import { confirm, input } from '@inquirer/prompts';+import { confirm, input, select } from '@inquirer/prompts';import { consola } from 'consola';import * as semver from 'semver';+import { createGithubStore } from '../../.github/scripts/desktopReleaseGithub.mjs';+import { formatIntent } from '../../.github/scripts/desktopReleaseIntent.mjs';+import { deliveredBaseline, sourcesHash } from '../../.github/scripts/desktopReleaseSources.mjs';+const ROOT_DIR = process.cwd();const PACKAGE_JSON_PATH = path.join(ROOT_DIR, 'package.json');+const exec = promisify(execFile);++interface HotfixSources {+ baseOssSha: string;+ baseSourcesHash: string;+ baseVersion: string;+ cloudSha: string;+ overrideReason?: string;+}++async function chooseSources(options: {+ 'base'?: string;+ 'cloud-ref'?: string;+ 'reason'?: string;+}): Promise<HotfixSources> {+ const repository =+ process.env.GITHUB_REPOSITORY ||+ (+ await exec('gh', ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'])+ ).stdout.trim();+ const token =+ process.env.GH_TOKEN ||+ process.env.GITHUB_TOKEN ||+ (await exec('gh', ['auth', 'token'])).stdout.trim();+ const store = createGithubStore({ repository, token, apiUrl: process.env.GITHUB_API_URL });+ let base = options.base;+ if (!base) {+ const candidates = await store.listDelivered();+ if (!candidates.length)+ throw new Error(+ 'No Stable release has recorded delivery proof; restore and verify a baseline first.',+ );+ base = await select({+ message: 'Which delivered Stable release should this hotfix repair?',+ choices: candidates.map((candidate: { cloudSha: string; version: string }) => ({+ name: `v${candidate.version} — Cloud ${candidate.cloudSha.slice(0, 8)}`,+ value: candidate.version,+ })),+ });+ }+ const baseline = await deliveredBaseline(store, base);+ const mainSha = (await exec('git', ['rev-parse', 'origin/main'])).stdout.trim();+ await store.assertHotfixBase(baseline, mainSha);+ const cloudSha = options['cloud-ref'] || baseline.cloudSha;+ if (cloudSha !== baseline.cloudSha && !options.reason?.trim())+ throw new Error('--cloud-ref requires --reason when changing the inherited Cloud source');+ const result = {+ baseVersion: baseline.version,+ baseOssSha: baseline.ossSha,+ baseSourcesHash: sourcesHash(baseline),+ cloudSha,+ ...(options.reason && { overrideReason: options.reason }),+ };+ // Validate the exact metadata before pushing a branch or creating a PR.+ formatIntent({ schemaVersion: 1, mode: 'hotfix', ...result });+ return result;+}function checkGitRepo(): void {try {@@ -73,9 +137,13 @@ async function confirmHotfix(opts: {branchName: string;currentVersion: string;isExistingBranch: boolean;+ sources: HotfixSources;version: string;}): Promise<boolean> {- const { version, currentVersion, branchName, isExistingBranch } = opts;+ const { version, currentVersion, branchName, isExistingBranch, sources } = opts;+ consola.info(+ `Base: v${sources.baseVersion}\nOSS: ${sources.baseOssSha}\nCloud: ${sources.cloudSha}`,+ );if (isExistingBranch) {consola.box(@@ -137,7 +205,11 @@ function pushBranch(branchName: string): void {}}-async function createPullRequest(version: string, branchName: string): Promise<void> {+async function createPullRequest(+ version: string,+ branchName: string,+ sources: HotfixSources,+): Promise<void> {const title = await input({default: `🐛 fix: hotfix v${version}`,message: 'PR title:',@@ -146,6 +218,13 @@ async function createPullRequest(version: string, branchName: string): Promise<vThis PR starts a hotfix release from \`main\`.+### Desktop sources+- Base release: v${sources.baseVersion}+- Base OSS: \`${sources.baseOssSha}\`+- Cloud: \`${sources.cloudSha}\`+${sources.overrideReason ? `- Cloud repair: ${sources.overrideReason}\n` : ''}+${formatIntent({ schemaVersion: 1, mode: 'hotfix', ...sources })}+### Release Process1. ✅ Hotfix branch created from main2. ✅ Pushed to remote@@ -155,13 +234,24 @@ This PR starts a hotfix release from \`main\`.---Created by hotfix script`;+ const directory = await mkdtemp(path.join(tmpdir(), 'lobehub-hotfix-'));try {consola.info('🔀 Creating Pull Request...');- execFileSync(- 'gh',- ['pr', 'create', '--title', title, '--body', body, '--base', 'main', '--head', branchName],- { stdio: 'inherit' },- );+ const bodyFile = path.join(directory, 'body.md');+ await writeFile(bodyFile, body);+ const result = await exec('gh', [+ 'pr',+ 'create',+ '--title',+ title,+ '--body-file',+ bodyFile,+ '--base',+ 'main',+ '--head',+ branchName,+ ]);+ consola.info(result.stdout.trim());consola.success('✅ PR created successfully!');} catch (error) {consola.error('❌ Failed to create PR');@@ -169,7 +259,9 @@ Created by hotfix script`;consola.info('\n💡 Tip: Make sure GitHub CLI (gh) is installed and logged in');consola.info(' Install: https://cli.github.com/');consola.info(' Login: gh auth login');- process.exit(1);+ throw error;+ } finally {+ await rm(directory, { recursive: true, force: true });}}@@ -200,6 +292,23 @@ function extractVersionFromBranch(branchName: string): string | null {}async function main(): Promise<void> {+ const { values } = parseArgs({+ options: {+ 'base': { type: 'string' },+ 'cloud-ref': { type: 'string' },+ 'reason': { type: 'string' },+ 'help': { type: 'boolean' },+ },+ });+ if (values.help) {+ consola.log(+ 'Usage: bun run hotfix:branch [--base v2.2.21] [--cloud-ref <SHA> --reason <repair>]',+ );+ consola.log(+ 'Without --base, select a Stable release with matching source and delivery records.',+ );+ return;+ }consola.info('🩹 LobeChat Hotfix Script\n');checkGitRepo();@@ -219,12 +328,15 @@ async function main(): Promise<void> {const currentVersion = getCurrentVersion();const version = extractVersionFromBranch(currentBranch) ?? bumpPatchVersion(currentVersion);+ await exec('git', ['fetch', 'origin', 'main']);+ const sources = await chooseSources(values);const confirmed = await confirmHotfix({branchName: currentBranch,currentVersion,isExistingBranch: true,version,+ sources,});if (!confirmed) {consola.info('❌ Hotfix process cancelled');@@ -232,7 +344,7 @@ async function main(): Promise<void> {}pushBranch(currentBranch);- await createPullRequest(version, currentBranch);+ await createPullRequest(version, currentBranch, sources);showCompletion(version, currentBranch);} else {consola.info('📥 Pulling latest main branch...');@@ -241,12 +353,14 @@ async function main(): Promise<void> {const currentVersion = getCurrentVersion();const newVersion = bumpPatchVersion(currentVersion);const branchName = createHotfixBranchName(newVersion);+ const sources = await chooseSources(values);const confirmed = await confirmHotfix({branchName,currentVersion,isExistingBranch: false,version: newVersion,+ sources,});if (!confirmed) {consola.info('❌ Hotfix process cancelled');@@ -255,7 +369,7 @@ async function main(): Promise<void> {createHotfixBranch(branchName);pushBranch(branchName);- await createPullRequest(newVersion, branchName);+ await createPullRequest(newVersion, branchName, sources);showCompletion(newVersion, branchName);}}