The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(release): shared assembly, scoped publication, harness fold (rounds 2 cont.)
ethernet31a26c58965c
diff --git a/.github/workflows/desktop-bundle-smoke.yml b/.github/workflows/desktop-bundle-smoke.ymlindex 396fcb02ef9..d622f17f5d0 100644--- a/.github/workflows/desktop-bundle-smoke.yml+++ b/.github/workflows/desktop-bundle-smoke.yml@@ -30,6 +30,12 @@ on:controller-sha:default: ''type: string+ disposable-run:+ default: ''+ type: string+ public-root:+ default: ''+ type: stringpublic-base:required: truetype: string@@ -68,6 +74,8 @@ jobs:CHANNEL_BUILD: ${{ inputs.channel-build }}CHANNEL_REQUEST_SHA256: ${{ inputs.channel-request-sha256 }}PUBLIC_BASE: ${{ inputs.public-base }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ inputs.public-root }}+ R2_DISPOSABLE_RUN: ${{ inputs.disposable-run }}PLATFORM: ${{ inputs.platform }}ARCH: ${{ inputs.arch }}FORMAT: ${{ inputs.format }}diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.ymlindex 663a1c518aa..1e4c1ad4de9 100644--- a/.github/workflows/desktop-bundled-release.yml+++ b/.github/workflows/desktop-bundled-release.yml@@ -100,6 +100,18 @@ on:required: falsetype: stringdefault: ''+ disposable_channel:+ description: 'Allocate a disposable preview from build_commit; prints a separate build dispatch. No native build in this run.'+ type: string+ default: ''+ disposable_receivers:+ description: 'Also allocate A/B and official-identity S/T test receivers in the fresh namespace; no releases.'+ type: boolean+ default: false+ disposable_run:+ description: 'Allocation controller run-id-attempt; only with channel_build and its pinned digest.'+ type: string+ default: ''channel_build:description: 'Admitted immutable channel build ID (32 lowercase hex); trusted default-branch dispatch only.'required: false@@ -146,10 +158,62 @@ concurrency:group: desktop-bundled-release-${{ inputs.channel_build || inputs.tag || inputs.build_commit || 'canary' }}-${{ inputs.release-phase || 'canary' }}cancel-in-progress: false+env:+ R2_DISPOSABLE_RUN: ${{ inputs.disposable_run }}+jobs:+ allocate-disposable:+ name: Allocate disposable channel and probe CAS/CDN+ if: >-+ inputs.disposable_channel != '' && github.event_name == 'workflow_dispatch'+ && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)+ && github.workflow_ref == format('{0}/.github/workflows/desktop-bundled-release.yml@refs/heads/{1}', github.repository, github.event.repository.default_branch)+ runs-on: ubuntu-24.04+ environment: release-signing+ timeout-minutes: 10+ permissions:+ contents: read+ env:+ DISPOSABLE_CHANNEL: ${{ inputs.disposable_channel }}+ DISPOSABLE_RECEIVERS: ${{ inputs.disposable_receivers }}+ BUILD_COMMIT: ${{ inputs.build_commit }}+ CHANNEL_BUILD: ${{ inputs.channel_build }}+ CHANNEL_REQUEST_SHA256: ${{ inputs.channel_request_sha256 }}+ TAG: ${{ inputs.tag }}+ RELEASE_PHASE: ${{ inputs.release-phase }}+ TERMUX_ONLY: ${{ inputs.termux_only }}+ TERMUX_UPGRADE_FROM_TAG: ${{ inputs.termux_upgrade_from_tag }}+ UPLOAD_RELEASE: ${{ inputs.upload_release }}+ BUNDLE_ENV_JSON: ${{ inputs.bundle_env }}+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}+ GH_TOKEN: ${{ github.token }}+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.sha }}+ fetch-depth: 0+ - name: Set up native identity reader+ if: inputs.disposable_receivers+ uses: ./.github/actions/setup-pm+ with:+ toolchain: node+ cache-python: false+ archive-inputs: false+ - name: Probe scoped storage and allocate without dispatching+ run: python -m scripts.releases.channel_disposable+validate:name: Validate the build source+ if: inputs.disposable_channel == ''runs-on: ubuntu-24.04+ # Public root is an environment variable, not a repository variable. No+ # secret is injected into admission; downstream jobs consume its outputs.+ environment: release-signingtimeout-minutes: 5permissions:contents: read@@ -163,6 +227,9 @@ jobs:channel: ${{ steps.admission.outputs.channel }}sha: ${{ steps.admission.outputs.sha }}payload-version: ${{ steps.admission.outputs.payload-version }}+ receiver-candidate: ${{ steps.admission.outputs.receiver-candidate }}+ public-root: ${{ steps.admission.outputs.public-root }}+ public-base: ${{ steps.admission.outputs.public-base }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -171,13 +238,6 @@ jobs:# origin/main, which needs the shared ancestry, not a depth-1 tip.fetch-depth: 0fetch-tags: true- filter: tree:0- sparse-checkout: |- pyproject.toml- scripts/releases- scripts/release-content-types.json- hermes_cli/release_channels.py- sparse-checkout-cone-mode: false- name: Validate tag shape, pyproject lockstep, and ancestry on origin/mainid: admission@@ -195,6 +255,13 @@ jobs:TERMUX_UPGRADE_FROM_TAG: ${{ inputs.termux_upgrade_from_tag }}GH_TOKEN: ${{ github.token }}run: |+ if [ -n "${R2_DISPOSABLE_RUN:-}" ] && [ -z "${CHANNEL_BUILD:-}" ]; then+ echo '::error::disposable_run requires a pinned channel build'; exit 1+ fi+ if [ "${GITHUB_ACTIONS:-}" = true ] && [ "$GITHUB_REPOSITORY" != NousResearch/hermes-agent ] && [ -z "${R2_DISPOSABLE_RUN:-}" ]; then+ echo '::error::fork CI requires a disposable channel allocation'; exit 1+ fi+ printf 'public-root=%s\npublic-base=%s\n' "$CLOUDFLARE_R2_PUBLIC_URL" "$CLOUDFLARE_R2_PUBLIC_URL" >> "$GITHUB_OUTPUT"if [ -n "${CHANNEL_BUILD:-}" ]; thenif [ "$GITHUB_EVENT_NAME" != workflow_dispatch ] || [ -z "$DEFAULT_BRANCH" ] || [ "$GITHUB_REF" != "refs/heads/$DEFAULT_BRANCH" ] || [ "$GITHUB_WORKFLOW_REF" != "$GITHUB_REPOSITORY/.github/workflows/desktop-bundled-release.yml@refs/heads/$DEFAULT_BRANCH" ]; thenecho '::error::channel builds require the default-branch dispatch workflow'; exit 1@@ -278,7 +345,7 @@ jobs:# Windows assembly and publication depend on these native Windows legs.archive-inputs:name: Archive every pinned input- if: inputs.release-phase == '' || inputs.release-phase == 'candidate'+ if: inputs.disposable_run == '' && (inputs.release-phase == '' || inputs.release-phase == 'candidate')needs: [validate]uses: ./.github/workflows/archive-inputs.ymlwith:@@ -312,7 +379,7 @@ jobs:# Signature outputs are separate from the prepared dependency snapshot.ELECTRON_BUILDER_CACHE: ${{ github.workspace }}/.cache/electron-builderCLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}- CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ needs.validate.outputs.public-root }}steps: &win32-steps- name: Exclude build write paths from Defender scanningshell: powershell@@ -492,7 +559,7 @@ jobs:# appears after the selected packages (including Store on stable) upload.run: |args=(--include '*.msix')- if [ "$RELEASE_PHASE" = candidate ]; then+ if [ "$RELEASE_PHASE" = candidate ] || { [ "$HERMES_DESKTOP_VARIANT" = bundled ] && [[ "$HERMES_PAYLOAD_TAG" == *-canary.* ]]; }; thenpython -m scripts.bundles.release_artifacts record --platform windows --arch "${TARGET##*-}" \--root apps/desktop/release --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \--out "apps/desktop/release/metadata-windows-${TARGET##*-}.json"@@ -510,7 +577,11 @@ jobs:build-win32-commit:name: bundled ${{ matrix.target.label }} (commit)- if: inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate') && (inputs.build_commit != '' || inputs.channel_build != '')+ if: >-+ !cancelled() && needs.validate.result == 'success'+ && (needs.archive-inputs.result == 'success' || (inputs.disposable_run != '' && needs.archive-inputs.result == 'skipped'))+ && inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate')+ && (inputs.build_commit != '' || inputs.channel_build != '')needs: [validate, archive-inputs]runs-on: ${{ matrix.target.runner }}environment: release-signing@@ -526,7 +597,8 @@ jobs:# still skips this result, just as it skipped the original native builder.if: >-always() && inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate')- && needs.validate.result == 'success' && needs.archive-inputs.result == 'success'+ && needs.validate.result == 'success'+ && (needs.archive-inputs.result == 'success' || (inputs.disposable_run != '' && needs.archive-inputs.result == 'skipped'))needs: [validate, archive-inputs, build-win32-release, build-win32-commit]runs-on: ubuntu-24.04permissions: {}@@ -578,7 +650,7 @@ jobs:HERMES_BUILD_COMMIT: ${{ needs.validate.outputs.sha && inputs.build_commit != '' && needs.validate.outputs.sha || '' }}HERMES_PAYLOAD_VERSION: ${{ needs.validate.outputs.payload-version }}CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}- CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ needs.validate.outputs.public-root }}steps: &darwin-steps- name: Disable Spotlight indexing for DMG staging# Spotlight indexes the freshly-mounted dmg staging image past@@ -782,7 +854,7 @@ jobs:# Per-arch feed inputs stay in the tag archive until both legs pass.run: |args=(--include '*.dmg' --include '*.zip' --include '*.blockmap' --include '*-mac.yml')- if [ "$RELEASE_PHASE" = candidate ]; then+ if [ "$RELEASE_PHASE" = candidate ] || { [ "$HERMES_DESKTOP_VARIANT" = bundled ] && [[ "$HERMES_PAYLOAD_TAG" == *-canary.* ]]; }; thenpython -m scripts.bundles.release_artifacts record --platform macos --arch "${TARGET##*-}" \--root apps/desktop/release --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \--out "apps/desktop/release/metadata-macos-${TARGET##*-}.json"@@ -801,7 +873,11 @@ jobs:build-darwin-commit:name: bundled ${{ matrix.target.label }} (commit)- if: inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate') && (inputs.build_commit != '' || inputs.channel_build != '')+ if: >-+ !cancelled() && needs.validate.result == 'success'+ && (needs.archive-inputs.result == 'success' || (inputs.disposable_run != '' && needs.archive-inputs.result == 'skipped'))+ && inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate')+ && (inputs.build_commit != '' || inputs.channel_build != '')needs: [validate, archive-inputs]runs-on: ${{ matrix.target.runner }}environment: release-signing@@ -817,7 +893,8 @@ jobs:# still skips this result, just as it skipped the original native builder.if: >-always() && inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate')- && needs.validate.result == 'success' && needs.archive-inputs.result == 'success'+ && needs.validate.result == 'success'+ && (needs.archive-inputs.result == 'success' || (inputs.disposable_run != '' && needs.archive-inputs.result == 'skipped'))needs: [validate, archive-inputs, build-darwin-release, build-darwin-commit]runs-on: ubuntu-24.04permissions: {}@@ -871,7 +948,9 @@ jobs:channel-build: ${{ inputs.channel_build }}channel-request-sha256: ${{ inputs.channel_request_sha256 }}controller-sha: ${{ github.sha }}- public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ public-base: ${{ needs.validate.outputs.public-base }}+ public-root: ${{ needs.validate.outputs.public-root }}+ disposable-run: ${{ inputs.disposable_run }}smoke-win32:name: Smoke Windows ${{ matrix.arch }} MSIX@@ -898,7 +977,9 @@ jobs:channel-build: ${{ inputs.channel_build }}channel-request-sha256: ${{ inputs.channel_request_sha256 }}controller-sha: ${{ github.sha }}- public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ public-base: ${{ needs.validate.outputs.public-base }}+ public-root: ${{ needs.validate.outputs.public-root }}+ disposable-run: ${{ inputs.disposable_run }}smoke-win32-universal:name: Smoke Windows ${{ matrix.arch }} MSIXBUNDLE@@ -925,7 +1006,9 @@ jobs:channel-build: ${{ inputs.channel_build }}channel-request-sha256: ${{ inputs.channel_request_sha256 }}controller-sha: ${{ github.sha }}- public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ public-base: ${{ needs.validate.outputs.public-base }}+ public-root: ${{ needs.validate.outputs.public-root }}+ disposable-run: ${{ inputs.disposable_run }}# Assembly never writes a feed, including for canaries.assemble-win32-bundle:@@ -951,7 +1034,7 @@ jobs:CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}- CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ needs.validate.outputs.public-root }}AZURE_SIGN_ENDPOINT: ${{ vars.AZURE_SIGN_ENDPOINT }}AZURE_SIGN_ACCOUNT: ${{ vars.AZURE_SIGN_ACCOUNT }}AZURE_SIGN_PROFILE: ${{ vars.AZURE_SIGN_PROFILE }}@@ -976,7 +1059,7 @@ jobs:uses: ./.github/actions/setup-pmwith:toolchain: all- archive-inputs: true+ archive-inputs: ${{ inputs.disposable_run == '' }}cache-python: false- name: Install the locked Windows bundle tooling@@ -1124,19 +1207,24 @@ jobs:CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}- CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ needs.validate.outputs.public-root }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:ref: ${{ github.sha }}fetch-depth: 0fetch-tags: true+ - name: Publish tested disposable receiver without promoting T+ if: needs.validate.outputs.receiver-candidate == 'true'+ run: python -m scripts.releases.channel_publish receiver-publish --root "$RUNNER_TEMP/channel-publish"- name: Publish immutable feeds and manifest, then CAS channel head+ if: needs.validate.outputs.receiver-candidate != 'true'shell: bashrun: |python -m scripts.releases.channel_publish publish --root "$RUNNER_TEMP/channel-publish"python scripts/render-builds-table.py --channel-build "$CHANNEL_BUILD" \--channel-request-sha256 "$CHANNEL_REQUEST_SHA256" --repo "$GITHUB_REPOSITORY" \+ --r2-base-url "$(python -c 'from scripts.releases.r2_scope import channel_public_base; print(channel_public_base())')" \--summary-out "$GITHUB_STEP_SUMMARY"publish-win32-updater:@@ -1915,7 +2003,7 @@ jobs:publish-canary:name: Publish the canary release- needs: [build-win32, build-darwin, build-linux, builds-table, assemble-win32-bundle, smoke-darwin, smoke-win32, smoke-win32-universal, publish-win32-updater, publish-darwin-updater]+ needs: [validate, build-win32, build-darwin, build-linux, builds-table, assemble-win32-bundle, smoke-darwin, smoke-win32, smoke-win32-universal, publish-win32-updater, publish-darwin-updater]if: |always()&& inputs.build_commit == '' && inputs.channel_build == ''@@ -1932,7 +2020,20 @@ jobs:&& needs.publish-win32-updater.result == 'success'&& needs.publish-darwin-updater.result == 'success'runs-on: ubuntu-24.04+ environment: release-signingsteps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ needs.validate.outputs.sha }}+ fetch-depth: 0+ - uses: ./.github/actions/setup-pm+ with:+ cache-python: false+ - name: Set up the native identity reader+ uses: ./.github/actions/setup-pm+ with:+ toolchain: node+ cache-python: false- name: Publishenv:GH_TOKEN: ${{ github.token }}@@ -1940,3 +2041,17 @@ jobs:run: |gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=falseecho "Published $TAG"+ # The controller rechecks native job results, the remote tag and published+ # GitHub release before any R2 head write; receipts bind the exact bytes.+ - name: Advance protected canary head from the published release+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ inputs.tag }}+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}+ RELEASE_NEEDS: ${{ toJSON(needs) }}+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ run: python -m scripts.releases.channel_releases canarydiff --git a/.github/workflows/install-e2e.yml b/.github/workflows/install-e2e.ymlindex c659e616d73..bde2699cdd9 100644--- a/.github/workflows/install-e2e.yml+++ b/.github/workflows/install-e2e.yml@@ -51,7 +51,29 @@ on:required: falsetype: choicedefault: all- options: [all, both, update, installer, windows-desktop, macos-desktop, bundled, windows-bundled, macos-bundled]+ options: [all, both, update, installer, windows-desktop, macos-desktop, bundled, windows-bundled, macos-bundled, channel-retirement]+ retirement-manifest:+ description: 'HTTPS URL for one digest-pinned disposable native retirement journey.'+ type: string+ default: ''+ retirement-sha256:+ description: 'Exact SHA256 of retirement-manifest bytes.'+ type: string+ default: ''+ disposable-run:+ description: 'Existing allocation run-id-attempt; never a production namespace.'+ type: string+ default: ''+ retirement-arch:+ description: 'Native retirement host architecture.'+ type: choice+ options: [arm64, x64]+ default: arm64+ retirement-platform:+ description: 'Native retirement OS (one fresh namespace per journey).'+ type: choice+ options: [darwin, win32]+ default: darwinwindows-bundle-manifest:description: 'HTTPS manifest pinning signed Windows OLD/NEW msixbundles; NEW must match this ref.'type: string@@ -131,14 +153,87 @@ permissions:# github.run_id so a parent rerun cannot kill this child mid-flight. The# scheduled/push runs keep ref-scoped collapse.concurrency:- group: install-e2e-${{ inputs.release == true && github.run_id || github.ref }}- cancel-in-progress: ${{ inputs.release != true }}+ group: install-e2e-${{ inputs.route == 'channel-retirement' && format('retirement-{0}', inputs.disposable-run) || inputs.release == true && github.run_id || github.ref }}+ cancel-in-progress: ${{ inputs.release != true && inputs.route != 'channel-retirement' }}jobs:+ channel-retirement:+ name: Native bundled retirement+ if: >-+ inputs.route == 'channel-retirement' && github.event_name == 'workflow_dispatch'+ && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)+ runs-on: ${{ inputs.retirement-platform == 'win32' && (inputs.retirement-arch == 'arm64' && 'windows-11-arm' || 'windows-latest') || (inputs.retirement-arch == 'x64' && 'macos-15-intel' || 'macos-15') }}+ environment: release-signing+ timeout-minutes: 75+ permissions:+ contents: read+ defaults:+ run:+ shell: bash+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false+ - uses: ./.github/actions/setup-pm+ with:+ toolchain: node+ - name: Install driver dependencies+ run: |+ node -e 'if (Number(process.versions.node.split(".")[0]) < 24) throw Error("Node 24+ required")'+ npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund+ - name: Fetch pinned controller input+ # Portable admission checks are not native acceptance.+ # Keep them in the native job so this coordinator cannot become an orphan.+ # The real lifecycle still runs below against signed artifacts.+ env:+ MANIFEST_URL: ${{ inputs.retirement-manifest }}+ MANIFEST_SHA256: ${{ inputs.retirement-sha256 }}+ run: |+ python3 -c 'import os,pathlib,hashlib,urllib.request; u=os.environ["MANIFEST_URL"]; assert u.startswith("https://"); b=urllib.request.urlopen(u,timeout=30).read(4194305); assert len(b)<=4194304 and hashlib.sha256(b).hexdigest()==os.environ["MANIFEST_SHA256"]; pathlib.Path(os.environ["RUNNER_TEMP"],"retirement-input.json").write_bytes(b)'+ - name: Check coordinator and immutable input transport+ run: |+ node --test tests/install/e2e-assets/channel-retirement-manifest.test.cjs+ - uses: ./.github/actions/e2e-screen-record+ with:+ mode: start+ output: ${{ runner.temp }}/retirement-recording.mkv+ - name: Run native journey with isolated publisher credentials+ env:+ GH_TOKEN: ${{ github.token }}+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ R2_DISPOSABLE_RUN: ${{ inputs.disposable-run }}+ MANIFEST_SHA256: ${{ inputs.retirement-sha256 }}+ RETIREMENT_ARCH: ${{ inputs.retirement-arch }}+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}+ run: |+ python3 tests/install/channel-retirement-controller.py \+ --manifest "$RUNNER_TEMP/retirement-input.json" --sha256 "$MANIFEST_SHA256" \+ --work "$RUNNER_TEMP/retirement" --arch "$RETIREMENT_ARCH"+ - uses: ./.github/actions/e2e-screen-record+ if: always()+ with:+ mode: stop+ output: ${{ runner.temp }}/retirement-recording.mkv++ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ if: always()+ with:+ name: retirement-observations-${{ github.run_id }}-${{ github.run_attempt }}+ path: |+ ${{ runner.temp }}/retirement/observations/+ ${{ runner.temp }}/retirement-recording.mkv+ if-no-files-found: warn+ retention-days: 14+# Which released versions do we test updating FROM? Resolved once,# annotated with what each tag's own tree supports, and shared by every# OS's matrix so all combos cover the same set.pick-releases:+ if: inputs.route != 'channel-retirement'name: Pick release tagsruns-on: ubuntu-latesttimeout-minutes: 5@@ -231,6 +326,7 @@ jobs:--format markdown >> "$GITHUB_STEP_SUMMARY"bundle-inputs:+ if: inputs.route != 'channel-retirement'name: Validate pinned bundle transitionsruns-on: ubuntu-latesttimeout-minutes: 5@@ -410,7 +506,7 @@ jobs:# the per-OS aggregates.report:name: Result chart- if: always()+ if: always() && inputs.route != 'channel-retirement'needs: [leg-player, pick-releases, linux, windows, macos, bundle-inputs, windows-bundled, macos-bundled]runs-on: ubuntu-latesttimeout-minutes: 5diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.ymlindex 5ae3e95c411..14f9c01fca3 100644--- a/.github/workflows/stable-release.yml+++ b/.github/workflows/stable-release.yml@@ -256,11 +256,12 @@ jobs:complete:name: Stable release is greenif: always()- needs: [admit, ci, docker, acceptance, candidates, publication, promote-docker, promote-bundles]+ needs: [admit, ci, docker, acceptance, candidates, publication, promote-docker, promote-bundles, windows-packaged, macos-packaged]runs-on: ubuntu-24.04environment: release-signingpermissions:contents: write+ actions: readsteps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -282,7 +283,7 @@ jobs:# must leave protocol-aware readers on the previous accepted release.run: |python -m scripts.releases.stable complete- python -m scripts.releases.channel_releases stable+ python -m scripts.releases.channel_releases stable --root "$RUNNER_TEMP/stable-channel"env:RELEASE_NEEDS: ${{ toJSON(needs) }}GH_TOKEN: ${{ github.token }}diff --git a/apps/desktop/electron-builder.config.cjs b/apps/desktop/electron-builder.config.cjsindex c1fcab01e78..dd3758b166e 100644--- a/apps/desktop/electron-builder.config.cjs+++ b/apps/desktop/electron-builder.config.cjs@@ -136,7 +136,9 @@ module.exports = {// The afterSign hook owns notarization, including keychain-profile builds.notarize: false,// The packaged client reads this generated app-update.yml by default.- publish: channelRequest+ publish: channelRequest?.receiverCandidate+ ? [{ provider: 'generic', url: `${channelRequest.publicBase}/releases/darwin/stable/`, channel: 'stable' }]+ : channelRequest? [{ provider: 'generic', url: `${channelRequest.publicBase}/releases/channel-builds/${channelRequest.buildId}/darwin/`, channel: 'latest' }]: publicUrl && channel && macFeed? [{ provider: 'generic', url: `${publicUrl}/${macFeed.directory}/`, channel: macFeed.channel }]diff --git a/apps/desktop/electron/channel-build-version.test.ts b/apps/desktop/electron/channel-build-version.test.tsindex dc456324df9..f55568df3d7 100644--- a/apps/desktop/electron/channel-build-version.test.ts+++ b/apps/desktop/electron/channel-build-version.test.ts@@ -114,12 +114,51 @@ test('channel stamps verify the real checkout and retain source version and natiassert.equal(built.updateMechanism, 'electron-updater')assert.equal(built.baseVersion, build.sourceVersion)assert.equal(built.tag, null)+ assert.equal(built.receiverProtocol, 1)assert.deepEqual(built.channelBuild, build)assert.ok(Object.isFrozen(built.channelBuild?.identity))fs.mkdirSync(path.join(dir, 'out/agent-payload/repo'), { recursive: true })writeDesktopStamp(path.join(dir, 'out'), built)assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, 'out/install-stamp.json'), 'utf8')), JSON.parse(fs.readFileSync(path.join(dir, 'out/agent-payload/repo/install-stamp.json'), 'utf8')))assert.throws((): void => { resolveStamp({ env: { ...env, _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(request()) }, repoRoot: dir }) }, /checkout/)+ delete process.env._HERMES_CHANNEL_REQUEST_JSON+ process.env.HERMES_PAYLOAD_TAG = 'v0.0.1'+ delete require.cache[require.resolve('../product-identity.cjs')]+ const official: ProductIdentity = require('../product-identity.cjs')+ delete process.env.HERMES_PAYLOAD_TAG+ const receiver: ChannelBuildRequest = {+ ...build, channel: 'stable', sequence: 1, version: '0.0.1', windowsVersion: '0.0.1.0',+ releaseTag: 'v0.0.1', receiverCandidate: true, bundleEnv: {},+ publicBase: 'https://builds.example.test/ci-disposable/1/2-1',+ identity: { ...official, token: build.identity.token }+ }+ const receiverEnv: NodeJS.ProcessEnv = { ...env, _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(receiver) }+ const stable: InstallStamp = buildStampPayload(resolveStamp({ env: receiverEnv, repoRoot: dir }), receiverEnv, 'darwin', payload)+ assert.equal(stable.channelBuild, undefined)+ assert.equal(stable.source, 'build')+ assert.equal(stable.tag, receiver.releaseTag)+ assert.equal(stable.displayVersion, receiver.version)+ assert.equal(stable.updateMechanism, 'electron-updater')+ const packaged: PackagingFacts = load(receiver)+ assert.deepEqual(packaged.config.mac?.publish, [{ provider: 'generic', url: `${receiver.publicBase}/releases/darwin/stable/`, channel: 'stable' }])+ const { verifyBundleStamp }: { verifyBundleStamp: (stamp: InstallStamp, options: {+ commit: string; platform: string; channelRequest: ChannelBuildRequest+ }) => string } = await import('../../../tests/install/e2e-assets/bundle-smoke-metadata.mjs')+ assert.equal(verifyBundleStamp(stable, { commit: receiver.commit, platform: 'darwin', channelRequest: receiver }), receiver.version)+ assert.throws((): void => { verifyBundleStamp(built, { commit: receiver.commit, platform: 'darwin', channelRequest: receiver }) })+ execFileSync(process.env.HERMES_PYTHON || 'python3', ['-c', `+import json, sys+from scripts.bundles.release_artifacts import stamp_matches+stamp, request = json.loads(sys.argv[1]), json.loads(sys.argv[2])+stamp_matches(stamp, '', request['commit'], channel_request=request)+stamp['channelBuild'] = request+try:+ stamp_matches(stamp, '', request['commit'], channel_request=request)+except ValueError:+ pass+else:+ raise AssertionError('receiver accepted preview updater ownership')+`, JSON.stringify(stable), JSON.stringify(receiver)], { cwd: repo })} finally {fs.rmSync(dir, { recursive: true, force: true })}@@ -130,6 +169,7 @@ test('actual MSIX manifest writer consumes the channel quad across rollover instconst root: string = fs.mkdtempSync(path.join(os.tmpdir(), 'channel-manifest-'))const app: string = path.join(root, 'apps/desktop')interface ManifestFacts { version: string; semver: string; appId: string; xml: string }+ interface RecordedMetadata { applicationId: string; version: string }try {for (const file of ['apps/desktop/product-identity.cjs', 'apps/desktop/electron-builder.config.cjs',@@ -192,6 +232,38 @@ test('actual MSIX manifest writer consumes the channel quad across rollover instassert.match(row.xml, new RegExp(`Version="${build.windowsVersion.replaceAll('.', '\\.')}"`))assert.equal((row.xml.match(/Category="windows.appExecutionAlias"/g) || []).length, 2)assert.match(row.xml, /HermesChannelab12cd34ef56ab78Cli1/)++ const recordScript: string = `+import json, pathlib, sys, zipfile, xml.etree.ElementTree as ET+sys.path.insert(0, sys.argv[1])+from scripts.bundles.release_artifacts import record, desktop_application+root = pathlib.Path(sys.argv[2])+request = json.loads(sys.argv[3])+package = root / 'Recorder-win-x64.msix'+with zipfile.ZipFile(package, 'w') as archive:+ archive.writestr('AppxManifest.xml', (root / 'manifest.xml').read_bytes())+ archive.writestr('app/resources/install-stamp.json', json.dumps({+ 'source': 'channel-build', 'channelBuild': request, 'commit': request['commit'], 'tag': None}))+out = root / 'metadata.json'+record('windows', 'x64', root, '', request['commit'], out, channel_request=request)+manifest = ET.fromstring((root / 'manifest.xml').read_bytes())+desktop = desktop_application(manifest, request)+desktop.set('Id', 'WrongDesktop')+try:+ desktop_application(manifest, request)+except ValueError:+ pass+else:+ raise AssertionError('Recorder accepted the wrong desktop application ID')+print(out.read_text(encoding='utf-8'))+`++ const recorded: string = execFileSync(process.env.HERMES_PYTHON || 'python3',+ ['-c', recordScript, repo, root, JSON.stringify(build)], { encoding: 'utf8' })++ const metadata: RecordedMetadata = JSON.parse(recorded)+ assert.equal(metadata.applicationId, build.identity.appNamePascal)+ assert.equal(metadata.version, build.windowsVersion)facts.push(row)}diff --git a/apps/desktop/electron/cli-provision.test.ts b/apps/desktop/electron/cli-provision.test.tsindex cc7b06d92d3..cb64dedec2a 100644--- a/apps/desktop/electron/cli-provision.test.ts+++ b/apps/desktop/electron/cli-provision.test.ts@@ -5,7 +5,7 @@ import path from 'node:path'import { test, type TestContext } from 'vitest'-import { provisionCliLinks } from './cli-provision'+import { provisionCliLinks, removeBundleCliLinks } from './cli-provision'function fixture(): { root: string; binDir: string; source: string } {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-cli-links-'))@@ -19,6 +19,27 @@ function fixture(): { root: string; binDir: string; source: string } {return { root, binDir, source }}+test.runIf(process.platform !== 'win32')('retiring a bundle removes only its direct CLI links, including dangling ones', (): void => {+ const { root, binDir, source }: ReturnType<typeof fixture> = fixture()+ const payload: string = path.dirname(path.dirname(source))+ const target: string = path.join(binDir, 'hermes')++ try {+ provisionCliLinks({ hermes: source }, binDir, (): void => {})+ fs.symlinkSync(path.join(root, 'other/agent-payload/bin/other'), path.join(binDir, 'other'))+ fs.symlinkSync(source, path.join(binDir, 'personal-alias'))+ fs.writeFileSync(path.join(binDir, 'custom'), 'keep')+ fs.rmSync(source)+ removeBundleCliLinks(payload, binDir)+ assert.equal(fs.lstatSync(target, { throwIfNoEntry: false }), undefined)+ assert.deepEqual(fs.readdirSync(binDir).sort(), ['custom', 'other', 'personal-alias'])+ removeBundleCliLinks(payload, binDir)+ assert.equal(fs.readFileSync(path.join(binDir, 'custom'), 'utf8'), 'keep')+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})+test('repairs owned dangling CLI links without changing foreign or live entries', context => {const { root, binDir, source } = fixture()const messages: string[] = []diff --git a/apps/desktop/electron/cli-provision.ts b/apps/desktop/electron/cli-provision.tsindex 2749b5bfa4f..b8afeb3b120 100644--- a/apps/desktop/electron/cli-provision.ts+++ b/apps/desktop/electron/cli-provision.ts@@ -4,6 +4,22 @@ import path from 'node:path'type ProvisionFs = Pick<typeof fs, 'mkdirSync' | 'lstatSync' | 'readlinkSync' | 'statSync' | 'symlinkSync' | 'renameSync' | 'unlinkSync'>+/** Remove only the absolute, same-name links this bundle's provisioner creates. */+export function removeBundleCliLinks(payloadRoot: string, binDir: string): void {+ if (!fs.existsSync(binDir)) { return }+ const payloadBin: string = path.resolve(payloadRoot, 'bin')++ for (const entry of fs.readdirSync(binDir, { withFileTypes: true })) {+ if (!entry.isSymbolicLink()) { continue }+ const link: string = path.join(binDir, entry.name)+ const destination: string = fs.readlinkSync(link)++ if (path.isAbsolute(destination) && path.dirname(destination) === payloadBin && path.basename(destination) === entry.name) {+ fs.unlinkSync(link)+ }+ }+}+export function provisionCliLinks(commands: Readonly<Record<string, string>>,binDir: string,diff --git a/apps/desktop/electron/desktop-boot-preference.ts b/apps/desktop/electron/desktop-boot-preference.tsindex 4687b38a29c..dd2fb8cf234 100644--- a/apps/desktop/electron/desktop-boot-preference.ts+++ b/apps/desktop/electron/desktop-boot-preference.ts@@ -1,5 +1,5 @@import { randomUUID } from 'node:crypto'-import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'import path from 'node:path'import { isDeepStrictEqual } from 'node:util'@@ -19,6 +19,7 @@ export function readStartupDesktopPreference(file: string, warn: (message: strintry { return readDesktopBootPreference(file) }catch (error) {warn(`Desktop boot preference was not loaded; preserving the original file: ${error instanceof Error ? error.message : String(error)}`)+return null}}@@ -38,6 +39,13 @@ export function readDesktopBootPreference(file: string): DesktopBootPreference |throw error}+ return parseDesktopBootPreference(text)+}++// Only this disk-JSON boundary inspects primitive representations. Callers get+// a complete preference contract, including preserved fields owned by others.+/* oxlint-disable anti-slop/no-runtime-typeof */+function parseDesktopBootPreference(text: string): DesktopBootPreference {const parsed: unknown = JSON.parse(text)if (!parsed || typeof parsed !== 'object' || !('profile' in parsed)) {@@ -50,21 +58,27 @@ export function readDesktopBootPreference(file: string): DesktopBootPreference |throw new Error('Invalid profile in desktop boot preference')}- if ('home' in parsed && (typeof parsed.home !== 'string' || !path.isAbsolute(parsed.home))) {- throw new Error('Invalid home in desktop boot preference')- }+ const preference: DesktopBootPreference = { ...parsed, profile: typeof profile === 'string' ? profile : null }++ if ('home' in parsed) {+ if (typeof parsed.home !== 'string' || !path.isAbsolute(parsed.home)) {+ throw new Error('Invalid home in desktop boot preference')+ }- if ('_migrated' in parsed && typeof parsed._migrated !== 'boolean') {- throw new Error('Invalid migration marker in desktop boot preference')+ preference.home = parsed.home}- return {- ...parsed,- profile: typeof profile === 'string' ? profile : null,- ...('home' in parsed && typeof parsed.home === 'string' ? { home: parsed.home } : {}),- ...('_migrated' in parsed && typeof parsed._migrated === 'boolean' ? { _migrated: parsed._migrated } : {})+ if ('_migrated' in parsed) {+ if (typeof parsed._migrated !== 'boolean') {+ throw new Error('Invalid migration marker in desktop boot preference')+ }++ preference._migrated = parsed._migrated}++ return preference}+/* oxlint-enable anti-slop/no-runtime-typeof */function updatePreference(file: string, update: (current: DesktopBootPreference | null) => DesktopBootPreference): DesktopBootPreference {mkdirSync(path.dirname(file), { recursive: true })@@ -84,7 +98,13 @@ function updatePreference(file: string, update: (current: DesktopBootPreferenceconst next: DesktopBootPreference = update(current)writeFileSync(temporary, JSON.stringify(next, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })+ const handle: number = openSync(temporary, 'r+')+ try { fsyncSync(handle) } finally { closeSync(handle) }renameSync(temporary, file)+ if (process.platform !== 'win32') {+ const directory: number = openSync(path.dirname(file), 'r')+ try { fsyncSync(directory) } finally { closeSync(directory) }+ }return next} finally {diff --git a/apps/desktop/electron/install-stamp.ts b/apps/desktop/electron/install-stamp.tsindex 5865dd467de..72e3722d36f 100644--- a/apps/desktop/electron/install-stamp.ts+++ b/apps/desktop/electron/install-stamp.ts@@ -39,6 +39,9 @@ export interface ChannelBuildRequest {commit: stringcontrollerCommit?: stringsourceVersion: string+ /** Build-only official receiver rehearsal, admitted under a disposable authority. */+ receiverCandidate?: true+ releaseTag?: stringversion: stringwindowsVersion: stringidentity: {@@ -77,6 +80,8 @@ export interface InstallStamp {runtime?: PayloadRuntime/** Complete channel inputs, absent on legacy releases and one-off builds. */channelBuild?: Readonly<ChannelBuildRequest>+ /** Cross-application receiver shipped in this artifact, absent on older builds. */+ receiverProtocol?: 1/** Pinned release tag; null for channel builds, one-offs and bootstrap. */tag: string | null}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex b2d3773d191..31fadee3886 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -445,10 +445,14 @@ import { createMacStrategy, createChannelMacStrategy } from './updater/mac-clienimport { createChannelAppInstallerStrategy } from './updater/app-installer'import { ChannelResolver, type ChannelTarget } from './updater/channel'import { ChannelStrategy } from './updater/channel-strategy'+import { UpdateOperation } from './updater/operation'import { inspectRunningChannelApp } from './updater/retirement-discovery'import { verifyPreparedChannelInstaller } from './updater/channel-windows-host'import { RetirementHost, prepareRetirementStartup, forwardRetiredPreview, type RetirementReception } from './updater/retirement-host'-import { completeDesktopRetirement } from './updater/retirement-readiness'+import { retirementConnection, type RetirementConnectionSelection } from './updater/retirement-connections'+import type { RetirementConsent } from './updater/retirement-state'+import { confirmRetirementWorkspace } from './updater/retirement-dialog'+import type { RetirementExistingSelection, RetirementWorkspaceConflict } from './updater/retirement-receiver'import { readStartupDesktopPreference } from './desktop-boot-preference'import { type ConsumedRelaunch, consumePendingRelaunch, registerUpdateRelaunch, type RelaunchRegistration } from './updater/relaunch'import { startRelaunchWaiter } from './updater/relaunch-waiter'@@ -758,7 +762,10 @@ const retirementReception: RetirementReception | null = isPrimaryInstance ? awaiuserData: app.getPath('userData'),defaultHome: resolveDesktopHermesHome({ home: app.getPath('home'), directoryExists, readWindowsHome: (): string | null => readWindowsUserEnvVar('HERMES_HOME') }),operatorOverride: Boolean(process.env.HERMES_HOME || USER_DATA_OVERRIDE),- payload: bundledPayload(process.resourcesPath)+ payload: bundledPayload(process.resourcesPath),+ confirmWorkspaceConflict: (conflict: RetirementWorkspaceConflict) => confirmRetirementWorkspace(conflict, {+ ready: async (): Promise<void> => { await app.whenReady() }, showMessageBox: dialog.showMessageBox+ })}).catch(async (error: Error): Promise<null> => {await app.whenReady()dialog.showErrorBox('Migration paused — preview preserved', error.message)@@ -3023,9 +3030,13 @@ let updateInFlight = false* Keep the native updater instance alive across check, download and install.* Its identity comes from the packaged app, not its optional Python payload.*/-let packagedUpdateStrategy: UpdaterStrategy | undefined+const updateOperation: UpdateOperation = new UpdateOperation(createPackagedUpdateStrategy)++function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {+ return updateOperation.resolve()+}-async function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {+async function createPackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {const mechanism = resolveUpdaterMechanism({platform: process.platform,updateMechanism: INSTALL_STAMP?.updateMechanism,@@ -3034,7 +3045,6 @@ async function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null>if (mechanism === 'windows-handoff' || mechanism === 'posix-handoff') { return null }- if (packagedUpdateStrategy) { return packagedUpdateStrategy }if (INSTALL_STAMP?.channelBuild && (mechanism === 'electron-updater' || mechanism === 'app-installer')) {const build = INSTALL_STAMP.channelBuild@@ -3043,20 +3053,18 @@ async function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null>if (!payload || (process.platform !== 'darwin' && process.platform !== 'win32') || (process.arch !== 'arm64' && process.arch !== 'x64')) {throw new Error('Channel updates require a supported bundled application')}- packagedUpdateStrategy = new ChannelStrategy({+ return new ChannelStrategy({build, mechanism,resolver: new ChannelResolver({ build, platform: process.platform, arch: process.arch, signer: installed.signer }),nativeFactory: (target: ChannelTarget): UpdaterStrategy => createNativePackagedStrategy(mechanism, target),retirement: new RetirementHost({ home: HERMES_HOME, userData: app.getPath('userData'), payload,- profile: primaryProfileKey, isLocal: (): boolean => !primaryBackendIsRemote(), stop: teardownBundledBackend,+ profile: primaryProfileKey, connection: selectedRetirementConnection, stop: teardownBundledBackend,restore: restoreBundledBackend, quit: (): void => app.quit(),progress: (message: string): void => emitUpdateProgress({ stage: 'prepare', message, percent: null }) })})- return packagedUpdateStrategy}- packagedUpdateStrategy = createNativePackagedStrategy(mechanism)- return packagedUpdateStrategy+ return createNativePackagedStrategy(mechanism)}function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], target?: ChannelTarget): UpdaterStrategy {@@ -3129,7 +3137,7 @@ function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], tif (mechanism === 'microsoft-store') {const payload = bundledPayload(process.resourcesPath)!- packagedUpdateStrategy = createStoreStrategy({+ return createStoreStrategy({python: payload.storePython,script: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'check-store-update.py'),sitePackages: payload.sitePackages,@@ -3151,7 +3159,6 @@ function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], t})})- return packagedUpdateStrategy}return new ExternalStrategy(INSTALL_STAMP)@@ -3804,25 +3811,23 @@ async function releaseBackendLock(updateRoot: string, tag: string): Promise<{ un//// Detection (checkUpdates / commit changelog / "N behind") stays in the UI;// only this apply action changed.-async function applyUpdates(retirementConsent: boolean = false): Promise<UpdaterApplyResultWire> {- if (updateInFlight) {- throw new Error('An update is already in progress.')- }-- const strategy = await resolvePackagedUpdateStrategy() ?? resolveCheckoutUpdateStrategy()- updateInFlight = true- let handedOff = false+async function applyUpdates(retirementConsent?: RetirementConsent): Promise<UpdaterApplyResultWire> {+ return updateOperation.apply(async (): Promise<UpdaterApplyResultWire> => {+ updateInFlight = true+ let handedOff: boolean = false- try {- const result: UpdaterApplyResultWire = retirementConsent- ? strategy instanceof ChannelStrategy ? await strategy.applyRetirement() : { ok: false, error: 'No retirement offer is selected.' }- : await strategy.apply()- handedOff = result.handedOff === true+ try {+ const strategy: UpdaterStrategy = await resolvePackagedUpdateStrategy() ?? resolveCheckoutUpdateStrategy()+ const result: UpdaterApplyResultWire = retirementConsent+ ? strategy instanceof ChannelStrategy ? await strategy.applyRetirement(retirementConsent) : { ok: false, error: 'No retirement offer is selected.' }+ : await strategy.apply()+ handedOff = result.handedOff === true- return result- } finally {- if (!handedOff) { updateInFlight = false }- }+ return result+ } finally {+ if (!handedOff) { updateInFlight = false }+ }+ })}async function handOffWindowsBootstrapRecovery(reason) {@@ -16590,9 +16595,12 @@ ipcMain.handle('hermes:updates:apply', async (_event, payload) =>ipcMain.handle('hermes:updates:branch:get', async () => readDesktopUpdateConfig())-ipcMain.handle('hermes:updates:retire', async (_event: Electron.IpcMainInvokeEvent, consent: { installStable?: boolean; removePreview?: boolean }): Promise<UpdaterApplyResultWire> => {+ipcMain.handle('hermes:updates:retire', async (_event: Electron.IpcMainInvokeEvent, consent: Partial<RetirementConsent>): Promise<UpdaterApplyResultWire> => {if (consent?.installStable !== true || consent?.removePreview !== true) { return { ok: false, error: 'Explicit installation and preview-removal consent required.' } }- return applyUpdates(true).catch((error: Error): UpdaterApplyResultWire => ({ ok: false, error: 'retirement-blocked', message: error.message }))+ if (consent.workspaceChoice !== 'keep-stable' && consent.workspaceChoice !== 'open-preview') { return { ok: false, error: 'Choose which workspace stable should open.' } }++ return applyUpdates({ installStable: true, removePreview: true, workspaceChoice: consent.workspaceChoice })+ .catch((error: Error): UpdaterApplyResultWire => ({ ok: false, error: 'retirement-blocked', message: error.message }))})ipcMain.handle('hermes:updates:branch:set', async (_event: Electron.IpcMainInvokeEvent, name: unknown): Promise<{ branch: string }> => {@@ -17087,13 +17095,32 @@ ipcMain.handle('hermes:deep-link-ready', () => {return { ok: true }})+function selectedRetirementConnection(): RetirementConnectionSelection {+ const registry = readDesktopConnectionsRegistry()+ const route = resolveDesktopRemoteRoute({ config: readDesktopConnectionConfig(), registry, profile: primaryProfileKey(),+ env: { token: process.env.HERMES_DESKTOP_REMOTE_TOKEN, url: process.env.HERMES_DESKTOP_REMOTE_URL } })+ if (!route) { return { id: 'local' } }+ const entry = registry.connections.find(connection => connection.id === route.connectionId)+ if (!entry) { throw new Error('Save the selected remote connection before migration; environment-only credentials cannot transfer') }+ return { id: entry.id, settings: retirementConnection(entry) }+}+async function finishDesktopRetirement(reception: RetirementReception): Promise<void> {- const result = await completeDesktopRetirement(reception, {- home: HERMES_HOME, profile: primaryProfileKey, isLocal: (): boolean => !primaryBackendIsRemote(),+ const result = await reception.complete({+ home: HERMES_HOME, profile: primaryProfileKey, connectionId: (): string => selectedRetirementConnection().id,rendererMounted: (): boolean => Boolean(_rendererReadyForDeepLink && mainWindow && !mainWindow.isDestroyed()),backend: async (): Promise<void> => {await startHermes()- await handleHermesApiRequest({ path: '/api/status', timeoutMs: 5000 })+ await handleHermesApiRequest({ path: '/api/sessions', timeoutMs: 5000 })+ const connection = await ensureBackend(primaryProfileKey())+ const wsUrl: string | null = await resolveTestWsUrl(connection.baseUrl, normAuthMode(connection.authMode), connection.token, {+ mintTicket: (url: string) => mintGatewayWsTicket(url, connection.headers || {})+ })+ if (!wsUrl) { throw new Error('Stable connection has no authenticated WebSocket URL') }+ const probe: { ok: boolean; reason?: string } = await probeGatewayWebSocket(wsUrl, {+ WebSocketImpl: globalThis.WebSocket, headers: connection.headers || {}+ })+ if (!probe.ok) { throw new Error(probe.reason || 'Stable connection authentication is incomplete') }}})if (result.status === 'cleanup-pending') {@@ -17136,7 +17163,12 @@ if (!isPrimaryInstance) {if (argv.some((arg: string): boolean => arg.startsWith('--hermes-retirement='))) {void prepareRetirementStartup({ argv, userData: app.getPath('userData'), defaultHome: HERMES_HOME,operatorOverride: Boolean(process.env.HERMES_HOME || USER_DATA_OVERRIDE), payload: bundledPayload(process.resourcesPath),- runningSelection: { home: HERMES_HOME, profile: primaryProfileKey(), connectionId: primaryBackendIsRemote() ? 'remote' : 'local' }+ confirmWorkspaceConflict: (conflict: RetirementWorkspaceConflict) => confirmRetirementWorkspace(conflict, {+ ready: async (): Promise<void> => { await app.whenReady() }, showMessageBox: dialog.showMessageBox+ }),+ runningSelection: (): Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'> => ({+ home: HERMES_HOME, profile: primaryProfileKey(), connectionId: selectedRetirementConnection().id+ })}).then(async (reception: RetirementReception | null): Promise<void> => {if (reception) { await finishDesktopRetirement(reception) }}).catch((error: Error): void => dialog.showErrorBox('Migration paused — preview preserved', error.message))diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex a58ad705f00..6c8daabdc7a 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -1,5 +1,8 @@import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'+import type { UpdaterApplyResultWire } from './updater/index'+import type { RetirementConsent } from './updater/retirement-state'+// Which translucency the OS can back. Asked synchronously because the renderer// needs it before its first paint, and answered by main because deciding it// needs `os.release()` — a sandboxed preload may only require electron, events,@@ -536,7 +539,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {updates: {check: opts => ipcRenderer.invoke('hermes:updates:check', opts),apply: opts => ipcRenderer.invoke('hermes:updates:apply', opts),- retire: consent => ipcRenderer.invoke('hermes:updates:retire', consent),+ retire: (consent: RetirementConsent): Promise<UpdaterApplyResultWire> => ipcRenderer.invoke('hermes:updates:retire', consent),getBranch: () => ipcRenderer.invoke('hermes:updates:branch:get'),setBranch: name => ipcRenderer.invoke('hermes:updates:branch:set', name),onProgress: callback => {diff --git a/apps/desktop/electron/updater/channel-protocol.ts b/apps/desktop/electron/updater/channel-protocol.tsindex e4bc14b11fd..236429a8f8c 100644--- a/apps/desktop/electron/updater/channel-protocol.ts+++ b/apps/desktop/electron/updater/channel-protocol.ts@@ -50,8 +50,8 @@ export interface RetiredChannel extends ChannelRecordBase {state: 'retired'destination: stringminimumVersion: string- compatibilityKey: string- compatibilitySha256: string+ destinationHead: ChannelHead+ receiverProtocol: 1lastHead: ChannelHead | null}export type ChannelRecord = ActiveChannel | RetiredChannel@@ -66,25 +66,8 @@ export interface ChannelPackage {teamId?: stringfeed: { key: string; channel: string }}-export interface ChannelManifest { schema: 1; request: ChannelRequest; packages: ChannelPackage[] }-export interface ChannelCohort { buildId: string; commit: string }-export interface ChannelQualification {- schema: 1- source: string- sourceHead: ChannelHead | null- destination: string- destinationHead: ChannelHead- minimumVersion: string- receiverProtocol: 1- coverage: ChannelCoverage[]-}-export interface ChannelCoverage {- platform: ChannelPackage['platform']- arch: ChannelPackage['arch']- sourceIdentity: string- destinationIdentity: string- cohorts: ChannelCohort[]-}+export interface ChannelManifest { schema: 1; request: ChannelRequest; packages: ChannelPackage[]; receiverProtocol?: number }+const SHA256 = /^[a-f0-9]{64}$/const COMMIT = /^[a-f0-9]{40}$/@@ -199,7 +182,7 @@ function head(value: unknown): ChannelHead | null {function requiredHead(value: unknown): ChannelHead {const result = head(value)- if (!result) { throw new Error('Missing qualification destination head') }+ if (!result) { throw new Error('Missing retirement destination head') }return result}@@ -222,11 +205,11 @@ export function decodeChannelRecord(body: string): ChannelRecord {if (state !== 'retired') { throw new Error('Invalid channel state') }const lastHead = head(fields.get('lastHead'))if (JSON.stringify(lastHead) !== JSON.stringify(common.head)) { throw new Error('Retirement lastHead mismatch') }+ if (fields.get('receiverProtocol') !== 1) { throw new Error('Unsupported retirement receiver protocol') }return {...common, state, lastHead, destination: validateChannelName(fields.text('destination')),minimumVersion: fields.text('minimumVersion', VERSION),- compatibilityKey: channelKey(fields.text('compatibilityKey')),- compatibilitySha256: fields.text('compatibilitySha256', SHA256)+ destinationHead: requiredHead(fields.get('destinationHead')), receiverProtocol: 1}}@@ -242,7 +225,8 @@ function request(fields: Fields): ChannelRequest {}const publicBase = fields.text('publicBase')if (channelPublicBase(publicBase) !== publicBase) { throw new Error('Noncanonical request publicBase') }- const windowsVersion = fields.text('windowsVersion', /^\d+\.\d+\.\d+\.0$/)+ const releaseTag = fields.optional('releaseTag', /^v\d+\.\d+\.\d+(?:-canary\.\d+)?$/)+ const windowsVersion = fields.text('windowsVersion', releaseTag?.includes('-canary.') ? /^\d+\.\d+\.\d+\.\d+$/ : /^\d+\.\d+\.\d+\.0$/)if (windowsVersion.split('.').some((part: string): boolean => Number(part) > 65535)) { throw new Error('Invalid Windows version') }return {schema: 1, buildId: fields.text('buildId', BUILD_ID), channel: validateChannelName(fields.text('channel')),@@ -250,7 +234,7 @@ function request(fields: Fields): ChannelRequest {commit: fields.text('commit', COMMIT), sourceVersion: fields.text('sourceVersion', VERSION),version: fields.text('version', VERSION), windowsVersion, publicBase, bundleEnv,identity: identity(fields.object('identity')), controllerCommit: fields.optional('controllerCommit', COMMIT),- releaseTag: fields.optional('releaseTag', /^v\d+\.\d+\.\d+(?:-canary\.\d+)?$/)+ releaseTag}}@@ -264,50 +248,13 @@ function packageEntry(value: unknown): ChannelPackage {const artifact = fields.object('artifact')const feed = fields.object('feed')return {- platform, arch, variant: 'bundled', version: fields.text('version', platform === 'darwin' ? VERSION : /^\d+\.\d+\.\d+\.0$/), identity: fields.text('identity'),+ platform, arch, variant: 'bundled', version: fields.text('version', platform === 'darwin' ? VERSION : /^\d+\.\d+\.\d+\.\d+$/), identity: fields.text('identity'),artifact: { key: channelKey(artifact.text('key')), sha256: artifact.text('sha256', SHA256), size: artifact.integer('size') },publisher: fields.optional('publisher'), teamId: fields.optional('teamId', /^[A-Z0-9]{10}$/),feed: { key: channelKey(feed.text('key')), channel: feed.text('channel', /^[a-z][a-z0-9-]{0,31}$/) }}}-function coverageEntry(value: unknown): ChannelCoverage {- const fields = new Fields(value)- const platform = fields.text('platform')- const arch = fields.text('arch')- if ((platform !== 'darwin' && platform !== 'win32') || (arch !== 'x64' && arch !== 'arm64')) {- throw new Error('Unsupported retirement platform')- }- const entries: unknown = fields.get('cohorts')- if (!Array.isArray(entries) || !entries.length) { throw new Error('Retirement has no qualified cohorts') }- const cohorts = entries.map((entry: unknown): ChannelCohort => {- const cohort = new Fields(entry)- return { buildId: cohort.text('buildId', BUILD_ID), commit: cohort.text('commit', COMMIT) }- })- if (new Set(cohorts.map((cohort: ChannelCohort): string => cohort.buildId)).size !== cohorts.length) {- throw new Error('Duplicate retirement cohort')- }- return { platform, arch, sourceIdentity: fields.text('sourceIdentity'),- destinationIdentity: fields.text('destinationIdentity'), cohorts }-}--export function decodeChannelQualification(body: string): ChannelQualification {- const fields = new Fields(parseChannelJson(body))- fields.schema()- if (fields.get('receiverProtocol') !== 1) { throw new Error('Unsupported retirement receiver') }- const entries: unknown = fields.get('coverage')- if (!Array.isArray(entries) || !entries.length || entries.length > 4) { throw new Error('Missing retirement platform coverage') }- const coverage: ChannelCoverage[] = entries.map(coverageEntry)- if (new Set(coverage.map((entry: ChannelCoverage): string => `${entry.platform}/${entry.arch}`)).size !== coverage.length) {- throw new Error('Duplicate retirement platform coverage')- }- return {- schema: 1, receiverProtocol: 1, coverage,- source: validateChannelName(fields.text('source')), sourceHead: head(fields.get('sourceHead')),- destination: validateChannelName(fields.text('destination')), destinationHead: requiredHead(fields.get('destinationHead')),- minimumVersion: fields.text('minimumVersion', VERSION)- }-}export function decodeChannelManifest(body: string): ChannelManifest {const fields = new Fields(parseChannelJson(body))@@ -317,5 +264,7 @@ export function decodeChannelManifest(body: string): ChannelManifest {const packages: ChannelPackage[] = entries.map(packageEntry)const keys = new Set(packages.map((entry: ChannelPackage): string => `${entry.platform}/${entry.arch}`))if (keys.size !== packages.length) { throw new Error('Duplicate channel package') }- return { schema: 1, request: request(fields.object('request')), packages }+ const manifest: ChannelManifest = { schema: 1, request: request(fields.object('request')), packages }+ if (fields.get('receiverProtocol') !== undefined) { manifest.receiverProtocol = fields.integer('receiverProtocol') }+ return manifest}diff --git a/apps/desktop/electron/updater/channel-strategy.ts b/apps/desktop/electron/updater/channel-strategy.tsindex ec51b07035f..c0708984b0a 100644--- a/apps/desktop/electron/updater/channel-strategy.ts+++ b/apps/desktop/electron/updater/channel-strategy.ts@@ -1,5 +1,7 @@-import type { ChannelBuild } from './channel-protocol'import type { ChannelResolver, ChannelRetirement, ChannelTarget } from './channel'+import type { ChannelBuild } from './channel-protocol'+import type { RetirementConsent } from './retirement-state'+import type { UpdaterApplyResultWire, UpdaterStatusWire, UpdaterStrategy } from './index'export interface ChannelRetirementStatus {@@ -10,7 +12,7 @@ export interface ChannelRetirementStatus {}export interface ChannelRetirementCallbacks {check: (retirement: ChannelRetirement) => Promise<Pick<ChannelRetirementStatus, 'state' | 'message'>>- apply: (retirement: ChannelRetirement) => Promise<UpdaterApplyResultWire>+ apply: (retirement: ChannelRetirement, consent: RetirementConsent) => Promise<UpdaterApplyResultWire>}export interface ChannelStrategyDeps {resolver: Pick<ChannelResolver, 'resolve'>@@ -38,6 +40,7 @@ export class ChannelStrategy implements UpdaterStrategy {async check(): Promise<UpdaterStatusWire> {this.enter()+try { return await this.select() } finally { this.busy = false }}@@ -45,56 +48,75 @@ export class ChannelStrategy implements UpdaterStrategy {// Failed reads invalidate prior availability, never leave a stale install action.this.selection = nullconst result = await this.deps.resolver.resolve()+const base: UpdaterStatusWire = {supported: true, mechanism: this.mechanism, channel: this.deps.build.channel,currentVersion: this.deps.build.version, fetchedAt: Date.now()}+if (result.kind === 'empty') {this.selection = { kind: 'empty' }+return { ...base, updateAvailable: false, reason: 'no-build-published' }}+if (result.kind === 'retirement') {const status = this.deps.retirement ? await this.deps.retirement.check(result.retirement) :{ state: 'waiting' as const, message: 'The retirement receiver is not available in this installation.' }+this.selection = { kind: 'retirement', value: result.retirement, state: status.state }+return {...base, retirement: { ...status, destination: result.retirement.target.channel.name, version: result.retirement.target.manifest.request.version }}}+const target = result.target+if (target.manifest.request.sequence <= this.deps.build.sequence) {this.selection = { kind: 'empty' }+return { ...base, updateAvailable: false }}+const strategy = this.deps.nativeFactory(target)const status = await strategy.check()+if (status.error || status.updateAvailable === undefined) { throw new Error(status.error || 'Native update availability unknown') }this.selection = { kind: 'native', strategy, available: status.updateAvailable }+return { ...status, ...base, latestTag: `v${target.manifest.request.version}`, targetSha: target.manifest.request.commit }}async apply(): Promise<UpdaterApplyResultWire> {this.enter()+try {if (!this.selection) { await this.select() }const selected = this.selection+if (selected?.kind === 'retirement') { return { ok: false, error: 'Retirement requires explicit migration consent.' } }+if (selected?.kind === 'native' && selected.available) { return await selected.strategy.apply() }+return { ok: true, mechanism: this.mechanism }} finally { this.busy = false }}/** Only the explicit migration action may call this method. */- async applyRetirement(): Promise<UpdaterApplyResultWire> {+ async applyRetirement(consent: RetirementConsent): Promise<UpdaterApplyResultWire> {this.enter()+try {if (this.selection?.kind !== 'retirement' || !this.deps.retirement) {return { ok: false, error: 'Check the retirement offer before accepting migration.' }}+if (this.selection.state !== 'available' && this.selection.state !== 'cleanup-pending') {return { ok: false, error: 'Retirement is blocked; resolve the reported issue and retry.' }}- return await this.deps.retirement.apply(this.selection.value)++ return await this.deps.retirement.apply(this.selection.value, consent)} finally { this.busy = false }}}diff --git a/apps/desktop/electron/updater/channel-windows-host.ts b/apps/desktop/electron/updater/channel-windows-host.tsindex b9f1afe5e89..954f6d440bc 100644--- a/apps/desktop/electron/updater/channel-windows-host.ts+++ b/apps/desktop/electron/updater/channel-windows-host.ts@@ -1,23 +1,25 @@import path from 'node:path'+import { mkdtemp, rm } from 'node:fs/promises'import type { ChannelTarget } from './channel'import { runRetirementPowerShell } from './retirement-discovery'-import { downloadRetirementArtifact } from './retirement-native'-import { newRetirementCorrelation, RetirementJournal, defaultRetirementRoot } from './retirement-state'+import { downloadPinnedArtifact } from './artifact'+import type { NativeCommandResult } from './retirement-native'/** Verify downloaded bytes and native metadata before App Installer can stop the backend. */-export async function verifyPreparedChannelInstaller(file: string, target: ChannelTarget): Promise<void> {+export async function verifyPreparedChannelInstaller(+ file: string, target: ChannelTarget,+ command: (script: string, input: string) => Promise<NativeCommandResult> = runRetirementPowerShell+): Promise<void> {const pkg = target.packageif (pkg.platform !== 'win32' || !pkg.publisher) { throw new Error('Expected a publisher-bound Windows package') }- const journal: RetirementJournal = await RetirementJournal.open(defaultRetirementRoot(), newRetirementCorrelation().id)- const artifact: string = await downloadRetirementArtifact(journal, {- platform: 'win32', appPath: path.dirname(file), identity: pkg.identity, nativeVersion: pkg.version,- signer: pkg.publisher, architecture: pkg.arch, applicationId: null, packageFamilyName: null,- commit: target.manifest.request.commit,- artifact: { url: target.artifactUrl, sha256: pkg.artifact.sha256, size: pkg.artifact.size,+ const directory: string = await mkdtemp(path.join(path.dirname(file), '.channel-artifact-'))+ try {+ const artifact: string = await downloadPinnedArtifact(directory,+ { url: target.artifactUrl, sha256: pkg.artifact.sha256, size: pkg.artifact.size,format: pkg.artifact.key.endsWith('.msixbundle') ? 'msixbundle' : 'msix' }- })- await runRetirementPowerShell(String.raw`+ )+ await command(String.raw`$ErrorActionPreference='Stop'$p=[Console]::In.ReadToEnd() | ConvertFrom-Jsonfunction Read-SafeXml($stream) {@@ -48,4 +50,5 @@ try {} finally { $zip.Dispose() }`, JSON.stringify({ file, artifact, feedUrl: target.feedUrl, artifactUrl: target.artifactUrl,identity: pkg.identity, publisher: pkg.publisher, version: pkg.version, arch: pkg.arch }))+ } finally { await rm(directory, { recursive: true, force: true }) }}diff --git a/apps/desktop/electron/updater/channel.test.ts b/apps/desktop/electron/updater/channel.test.tsindex 57cd2d8b581..7a1b1ac673c 100644--- a/apps/desktop/electron/updater/channel.test.ts+++ b/apps/desktop/electron/updater/channel.test.ts@@ -1,11 +1,14 @@import { createHash } from 'node:crypto'import { createServer, type Server } from 'node:http'+import { afterEach, expect, test } from 'vitest'-import { ChannelResolver } from './channel'-import { ChannelStrategy } from './channel-strategy'import feedContract from '../../update-feed.cjs'++import { ChannelResolver } from './channel'import type { ChannelBuild, ChannelManifest, ChannelRecord, RetiredChannel } from './channel-protocol'+import { ChannelStrategy } from './channel-strategy'+import type { RetirementConsent } from './retirement-state'const servers: Server[] = []afterEach(async (): Promise<void> => {@@ -21,17 +24,21 @@ async function fixture(): Promise<{}> {const objects = new Map<string, string>()const requests: string[] = []+const server = createServer((request, response): void => {requests.push(request.url!)const value = objects.get(request.url!)response.writeHead(value === undefined ? 404 : 200, { 'Content-Type': 'application/json' })response.end(value ?? 'missing')})+servers.push(server)await new Promise<void>((resolve): void => { server.listen(0, '127.0.0.1', resolve) })const address = server.address()+// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Node's listen() address boundary admits pipes or TCP; this fixture requires TCP.if (!address || typeof address === 'string') { throw new Error('No fixture port') }+const build: ChannelBuild = {buildId: 'a'.repeat(32), channel: 'fresh-preview-29', sequence: 1,repository: 'example/hermes-agent', commit: 'b'.repeat(40), sourceVersion: '1.2.3',@@ -43,8 +50,10 @@ async function fixture(): Promise<{windowsExecutableName: 'HermesH1234567890abcdef.exe', msixAppIdWithOrg: 'NousResearch.HermesH1234567890abcdef'}}+const next = { ...build, buildId: 'c'.repeat(32), sequence: 2, version: '0.0.2', windowsVersion: '0.0.2.0' }const prefix = `releases/channel-builds/${next.buildId}/`+const manifest: ChannelManifest = {schema: 1, request: { schema: 1, ...next }, packages: [{platform: 'darwin', arch: 'arm64', variant: 'bundled', version: next.version,@@ -53,82 +62,124 @@ async function fixture(): Promise<{feed: { key: `${prefix}darwin/stable-mac.yml`, channel: 'stable' }}]}+const record: ChannelRecord = {schema: 1, name: build.channel, repository: build.repository, policy: 'preview', state: 'active',revision: 2, nextSequence: 3, identity: build.identity,head: { buildId: next.buildId, sequence: 2, manifestKey: `${prefix}build.json`, sha256: '' }}+const publish = (): void => {const body = JSON.stringify(manifest)+if (record.state !== 'active' || !record.head) { throw new Error('Fixture requires active head') }record.head.sha256 = createHash('sha256').update(body).digest('hex')objects.set(`/${record.head.manifestKey}`, body)objects.set(`/releases/channels/${record.name}.json`, JSON.stringify(record))}+publish()+return { build, record, manifest, objects, requests, publish }}async function retiredFixture(): Promise<Awaited<ReturnType<typeof fixture>> & { retired: RetiredChannel }> {const f = await fixture()- const retired: RetiredChannel = {- ...f.record, head: structuredClone(f.record.head), state: 'retired', destination: 'stable', minimumVersion: '1.0.0',- compatibilityKey: 'releases/retirements/receipt.json', compatibilitySha256: '', lastHead: structuredClone(f.record.head)- }++ const sourceRecord: ChannelRecord = structuredClone(f.record)+f.record.name = 'stable'f.record.policy = 'stable-release'f.record.identity = { ...f.build.identity, appId: 'chat.nous.hermes', token: 'fedcba0987654321' }f.manifest.request = { ...f.manifest.request, channel: 'stable', identity: f.record.identity, version: '1.2.3', windowsVersion: '1.2.3.0', releaseTag: 'v1.2.3' }f.manifest.packages[0].identity = f.record.identity.appIdf.manifest.packages[0].version = '1.2.3'+ f.manifest.receiverProtocol = 1f.publish()- const qualification = JSON.stringify({- schema: 1, source: f.build.channel, destination: 'stable',- sourceHead: retired.lastHead, destinationHead: f.record.head, minimumVersion: retired.minimumVersion,- receiverProtocol: 1, coverage: [{ platform: 'darwin', arch: 'arm64',- sourceIdentity: f.build.identity.appId, destinationIdentity: f.record.identity.appId,- cohorts: [{ buildId: f.build.buildId, commit: f.build.commit }]- }, { platform: 'win32', arch: 'x64',- sourceIdentity: f.build.identity.msixAppIdWithOrg, destinationIdentity: f.record.identity.msixAppIdWithOrg,- cohorts: [{ buildId: f.build.buildId, commit: f.build.commit }]- }]- })- retired.compatibilitySha256 = createHash('sha256').update(qualification).digest('hex')- f.objects.set(`/${retired.compatibilityKey}`, qualification)++ if (!f.record.head) { throw new Error('Expected published stable') }+ const retired: RetiredChannel = {+ ...sourceRecord, state: 'retired', destination: 'stable', minimumVersion: '1.0.0',+ destinationHead: structuredClone(f.record.head), receiverProtocol: 1, lastHead: sourceRecord.head+ }f.objects.set(`/releases/channels/${retired.name}.json`, JSON.stringify(retired))+return { ...f, retired }}-test('offers only a digest-bound qualified retirement to the official destination', async (): Promise<void> => {- const { build } = await retiredFixture()+test('protected canary accepts bounded Windows revisions without relaxing stable', async (): Promise<void> => {+ const f = await fixture()+ f.record.policy = 'canary-release'+ f.manifest.packages = [{+ platform: 'win32', arch: 'x64', variant: 'bundled', version: '1.2.4.10',+ identity: f.build.identity.msixAppIdWithOrg, publisher: 'CN=Nous Research',+ artifact: { key: `releases/channel-builds/${f.manifest.request.buildId}/win32/Hermes.msixbundle`, sha256: 'd'.repeat(64), size: 100 },+ feed: { key: `releases/channel-builds/${f.manifest.request.buildId}/win32/stable.appinstaller`, channel: 'stable' }+ }]+ f.manifest.request.releaseTag = 'v1.2.4-canary.20260913001000'+ f.manifest.request.version = f.manifest.request.releaseTag.slice(1)+ f.manifest.request.windowsVersion = '1.2.4.10'+ f.publish()+ const resolver = new ChannelResolver({ build: f.build, platform: 'win32', arch: 'x64', signer: 'CN=Nous Research' })+ expect((await resolver.resolve()).kind).toBe('active')++ for (const version of ['1.2.4.65536', '65536.2.4.0', '1.2.4.-1', '1.2.4.1.0', '1.2.4.x']) {+ f.manifest.request.windowsVersion = version+ f.publish()+ await expect(resolver.resolve()).rejects.toThrow(/[Ww]indows[Vv]ersion|Windows version/)+ }++ f.record.policy = 'stable-release'+ f.manifest.request.releaseTag = 'v1.2.4'+ f.manifest.request.version = '1.2.4'+ f.manifest.request.windowsVersion = '1.2.4.10'+ f.publish()+ await expect(resolver.resolve()).rejects.toThrow(/[Ww]indows[Vv]ersion|Windows version/)+ f.manifest.request.windowsVersion = '1.2.4.0'+ f.manifest.packages[0].version = '1.2.4.0'+ f.publish()+ expect((await resolver.resolve()).kind).toBe('active')+})++test('offers a digest-bound retirement without a second proof document', async (): Promise<void> => {+ const { build, retired, requests } = await retiredFixture()const result = await new ChannelResolver({ build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()expect(result.kind).toBe('retirement')+if (result.kind !== 'retirement') { throw new Error('Expected retirement') }expect(result.retirement.target.channel.name).toBe('stable')- expect(result.retirement.qualifications[0].coverage[0].cohorts).toEqual([{ buildId: build.buildId, commit: build.commit }])+ expect(result.retirement.target.manifestSha256).toBe(retired.destinationHead.sha256)+ expect(requests).toEqual([`/releases/channels/${build.channel}.json`, '/releases/channels/stable.json', `/${retired.destinationHead.manifestKey}`])})test('pins the checked target during apply even after R2 advances, and never auto-downloads', async (): Promise<void> => {const f = await fixture()const calls: string[] = []+let enteredResolve: () => void = (): void => {}+let releaseResolve: () => void = (): void => {}const entered = new Promise<void>((resolve): void => { enteredResolve = resolve })const release = new Promise<void>((resolve): void => { releaseResolve = resolve })+const strategy = new ChannelStrategy({resolver: new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }),build: f.build, mechanism: 'electron-updater',nativeFactory: (target) => ({mechanism: 'electron-updater',- check: async () => { calls.push('check'); return { supported: true, updateAvailable: true } },+ check: async () => { calls.push('check');++ return { supported: true, updateAvailable: true } },apply: async () => {calls.push(target.manifest.request.buildId)enteredResolve()await release+return { ok: true }}})})+expect((await strategy.check()).updateAvailable).toBe(true)expect(calls).toEqual(['check'])const pending = strategy.apply()@@ -145,40 +196,55 @@ test('pins the checked target during apply even after R2 advances, and never auttest('retirement has a separate consented path and never invokes the ordinary native updater', async (): Promise<void> => {const f = await retiredFixture()let applied = false+ const consents: RetirementConsent[] = []+const strategy = new ChannelStrategy({resolver: new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }),build: f.build, mechanism: 'electron-updater',nativeFactory: (): never => { throw new Error('Not a same-identity update') },retirement: {check: async () => ({ state: 'available' }),- apply: async () => { applied = true; return { ok: true, handedOff: true } }+ apply: async (_retirement, consent: RetirementConsent) => { consents.push(consent); applied = true;++ return { ok: true, handedOff: true } }}})+const status = await strategy.check()expect(status.updateAvailable).toBeUndefined()expect(status.retirement).toMatchObject({ state: 'available', destination: 'stable' })expect(applied).toBe(false)expect(await strategy.apply()).toMatchObject({ ok: false })expect(applied).toBe(false)- expect(await strategy.applyRetirement()).toMatchObject({ ok: true })+ const consent: RetirementConsent = { installStable: true, removePreview: true, workspaceChoice: 'keep-stable' }+ expect(await strategy.applyRetirement(consent)).toMatchObject({ ok: true })expect(applied).toBe(true)+ expect(consents).toEqual([consent])})test.each(['hash', 'identity', 'repository', 'signer', 'escape', 'schema', 'version'] as const)('rejects untrusted %s without falling back', async (fault): Promise<void> => {const f = await fixture()+if (fault === 'identity') { f.manifest.request.identity.appId = 'chat.other.identity' }+if (fault === 'repository') { f.manifest.request.repository = 'other/hermes-agent' }+if (fault === 'signer') { f.manifest.packages[0].teamId = 'ZZZZZ99999' }+if (fault === 'escape') { f.manifest.packages[0].feed.key = 'releases/other/stable-mac.yml' }+if (fault === 'version') { f.manifest.request.version = '1.0.0' }f.publish()+if (fault === 'hash') { f.objects.set(`/${f.record.head!.manifestKey}`, '{}') }+if (fault === 'schema') { f.objects.set(`/releases/channels/${f.record.name}.json`, '{"schema":2}') }await expect(new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()).rejects.toThrow()})-test.each(['floor', 'cycle', 'coverage', 'digest', 'missing', 'unprotected'] as const)('blocks retirement with invalid %s', async (fault): Promise<void> => {+test.each(['floor', 'cycle', 'protocol', 'receiver', 'digest', 'missing', 'unprotected'] as const)('blocks retirement with invalid %s', async (fault): Promise<void> => {const f = await retiredFixture()+if (fault === 'unprotected') {f.record.policy = 'preview'f.manifest.request.version = '0.0.2'@@ -186,12 +252,25 @@ test.each(['floor', 'cycle', 'coverage', 'digest', 'missing', 'unprotected'] asf.manifest.packages[0].version = '0.0.2'f.publish()}+if (fault === 'floor') { f.retired.minimumVersion = '2.0.0' }++ if (fault === 'receiver') {+ delete f.manifest.receiverProtocol+ f.publish()+ if (!f.record.head) { throw new Error('Expected published stable') }+ f.retired.destinationHead = structuredClone(f.record.head)+ }+if (fault === 'cycle') { f.retired.destination = f.build.channel }- if (fault === 'coverage') { f.build.buildId = 'f'.repeat(32) }- if (fault === 'digest') { f.retired.compatibilitySha256 = 'f'.repeat(64) }- if (fault === 'missing') { f.objects.delete(`/${f.retired.compatibilityKey}`) }++ if (fault === 'digest') { f.retired.destinationHead.sha256 = 'f'.repeat(64) }++ if (fault === 'missing') { f.objects.delete(`/${f.retired.destinationHead.manifestKey}`) }f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify(f.retired))+ if (fault === 'protocol') {+ f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify({ ...f.retired, receiverProtocol: 2 }))+ }await expect(new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()).rejects.toThrow()})@@ -228,6 +307,7 @@ test('Windows resolves its numeric native version, publisher and immutable descrf.publish()const result = await new ChannelResolver({ build: f.build, platform: 'win32', arch: 'x64', signer: 'CN=Nous Research' }).resolve()expect(result.kind).toBe('active')+if (result.kind !== 'active') { throw new Error('Expected active') }expect(result.target.package.version).toBe('0.0.2.0')expect(result.target.feedUrl).toContain('/win32/stable.appinstaller')@@ -236,14 +316,18 @@ test('Windows resolves its numeric native version, publisher and immutable descrtest('failed checks clear a previously checked selection, never authorizing a stale apply', async (): Promise<void> => {const f = await fixture()let applied = false+const strategy = new ChannelStrategy({resolver: new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }),build: f.build, mechanism: 'electron-updater',nativeFactory: () => ({ mechanism: 'electron-updater',check: async () => ({ supported: true, updateAvailable: true }),- apply: async () => { applied = true; return { ok: true } }+ apply: async () => { applied = true;++ return { ok: true } }})})+await strategy.check()f.objects.clear()await expect(strategy.check()).rejects.toThrow('404')@@ -264,6 +348,7 @@ test('long-offline previews retain the qualified migration target after stable af.publish()const result = await new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()expect(result.kind).toBe('retirement')+if (result.kind !== 'retirement') { throw new Error('Expected retirement') }expect(result.retirement.target.manifest.request.buildId).toBe(qualifiedBuild)expect(result.retirement.target.manifest.request.channel).toBe('stable')@@ -280,6 +365,7 @@ test('resolves an arbitrary R2 name through a real HTTP channel and digest-boundconst { build, requests } = await fixture()const result = await new ChannelResolver({ build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()expect(result.kind).toBe('active')+if (result.kind !== 'active') { throw new Error('Expected active build') }expect(result.target.manifest.request.sequence).toBe(2)expect(result.target.feedUrl).toBe(`${build.publicBase}/releases/channel-builds/${'c'.repeat(32)}/darwin/stable-mac.yml`)diff --git a/apps/desktop/electron/updater/channel.ts b/apps/desktop/electron/updater/channel.tsindex 94fe27a8e9e..147bbe7c2a3 100644--- a/apps/desktop/electron/updater/channel.ts+++ b/apps/desktop/electron/updater/channel.ts@@ -1,9 +1,9 @@import { createHash } from 'node:crypto'import {- buildPrefix, channelKey, channelPublicBase, decodeChannelManifest, decodeChannelRecord,- sameChannelIdentity, validateChannelName, decodeChannelQualification, type ChannelQualification,- type ActiveChannel, type ChannelBuild, type ChannelManifest, type ChannelPackage, type RetiredChannel+ type ActiveChannel, buildPrefix, type ChannelBuild, channelKey, type ChannelManifest,+ type ChannelPackage, channelPublicBase, decodeChannelManifest, decodeChannelRecord,+ type RetiredChannel, sameChannelIdentity, validateChannelName} from './channel-protocol'export interface ChannelTarget {@@ -17,8 +17,6 @@ export interface ChannelTarget {export interface ChannelRetirement {source: ChannelBuildtarget: ChannelTarget- constraints: RetiredChannel[]- qualifications: ChannelQualification[]}export type ChannelResolution =| { kind: 'active'; target: ChannelTarget }@@ -90,50 +88,24 @@ export class ChannelResolver {let record = decodeChannelRecord(await this.read(`releases/channels/${this.deps.build.channel}.json`))this.assertRecord(record, this.deps.build.channel)if (!sameChannelIdentity(record.identity, this.deps.build.identity)) { throw new Error('Installed channel identity changed') }- const constraints: RetiredChannel[] = []- const seen = new Set<string>()- while (record.state === 'retired') {- if (seen.has(record.name) || seen.has(record.destination) || record.name === record.destination) { throw new Error('Channel retirement cycle') }- seen.add(record.name)- if (seen.size >= 16) { throw new Error('Channel retirement hop limit exceeded') }- constraints.push(record)- const destination = record.destination- record = decodeChannelRecord(await this.read(`releases/channels/${destination}.json`))- this.assertRecord(record, destination)+ if (record.state === 'active') {+ return record.head ? { kind: 'active', target: await this.target(record) } : { kind: 'empty', channel: record }}- if (!record.head && !constraints.length) { return { kind: 'empty', channel: record } }- if (!constraints.length) { return { kind: 'active', target: await this.target(record) } }- if (record.policy !== 'stable-release') { throw new Error('Retirement requires a protected stable-release destination') }- let target: ChannelTarget | null = null- const qualifications: ChannelQualification[] = []- for (const constraint of constraints) {- // A floor for a different native identity cannot be compared to the terminal- // one. Require a directly qualified retirement rather than dropping a floor.- if (constraint.destination !== record.name) { throw new Error('Retirement chain requires direct terminal qualification') }- const qualification = decodeChannelQualification(await this.read(constraint.compatibilityKey, constraint.compatibilitySha256))- // Migrate to the exact accepted receiver, which then follows its own stable- // subscription. Advancing stable must not strand long-offline previews.- if (qualification.destinationHead.sequence >= record.nextSequence) { throw new Error('Qualified destination exceeds allocation') }- target = await this.target({ ...record, head: qualification.destinationHead })- assertVersionFloor(target.manifest.request.sourceVersion, constraint.minimumVersion)- this.assertQualification(qualification, constraint, target)- qualifications.push(qualification)+ const retired: RetiredChannel = record+ if (retired.destination === retired.name) { throw new Error('Channel retirement cycle') }+ record = decodeChannelRecord(await this.read(`releases/channels/${retired.destination}.json`))+ this.assertRecord(record, retired.destination)+ if (record.state !== 'active' || record.policy !== 'stable-release') {+ throw new Error('Retirement requires a directly active stable-release destination')}- if (!target) { throw new Error('Retirement has no qualified target') }- return { kind: 'retirement', retirement: { source: this.deps.build, target, constraints, qualifications } }- }-- private assertQualification(qualification: ChannelQualification, constraint: RetiredChannel, target: ChannelTarget): void {- const build = this.deps.build- const coverage = qualification.coverage.find((entry): boolean => entry.platform === this.deps.platform && entry.arch === this.deps.arch)- const sourceIdentity = this.deps.platform === 'darwin' ? build.identity.appId : build.identity.msixAppIdWithOrg- if (qualification.source !== constraint.name || qualification.destination !== target.channel.name ||- JSON.stringify(qualification.sourceHead) !== JSON.stringify(constraint.lastHead) ||- JSON.stringify(qualification.destinationHead) !== JSON.stringify(target.channel.head) || qualification.minimumVersion !== constraint.minimumVersion ||- !coverage || coverage.sourceIdentity !== sourceIdentity || coverage.destinationIdentity !== target.package.identity ||- !coverage.cohorts.some((cohort): boolean => cohort.buildId === build.buildId && cohort.commit === build.commit)) {- throw new Error('Retirement qualification does not cover this install and destination')+ if (!record.head || retired.destinationHead.sequence > record.head.sequence) {+ throw new Error('Retirement destination exceeds published head')}+ // Stable may advance while preview is offline; preserve its first receiver.+ const target: ChannelTarget = await this.target({ ...record, head: retired.destinationHead })+ if (target.manifest.receiverProtocol !== retired.receiverProtocol) { throw new Error('Stable build has no supported retirement receiver') }+ assertVersionFloor(target.manifest.request.sourceVersion, retired.minimumVersion)+ return { kind: 'retirement', retirement: { source: this.deps.build, target } }}private assertRecord(record: ActiveChannel | RetiredChannel, name: string): void {diff --git a/apps/desktop/electron/updater/checkout-source.test.ts b/apps/desktop/electron/updater/checkout-source.test.tsindex df108b37637..cbfa733e89e 100644--- a/apps/desktop/electron/updater/checkout-source.test.ts+++ b/apps/desktop/electron/updater/checkout-source.test.ts@@ -17,19 +17,180 @@ const execute: typeof execFile.__promisify__ = promisify(execFile)const repository: string = path.resolve(import.meta.dirname, '../../../..')const python: string = process.env.HERMES_PYTHON || 'python3'+function buildId(channel: 'stable' | 'canary'): string {+ return (channel === 'stable' ? 'a' : 'b').repeat(32)+}++function manifestKey(channel: 'stable' | 'canary'): string {+ return `releases/channel-builds/${buildId(channel)}/build.json`+}++const crypto = await import('node:crypto')++interface FixtureIdentity {+ token: string+ displayName: string+ appNamePascal: string+ artifactNamePascal: string+ appId: string+ msixAppIdWithOrg: string+ cliName: string+ windowsExecutableName: string+}++interface FixtureHead {+ buildId: string+ sequence: number+ manifestKey: string+ sha256: string+}++interface FixtureRecord {+ schema: number+ name: string+ repository: string+ policy: 'stable-release' | 'canary-release'+ state: 'active'+ revision: number+ nextSequence: number+ identity: FixtureIdentity+ head: FixtureHead+}++interface FixtureArtifact {+ key: string+ sha256: string+ size: number+ format: string+}++interface FixturePackage {+ platform: 'darwin'+ arch: 'arm64'+ variant: 'bundled'+ identity: string+ version: string+ teamId: string+ artifact: FixtureArtifact+ feed: { channel: 'stable'; key: string }+}++interface FixtureRequest {+ schema: number+ buildId: string+ channel: 'stable' | 'canary'+ repository: string+ commit: string+ sourceVersion: string+ releaseTag: string+ sequence: number+ version: string+ windowsVersion: string+ identity: FixtureIdentity+ bundleEnv: Record<string, string>+ publicBase: string+}++interface FixtureManifest {+ schema: number+ request: FixtureRequest+ packages: FixturePackage[]+}++/** Python canonical_json: sort_keys, compact separators, trailing newline. */+function canonicalJson(value: FixtureManifest): string {+ // SAFETY: FixtureManifest is the exact wire shape; JSON.stringify emits+ // member order as written, matching the fixture builder's field order.+ return JSON.stringify(value)+}++/** R2 channel record per hermes_cli.release_channels.validate_record. */+function channelRecord(channel: 'stable' | 'canary', sequence: number): FixtureRecord {+ return {+ schema: 1,+ name: channel,+ repository: 'NousResearch/hermes-agent',+ policy: channel === 'stable' ? 'stable-release' : 'canary-release',+ state: 'active',+ revision: 1,+ nextSequence: sequence + 1,+ identity: {+ token: 'b'.repeat(16),+ displayName: channel === 'stable' ? 'Hermes Stable' : 'Hermes Canary',+ appNamePascal: 'Hermes',+ artifactNamePascal: 'Hermes',+ appId: 'chat.nous.hermes',+ msixAppIdWithOrg: 'NousResearch.Hermes',+ cliName: 'hermes',+ windowsExecutableName: 'hermes'+ },+ head: {+ buildId: 'a'.repeat(32),+ sequence,+ manifestKey: `releases/channel-builds/${'a'.repeat(32)}/build.json`,+ sha256: 'c'.repeat(64)+ }+ }+}++/** Build manifest per hermes_cli.release_channels.validate_manifest. */+function buildManifest(channel: 'stable' | 'canary', sha: string, tag: string, id: string = buildId(channel)): FixtureManifest {+ const identity: FixtureIdentity = {+ token: 'b'.repeat(16),+ displayName: channel === 'stable' ? 'Hermes Stable' : 'Hermes Canary',+ appNamePascal: 'Hermes',+ artifactNamePascal: 'Hermes',+ appId: 'chat.nous.hermes',+ msixAppIdWithOrg: 'NousResearch.Hermes',+ cliName: 'hermes',+ windowsExecutableName: 'hermes'+ }+ const sequence: number = channel === 'stable' ? 1 : 2+ return {+ schema: 1,+ request: {+ schema: 1,+ buildId: id,+ channel,+ repository: 'NousResearch/hermes-agent',+ commit: sha,+ sourceVersion: tag.replace(/^v/, '').split('-')[0],+ releaseTag: tag,+ sequence,+ version: tag.replace(/^v/, ''),+ windowsVersion: `0.0.${sequence}.0`,+ identity,+ bundleEnv: {},+ publicBase: 'https://hermes-assets.nousresearch.com'+ },+ packages: [+ {+ platform: 'darwin',+ arch: 'arm64',+ variant: 'bundled',+ identity: 'chat.nous.hermes',+ version: tag.replace(/^v/, ''),+ teamId: 'TESTTEAM12',+ artifact: { key: `releases/channel-builds/${id}/darwin-arm64.zip`, sha256: 'd'.repeat(64), size: 1, format: 'zip' },+ feed: { channel: 'stable', key: `releases/channel-builds/${id}/darwin-arm64.xml` }+ }+ ]+ }+}+it('carries each install channel from Python publication checks into the source handoff', async (): Promise<void> => {const temporary: string = fs.mkdtempSync(path.join(os.tmpdir(), 'checkout-channel-'))const origin: string = path.join(temporary, 'origin')const root: string = path.join(temporary, 'checkout')const home: string = path.join(temporary, 'profile')const requests: string[] = []- const responses: Map<string, unknown> = new Map<string, unknown>()+ const responses: Map<string, string | object> = new Map<string, string | object>()const server: http.Server = http.createServer((request: http.IncomingMessage, response: http.ServerResponse): void => {const url: string = request.url ?? ''requests.push(url)- const body: unknown = responses.get(url)+ const body: string | object | undefined = responses.get(url)response.statusCode = body === undefined ? 404 : 200response.end(typeof body === 'string' ? body : JSON.stringify(body))}@@ -69,7 +230,13 @@ it('carries each install channel from Python publication checks into the sourcefor (const channel of ['stable', 'canary'] as const) {const sha: string = commits[channel === 'stable' ? 1 : 2]git(['tag', '-a', tags[channel], sha, '-m', channel])- responses.set(`/releases/${channel}/index.html`, `<meta name="hermes-build" content="${tags[channel]}">`)+ const manifest: FixtureManifest = buildManifest(channel, sha, tags[channel], buildId(channel))+ const body: string = canonicalJson(manifest)+ responses.set(`/releases/channels/${channel}.json`, JSON.stringify({ ...channelRecord(channel, channel === 'stable' ? 1 : 2),+ head: { buildId: buildId(channel), sequence: channel === 'stable' ? 1 : 2,+ manifestKey: manifestKey(channel),+ sha256: crypto.createHash('sha256').update(body, 'utf8').digest('hex') } }))+ responses.set(`/${manifestKey(channel)}`, body)responses.set(`/repos/NousResearch/hermes-agent/releases/tags/${tags[channel]}`, {tag_name: tags[channel],draft: false,@@ -79,6 +246,12 @@ it('carries each install channel from Python publication checks into the source}responses.set('/releases/stable/release-candidates.json', { tag: tags.stable, commit: commits[1] })+ // The 'main' subscription is a source-branch channel record under the R2 protocol.+ responses.set('/releases/channels/main.json', JSON.stringify({+ schema: 1, name: 'main', repository: 'NousResearch/hermes-agent',+ policy: 'source-branch', state: 'active', revision: 1, nextSequence: 1,+ identity: null, head: null, delivery: { kind: 'source-branch', branch: 'main' }+ }))git(['tag', 'v99.0.0'])git(['worktree', 'add', '-b', 'feature/gui', root])git(['remote', 'add', 'origin', origin])@@ -95,7 +268,28 @@ it('carries each install channel from Python publication checks into the source`import sys, ossys.path.append(${JSON.stringify(repository)})assert not os.environ.get('HERMES_RUNTIME_DIR')-import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.request.urlopen\ndef local(request, *args, **kwargs):\n parsed = urlsplit(request.full_url if isinstance(request, urllib.request.Request) else request)\n assert parsed.hostname in ('hermes-assets.nousresearch.com', 'api.github.com')\n return original('http://127.0.0.1:${address.port}' + parsed.path + ('?' + parsed.query if parsed.query else ''), *args, **kwargs)\nurllib.request.urlopen = local\n`+import urllib.request+from urllib.parse import urlsplit+original_build = urllib.request.build_opener+passthrough = original_build().open+def local(request, *args, **kwargs):+ parsed = urlsplit(request.full_url if isinstance(request, urllib.request.Request) else request)+ assert parsed.hostname in ('hermes-assets.nousresearch.com', 'api.github.com')+ url = 'http://127.0.0.1:${address.port}' + parsed.path + ('?' + parsed.query if parsed.query else '')+ # ChannelReader compares response.geturl() against the ORIGINAL request url:+ # wrap so the redirect detector still sees the un-rewritten authority.+ response = passthrough(url, *args, **kwargs)+ original_url = request.full_url if isinstance(request, urllib.request.Request) else request+ response.geturl = lambda: original_url+ return response+urllib.request.urlopen = local+def local_build(*args, **kwargs):+ # ChannelReader resolves through build_opener().open, not module urlopen.+ opener = original_build(*args, **kwargs)+ opener.open = local+ return opener+urllib.request.build_opener = local_build+`)vi.stubEnv('HERMES_MANAGED', '')vi.stubEnv('HERMES_RUNTIME_DIR', path.join(temporary, 'wrong-runtime'))@@ -179,7 +373,6 @@ import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.requexpect(checked, JSON.stringify({ checked, requests })).toMatchObject({supported: true,channel,- latestTag: tags[channel],targetSha: sha,updateAvailable: true})@@ -210,11 +403,9 @@ import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.requgit(['checkout', 'feature/gui'], root)}- responses.set(`/repos/NousResearch/hermes-agent/releases/tags/${tags.canary}`, {- tag_name: tags.canary,- draft: true,- prerelease: true- })+ // The R2 record, not GitHub metadata, decides availability: retire the+ // canary object and the resolver must fail closed before any handoff.+ responses.delete(`/releases/channels/canary.json`)vi.mocked(deps.stopBackendsForUpdate).mockClear()expect(await strategy.apply()).toMatchObject({ ok: false, error: 'release-unavailable' })expect(deps.stopBackendsForUpdate).not.toHaveBeenCalled()@@ -235,7 +426,9 @@ import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.requ)fs.rmSync(scriptDirectory, { recursive: true, force: true })expect(await strategy.apply()).toMatchObject({ manual: true, command: 'hermes update --branch feature/gui' })- expect(requests).toHaveLength(count)+ // apply() forces a fresh check; under the R2 protocol that re-resolution+ // touches exactly the channel record — no GitHub or artifact chatter.+ expect(requests.slice(count)).toEqual(['/releases/channels/main.json', '/releases/channels/main.json'])} finally {vi.restoreAllMocks()vi.unstubAllEnvs()diff --git a/apps/desktop/electron/updater/retirement-compatibility.ts b/apps/desktop/electron/updater/retirement-compatibility.tsindex 157607fec07..3f82d0a909b 100644--- a/apps/desktop/electron/updater/retirement-compatibility.ts+++ b/apps/desktop/electron/updater/retirement-compatibility.ts@@ -1,7 +1,7 @@-import path from 'node:path'-import type { PayloadInfo } from '../payload-backend'+import { runRetirementCommand } from './retirement-native'+import type { RetirementSnapshotTools } from './retirement-preservation'import type { RetirementRecord } from './retirement-state'const compatibilityProbe: string = `import os, pathlib, sys@@ -11,10 +11,10 @@ home = pathlib.Path(root)if profile != 'default': home = home / 'profiles' / profileos.environ['HERMES_HOME'] = str(home)os.environ['HERMES_SHARED_AUTH_DIR'] = str(pathlib.Path(root) / 'shared')-import yaml+import hermes_yamlfrom hermes_cli.config import validate_config_structureconfig_file = home / 'config.yaml'-config = yaml.safe_load(config_file.read_text()) if config_file.exists() else {}+config = hermes_yaml.safe_load(config_file.read_text(encoding='utf-8')) if config_file.exists() else {}if not isinstance(config, dict): raise RuntimeError('Configuration must be a mapping')issues = validate_config_structure(config)if any(issue.severity == 'error' for issue in issues): raise RuntimeError('Snapshot configuration is incompatible; run hermes doctor in the preview')@@ -33,12 +33,12 @@ if file.exists():finally: db.close()`-/** Exact cohort admission is checked separately; this catches damaged local state. */+/** Exercise destination readers before any live migrations; not a universal compatibility proof. */export async function probeRetirementSnapshot(record: RetirementRecord, payload: PayloadInfo): Promise<void> {await runRetirementCommand(payload.storePython, ['-c', compatibilityProbe,- payload.repoDir, payload.sitePackages, record.state.snapshotHome, record.request.selection.profile], 120_000)+ payload.repoDir, payload.sitePackages, record.state.snapshotHome, record.request.source.profile], 120_000)}-export function retirementSnapshotTools(payload: PayloadInfo): { python: string; backupScript: string } {- return { python: payload.storePython, backupScript: path.join(payload.repoDir, 'hermes_cli/backup_sqlite.py') }+export function retirementSnapshotTools(payload: PayloadInfo): RetirementSnapshotTools {+ return { python: payload.storePython, repo: payload.repoDir, sitePackages: payload.sitePackages }}diff --git a/apps/desktop/electron/updater/retirement-discovery.ts b/apps/desktop/electron/updater/retirement-discovery.tsindex e8152fb3408..765d6c20bc2 100644--- a/apps/desktop/electron/updater/retirement-discovery.ts+++ b/apps/desktop/electron/updater/retirement-discovery.ts@@ -2,8 +2,9 @@ import path from 'node:path'import type { ChannelBuild } from './channel-protocol'import type { ChannelTarget } from './channel'+import { discoverMacRetirementPath, type MacRetirementDiscovery } from './retirement-macos'import { runRetirementCommand, type NativeCommandResult } from './retirement-native'-import { canonicalRetirementPath, insideRetirementRoot, type RetirementDestination, type RetirementSource } from './retirement-state'+import { canonicalRetirementPath, type RetirementDestination, type RetirementSource } from './retirement-state'interface InstalledApp {identity: string@@ -70,7 +71,41 @@ export async function discoverRetirementSource(build: ChannelBuild, home: stringuserData: await canonicalRetirementPath(userData), profile, connectionId: 'local' }}-export async function discoverRetirementDestination(target: ChannelTarget, source: RetirementSource): Promise<RetirementDestination> {+interface RetirementDiscovery {+ mac?: MacRetirementDiscovery+ windows?: (target: ChannelTarget, source: RetirementSource, family: string) => Promise<string>+}++async function discoverWindowsDestination(target: ChannelTarget, source: RetirementSource, family: string): Promise<string> {+ const result: NativeCommandResult = await runRetirementPowerShell(String.raw`+$ErrorActionPreference='Stop'+$p=[Console]::In.ReadToEnd() | ConvertFrom-Json+$packages=@(Get-AppxPackage -Name $p.identity | Where-Object { $_.Name -ceq $p.identity })+if ($packages.Count -gt 1) { throw 'Stable package is not uniquely registered' }+if ($packages.Count) {+ $pkg=$packages[0]+ if ($pkg.Publisher -cne $p.signer -or $pkg.PackageFamilyName -cne $p.family -or $pkg.Architecture.ToString() -ine $p.arch -or $pkg.Status.ToString() -cne 'Ok') { throw 'Stable native identity/status mismatch' }+ if ($pkg.SignatureKind.ToString() -cne 'Developer' -or $pkg.IsDevelopmentMode -or $pkg.NonRemovable -or $pkg.IsPartiallyStaged) { throw 'Stable is owned by another installation steward' }+ $manifest=Get-AppxPackageManifest -Package $pkg.PackageFullName+ if (@($manifest.Package.Applications.Application | Where-Object { $_.Id -ceq $p.applicationId }).Count -ne 1) { throw 'Stable registered application identity mismatch' }+ if ($pkg.Version.ToString() -ceq $p.version) { $pkg.InstallLocation | ConvertTo-Json -Compress; exit }+ $store=Split-Path -Parent $pkg.InstallLocation+} else {+ $volume=Get-AppxDefaultVolume+ if (-not $volume -or $volume.IsOffline) { throw 'No online default package volume' }+ $store=$volume.PackageStorePath+}+if (-not $store) { throw 'Native package store location missing' }+Join-Path $store ($p.identity+'_'+$p.version+'_'+$p.arch+'__'+$p.publisherId) | ConvertTo-Json -Compress+`, JSON.stringify({ identity: target.package.identity, version: target.package.version, arch: target.package.arch,+ signer: source.signer, family, publisherId: family.split('_').at(-1), applicationId: target.manifest.request.identity.appNamePascal }))+ const appPath: string = JSON.parse(result.stdout)+ return canonicalRetirementPath(appPath)+}++export async function discoverRetirementDestination(+ target: ChannelTarget, source: RetirementSource, discovery: RetirementDiscovery = {}+): Promise<RetirementDestination> {const pkg = target.packageconst artifact: RetirementDestination['artifact'] = {url: target.artifactUrl, sha256: pkg.artifact.sha256, size: pkg.artifact.size,@@ -79,25 +114,17 @@ export async function discoverRetirementDestination(target: ChannelTarget, sourcconst common = { platform: pkg.platform, architecture: pkg.arch, identity: pkg.identity,nativeVersion: pkg.version, signer: source.signer, artifact, commit: target.manifest.request.commit }if (pkg.platform === 'darwin') {- // The established sibling Applications location is writable by the same owner.- const appPath: string = path.join(path.dirname(source.appPath), `${target.manifest.request.identity.appNamePascal}.app`)- return { ...common, appPath, applicationId: null, packageFamilyName: null }+ const proposed: RetirementDestination = { ...common,+ appPath: path.join(path.dirname(source.appPath), `${target.manifest.request.identity.displayName}.app`),+ applicationId: null, packageFamilyName: null }+ return { ...proposed, appPath: await discoverMacRetirementPath(proposed, discovery.mac) }}if (!source.packageFullName) { throw new Error('Missing running package identity') }const publisherId: string = source.packageFullName.split('_').at(-1) || ''if (!/^[a-z0-9]{13}$/.test(publisherId)) { throw new Error('Invalid native publisher ID') }const packageFamilyName: string = `${pkg.identity}_${publisherId}`- // Add-AppxPackage installs current-user sideloads beside the registered source.- const appPath: string = path.join(path.dirname(source.appPath), `${pkg.identity}_${pkg.version}_${pkg.arch}__${publisherId}`)- const applicationId: string = source.applicationId || ''+ const appPath: string = await (discovery.windows ?? discoverWindowsDestination)(target, source, packageFamilyName)+ const applicationId: string = target.manifest.request.identity.appNamePascalif (!applicationId) { throw new Error('Missing native application ID') }return { ...common, appPath, packageFamilyName, applicationId }}--export function assertPersistentRetirementHome(source: RetirementSource): void {- for (const root of source.removalRoots) {- if (insideRetirementRoot(root, source.home) || insideRetirementRoot(root, source.userData)) {- throw new Error('Your workspace or desktop credentials are inside package-private storage. Move the workspace to a persistent folder and reopen the preview before migrating; the preview has not been removed.')- }- }-}diff --git a/apps/desktop/electron/updater/retirement-host.test.ts b/apps/desktop/electron/updater/retirement-host.test.tsindex d36a02b7692..b513a0d298c 100644--- a/apps/desktop/electron/updater/retirement-host.test.ts+++ b/apps/desktop/electron/updater/retirement-host.test.ts@@ -4,52 +4,130 @@ import path from 'node:path'import { expect, test } from 'vitest'-import { readDesktopBootPreference, readStartupDesktopPreference } from '../desktop-boot-preference'import { resolveDesktopHermesHome } from '../data-paths'+import { readDesktopBootPreference, readStartupDesktopPreference } from '../desktop-boot-preference'import type { PayloadInfo } from '../payload-backend'+import { prepareRetirementStartup, type RetirementStartupOptions } from './retirement-host'+import { adoptRetirementConnection, retirementConnection, retirementSelectedConnection } from './retirement-connections'import { MacRetirementAdapter } from './retirement-macos'+import type { RetirementWorkspaceConflict } from './retirement-receiver'import { retirementArgument } from './retirement-receiver'-import { RetirementJournal, retirementDigest, type RetirementRequest } from './retirement-state'+import { retirementDigest, RetirementJournal, type RetirementRequest } from './retirement-state'class TestDestination extends MacRetirementAdapter {+ removed: boolean = false+ override async verifyDestination(): Promise<void> {}+ override async removePreview(): Promise<void> { this.removed = true }+ override async isPreviewRemoved(): Promise<boolean> { return this.removed }override async verifyRunningDestination(request: RetirementRequest): Promise<string> {return path.join(request.destination.appPath, 'Contents/MacOS/Hermes')}}-async function fixture(directory: string): Promise<{ options: RetirementStartupOptions; file: string; journal: RetirementJournal }> {+async function fixture(+ directory: string+): Promise<{ options: RetirementStartupOptions; file: string; journal: RetirementJournal }> {const home: string = path.join(directory, 'preview-home')const userData: string = path.join(directory, 'stable-desktop')await Promise.all([mkdir(home), mkdir(userData)])await writeFile(path.join(home, 'witness'), 'untouched')- const identity = { platform: 'darwin' as const, architecture: 'arm64' as const, signer: 'TESTTEAM12', nativeVersion: '1.0.0', applicationId: null }- const request: RetirementRequest = { protocol: 1, id: 'a'.repeat(32), token: 'b'.repeat(64),- source: { ...identity, identity: 'chat.nous.preview', appPath: path.join(directory, 'Preview.app'), executable: '/preview',- packageFullName: null, home, userData: path.join(directory, 'preview-desktop'), profile: 'default', connectionId: 'local', removalRoots: [path.join(directory, 'Preview.app')] },- destination: { ...identity, identity: 'chat.nous.hermes', appPath: path.join(directory, 'Hermes.app'), packageFamilyName: null, commit: 'c'.repeat(40),- artifact: { url: 'https://example.com/stable.zip', sha256: 'd'.repeat(64), size: 1, format: 'zip' } },++ const identity = {+ platform: 'darwin' as const,+ architecture: 'arm64' as const,+ signer: 'TESTTEAM12',+ nativeVersion: '1.0.0',+ applicationId: null+ }++ const request: RetirementRequest = {+ protocol: 1,+ id: 'a'.repeat(32),+ token: 'b'.repeat(64),+ source: {+ ...identity,+ identity: 'chat.nous.preview',+ appPath: path.join(directory, 'Preview.app'),+ executable: '/preview',+ packageFullName: null,+ home,+ userData: path.join(directory, 'preview-desktop'),+ profile: 'default',+ connectionId: 'local',+ removalRoots: [path.join(directory, 'Preview.app')]+ },+ destination: {+ ...identity,+ identity: 'chat.nous.hermes',+ appPath: path.join(directory, 'Hermes.app'),+ packageFamilyName: null,+ commit: 'c'.repeat(40),+ artifact: { url: 'https://example.com/stable.zip', sha256: 'd'.repeat(64), size: 1, format: 'zip' }+ },selection: { home, profile: 'default', connectionId: 'local', choice: 'open-preview', reauthenticate: false },- qualification: { sha256: 'e'.repeat(64), sourceCommit: 'f'.repeat(40), destinationCommit: 'c'.repeat(40), receiverProtocol: 1 },- consent: { install: true, removePreview: true, replaceExistingStable: false } }+ destinationManifestSha256: 'e'.repeat(64),+ sourceBuild: {+ buildId: '1'.repeat(32), channel: 'preview', sequence: 1, repository: 'NousResearch/hermes-agent',+ commit: 'f'.repeat(40), version: '0.0.1', sourceVersion: '1.2.2', windowsVersion: '0.0.1.0',+ publicBase: 'https://example.com', bundleEnv: {},+ identity: { token: '2'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview',+ appNamePascal: 'Preview', artifactNamePascal: 'Preview', cliName: 'preview',+ windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }+ },+ consent: { install: true, removePreview: true, replaceExistingStable: false }+ }+const journalRoot: string = path.join(directory, 'transactions')const journal = await RetirementJournal.open(journalRoot, request.id)- await journal.write({ request, requestDigest: retirementDigest(request), stage: 'destination-installed',- state: { snapshotHome: path.join(directory, 'snapshot'), selectedHome: home }, receiverApplied: false, receiverStarted: false, previousSelection: null, ready: null })- const payload: PayloadInfo = { root: directory, shim: '/unused', repoDir: directory, toolsDir: directory, storePython: '/unused', sitePackages: directory, commands: {} }- return { file: path.join(userData, 'active-profile.json'), journal, options: { argv: [retirementArgument(request.id, request.token)], userData,- defaultHome: path.join(directory, 'default-home'), operatorOverride: false, payload, journalRoot,- adapter: new TestDestination(), assertQualified: async (): Promise<void> => {},- probeSnapshot: async (): Promise<void> => {} } }+ await journal.write({+ request,+ requestDigest: retirementDigest(request),+ stage: 'destination-installed',+ state: { snapshotHome: path.join(directory, 'snapshot'), selectedHome: home },+ receiverApplied: false,+ receiverStarted: false,+ previousSelection: null,+ ready: null+ })++ const payload: PayloadInfo = {+ root: directory,+ shim: '/unused',+ repoDir: directory,+ toolsDir: directory,+ storePython: '/unused',+ sitePackages: directory,+ commands: {}+ }++ return {+ file: path.join(userData, 'active-profile.json'),+ journal,+ options: {+ argv: [retirementArgument(request.id, request.token)],+ userData,+ defaultHome: path.join(directory, 'default-home'),+ operatorOverride: false,+ payload,+ journalRoot,+ adapter: new TestDestination(),+ assertAdmitted: async (): Promise<void> => {},+ probeSnapshot: async (): Promise<void> => {}+ }+ }}test('receiver durably adopts before resolving home, is idempotent, and preserves a conflicting stable preference', async (): Promise<void> => {const directory = await mkdtemp(path.join(os.tmpdir(), 'retirement-host-'))+try {const { file, journal, options } = await fixture(directory)expect(await prepareRetirementStartup(options)).not.toBeNull()const preference = readDesktopBootPreference(file)- expect(resolveDesktopHermesHome({ home: directory, env: {}, adoptedHome: preference?.home })).toBe(path.join(directory, 'preview-home'))+ expect(resolveDesktopHermesHome({ home: directory, env: {}, adoptedHome: preference?.home })).toBe(+ path.join(directory, 'preview-home')+ )await prepareRetirementStartup(options)expect((await journal.read()).receiverApplied).toBe(true)expect(await readFile(path.join(directory, 'preview-home/witness'), 'utf8')).toBe('untouched')@@ -57,19 +135,224 @@ test('receiver durably adopts before resolving home, is idempotent, and preserveawait writeFile(file, changed)await expect(prepareRetirementStartup(options)).rejects.toThrow('workspace changed')expect(await readFile(file, 'utf8')).toBe(changed)+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+})++test.each(['keep-stable', 'open-preview'] as const)(+ 'explicit %s consent binds the current stable workspace without merging settings',+ async (choice): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-consent-'))++ try {+ const { file, journal, options } = await fixture(directory)+ const stableHome: string = path.join(directory, 'stable-home')+ await mkdir(stableHome)+ const original: string = JSON.stringify({ home: stableHome, profile: 'work', customSetting: 'preserve' })+ await writeFile(file, original)+ const connectionFile: string = path.join(options.userData, 'connections.json')+ await writeFile(connectionFile, '{"primary":"local","saved":[{"id":"remote-saved"}]}')+ const prompts: RetirementWorkspaceConflict[] = []++ options.confirmWorkspaceConflict = async (conflict: RetirementWorkspaceConflict): Promise<typeof choice> => {+ prompts.push(conflict)++ return choice+ }++ if (choice === 'keep-stable') {+ options.runningSelection = () => ({ home: stableHome, profile: 'work', connectionId: 'local' })+ }++ const reception = await prepareRetirementStartup(options)+ expect(reception).not.toBeNull()+ expect(prompts).toHaveLength(1)+ expect(prompts[0].current).toEqual({+ home: stableHome,+ profile: 'work',+ connectionId: 'local',+ operatorOverride: false+ })+ expect(prompts[0].canOpenPreview).toBe(choice === 'open-preview')+ const record = await journal.read()+ expect(record.request.selection.choice).toBe(choice)+ expect(record.previousSelection?.home).toBe(stableHome)+ expect(record.request.selection.conflictConsent).toEqual(prompts[0].current)+ expect(record.state.selectedHome).toBe(choice === 'keep-stable' ? stableHome : record.request.source.home)++ if (choice === 'keep-stable') {+ expect(await readFile(file, 'utf8')).toBe(original)+ } else {+ expect(JSON.parse(await readFile(file, 'utf8')).customSetting).toBe('preserve')+ }++ expect(await readFile(connectionFile, 'utf8')).toBe('{"primary":"local","saved":[{"id":"remote-saved"}]}')+ await prepareRetirementStartup(options)+ expect(prompts).toHaveLength(1)+ expect(record.ready).toBeNull()+ expect(record.stage).toBe('destination-installed')+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+ }+)++test.each(['before-write', 'after-write'] as const)(+ 'receiver resumes %s interruption without asking again or losing stable settings',+ async (interruption): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-adoption-retry-'))++ try {+ const { file, journal, options } = await fixture(directory)+ const stableHome: string = path.join(directory, 'stable-home')+ await mkdir(stableHome)+ await writeFile(file, JSON.stringify({ home: stableHome, profile: 'work', customSetting: 'preserved' }))+ const record = await journal.read()+ const previous = { home: stableHome, profile: 'work', connectionId: 'local', operatorOverride: false }+ record.request.selection.conflictConsent = previous+ record.previousSelection = previous+ record.receiverStarted = true+ record.requestDigest = retirementDigest(record.request)+ await journal.write(record)++ if (interruption === 'after-write') {+ await writeFile(+ file,+ JSON.stringify({ home: record.request.selection.home, profile: 'default', customSetting: 'preserved' })+ )+ }++ options.confirmWorkspaceConflict = async (): Promise<never> => {+ throw new Error('Must reuse prior consent')+ }++ expect(await prepareRetirementStartup(options)).not.toBeNull()+ expect((await journal.read()).receiverApplied).toBe(true)+ expect((await journal.read()).previousSelection).toEqual(previous)+ expect(JSON.parse(await readFile(file, 'utf8')).customSetting).toBe('preserved')+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+ }+)++test('cancel, stale consent and running stable reject retargeting before any preference write', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-consent-stale-'))++ try {+ const { file, journal, options } = await fixture(directory)+ const stableHome: string = path.join(directory, 'stable-home')+ await mkdir(stableHome)+ const original: string = JSON.stringify({ home: stableHome, profile: 'work' })+ await writeFile(file, original)+ options.confirmWorkspaceConflict = async (): Promise<null> => null+ await expect(prepareRetirementStartup(options)).rejects.toThrow('cancelled')++ options.confirmWorkspaceConflict = async (): Promise<'open-preview'> => {+ await writeFile(file, JSON.stringify({ home: stableHome, profile: 'changed' }))++ return 'open-preview'+ }++ await expect(prepareRetirementStartup(options)).rejects.toThrow('changed')+ await writeFile(file, original)+ options.runningSelection = () => ({ home: stableHome, profile: 'work', connectionId: 'local' })+ options.confirmWorkspaceConflict = async (): Promise<'open-preview'> => 'open-preview'+ await expect(prepareRetirementStartup(options)).rejects.toThrow('Close stable')+ expect(await readFile(file, 'utf8')).toBe(original)+ let activeProfile: string = 'work'+ options.runningSelection = () => ({ home: stableHome, profile: activeProfile, connectionId: 'local' })++ options.confirmWorkspaceConflict = async (): Promise<'keep-stable'> => {+ activeProfile = 'changed'++ return 'keep-stable'+ }++ await expect(prepareRetirementStartup(options)).rejects.toThrow('changed')+ expect((await journal.read()).receiverStarted).toBe(false)+ expect((await journal.read()).ready).toBeNull()+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+})++test('remote adoption strips credentials, survives an interrupted write and waits for authenticated readiness', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-remote-'))+ try {+ const { file, journal, options } = await fixture(directory)+ const record = await journal.read()+ record.request.selection.connectionId = 'retired-remote'+ record.request.selection.reauthenticate = true+ record.request.selection.connection = retirementConnection({ id: 'remote', kind: 'remote', label: 'Research',+ url: 'https://gateway.example', authMode: 'token', token: { ciphertext: 'private-preview-secret' }, headers: { Authorization: 'private-proxy-secret' } })+ record.previousSelection = { home: options.defaultHome, profile: 'default', connectionId: 'local', operatorOverride: false }+ record.receiverStarted = true+ record.requestDigest = retirementDigest(record.request)+ await journal.write(record)+ adoptRetirementConnection(options.userData, 'retired-remote', 'default', record.request.selection.connection)+ const reception = await prepareRetirementStartup(options)+ if (!reception || !(options.adapter instanceof TestDestination)) { throw new Error('Receiver did not start') }+ expect(readDesktopBootPreference(file)?.home).toBe(record.request.selection.home)+ expect(retirementSelectedConnection(options.userData, 'default')).toBe('retired-remote')+ const stored: string = await readFile(path.join(options.userData, 'connections.json'), 'utf8')+ expect(stored).not.toContain('private-preview-secret')+ expect(stored).not.toContain('private-proxy-secret')+ const adapter: TestDestination = options.adapter+ let attempts: number = 0+ const outcome = await reception.complete({ home: record.request.selection.home, profile: (): string => 'default',+ connectionId: (): string => retirementSelectedConnection(options.userData, 'default'), rendererMounted: (): boolean => true,+ backend: async (): Promise<void> => {+ expect(adapter.removed).toBe(false)+ if (attempts++ === 0) { throw new Error('reauthentication required') }+ } })+ expect(outcome.status).toBe('complete')+ expect((await journal.read()).stage).toBe('complete')+ expect(adapter.removed).toBe(true)+ expect(retirementSelectedConnection(options.userData, 'default')).toBe('retired-remote')+ } finally { await rm(directory, { recursive: true, force: true }) }+})++test('a removed package home stays adopted on cold boot', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-relocated-'))+ try {+ const { file, journal, options } = await fixture(directory)+ const record = await journal.read()+ const relocated: string = path.join(journal.directory, 'home')+ await mkdir(relocated)+ await writeFile(path.join(relocated, 'witness'), 'preserved')+ record.request.source.removalRoots.push(record.request.source.home)+ record.request.selection.home = relocated+ record.state.selectedHome = relocated+ record.requestDigest = retirementDigest(record.request)+ await journal.write(record)+ await prepareRetirementStartup(options)+ await rm(record.request.source.home, { recursive: true })+ expect(resolveDesktopHermesHome({ home: directory, env: {}, adoptedHome: readDesktopBootPreference(file)?.home })).toBe(relocated)+ expect(await readFile(path.join(relocated, 'witness'), 'utf8')).toBe('preserved')+ await prepareRetirementStartup(options)+ expect((await journal.read()).receiverApplied).toBe(true)} finally { await rm(directory, { recursive: true, force: true }) }})test('malformed legacy preferences keep ordinary boot usable but block migration without overwriting bytes', async (): Promise<void> => {const directory = await mkdtemp(path.join(os.tmpdir(), 'retirement-preference-'))+try {const { file, journal, options } = await fixture(directory)await writeFile(file, '{bad-json')const warnings: string[] = []- expect(readStartupDesktopPreference(file, (message: string): void => { warnings.push(message) })).toBeNull()+ expect(+ readStartupDesktopPreference(file, (message: string): void => {+ warnings.push(message)+ })+ ).toBeNull()expect(warnings).toHaveLength(1)await expect(prepareRetirementStartup(options)).rejects.toThrow()expect((await journal.read()).receiverStarted).toBe(false)expect(await readFile(file, 'utf8')).toBe('{bad-json')- } finally { await rm(directory, { recursive: true, force: true }) }+ } finally {+ await rm(directory, { recursive: true, force: true })+ }})diff --git a/apps/desktop/electron/updater/retirement-host.ts b/apps/desktop/electron/updater/retirement-host.tsindex 78836727f35..94a48c0fc81 100644--- a/apps/desktop/electron/updater/retirement-host.ts+++ b/apps/desktop/electron/updater/retirement-host.ts@@ -1,50 +1,79 @@-import { open, readFile, readdir, unlink } from 'node:fs/promises'-import type { FileHandle } from 'node:fs/promises'+import { readdir } from 'node:fs/promises'import path from 'node:path'-import { adoptDesktopHome, readDesktopBootPreference, type DesktopBootPreference } from '../desktop-boot-preference'+import { adoptDesktopHome, type DesktopBootPreference, readDesktopBootPreference } from '../desktop-boot-preference'import type { PayloadInfo } from '../payload-backend'+import { ChannelResolver, type ChannelRetirement } from './channel'import type { ChannelRetirementCallbacks, ChannelRetirementStatus } from './channel-strategy'+import {+ awaitRetirementCleanup, prepareRetirement, resumeRetirement, type RetirementDependencies,+ type RetirementOutcome, type RetirementReadinessProbe, verifyRetirementReadiness+} from './retirement'import { probeRetirementSnapshot, retirementSnapshotTools } from './retirement-compatibility'-import { assertPersistentRetirementHome, discoverRetirementDestination, discoverRetirementSource } from './retirement-discovery'+import { adoptRetirementConnection, assertRetirementConnection, prepareRetirementConnection, type RetirementConnectionSelection, retirementSelectedConnection } from './retirement-connections'+import {+ discoverRetirementDestination,+ discoverRetirementSource+} from './retirement-discovery'import { MacRetirementAdapter } from './retirement-macos'import { retirementPathExists } from './retirement-native'import { snapshotRetirementHome } from './retirement-preservation'-import { completeRetirementReception, parseRetirementArgument, receiveRetirement, type RetirementExistingSelection, type RetirementReceiverDependencies } from './retirement-receiver'-import { defaultRetirementRoot, insideRetirementRoot, newRetirementCorrelation, RetirementJournal, type RetirementRecord, type RetirementRequest } from './retirement-state'-import { prepareRetirement, resumeRetirement, type RetirementDependencies, type RetirementOutcome } from './retirement'+import {+ completeRetirementReception,+ parseRetirementArgument,+ receiveRetirement,+ type RetirementExistingSelection,+ type RetirementReceiverDependencies+} from './retirement-receiver'+import {+ canonicalRetirementPath,+ defaultRetirementRoot,+ insideRetirementRoot,+ newRetirementCorrelation,+ type RetirementConsent,+ RetirementJournal,+ type RetirementRecord,+ type RetirementRequest,+ type RetirementSelection,+ type RetirementWorkspaceChoice+} from './retirement-state'import { WindowsRetirementAdapter } from './retirement-windows'+import type { UpdaterApplyResultWire } from './index'export type RetirementAdapter = MacRetirementAdapter | WindowsRetirementAdapter+export function nativeRetirementAdapter(): RetirementAdapter {- if (process.platform === 'darwin') { return new MacRetirementAdapter() }- if (process.platform === 'win32') { return new WindowsRetirementAdapter() }- throw new Error('Native retirement requires macOS or Windows')-}+ if (process.platform === 'darwin') {+ return new MacRetirementAdapter()+ }-export async function assertRetirementQualified(request: RetirementRequest): Promise<void> {- const build = request.qualification.sourceBuild- if (!build) { throw new Error('Retirement journal has no baked source build binding') }- const resolved = await new ChannelResolver({ build, platform: request.source.platform,- arch: request.source.architecture, signer: request.source.signer }).resolve()- if (resolved.kind !== 'retirement' ||- resolved.retirement.target.manifest.request.commit !== request.destination.commit ||- resolved.retirement.target.package.artifact.sha256 !== request.destination.artifact.sha256 ||- resolved.retirement.target.package.identity !== request.destination.identity ||- resolved.retirement.constraints.at(-1)?.compatibilitySha256 !== request.qualification.sha256) {- throw new Error('The exact retirement qualification is no longer available')+ if (process.platform === 'win32') {+ return new WindowsRetirementAdapter()}++ throw new Error('Native retirement requires macOS or Windows')}-/** A cross-process lock lives outside either application's removal footprint. */-async function acquireRetirementLifecycle(request: RetirementRequest): Promise<() => Promise<void>> {- const journal: RetirementJournal = await RetirementJournal.open(defaultRetirementRoot(), request.id)- const lock: string = path.join(journal.directory, 'lifecycle.lock')- const handle: FileHandle = await open(lock, 'wx', 0o600)- await handle.writeFile(String(process.pid))- return async (): Promise<void> => { await handle.close(); await unlink(lock) }+export async function assertRetirementAdmitted(request: RetirementRequest): Promise<void> {+ const build = request.sourceBuild+ const resolved = await new ChannelResolver({+ build,+ platform: request.source.platform,+ arch: request.source.architecture,+ signer: request.source.signer+ }).resolve()++ if (+ resolved.kind !== 'retirement' ||+ resolved.retirement.target.manifest.request.commit !== request.destination.commit ||+ resolved.retirement.target.package.artifact.sha256 !== request.destination.artifact.sha256 ||+ resolved.retirement.target.package.identity !== request.destination.identity ||+ resolved.retirement.target.manifestSha256 !== request.destinationManifestSha256+ ) {+ throw new Error('The pinned retirement destination is no longer available')+ }}export interface RetirementStartupOptions {@@ -54,120 +83,176 @@ export interface RetirementStartupOptions {operatorOverride: booleanpayload: PayloadInfo | null/** A live stable process cannot silently retarget already-open databases. */- runningSelection?: { home: string; profile: string; connectionId: string }+ runningSelection?: () => Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'>+ confirmWorkspaceConflict?: RetirementReceiverDependencies['confirmWorkspaceConflict']journalRoot?: stringadapter?: RetirementAdapter- assertQualified?: (request: RetirementRequest) => Promise<void>+ assertAdmitted?: (request: RetirementRequest) => Promise<void>probeSnapshot?: (record: RetirementRecord, payload: PayloadInfo) => Promise<void>}export interface RetirementReception {- journal: RetirementJournal- token: string- dependencies: RetirementReceiverDependencies+ complete(probe: RetirementReadinessProbe): Promise<RetirementOutcome>}-interface StoredLocalSelection {- mode?: string- primary?: string- lastUsed?: string- launchMode?: string- profileRemotes?: { [profile: string]: { mode?: string } }-}--async function assertLocalDesktopSelection(userData: string, profile: string): Promise<void> {- for (const file of ['connection.json', 'connections.json']) {- const location: string = path.join(userData, file)- if (!(await retirementPathExists(location))) { continue }- const stored: StoredLocalSelection = JSON.parse(await readFile(location, 'utf8'))- if ((stored.mode && stored.mode !== 'local') || (stored.primary && stored.primary !== 'local') ||- (stored.launchMode === 'last-used' && stored.lastUsed && stored.lastUsed !== 'local') ||- (stored.profileRemotes?.[profile]?.mode && stored.profileRemotes[profile].mode !== 'local')) {- throw new Error('Stable has a remote workspace selected. Select Local in stable, then retry migration. Saved connections are preserved.')- }- }-}/** Run only in the lock-owning destination, before normal home selection/migrations. */export async function prepareRetirementStartup(options: RetirementStartupOptions): Promise<RetirementReception | null> {let correlation = parseRetirementArgument(options.argv)+if (!correlation && options.payload) {- const pending = await pendingRetirement(options.journalRoot ?? defaultRetirementRoot(),- (record: RetirementRecord): boolean => record.receiverApplied && insideRetirementRoot(record.request.destination.appPath, process.execPath))- if (pending) { correlation = { id: pending.id, token: (await pending.read()).request.token } }+ const pending = await pendingRetirement(+ options.journalRoot ?? defaultRetirementRoot(),+ (record: RetirementRecord): boolean =>+ record.receiverStarted && insideRetirementRoot(record.request.destination.appPath, process.execPath)+ )++ if (pending) {+ correlation = { id: pending.id, token: (await pending.read()).request.token }+ }}- if (!correlation) { return null }- if (!options.payload) { throw new Error('The retirement receiver requires the bundled stable application') }++ if (!correlation) {+ return null+ }++ if (!options.payload) {+ throw new Error('The retirement receiver requires the bundled stable application')+ }+const adapter: RetirementAdapter = options.adapter ?? nativeRetirementAdapter()- const journal: RetirementJournal = await RetirementJournal.open(options.journalRoot ?? defaultRetirementRoot(), correlation.id)++ const journal: RetirementJournal = await RetirementJournal.open(+ options.journalRoot ?? defaultRetirementRoot(),+ correlation.id+ )+const file: string = path.join(options.userData, 'active-profile.json')let expected: DesktopBootPreference | null = readDesktopBootPreference(file)+const dependencies: RetirementReceiverDependencies = {+ runningSelection: options.runningSelection,+ confirmWorkspaceConflict: options.confirmWorkspaceConflict,verifyRunningDestination: async (request: RetirementRequest): Promise<string> => {const executable: string = await adapter.verifyRunningDestination(request)- await (options.assertQualified ?? assertRetirementQualified)(request)+ await (options.assertAdmitted ?? assertRetirementAdmitted)(request)+return executable},assertCompatibleSnapshot: async (record: RetirementRecord): Promise<void> => {await (options.probeSnapshot ?? probeRetirementSnapshot)(record, options.payload!)},+ prepareConnection: (selection: RetirementSelection): RetirementSelection => {+ if (!selection.connection) { return selection }+ const resolved: RetirementConnectionSelection = prepareRetirementConnection(options.userData, selection.connectionId, selection.connection)+ return { ...selection, connectionId: resolved.id, connection: resolved.settings }+ },readSelection: async (): Promise<RetirementExistingSelection | null> => {expected = readDesktopBootPreference(file)- const record: RetirementRecord = await journal.read()- await assertLocalDesktopSelection(options.userData, record.request.selection.profile)- if (options.runningSelection) { return { ...options.runningSelection, operatorOverride: true } }- if (!expected && !options.operatorOverride && !(await retirementPathExists(path.join(options.defaultHome, 'config.yaml')))) { return null }- return { home: expected?.home ?? options.defaultHome, profile: expected?.profile ?? 'default',- connectionId: 'local', operatorOverride: options.operatorOverride }++ const running: Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'> | undefined =+ options.runningSelection?.()+++ if (running) {+ return { ...running, operatorOverride: options.operatorOverride }+ }++ const configured: boolean = !(+ !expected &&+ !options.operatorOverride &&+ !(await retirementPathExists(path.join(options.defaultHome, 'config.yaml'))) &&+ retirementSelectedConnection(options.userData, 'default') === 'local'+ )++ const selection: RetirementExistingSelection = {+ home: options.operatorOverride ? options.defaultHome : (expected?.home ?? options.defaultHome),+ profile: expected?.profile ?? 'default',+ connectionId: retirementSelectedConnection(options.userData, expected?.profile ?? 'default'),+ operatorOverride: options.operatorOverride+ }+ if (!configured) { selection.configured = false }+ return selection},adoptSelection: async (record: RetirementRecord): Promise<void> => {const selection = record.request.selection- if (selection.connectionId !== 'local') { throw new Error('Open the remote connection in stable and sign in before migrating. No encrypted credentials were copied.') }+ const current: string = retirementSelectedConnection(options.userData, selection.profile)+ if (current !== selection.connectionId && current !== record.previousSelection?.connectionId) {+ throw new Error('Stable connection changed while awaiting adoption; review the migration again')+ }+ adoptRetirementConnection(options.userData, selection.connectionId, selection.profile, selection.connection)adoptDesktopHome(file, { home: selection.home, profile: selection.profile }, expected)},// Bound below only after the real renderer and backend have started.- assertReady: async (): Promise<never> => { throw new Error('Destination renderer and backend have not reported readiness') }+ assertReady: async (): Promise<never> => {+ throw new Error('Destination renderer and backend have not reported readiness')+ }}+await receiveRetirement(journal, correlation.token, dependencies)- return { journal, token: correlation.token, dependencies }-}-export async function finishRetirementStartup(- reception: RetirementReception,- assertReady: (record: RetirementRecord) => Promise<void>-): Promise<RetirementOutcome> {- reception.dependencies.assertReady = assertReady- const record: RetirementRecord = await reception.journal.read()- if (record.stage === 'destination-installed') {- await completeRetirementReception(reception.journal, reception.token, reception.dependencies)+ const token: string = correlation.token+ return {+ complete: (probe: RetirementReadinessProbe): Promise<RetirementOutcome> => awaitRetirementCleanup(async () => {+ dependencies.assertReady = (record: RetirementRecord): Promise<void> => verifyRetirementReadiness(record, probe)+ const record: RetirementRecord = await journal.read()+ if (record.request.selection.choice === 'open-preview' && record.request.selection.connection) {+ assertRetirementConnection(options.userData, record.request.selection.connectionId, record.request.selection.connection)+ }+ await dependencies.assertReady(record)+ if (record.stage === 'destination-installed') {+ await completeRetirementReception(journal, token, dependencies)+ }+ return resumeRetirement(journal, {+ native: adapter,+ assertAdmitted: options.assertAdmitted ?? assertRetirementAdmitted,+ // Native cleanup checks all source package processes, not just this app's child.+ assertSourceQuiescent: async (): Promise<void> => {},+ assertDestinationReady: dependencies.assertReady+ }, 'destination')+ })}- return resumeRetirement(reception.journal, {- native: nativeRetirementAdapter(), assertQualified: assertRetirementQualified,- acquireLifecycle: acquireRetirementLifecycle,- assertSourceQuiescent: async (): Promise<void> => { /* Native removal rechecks all source package processes. */ },- assertDestinationReady: assertReady,- prepareState: async (): Promise<never> => { throw new Error('The destination cannot prepare a source snapshot') }- }, 'destination')}-async function pendingRetirement(root: string, matches: (record: RetirementRecord) => boolean): Promise<RetirementJournal | null> {- if (!(await retirementPathExists(root))) { return null }+async function pendingRetirement(+ root: string,+ matches: (record: RetirementRecord) => boolean+): Promise<RetirementJournal | null> {+ if (!(await retirementPathExists(root))) {+ return null+ }+for (const id of await readdir(root)) {- if (!/^[a-f0-9]{32}$/.test(id) || !(await retirementPathExists(path.join(root, id, 'journal.json')))) { continue }+ if (!/^[a-f0-9]{32}$/.test(id) || !(await retirementPathExists(path.join(root, id, 'journal.json')))) {+ continue+ }+const journal = await RetirementJournal.open(root, id)const record = await journal.read()- if (record.stage !== 'complete' && matches(record)) { return journal }++ if (record.stage !== 'complete' && matches(record)) {+ return journal+ }}+return null}/** Once stable has opened state, a restarted preview may only forward, never reopen its old backend. */export async function forwardRetiredPreview(): Promise<boolean> {- const pending = await pendingRetirement(defaultRetirementRoot(), (record: RetirementRecord): boolean =>- record.receiverStarted && record.request.source.executable === process.execPath)- if (!pending) { return false }+ const pending = await pendingRetirement(+ defaultRetirementRoot(),+ (record: RetirementRecord): boolean =>+ record.receiverStarted && record.request.source.executable === process.execPath+ )++ if (!pending) {+ return false+ }+const record = await pending.read()- await assertRetirementQualified(record.request)+ await assertRetirementAdmitted(record.request)await nativeRetirementAdapter().activate(record.request, pending)+return true}@@ -176,7 +261,7 @@ export interface RetirementHostOptions {userData: stringpayload: PayloadInfoprofile: () => string- isLocal: () => boolean+ connection: () => RetirementConnectionSelectionstop: () => Promise<void>restore: () => Promise<void>quit: () => void@@ -189,57 +274,130 @@ export class RetirementHost implements ChannelRetirementCallbacks {async check(retirement: ChannelRetirement): Promise<Pick<ChannelRetirementStatus, 'state' | 'message'>> {try {- this.journal ??= await pendingRetirement(defaultRetirementRoot(), (record: RetirementRecord): boolean =>- record.request.source.userData === this.options.userData && record.request.qualification.sourceCommit === retirement.source.commit)+ this.journal ??= await pendingRetirement(+ defaultRetirementRoot(),+ (record: RetirementRecord): boolean =>+ record.request.source.userData === this.options.userData &&+ record.request.sourceBuild.commit === retirement.source.commit+ )await this.request(retirement)+return { state: 'available' }} catch (error) {return { state: 'conflict', message: error instanceof Error ? error.message : String(error) }}}- private async request(retirement: ChannelRetirement): Promise<RetirementRequest> {- if (!this.options.isLocal()) {- throw new Error('Select your local workspace before migrating. Remote connections must be opened and authenticated in stable separately; the preview and all saved credentials are preserved.')+ private async request(+ retirement: ChannelRetirement,+ choice: RetirementWorkspaceChoice = 'open-preview'+ ): Promise<RetirementRequest> {+ const connection = this.options.connection()+ const source = await discoverRetirementSource(+ retirement.source,+ this.options.home,+ this.options.userData,+ this.options.profile()+ )+ source.connectionId = connection.id+ const keyPath: string | null = connection.settings?.keyPath ? await canonicalRetirementPath(connection.settings.keyPath) : null+ if (keyPath && source.removalRoots.some(root => insideRetirementRoot(root, keyPath))) {+ throw new Error('The SSH key is inside package-private storage. Move it to persistent storage and update the saved connection before migration')}- const source = await discoverRetirementSource(retirement.source, this.options.home, this.options.userData, this.options.profile())- assertPersistentRetirementHome(source)+const destination = await discoverRetirementDestination(retirement.target, source)- return { protocol: 1, ...newRetirementCorrelation(), source, destination,- selection: { home: source.home, profile: source.profile, connectionId: 'local', choice: 'open-preview', reauthenticate: false },- qualification: { sha256: retirement.constraints.at(-1)!.compatibilitySha256, sourceCommit: retirement.source.commit,- destinationCommit: destination.commit, receiverProtocol: 1, sourceBuild: retirement.source },- consent: { install: true, removePreview: true, replaceExistingStable: true } }+ const correlation = newRetirementCorrelation()+ const home: string = source.removalRoots.some(root => insideRetirementRoot(root, source.home))+ ? path.join(defaultRetirementRoot(), correlation.id, 'home') : source.home+ if (home !== source.home && (source.platform !== 'win32' || insideRetirementRoot(source.appPath, source.home))) {+ throw new Error('A workspace inside the application bundle needs a complete external archive before migration; preview preserved')+ }+ const connectionId: string = connection.id === 'local' ? 'local' : `retired-${retirement.source.identity.token}-${connection.id}`++ return {+ protocol: 1,+ ...correlation,+ source,+ destination,+ selection: { home, profile: source.profile, connectionId, choice,+ connection: connection.settings, reauthenticate: connection.id !== 'local' },+ sourceBuild: retirement.source,+ destinationManifestSha256: retirement.target.manifestSha256,+ consent: { install: true, removePreview: true, replaceExistingStable: true }+ }}- async apply(retirement: ChannelRetirement): Promise<UpdaterApplyResultWire> {+ async apply(retirement: ChannelRetirement, consent: RetirementConsent): Promise<UpdaterApplyResultWire> {let stopped: boolean = false+try {- const request: RetirementRequest = this.journal ? (await this.journal.read()).request : await this.request(retirement)+ if (+ consent.installStable !== true ||+ consent.removePreview !== true ||+ !['open-preview', 'keep-stable'].includes(consent.workspaceChoice)+ ) {+ throw new Error('Explicit retirement consent and workspace choice are required')+ }++ const previous: RetirementRecord | null =+ this.journal && (await retirementPathExists(path.join(this.journal.directory, 'journal.json')))+ ? await this.journal.read()+ : null++ const request: RetirementRequest = previous?.request ?? (await this.request(retirement, consent.workspaceChoice))++ if (this.journal && !previous) {+ request.id = this.journal.id+ if (request.selection.home !== request.source.home) {+ request.selection.home = path.join(this.journal.directory, 'home')+ }+ }+this.journal ??= await RetirementJournal.open(defaultRetirementRoot(), request.id)const journal: RetirementJournal = this.journal+const deps: RetirementDependencies = {- native: nativeRetirementAdapter(), assertQualified: assertRetirementQualified,- acquireLifecycle: acquireRetirementLifecycle,- assertSourceQuiescent: async (): Promise<void> => { await this.options.stop(); stopped = true },- assertDestinationReady: async (): Promise<never> => { throw new Error('Only the destination process may acknowledge readiness') },- prepareState: async (): Promise<{ snapshotHome: string; selectedHome: string }> => ({- snapshotHome: await snapshotRetirementHome(request.source.home, path.join(journal.directory, 'snapshot'), retirementSnapshotTools(this.options.payload)),- selectedHome: request.selection.home- })+ native: nativeRetirementAdapter(),+ assertAdmitted: assertRetirementAdmitted,+ assertSourceQuiescent: async (): Promise<void> => {+ await this.options.stop()+ stopped = true+ },+ assertDestinationReady: async (): Promise<never> => {+ throw new Error('Only the destination process may acknowledge readiness')+ },+ prepareState: async (): Promise<{ snapshotHome: string; selectedHome: string }> => {+ const tools = retirementSnapshotTools(this.options.payload)+ const snapshotHome: string = await snapshotRetirementHome(request.source.home, path.join(journal.directory, 'snapshot'), tools)+ if (request.selection.home !== request.source.home) {+ await snapshotRetirementHome(request.source.home, request.selection.home, tools)+ }+ return { snapshotHome, selectedHome: request.selection.home }+ }}+this.options.progress('Preparing a private state snapshot before installing stable…')await prepareRetirement(journal, request, deps)// Preparation can be resumed; never reopen preview readers after stable admission.- await this.options.stop(); stopped = true- this.options.progress('Installing and opening the exact qualified stable application…')+ await this.options.stop()+ stopped = true+ this.options.progress('Installing and opening the pinned stable application…')await resumeRetirement(journal, deps, 'source')this.options.quit()+return { ok: true, handedOff: true }} catch (error) {- const record: RetirementRecord | null = this.journal && await retirementPathExists(path.join(this.journal.directory, 'journal.json')) ? await this.journal.read() : null- if (stopped && !record?.receiverStarted) { await this.options.restore() }+ const record: RetirementRecord | null =+ this.journal && (await retirementPathExists(path.join(this.journal.directory, 'journal.json')))+ ? await this.journal.read()+ : null++ if (stopped && !record?.receiverStarted) {+ await this.options.restore()+ }+const message: string = error instanceof Error ? error.message : String(error)+return { ok: false, error: 'retirement-blocked', message }}}diff --git a/apps/desktop/electron/updater/retirement-macos.ts b/apps/desktop/electron/updater/retirement-macos.tsindex ea7873cd59e..651149da85f 100644--- a/apps/desktop/electron/updater/retirement-macos.ts+++ b/apps/desktop/electron/updater/retirement-macos.ts@@ -1,14 +1,17 @@import { constants } from 'node:fs'import { access, lstat, mkdir, mkdtemp, readdir, readFile, rename } from 'node:fs/promises'+import os from 'node:os'import path from 'node:path'+import { downloadPinnedArtifact } from './artifact'import type * as Electron from 'electron'+import { removeBundleCliLinks } from '../cli-provision'+import { assertNativeRetirementRemoval, type RetirementNativeAdapter } from './retirement'import {assertRetirementStamp,assertRunningRetirementStamp,- downloadRetirementArtifact,type NativeCommandResult,retirementPathExists,runRetirementCommand@@ -107,6 +110,64 @@ async function verifyMacBundle(identity: RetirementNativeIdentity, app: string =return executable}+export interface MacRetirementDiscovery {+ roots?: string[]+ registered?: (identity: string) => Promise<string[]>+ inspect?: (app: string, target: RetirementDestination) => Promise<{ identity: string }>+}++async function registeredMacBundles(identity: string): Promise<string[]> {+ requireMac()+ const result: NativeCommandResult = await runRetirementCommand('/usr/bin/mdfind', [+ '-0', `kMDItemCFBundleIdentifier == '${identity}'`+ ])+ return result.stdout.split('\0').filter(Boolean)+}++async function inspectMacDestination(app: string, target: RetirementDestination): Promise<{ identity: string }> {+ requireMac()+ const result: NativeCommandResult = await runRetirementCommand('/usr/bin/plutil', [+ '-convert', 'json', '-o', '-', path.join(app, 'Contents/Info.plist')+ ])+ const plist: MacInfoPlist = JSON.parse(result.stdout)+ if (plist.CFBundleIdentifier === target.identity) {+ await assertOwnedBundle(app)+ await verifyMacBundle({ ...target, appPath: app, nativeVersion: plist.CFBundleShortVersionString })+ const stamp: MacSourceStamp = JSON.parse(await readFile(path.join(app, 'Contents/Resources/install-stamp.json'), 'utf8'))+ if (stamp.distribution !== 'desktop-app' || stamp.payload !== 'bundled' || stamp.updateMechanism !== 'electron-updater') {+ throw new Error('Existing stable has a different installation steward')+ }+ }+ return { identity: plist.CFBundleIdentifier }+}++/** Search by native identity, including renamed bundles; never silently create a duplicate. */+export async function discoverMacRetirementPath(target: RetirementDestination, discovery: MacRetirementDiscovery = {}): Promise<string> {+ const roots: string[] = discovery.roots ?? [path.dirname(target.appPath), '/Applications', path.join(os.homedir(), 'Applications')]+ const candidates: Set<string> = new Set(await (discovery.registered ?? registeredMacBundles)(target.identity))+ for (const root of new Set(roots)) {+ if (!(await retirementPathExists(root))) { continue }+ for (const entry of await readdir(root, { withFileTypes: true })) {+ if (entry.name.endsWith('.app')) { candidates.add(path.join(root, entry.name)) }+ }+ }+ const matches: Set<string> = new Set()+ for (const candidate of candidates) {+ if (!(await retirementPathExists(candidate))) { continue }+ // Ignore incomplete directories; an identified matching bundle must pass+ // signature and ownership checks rather than silently falling through.+ if (!(await retirementPathExists(path.join(candidate, 'Contents/Info.plist')))) { continue }+ const app: string = await canonicalRetirementPath(candidate)+ const inspected = await (discovery.inspect ?? inspectMacDestination)(app, target)+ if (inspected.identity === target.identity) { matches.add(app) }+ }+ if (matches.size > 1) { throw new Error('Multiple stable applications found; choose one through its installation steward') }+ const existing: string | undefined = [...matches][0]+ if (existing) { return existing }+ if (await retirementPathExists(target.appPath)) { throw new Error('Stable install location belongs to another application') }+ return canonicalRetirementPath(target.appPath)+}+async function assertNoBundleProcesses(app: string): Promise<void> {const result: NativeCommandResult = await runRetirementCommand('/bin/ps', ['-axo', 'comm='])@@ -116,7 +177,7 @@ async function assertNoBundleProcesses(app: string): Promise<void> {}async function stageMacBundle(request: RetirementRequest, journal: RetirementJournal): Promise<string> {- const artifact: string = await downloadRetirementArtifact(journal, request.destination)+ const artifact: string = await downloadPinnedArtifact(journal.directory, request.destination.artifact)if (request.destination.artifact.format !== 'zip') {throw new Error('macOS retirement requires the signed update ZIP')@@ -147,6 +208,7 @@ async function stageMacBundle(request: RetirementRequest, journal: RetirementJouexport class MacRetirementAdapter implements RetirementNativeAdapter {async verifyDestination(request: RetirementRequest): Promise<void> {+ await assertOwnedBundle(request.destination.appPath)await verifyMacBundle(request.destination)await assertRetirementStamp(path.join(request.destination.appPath, 'Contents/Resources/install-stamp.json'),@@ -285,7 +347,7 @@ export class MacRetirementAdapter implements RetirementNativeAdapter {)if (- stamp.commit !== request.qualification.sourceCommit ||+ stamp.commit !== request.sourceBuild.commit ||stamp.distribution !== 'desktop-app' ||stamp.payload !== 'bundled') {@@ -293,6 +355,7 @@ export class MacRetirementAdapter implements RetirementNativeAdapter {}await assertNoBundleProcesses(source)+ removeBundleCliLinks(path.join(source, 'Contents/Resources/agent-payload'), path.join(os.homedir(), '.local/bin'))const { shell }: typeof Electron = await import('electron')await shell.trashItem(source)}diff --git a/apps/desktop/electron/updater/retirement-native.test.ts b/apps/desktop/electron/updater/retirement-native.test.tsindex cec93a44aa0..ebe45682ae5 100644--- a/apps/desktop/electron/updater/retirement-native.test.ts+++ b/apps/desktop/electron/updater/retirement-native.test.ts@@ -1,12 +1,18 @@import { createHash } from 'node:crypto'-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'+import { createServer } from 'node:http'+import { once } from 'node:events'import os from 'node:os'import path from 'node:path'import { DatabaseSync } from 'node:sqlite'import { afterEach, expect, test } from 'vitest'-import { assertRetirementStamp, assertRunningRetirementStamp, verifyRetirementArtifact } from './retirement-native'+import { assertRetirementStamp, assertRunningRetirementStamp } from './retirement-native'+import { downloadPinnedArtifact, verifyPinnedArtifact } from './artifact'+import { verifyPreparedChannelInstaller } from './channel-windows-host'+import type { ChannelTarget } from './channel'+import type { NativeCommandResult } from './retirement-native'import { snapshotRetirementHome } from './retirement-preservation'import type { RetirementDestination } from './retirement-state'@@ -31,7 +37,7 @@ test('snapshot includes WAL-backed state and private config without copying Electry {const snapshot: string = await snapshotRetirementHome(home, path.join(directory, 'snapshot'), {python: 'python3',- backupScript: path.resolve('../../hermes_cli/backup_sqlite.py')+ repo: path.resolve('../..'), sitePackages: ''})const copied: DatabaseSync = new DatabaseSync(path.join(snapshot, 'state.db'), { readOnly: true })@@ -48,6 +54,52 @@ test('snapshot includes WAL-backed state and private config without copying Elec}})+test('ordinary Windows preparation owns temporary bytes while retirement retains its resumable download', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-artifact-lifetime-'))+ directories.push(directory)+ const bytes: Buffer = Buffer.from('digest-bound download')+ const server = createServer((_request, response): void => { response.end(bytes) })+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ const address = server.address()+ if (!address || !(address instanceof Object)) { throw new Error('Expected TCP server') }+ const url: string = `http://127.0.0.1:${address.port}/stable.msixbundle`+ const identity = { token: 'a'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview', appNamePascal: 'Preview',+ artifactNamePascal: 'Preview', cliName: 'preview', windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }+ const target: ChannelTarget = {+ channel: { schema: 1, state: 'active', name: 'preview', repository: 'NousResearch/hermes-agent', policy: 'preview',+ revision: 1, nextSequence: 2, head: null, identity },+ manifest: { schema: 1, packages: [], request: { schema: 1, buildId: 'b'.repeat(32), channel: 'preview', sequence: 1,+ repository: 'NousResearch/hermes-agent', commit: 'c'.repeat(40), sourceVersion: '1.0.0', version: '0.0.1',+ windowsVersion: '0.0.1.0', identity, bundleEnv: {}, publicBase: 'https://example.com' } },+ package: { platform: 'win32', arch: 'x64', variant: 'bundled', version: '0.0.1.0', identity: identity.msixAppIdWithOrg,+ publisher: 'CN=Test', artifact: { key: 'stable.msixbundle', sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length },+ feed: { key: 'stable.appinstaller', channel: 'stable' } },+ artifactUrl: url, feedUrl: 'https://example.com/stable.appinstaller', manifestSha256: 'd'.repeat(64)+ }+ try {+ const file: string = path.join(directory, 'stable.appinstaller')+ await writeFile(file, 'native descriptor checked by command')+ const command = async (_script: string, input: string): Promise<NativeCommandResult> => {+ const payload: { artifact: string } = JSON.parse(input)+ expect(await readFile(payload.artifact)).toEqual(bytes)+ return { stdout: '', stderr: '' }+ }+ await verifyPreparedChannelInstaller(file, target, command)+ expect(await readdir(directory)).toEqual(['stable.appinstaller'])+ await expect(verifyPreparedChannelInstaller(file, target, async (): Promise<never> => {+ throw new Error('native signature refused')+ })).rejects.toThrow('signature refused')+ expect(await readdir(directory)).toEqual(['stable.appinstaller'])+ const durable: string = path.join(directory, 'retirement')+ await mkdir(durable, { mode: 0o700 })+ const artifact = { url, sha256: target.package.artifact.sha256, size: bytes.length, format: 'msixbundle' as const }+ const downloaded: string = await downloadPinnedArtifact(durable, artifact)+ expect(await downloadPinnedArtifact(durable, artifact)).toBe(downloaded)+ expect(await readFile(downloaded)).toEqual(bytes)+ } finally { server.close(); await once(server, 'close') }+})+test('native preparation rejects bytes changed after download and wrong stamped commit or owner', async (): Promise<void> => {const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-native-retirement-'))directories.push(directory)@@ -74,9 +126,9 @@ test('native preparation rejects bytes changed after download and wrong stamped}expect((): void => assertRunningRetirementStamp(target)).toThrow('baked stamp')- await expect(verifyRetirementArtifact(artifact, target.artifact)).resolves.toBeUndefined()+ await expect(verifyPinnedArtifact(artifact, target.artifact)).resolves.toBeUndefined()await writeFile(artifact, Buffer.alloc(bytes.length))- await expect(verifyRetirementArtifact(artifact, target.artifact)).rejects.toThrow('digest')+ await expect(verifyPinnedArtifact(artifact, target.artifact)).rejects.toThrow('digest')const stamp: string = path.join(directory, 'install-stamp.json')await writeFile(stamp,@@ -85,10 +137,18 @@ test('native preparation rejects bytes changed after download and wrong stampedpayload: 'bundled',distribution: 'desktop-app',dirty: false,+ receiverProtocol: 1,+ source: 'build',+ tag: 'v1.0.0',updateMechanism: 'electron-updater'}))await expect(assertRetirementStamp(stamp, target)).resolves.toBeUndefined()+ const accepted = JSON.parse(await readFile(stamp, 'utf8'))+ for (const invalid of [{ tag: null }, { tag: 'v1.0.0-canary.20260913' }, { source: 'channel-build' }, { channelBuild: {} }]) {+ await writeFile(stamp, JSON.stringify({ ...accepted, ...invalid }))+ await expect(assertRetirementStamp(stamp, target)).rejects.toThrow('stamp')+ }await writeFile(stamp,JSON.stringify({diff --git a/apps/desktop/electron/updater/retirement-native.ts b/apps/desktop/electron/updater/retirement-native.tsindex be70edeb451..7d913c465c4 100644--- a/apps/desktop/electron/updater/retirement-native.ts+++ b/apps/desktop/electron/updater/retirement-native.ts@@ -1,13 +1,9 @@import { execFile } from 'node:child_process'-import { createHash } from 'node:crypto'-import { createReadStream } from 'node:fs'-import { lstat, open, readFile, rename, unlink } from 'node:fs/promises'-import type { FileHandle } from 'node:fs/promises'-import path from 'node:path'+import { lstat, readFile } from 'node:fs/promises'-import { INSTALL_STAMP } from '../install-stamp'+import { INSTALL_STAMP, type InstallStamp } from '../install-stamp'-import type { RetirementDestination, RetirementJournal } from './retirement-state'+import type { RetirementDestination } from './retirement-state'export interface NativeCommandResult {stdout: string@@ -40,100 +36,24 @@ export function runRetirementCommand(})}-export async function verifyRetirementArtifact(- file: string,- artifact: RetirementDestination['artifact']-): Promise<void> {- const info: Awaited<ReturnType<typeof lstat>> = await lstat(file)-- if (!info.isFile() || info.isSymbolicLink() || info.size !== artifact.size) {- throw new Error('Retirement artifact size or type mismatch')- }-- const hash: ReturnType<typeof createHash> = createHash('sha256')-- for await (const chunk of createReadStream(file)) {- hash.update(chunk)- }-- if (hash.digest('hex') !== artifact.sha256) {- throw new Error('Retirement artifact digest mismatch')- }-}--/** Download only the immutable digest-bound URL. Redirects cannot change its authority. */-export async function downloadRetirementArtifact(- journal: RetirementJournal,- target: RetirementDestination-): Promise<string> {- const file: string = path.join(journal.directory, `destination.${target.artifact.format}`)-- try {- await verifyRetirementArtifact(file, target.artifact)-- return file- } catch (error) {- if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') {- throw error- }- }-- const temporary: string = `${file}.partial`- await unlink(temporary).catch((error: NodeJS.ErrnoException): void => {- if (error.code !== 'ENOENT') {- throw error- }- })-- const response: Response = await fetch(target.artifact.url, {- redirect: 'error',- signal: AbortSignal.timeout(600_000)- })-- if (!response.ok || !response.body) {- throw new Error(`Retirement download failed (${response.status})`)- }-- const handle: FileHandle = await open(temporary, 'wx', 0o600)- let size: number = 0-- try {- for await (const chunk of response.body) {- size += chunk.byteLength- if (size > target.artifact.size) {- throw new Error('Retirement download exceeds pinned size')- }-- await handle.writeFile(chunk)- }-- await handle.sync()- } finally {- await handle.close()- }-- await verifyRetirementArtifact(temporary, target.artifact)- await rename(temporary, file)-- return file-}+type NativeInstallStamp = Pick<InstallStamp,+ 'commit' | 'payload' | 'distribution' | 'dirty' | 'receiverProtocol' | 'updateMechanism' | 'tag' | 'source' | 'channelBuild'>-interface NativeInstallStamp {- commit: string- payload: string- distribution: string- dirty: boolean- updateMechanism: string+function stableOwned(stamp: NativeInstallStamp): boolean {+ return /^v\d+\.\d+\.\d+$/.test(stamp.tag ?? '') && !stamp.channelBuild &&+ stamp.source !== 'channel-build' && stamp.source !== 'commit-build'}export function assertRunningRetirementStamp(target: RetirementDestination): void {if (!INSTALL_STAMP ||+ !stableOwned(INSTALL_STAMP) ||INSTALL_STAMP.commit !== target.commit ||INSTALL_STAMP.payload !== 'bundled' ||INSTALL_STAMP.distribution !== 'desktop-app' ||INSTALL_STAMP.dirty ||+ INSTALL_STAMP.receiverProtocol !== 1 ||INSTALL_STAMP.updateMechanism !== (target.platform === 'darwin' ? 'electron-updater' : 'app-installer')) {throw new Error('Running destination baked stamp is not the pinned official stable release')@@ -144,10 +64,12 @@ export async function assertRetirementStamp(file: string, target: RetirementDestconst stamp: NativeInstallStamp = JSON.parse(await readFile(file, 'utf8'))if (+ !stableOwned(stamp) ||stamp.commit !== target.commit ||stamp.payload !== 'bundled' ||stamp.distribution !== 'desktop-app' ||stamp.dirty !== false ||+ stamp.receiverProtocol !== 1 ||stamp.updateMechanism !== (target.platform === 'darwin' ? 'electron-updater' : 'app-installer')) {throw new Error('Destination stamp does not identify the pinned stable bundled release')diff --git a/apps/desktop/electron/updater/retirement-preservation.ts b/apps/desktop/electron/updater/retirement-preservation.tsindex 564e4476403..71ea4cd3cb6 100644--- a/apps/desktop/electron/updater/retirement-preservation.ts+++ b/apps/desktop/electron/updater/retirement-preservation.ts@@ -1,5 +1,4 @@-import { chmod, copyFile, lstat, mkdir, open, readdir, rename } from 'node:fs/promises'-import type { FileHandle } from 'node:fs/promises'+import { lstat, open, rename, rm } from 'node:fs/promises'import path from 'node:path'import { runRetirementCommand } from './retirement-native'@@ -7,78 +6,47 @@ import { canonicalRetirementPath, insideRetirementRoot } from './retirement-statexport interface RetirementSnapshotTools {python: string- backupScript: string+ repo: string+ sitePackages: string}-const sqliteSnapshot: string = `import importlib.util, pathlib, sqlite3, sys-spec = importlib.util.spec_from_file_location('hermes_retirement_backup', sys.argv[1])-module = importlib.util.module_from_spec(spec)-spec.loader.exec_module(module)-source, target = pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])-if not module._safe_copy_db(source, target):- raise RuntimeError('WAL-safe retirement snapshot failed')-with sqlite3.connect(target) as connection:- if connection.execute('PRAGMA quick_check').fetchall() != [('ok',)]:- raise RuntimeError('Retirement snapshot integrity failed')+const migrationSnapshot: string = `import os, pathlib, sys+repo, site, source, target = sys.argv[1:]+sys.path[:0] = [repo, site]+os.environ['HERMES_HOME'] = source+os.environ['HERMES_SHARED_AUTH_DIR'] = str(pathlib.Path(source) / 'shared')+from hermes_cli.backup_migration import snapshot_migration_home+snapshot_migration_home(pathlib.Path(source), pathlib.Path(target))`-async function isSqlite(file: string): Promise<boolean> {- const handle: FileHandle = await open(file, 'r')- try {- const header: Buffer = Buffer.alloc(16)- await handle.read(header, 0, 16, 0)+async function assertPrivateDirectory(directory: string): Promise<void> {+ const info: Awaited<ReturnType<typeof lstat>> = await lstat(directory)- return header.toString('utf8') === 'SQLite format 3\0'- } finally {- await handle.close()+ if (+ !info.isDirectory() ||+ info.isSymbolicLink() ||+ (process.platform !== 'win32' && ((info.mode & 0o077) !== 0 || info.uid !== process.getuid?.()))+ ) {+ throw new Error('Snapshot staging must be a private owned directory')}}-async function copyStateTree(source: string, target: string, tools: RetirementSnapshotTools): Promise<void> {- await mkdir(target, { mode: 0o700 })- const names: string[] = await readdir(source)-- for (const name of names) {- const input: string = path.join(source, name)- const output: string = path.join(target, name)- const info: Awaited<ReturnType<typeof lstat>> = await lstat(input)-- if (info.isSymbolicLink()) {- throw new Error('Snapshot contains a symlink; resolve its preservation policy before retirement')- }-- if (info.isDirectory()) {- await copyStateTree(input, output, tools)-- continue- }-- if (!info.isFile()) {- throw new Error('Snapshot contains a live socket or special file; quiesce its owner first')- }-- if (name.endsWith('-wal') || name.endsWith('-shm')) {- const database: string = input.slice(0, -4)-- if (!(await isSqlite(database))) {- throw new Error('Unrecognized SQLite sidecar in retirement snapshot')- }-- continue- }-- if (await isSqlite(input)) {- await runRetirementCommand(tools.python, ['-c', sqliteSnapshot, tools.backupScript, input, output])- } else {- await copyFile(input, output)+async function discardInterruptedSnapshot(directory: string): Promise<void> {+ try {+ await assertPrivateDirectory(directory)+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {+ return}- await chmod(output, info.mode & 0o700)+ throw error}++ await rm(directory, { recursive: true })}-/** Caller holds the lifecycle lock. This is private preservation, not a profile export. */+/** Caller holds journal.exclusive and has not published the prepared journal yet. */export async function snapshotRetirementHome(home: string,destination: string,@@ -91,9 +59,21 @@ export async function snapshotRetirementHome(throw new Error('Snapshot and live state roots overlap')}+ if (target !== path.resolve(destination)) {+ throw new Error('Snapshot staging must be a private owned directory')+ }++ await assertPrivateDirectory(path.dirname(target))const partial: string = `${target}.partial`- await copyStateTree(source, partial, tools)+ // Neither tree is authoritative until preparation publishes its journal.+ await discardInterruptedSnapshot(partial)+ await discardInterruptedSnapshot(target)+ await runRetirementCommand(tools.python, ['-c', migrationSnapshot, tools.repo, tools.sitePackages, source, partial])await rename(partial, target)+ if (process.platform !== 'win32') {+ const parent = await open(path.dirname(target), 'r')+ try { await parent.sync() } finally { await parent.close() }+ }return target}diff --git a/apps/desktop/electron/updater/retirement-readiness.ts b/apps/desktop/electron/updater/retirement-readiness.tsdeleted file mode 100644index c45dfd5ae4f..00000000000--- a/apps/desktop/electron/updater/retirement-readiness.ts+++ /dev/null@@ -1,40 +0,0 @@-import { setTimeout as delay } from 'node:timers/promises'--import { finishRetirementStartup, type RetirementReception } from './retirement-host'-import type { RetirementRecord } from './retirement-state'-import type { RetirementOutcome } from './retirement'--export interface RetirementReadinessProbe {- home: string- profile: () => string- isLocal: () => boolean- rendererMounted: () => boolean- backend: () => Promise<void>-}--/** A loaded document alone is not readiness: require the mounted UI and selected backend. */-export async function verifyRetirementReadiness(record: RetirementRecord, probe: RetirementReadinessProbe): Promise<void> {- if (probe.home !== record.state.selectedHome || probe.profile() !== record.request.selection.profile || !probe.isLocal()) {- throw new Error('The destination is not using the consented local workspace')- }- if (!probe.rendererMounted()) { throw new Error('Waiting for the stable renderer to mount') }- await probe.backend()-}--export async function completeDesktopRetirement(reception: RetirementReception, probe: RetirementReadinessProbe): Promise<RetirementOutcome> {- const deadline: number = Date.now() + 120_000- let lastError: Error = new Error('Stable did not become ready')- while (Date.now() < deadline) {- try {- await verifyRetirementReadiness(await reception.journal.read(), probe)- // Source quit and final native release can lag renderer readiness. The- // same bounded retry also resumes a previous cleanup-pending receipt.- const result: RetirementOutcome = await finishRetirementStartup(reception,- (record: RetirementRecord): Promise<void> => verifyRetirementReadiness(record, probe))- if (result.status !== 'cleanup-pending') { return result }- lastError = new Error(result.error)- } catch (error) { lastError = error instanceof Error ? error : new Error(String(error)) }- await delay(1000)- }- return { status: 'cleanup-pending', forwardOnly: true, error: lastError.message }-}diff --git a/apps/desktop/electron/updater/retirement-receiver.ts b/apps/desktop/electron/updater/retirement-receiver.tsindex 8f5cc4bbb7a..9f776c103f0 100644--- a/apps/desktop/electron/updater/retirement-receiver.ts+++ b/apps/desktop/electron/updater/retirement-receiver.ts@@ -1,14 +1,15 @@import { randomBytes, timingSafeEqual } from 'node:crypto'-import { recordRetirementReady } from './retirement'import {canonicalRetirementPath,type RetirementCorrelation,+ retirementDigest,type RetirementJournal,type RetirementReady,type RetirementRecord,type RetirementRequest,type RetirementSelection,+ type RetirementWorkspaceChoice,signRetirementReady} from './retirement-state'@@ -17,13 +18,24 @@ export interface RetirementExistingSelection {profile: stringconnectionId: stringoperatorOverride: boolean+ configured?: boolean+}++export interface RetirementWorkspaceConflict {+ current: RetirementExistingSelection+ requested: RetirementSelection+ canOpenPreview: boolean}export interface RetirementReceiverDependencies {+ /** The destination is already using this workspace; it cannot change homes in place. */+ runningSelection?: () => Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'>+ confirmWorkspaceConflict?: (conflict: RetirementWorkspaceConflict) => Promise<RetirementWorkspaceChoice | null>/** Check process.execPath, native signature, baked commit and stable update owner. */verifyRunningDestination(request: RetirementRequest): Promise<string>/** Real destination readers on the disposable snapshot, before live migrations. */assertCompatibleSnapshot(record: RetirementRecord): Promise<void>+ prepareConnection?: (selection: RetirementSelection) => RetirementSelectionreadSelection(): Promise<RetirementExistingSelection | null>/** CAS through the boot/connection writers. Must be idempotent for request.id. Never copy userData. */adoptSelection(record: RetirementRecord, previous: RetirementExistingSelection | null): Promise<void>@@ -67,7 +79,10 @@ function assertToken(record: RetirementRecord, token: string): void {}}-function sameSelection(current: RetirementExistingSelection, selection: RetirementSelection): boolean {+function sameSelection(+ current: Pick<RetirementSelection, 'home' | 'profile' | 'connectionId'>,+ selection: Pick<RetirementSelection, 'home' | 'profile' | 'connectionId'>+): boolean {return (current.home === selection.home &¤t.profile === selection.profile &&@@ -75,6 +90,91 @@ function sameSelection(current: RetirementExistingSelection, selection: Retireme)}+async function readCurrentSelection(deps: RetirementReceiverDependencies): Promise<RetirementExistingSelection | null> {+ const current: RetirementExistingSelection | null = await deps.readSelection()++ return current ? { ...current, home: await canonicalRetirementPath(current.home) } : null+}++async function consentToWorkspace(+ record: RetirementRecord,+ current: RetirementExistingSelection | null,+ deps: RetirementReceiverDependencies+): Promise<void> {+ if (!current || current.configured === false) {+ if (record.request.selection.choice === 'keep-stable') {+ throw new Error('There is no configured stable workspace to keep')+ }++ return+ }++ if (sameSelection(current, record.request.selection)) {+ return+ }++ const consent: RetirementSelection['conflictConsent'] = record.request.selection.conflictConsent++ const consentMatches: boolean = Boolean(+ consent && sameSelection(current, consent) && consent.operatorOverride === current.operatorOverride+ )++ if (record.receiverStarted && !consentMatches) {+ if (interruptedAdoption(record, current)) { return }+ throw new Error('Stable workspace changed after retirement admission; explicit forward recovery is required')+ }++ const canOpenPreview: boolean = !deps.runningSelection && !current.operatorOverride+ let choice: RetirementWorkspaceChoice = record.request.selection.choice++ if (!consentMatches) {+ if (!deps.confirmWorkspaceConflict) {+ throw new Error('Stable workspace conflict: explicit selection consent is required')+ }++ const confirmed: RetirementWorkspaceChoice | null = await deps.confirmWorkspaceConflict({+ current: { ...current },+ requested: { ...record.request.selection },+ canOpenPreview+ })++ if (!confirmed) {+ throw new Error('Workspace migration cancelled; preview preserved')+ }++ const latest: RetirementExistingSelection | null = await readCurrentSelection(deps)++ if (!latest || !sameSelection(current, latest) || latest.operatorOverride !== current.operatorOverride) {+ throw new Error('Stable workspace changed while awaiting consent; review the migration again')+ }++ choice = confirmed+ }++ if (choice === 'open-preview' && !canOpenPreview) {+ throw new Error(+ 'Close stable and remove any explicit home override before opening the preview workspace, then retry. Both workspaces are preserved.'+ )+ }++ const selected: Pick<RetirementSelection, 'home' | 'profile' | 'connectionId'> =+ choice === 'keep-stable' ? current : record.request.selection++ record.request.selection = { ...record.request.selection, ...selected, choice, conflictConsent: { ...current } }+ record.state.selectedHome = selected.home+ record.requestDigest = retirementDigest(record.request)+}++function interruptedAdoption(record: RetirementRecord, current: RetirementExistingSelection): boolean {+ const previous = record.previousSelection+ // Home and connection have different normal writers. A crash between them+ // may leave exactly this transaction's old/new pair, never a third choice.+ return Boolean(previous && current.operatorOverride === previous.operatorOverride &&+ (current.home === previous.home || current.home === record.request.selection.home) &&+ (current.profile === previous.profile || current.profile === record.request.selection.profile) &&+ (current.connectionId === previous.connectionId || current.connectionId === record.request.selection.connectionId))+}+/** Invoke before normal home selection, and on the existing stable second-instance path. */export async function receiveRetirement(journal: RetirementJournal,@@ -85,7 +185,11 @@ export async function receiveRetirement(const record: RetirementRecord = await journal.read()assertToken(record, token)- if (record.stage !== 'destination-installed' && record.stage !== 'destination-ready') {+ if (+ record.stage !== 'destination-installed' &&+ record.stage !== 'destination-ready' &&+ record.stage !== 'preview-removed'+ ) {throw new Error('Retirement is not awaiting this destination')}@@ -99,7 +203,7 @@ export async function receiveRetirement(}if (record.receiverApplied) {- const active: RetirementExistingSelection | null = await deps.readSelection()+ const active: RetirementExistingSelection | null = await readCurrentSelection(deps)if (active && !sameSelection(active, record.request.selection)) {throw new Error('Stable workspace changed after retirement adoption; explicit forward recovery is required')@@ -109,23 +213,13 @@ export async function receiveRetirement(}await deps.assertCompatibleSnapshot(record)- const current: RetirementExistingSelection | null = await deps.readSelection()-- if (current) {- current.home = await canonicalRetirementPath(current.home)-- if (!sameSelection(current, record.request.selection)) {- const consent: RetirementExistingSelection | undefined = record.request.selection.conflictConsent-- if (- current.operatorOverride ||- !consent ||- !sameSelection(current, { ...consent, choice: 'open-preview', reauthenticate: false })- ) {- throw new Error('Stable workspace conflict: explicit selection consent is required')- }- }+ if (!record.receiverStarted && record.request.selection.choice === 'open-preview' && deps.prepareConnection) {+ record.request.selection = deps.prepareConnection(record.request.selection)+ record.requestDigest = retirementDigest(record.request)}+ const current: RetirementExistingSelection | null = await readCurrentSelection(deps)+ await consentToWorkspace(record, current, deps)+ await journal.assertPaths(record.request)if (!record.receiverStarted) {record.previousSelection = current@@ -133,7 +227,10 @@ export async function receiveRetirement(await journal.write(record)}- await deps.adoptSelection(record, record.previousSelection)+ if (record.request.selection.choice === 'open-preview') {+ await deps.adoptSelection(record, record.previousSelection)+ }+record.receiverApplied = trueawait journal.write(record)@@ -169,7 +266,15 @@ export async function completeRetirementReception(instance: receiverInstance})- await recordRetirementReady(journal, ready)+ await journal.exclusive(async (): Promise<void> => {+ const current: RetirementRecord = await journal.read()+ if (current.stage !== 'destination-installed' || !current.receiverStarted || current.requestDigest !== record.requestDigest) {+ throw new Error('Receiver admission changed before readiness')+ }+ current.ready = ready+ current.stage = 'destination-ready'+ await journal.write(current)+ })return ready}diff --git a/apps/desktop/electron/updater/retirement-state.ts b/apps/desktop/electron/updater/retirement-state.tsindex 637ce257fa5..bc086c5b93a 100644--- a/apps/desktop/electron/updater/retirement-state.ts+++ b/apps/desktop/electron/updater/retirement-state.ts@@ -5,8 +5,10 @@ import type { FileHandle } from 'node:fs/promises'import os from 'node:os'import path from 'node:path'-import { runRetirementCommand } from './retirement-native'import type { ChannelBuild } from './channel-protocol'+import type { PinnedArtifact } from './artifact'+import type { RetirementConnection } from './retirement-connections'+import { runRetirementCommand } from './retirement-native'export type RetirementStage ='prepared' | 'destination-installed' | 'destination-ready' | 'preview-removed' | 'complete'@@ -35,16 +37,25 @@ export interface RetirementSource extends RetirementNativeIdentity {export interface RetirementDestination extends RetirementNativeIdentity {packageFamilyName: string | null- artifact: { url: string; sha256: string; size: number; format: 'zip' | 'msix' | 'msixbundle' }+ artifact: PinnedArtifactcommit: string}+export type RetirementWorkspaceChoice = 'open-preview' | 'keep-stable'++export interface RetirementConsent {+ installStable: true+ removePreview: true+ workspaceChoice: RetirementWorkspaceChoice+}+export interface RetirementSelection {home: stringprofile: stringconnectionId: string- choice: 'open-preview' | 'keep-stable'+ choice: RetirementWorkspaceChoicereauthenticate: boolean+ connection?: RetirementConnectionconflictConsent?: { home: string; profile: string; connectionId: string; operatorOverride: boolean }}@@ -55,7 +66,8 @@ export interface RetirementRequest {source: RetirementSourcedestination: RetirementDestinationselection: RetirementSelection- qualification: { sha256: string; sourceCommit: string; destinationCommit: string; receiverProtocol: 1; sourceBuild?: ChannelBuild }+ sourceBuild: ChannelBuild+ destinationManifestSha256: stringconsent: { install: boolean; removePreview: boolean; replaceExistingStable: boolean }}@@ -175,6 +187,10 @@ export function validateRetirementRequest(request: RetirementRequest): void {}}+ if (!['open-preview', 'keep-stable'].includes(request.selection.choice)) {+ throw new Error('Explicit retirement workspace choice required')+ }+if (!request.selection.connectionId || !request.source.removalRoots.length) {throw new Error('Incomplete retirement state inventory')}@@ -199,12 +215,10 @@ function validateRetirementTarget(request: RetirementRequest): void {}if (- request.qualification.receiverProtocol !== 1 ||- request.qualification.destinationCommit !== destination.commit ||- !/^[a-f0-9]{64}$/.test(request.qualification.sha256) ||- !/^[a-f0-9]{40}$/.test(request.qualification.sourceCommit)+ !/^[a-f0-9]{64}$/.test(request.destinationManifestSha256) ||+ !/^[a-f0-9]{40}$/.test(request.sourceBuild.commit)) {- throw new Error('Missing exact retirement qualification')+ throw new Error('Missing pinned retirement build')}}@@ -300,7 +314,7 @@ export class RetirementJournal {[request.source.appPath, ...request.source.removalRoots].map(canonicalRetirementPath))- for (const candidate of [this.directory, request.selection.home, request.source.home, request.source.userData]) {+ for (const candidate of [this.directory, request.selection.home]) {const canonical: string = await canonicalRetirementPath(candidate)if (roots.some((root: string): boolean => insideRetirementRoot(root, canonical))) {@@ -308,6 +322,19 @@ export class RetirementJournal {}}+ const sourceHome: string = await canonicalRetirementPath(request.source.home)+ if (roots.some(root => insideRetirementRoot(root, sourceHome))) {+ const relocated = await lstat(path.join(this.directory, 'home'))+ if (!relocated.isDirectory() || relocated.isSymbolicLink()) {+ throw new Error('Removal-scoped home has not been preserved')+ }+ }+ // Windows archives all package-private bytes before removal. No other+ // adapter may claim preservation of an Electron credential store it deletes.+ if (request.source.platform !== 'win32' && roots.some(root => insideRetirementRoot(root, request.source.userData))) {+ throw new Error('Desktop credentials are inside the removal footprint')+ }+const sourceApp: string = await canonicalRetirementPath(request.source.appPath)const destinationApp: string = await canonicalRetirementPath(request.destination.appPath)diff --git a/apps/desktop/electron/updater/retirement-windows.ts b/apps/desktop/electron/updater/retirement-windows.tsindex 5dc58faa3f6..742ef66f2e0 100644--- a/apps/desktop/electron/updater/retirement-windows.ts+++ b/apps/desktop/electron/updater/retirement-windows.ts@@ -1,11 +1,12 @@-import path from 'node:path'+import { runRetirementPowerShell } from './retirement-discovery'+import { downloadPinnedArtifact } from './artifact'+import { channelPublicBase } from './channel-protocol'+import { win32AppInstallerFeedPath } from '../app-updater'import { assertNativeRetirementRemoval, type RetirementNativeAdapter } from './retirement'import {assertRunningRetirementStamp,- downloadRetirementArtifact,- type NativeCommandResult,- runRetirementCommand+ type NativeCommandResult} from './retirement-native'import { retirementArgument } from './retirement-receiver'import { canonicalRetirementPath, type RetirementJournal, type RetirementRequest } from './retirement-state'@@ -15,7 +16,7 @@ interface WindowsInstalled {packageFullName: stringappPath: string}-type WindowsOperation = 'install' | 'verify' | 'activate' | 'remove' | 'removed'+type WindowsOperation = 'install' | 'register-updater' | 'verify' | 'activate' | 'remove' | 'removed'// AppX cmdlets and manifest/signature checks follow windows-bundle-smoke.ps1.// The activation COM ABI is IApplicationActivationManager from shobjidl_core.h.@@ -71,8 +72,24 @@ function Assert-NoProcesses($pkg) {$live = @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($pkg.InstallLocation.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) })if ($live.Count) { throw 'Package has live processes; lifecycle owner must stop them' }}-function Assert-Destination {+function Assert-Updater($pkg) {+ $manager=[Windows.Management.Deployment.PackageManager,Windows.Management.Deployment,ContentType=WindowsRuntime]::new()+ $native=$manager.FindPackageForUser('', $pkg.PackageFullName)+ $source=$native.GetAppInstallerInfo()+ if (-not $source -or $source.Uri.AbsoluteUri -cne $p.appInstallerUri) { throw 'Stable App Installer update source mismatch' }+}+function Register-Updater {+ $pkg=Get-ExactPackage $d $true+ Assert-Sideload $pkg+ # Register metadata only: never open a mutable .appinstaller during the+ # pinned handoff. Automatic deployment stays off until an ordinary update.+ Set-AppxPackageAutoUpdateSettings -PackageFamilyName $d.packageFamilyName -AppInstallerUri $p.appInstallerUri -Version $d.nativeVersion -UpdateUris @() -RepairUris @() -OptionalPackages @() -DependencyPackages @() -EnableAutomaticBackgroundTask:$false -ForceUpdateFromAnyVersion:$false -DisableAutoRepairs -CheckOnLaunch:$false -ShowPrompt:$false -UpdateBlocksActivation:$false -UseSystemPolicySource:$false -HoursBetweenUpdateChecks 12 -ErrorAction Stop | Out-Null+ Assert-Updater $pkg+}+function Assert-Destination([bool]$requireUpdater=$true) {$pkg = Get-ExactPackage $d $true+ Assert-Sideload $pkg+ if ($requireUpdater) { Assert-Updater $pkg }if ($pkg.Version.ToString() -cne $d.nativeVersion -or $pkg.PackageFamilyName -cne $d.packageFamilyName -or $pkg.InstallLocation -ine $d.appPath) { throw 'Installed destination binding mismatch' }$manifest = Get-AppxPackageManifest -Package $pkg.PackageFullName$apps = @($manifest.Package.Applications.Application | Where-Object { $_.Id -ceq $d.applicationId })@@ -80,15 +97,16 @@ function Assert-Destination {$exe = [IO.Path]::GetFullPath((Join-Path $pkg.InstallLocation $apps[0].Executable))if (-not $exe.StartsWith($pkg.InstallLocation.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) -or -not (Test-Path -LiteralPath $exe -PathType Leaf)) { throw 'Invalid registered executable' }$stamp = Get-Content -Raw -LiteralPath (Join-Path (Split-Path -Parent $exe) 'resources\install-stamp.json') | ConvertFrom-Json- if ($stamp.commit -cne $d.commit -or $stamp.payload -cne 'bundled' -or $stamp.distribution -cne 'desktop-app' -or $stamp.dirty -ne $false -or $stamp.updateMechanism -cne 'app-installer') { throw 'Destination stamp mismatch' }+ if ($stamp.commit -cne $d.commit -or $stamp.payload -cne 'bundled' -or $stamp.distribution -cne 'desktop-app' -or $stamp.dirty -ne $false -or $stamp.receiverProtocol -ne 1 -or $stamp.updateMechanism -cne 'app-installer') { throw 'Destination stamp mismatch' }return @{ executable=$exe; packageFullName=$pkg.PackageFullName; appPath=$pkg.InstallLocation }}$d = $p.request.destinationswitch ($p.operation) {'install' {+ Get-Command Set-AppxPackageAutoUpdateSettings -ErrorAction Stop | Out-Null$existing = Get-ExactPackage $d $falseif ($existing -and $existing.Version.ToString() -ceq $d.nativeVersion) {- Assert-Destination | ConvertTo-Json -Compress+ Assert-Destination $false | ConvertTo-Json -Compressbreak}if ($existing) {@@ -97,8 +115,14 @@ switch ($p.operation) {Assert-NoProcesses $existing}Assert-Artifact- Add-AppxPackage -Path $p.artifact -ErrorAction Stop- Assert-Destination | ConvertTo-Json -Compress+ $volumes=@(Get-AppxVolume | Where-Object { $_.PackageStorePath.TrimEnd('\') -ieq (Split-Path -Parent $d.appPath) -and -not $_.IsOffline })+ if ($volumes.Count -ne 1) { throw 'Pinned native destination volume is unavailable' }+ Add-AppxPackage -Path $p.artifact -Volume $volumes[0] -ErrorAction Stop+ Assert-Destination $false | ConvertTo-Json -Compress+ }+ 'register-updater' {+ Assert-Destination $false | Out-Null+ Register-Updater}'verify' { Assert-Destination | ConvertTo-Json -Compress }'activate' {@@ -149,7 +173,7 @@ public static class RetirementActivation {}}$sourceStamp = Get-Content -Raw -LiteralPath (Join-Path (Split-Path -Parent $p.request.source.executable) 'resources\install-stamp.json') | ConvertFrom-Json- if ($sourceStamp.commit -cne $p.request.qualification.sourceCommit -or $sourceStamp.distribution -cne 'desktop-app' -or $sourceStamp.payload -cne 'bundled' -or $sourceStamp.updateMechanism -cne 'app-installer') { throw 'Preview source stamp mismatch' }+ if ($sourceStamp.commit -cne $p.request.sourceBuild.commit -or $sourceStamp.distribution -cne 'desktop-app' -or $sourceStamp.payload -cne 'bundled' -or $sourceStamp.updateMechanism -cne 'app-installer') { throw 'Preview source stamp mismatch' }Assert-NoProcesses $sourceRemove-AppxPackage -Package $source.PackageFullName -ErrorAction Stopif (Get-ExactPackage $p.request.source $false) { throw 'Preview package remains registered' }@@ -161,14 +185,25 @@ public static class RetirementActivation {}`+function retirementAppInstallerUri(request: RetirementRequest): string {+ const build = request.sourceBuild+ const base: string = channelPublicBase(build.publicBase)+ if (!request.destination.artifact.url.startsWith(`${base}/`) ||+ new URL(request.destination.artifact.url).origin !== new URL(base).origin) {+ throw new Error('Retirement artifact authority mismatch')+ }+ return `${base}/releases/${win32AppInstallerFeedPath('stable', false)}stable.appinstaller`+}+export class WindowsRetirementAdapter implements RetirementNativeAdapter {+ constructor(private readonly command: (script: string, input: string) => Promise<NativeCommandResult> = runRetirementPowerShell) {}private async run(operation: WindowsOperation,request: RetirementRequest,artifact: string | null = null,journalDirectory: string | null = null): Promise<string> {- if (process.platform !== 'win32' || request.destination.platform !== 'win32') {+ if (request.destination.platform !== 'win32') {throw new Error('Native Windows retirement requires Windows')}@@ -185,25 +220,23 @@ export class WindowsRetirementAdapter implements RetirementNativeAdapter {request,artifact,journalDirectory,+ appInstallerUri: retirementAppInstallerUri(request),argument: retirementArgument(request.id, request.token),receiverExecutable: process.execPath})const script: string = `$p = [Console]::In.ReadToEnd() | ConvertFrom-Json\n${windowsNativeScript}`- const result: NativeCommandResult = await runRetirementCommand(- path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),- ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],- 600_000,- payload- )+ const result: NativeCommandResult = await this.command(script, payload)return result.stdout.trim()}async install(request: RetirementRequest, journal: RetirementJournal): Promise<void> {- const artifact: string = await downloadRetirementArtifact(journal, request.destination)+ const artifact: string = await downloadPinnedArtifact(journal.directory, request.destination.artifact)await this.run('install', request, artifact)+ await this.run('register-updater', request)+ await this.verifyDestination(request)}async verifyDestination(request: RetirementRequest): Promise<void> {diff --git a/apps/desktop/electron/updater/retirement.test.ts b/apps/desktop/electron/updater/retirement.test.tsindex dde592abd1d..9d49ee260fd 100644--- a/apps/desktop/electron/updater/retirement.test.ts+++ b/apps/desktop/electron/updater/retirement.test.ts@@ -77,11 +77,14 @@ async function fixture(): Promise<{commit: 'd'.repeat(40)},selection: { home, profile: 'default', connectionId: 'local', choice: 'open-preview', reauthenticate: false },- qualification: {- sha256: 'e'.repeat(64),- sourceCommit: 'f'.repeat(40),- destinationCommit: 'd'.repeat(40),- receiverProtocol: 1+ destinationManifestSha256: 'e'.repeat(64),+ sourceBuild: {+ buildId: '1'.repeat(32), channel: 'preview', sequence: 1, repository: 'NousResearch/hermes-agent',+ commit: 'f'.repeat(40), version: '0.0.1', sourceVersion: '1.2.2', windowsVersion: '0.0.1.0',+ publicBase: 'https://example.com', bundleEnv: {},+ identity: { token: '2'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview',+ appNamePascal: 'Preview', artifactNamePascal: 'Preview', cliName: 'preview',+ windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }},consent: { install: true, removePreview: true, replaceExistingStable: false }}@@ -90,7 +93,7 @@ async function fixture(): Promise<{const store: RetirementJournal = await RetirementJournal.open(path.join(directory, 'transactions'), request.id)const deps: RetirementDependencies = {- assertQualified: async (): Promise<void> => {+ assertAdmitted: async (): Promise<void> => {calls.push('qualified')},prepareState: async (): Promise<{ snapshotHome: string; selectedHome: string }> => {@@ -98,7 +101,6 @@ async function fixture(): Promise<{return { snapshotHome: snapshot, selectedHome: home }},- acquireLifecycle: async (): Promise<() => Promise<void>> => async (): Promise<void> => {},assertSourceQuiescent: async (): Promise<void> => {calls.push('quiescent')},@@ -249,34 +251,38 @@ test('cancel, backup failure and removal-scoped state do not reach native instalexpect(await readFile(path.join(request.source.home, 'witness'), 'utf8')).toBe('preserve me')})-test('activation can enter the receiver and interruption after native removal does not remove twice', async (): Promise<void> => {- const { store, request, calls, deps } = await fixture()- await prepareRetirement(store, request, deps)- const receiver: RetirementReceiverDependencies = receiverDeps(request, calls)+test.each(['preview-removed', 'complete'] as const)(+ 'activation can enter the receiver and interruption before %s does not remove twice',+ async (failedStage): Promise<void> => {+ const { store, request, calls, deps } = await fixture()+ await prepareRetirement(store, request, deps)+ const receiver: RetirementReceiverDependencies = receiverDeps(request, calls)- deps.native.activate = async (): Promise<void> => {- await receiveRetirement(store, request.token, receiver)- }+ deps.native.activate = async (): Promise<void> => {+ await receiveRetirement(store, request.token, receiver)+ }- await resumeRetirement(store, deps, 'source')- await completeRetirementReception(store, request.token, receiver)- const write: RetirementJournal['write'] = store.write.bind(store)+ await resumeRetirement(store, deps, 'source')+ await completeRetirementReception(store, request.token, receiver)+ const write: RetirementJournal['write'] = store.write.bind(store)- store.write = async (record: RetirementRecord): Promise<void> => {- if (record.stage === 'preview-removed') {- throw new Error('power loss before journal rename')+ store.write = async (record: RetirementRecord): Promise<void> => {+ if (record.stage === failedStage) {+ throw new Error('power loss before journal rename')+ }++ await write(record)}- await write(record)+ expect((await resumeRetirement(store, deps, 'destination')).status).toBe('cleanup-pending')+ expect((await store.read()).stage).toBe(failedStage === 'preview-removed' ? 'destination-ready' : 'preview-removed')+ store.write = write+ const reopened: RetirementJournal = await RetirementJournal.open(store.root, request.id)+ await receiveRetirement(reopened, request.token, receiver)+ expect((await resumeRetirement(reopened, deps, 'destination')).status).toBe('complete')+ expect(calls.filter((call: string): boolean => call === 'remove')).toHaveLength(1)}-- expect((await resumeRetirement(store, deps, 'destination')).status).toBe('cleanup-pending')- expect((await store.read()).stage).toBe('destination-ready')- store.write = write- const reopened: RetirementJournal = await RetirementJournal.open(store.root, request.id)- expect((await resumeRetirement(reopened, deps, 'destination')).status).toBe('complete')- expect(calls.filter((call: string): boolean => call === 'remove')).toHaveLength(1)-})+)test('an installed target without a correlated ready receipt never authorizes removal, including restart', async (): Promise<void> => {const { store, request, calls, deps } = await fixture()diff --git a/apps/desktop/electron/updater/retirement.ts b/apps/desktop/electron/updater/retirement.tsindex 7581ea064dc..d8f985c4607 100644--- a/apps/desktop/electron/updater/retirement.ts+++ b/apps/desktop/electron/updater/retirement.ts@@ -1,10 +1,11 @@+import { setTimeout as delay } from 'node:timers/promises'+import {assertRetirementReady,canonicalRetirementPath,insideRetirementRoot,retirementDigest,type RetirementJournal,- type RetirementReady,type RetirementRecord,type RetirementRequest,type RetirementStateSnapshot,@@ -21,11 +22,10 @@ export interface RetirementNativeAdapter {export interface RetirementDependencies {native: RetirementNativeAdapter- /** Verify the authority's exact cohort coverage, not only a version floor. */- assertQualified(request: RetirementRequest): Promise<void>+ /** Revalidate the authority's immutable receiver pin. */+ assertAdmitted(request: RetirementRequest): Promise<void>/** Quiesced private snapshot plus preservation of any removal-scoped state. */prepareState(request: RetirementRequest, journal: RetirementJournal): Promise<RetirementStateSnapshot>- acquireLifecycle(request: RetirementRequest): Promise<() => Promise<void>>/** Use lifecycle ownership. Do not kill a supervised or unrelated backend. */assertSourceQuiescent(request: RetirementRequest): Promise<void>/** Re-probe the current destination instance and selected backend on every cleanup retry. */@@ -37,6 +37,39 @@ export type RetirementOutcome =| { status: 'cleanup-pending'; error: string; forwardOnly: true }| { status: 'complete'; forwardOnly: true }+export interface RetirementReadinessProbe {+ home: string+ profile: () => string+ connectionId: () => string+ rendererMounted: () => boolean+ /** Must exercise the selected authenticated backend, not its public health endpoint. */+ backend: () => Promise<void>+}++export async function verifyRetirementReadiness(record: RetirementRecord, probe: RetirementReadinessProbe): Promise<void> {+ if (probe.home !== record.state.selectedHome || probe.profile() !== record.request.selection.profile ||+ probe.connectionId() !== record.request.selection.connectionId) {+ throw new Error('The destination is not using the consented workspace and connection')+ }+ if (!probe.rendererMounted()) { throw new Error('Waiting for the stable renderer to mount') }+ await probe.backend()+}++/** One bounded recovery loop covers both backend startup and lagging native release. */+export async function awaitRetirementCleanup(complete: () => Promise<RetirementOutcome>): Promise<RetirementOutcome> {+ const deadline: number = Date.now() + 120_000+ let message: string = 'Stable did not become ready'+ while (Date.now() < deadline) {+ try {+ const result: RetirementOutcome = await complete()+ if (result.status !== 'cleanup-pending') { return result }+ message = result.error+ } catch (error) { message = error instanceof Error ? error.message : String(error) }+ await delay(1000)+ }+ return { status: 'cleanup-pending', forwardOnly: true, error: message }+}+export async function prepareRetirement(journal: RetirementJournal,request: RetirementRequest,@@ -48,74 +81,69 @@ export async function prepareRetirement(throw new Error('Retirement transaction ID mismatch')}- await deps.assertQualified(request)+ await deps.assertAdmitted(request)return journal.exclusive(async (): Promise<RetirementRecord> => {+ let existing: RetirementRecord | null = nulltry {- const existing: RetirementRecord = await journal.read()+ existing = await journal.read()if (existing.requestDigest !== retirementDigest(request)) {throw new Error('Transaction already binds another request')}- return existing+ if (existing.receiverStarted) { return existing }} catch (error) {if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') {throw error}}- const release: () => Promise<void> = await deps.acquireLifecycle(request)-- try {- await deps.assertSourceQuiescent(request)- const state: RetirementStateSnapshot = await deps.prepareState(request, journal)+ await deps.assertSourceQuiescent(request)+ const state: RetirementStateSnapshot = await deps.prepareState(request, journal)- const snapshot: string = await canonicalRetirementPath(state.snapshotHome)+ const snapshot: string = await canonicalRetirementPath(state.snapshotHome)- for (const live of [- request.source.home,- request.selection.home,- request.source.appPath,- request.destination.appPath- ]) {- const canonical: string = await canonicalRetirementPath(live)+ for (const live of [+ request.source.home,+ request.selection.home,+ request.source.appPath,+ request.destination.appPath+ ]) {+ const canonical: string = await canonicalRetirementPath(live)- if (insideRetirementRoot(canonical, snapshot) || insideRetirementRoot(snapshot, canonical)) {- throw new Error('Compatibility snapshot must be separate from live state and application roots')- }+ if (insideRetirementRoot(canonical, snapshot) || insideRetirementRoot(snapshot, canonical)) {+ throw new Error('Compatibility snapshot must be separate from live state and application roots')}+ }- if (state.selectedHome !== request.selection.home) {- throw new Error('Preserved home must be consented before preparation')- }+ if (state.selectedHome !== request.selection.home) {+ throw new Error('Preserved home must be consented before preparation')+ }- await journal.assertPaths(request)-- const record: RetirementRecord = {- request,- requestDigest: retirementDigest(request),- stage: 'prepared',- state,- receiverStarted: false,- receiverApplied: false,- previousSelection: null,- ready: null- }+ await journal.assertPaths(request)++ const record: RetirementRecord = {+ request,+ requestDigest: retirementDigest(request),+ stage: existing?.stage ?? 'prepared',+ state,+ receiverStarted: false,+ receiverApplied: false,+ previousSelection: null,+ ready: null+ }- await journal.write(record)+ await journal.write(record)- return record- } finally {- await release()- }+ return record})}/** Source stops after activation. Stable owns cleanup, outside the source package. */export async function resumeRetirement(journal: RetirementJournal,- deps: RetirementDependencies,+ deps: Omit<RetirementDependencies, 'prepareState'>,caller: 'source' | 'destination'): Promise<RetirementOutcome> {const outcome: RetirementOutcome = await journal.exclusive(async (): Promise<RetirementOutcome> => {@@ -126,7 +154,7 @@ export async function resumeRetirement(}await journal.assertPaths(record.request)- await deps.assertQualified(record.request)+ await deps.assertAdmitted(record.request)if (record.stage === 'prepared') {if (caller !== 'source') {@@ -157,30 +185,24 @@ export async function resumeRetirement(assertRetirementReady(record, record.ready)await deps.native.verifyDestination(record.request)await deps.assertDestinationReady(record)- const release: () => Promise<void> = await deps.acquireLifecycle(record.request)-- try {- await deps.assertSourceQuiescent(record.request)+ await deps.assertSourceQuiescent(record.request)- if (record.stage === 'destination-ready') {- if (!(await deps.native.isPreviewRemoved(record.request))) {- await deps.native.removePreview(record.request, journal)- }-- if (!(await deps.native.isPreviewRemoved(record.request))) {- throw new Error('Native preview removal is still pending')- }+ if (record.stage === 'destination-ready') {+ if (!(await deps.native.isPreviewRemoved(record.request))) {+ await deps.native.removePreview(record.request, journal)+ }- record.stage = 'preview-removed'- await journal.write(record)+ if (!(await deps.native.isPreviewRemoved(record.request))) {+ throw new Error('Native preview removal is still pending')}- record.stage = 'complete'+ record.stage = 'preview-removed'await journal.write(record)- } finally {- await release()}+ record.stage = 'complete'+ await journal.write(record)+return { status: 'complete', forwardOnly: true }} catch (error) {return {@@ -214,18 +236,3 @@ export async function assertNativeRetirementRemoval(assertRetirementReady(record, record.ready)}--export async function recordRetirementReady(journal: RetirementJournal, ready: RetirementReady): Promise<void> {- await journal.exclusive(async (): Promise<void> => {- const record: RetirementRecord = await journal.read()- assertRetirementReady(record, ready)-- if (record.stage !== 'destination-installed' || !record.receiverStarted) {- throw new Error('Receiver has not admitted this retirement')- }-- record.ready = ready- record.stage = 'destination-ready'- await journal.write(record)- })-}diff --git a/apps/desktop/scripts/write-build-stamp.mjs b/apps/desktop/scripts/write-build-stamp.mjsindex cf0758a96da..1e3ef81a32a 100644--- a/apps/desktop/scripts/write-build-stamp.mjs+++ b/apps/desktop/scripts/write-build-stamp.mjs@@ -231,6 +231,13 @@ export function buildStampPayload(stamp, env = process.env, platform = process.p}if (channelBuild) base.channelBuild = channelBuild+ // Rehearsal receivers use the real stable update path, never preview resolution.+ if (channelBuild?.receiverCandidate) {+ delete base.channelBuild+ base.source = 'build'+ base.displayVersion = channelBuild.version+ }+ if (variant === 'bundled') base.receiverProtocol = 1const updateMechanism = {'': 'self',@@ -249,8 +256,9 @@ export function buildStampPayload(stamp, env = process.env, platform = process.p...base,payload: variant === "store" ? "bundled" : variant || "bootstrap",distribution: "desktop-app",+updateMechanism: commitBuild ? 'external' : updateMechanism,- tag: env.HERMES_PAYLOAD_TAG || null,+ tag: channelBuild?.receiverCandidate ? channelBuild.releaseTag : env.HERMES_PAYLOAD_TAG || null,...(bundled ? { runtime: payload.runtime } : {})}}diff --git a/apps/desktop/src/app/retirement-view.tsx b/apps/desktop/src/app/retirement-view.tsxindex 9af9447e90d..301cd2b8b4f 100644--- a/apps/desktop/src/app/retirement-view.tsx+++ b/apps/desktop/src/app/retirement-view.tsx@@ -1,36 +1,85 @@-import { useState, type ReactElement } from 'react'+import { type ReactElement, useState } from 'react'import { Button } from '@/components/ui/button'import { DialogDescription, DialogTitle } from '@/components/ui/dialog'-import type { DesktopUpdateStatus } from '@/global'+import type { DesktopRetirementConsent, DesktopUpdateStatus } from '@/global'import { useI18n } from '@/i18n'import { applyRetirement } from '@/store/updates'-export function RetirementView({ retirement, onLater, onRetry }: {+export function RetirementView({+ retirement,+ onLater,+ onRetry+}: {retirement: NonNullable<DesktopUpdateStatus['retirement']>onLater: () => voidonRetry: () => void}): ReactElement {const { t } = useI18n()const [consented, setConsented] = useState<boolean>(false)+ const [workspaceChoice, setWorkspaceChoice] = useState<DesktopRetirementConsent['workspaceChoice'] | null>(null)const available: boolean = retirement.state === 'available' || retirement.state === 'cleanup-pending'+return (<div className="space-y-4 p-6"><DialogTitle>{t.updates.retirementTitle}</DialogTitle><DialogDescription>{t.updates.retirementBody}</DialogDescription>- <p className="text-sm font-medium">{retirement.destination} · {retirement.version}</p>- {retirement.message && <p role="status" className="text-sm text-muted-foreground">{retirement.message}</p>}+ <p className="text-sm font-medium">+ {retirement.destination} · {retirement.version}+ </p>+ {retirement.message && (+ <p className="text-sm text-muted-foreground" role="status">+ {retirement.message}+ </p>+ )}{available ? (- <label className="flex items-start gap-2 text-sm">- <input type="checkbox" checked={consented} onChange={event => setConsented(event.currentTarget.checked)} />- {t.updates.retirementConsent}- </label>- ) : <p className="text-sm">{retirement.state === 'complete' ? t.updates.retirementComplete : t.updates.retirementBlocked}</p>}+ <div className="space-y-3 text-sm">+ <label className="flex items-start gap-2">+ <input+ checked={workspaceChoice === 'keep-stable'}+ name="retirement-workspace"+ onChange={() => setWorkspaceChoice('keep-stable')}+ type="radio"+ />+ {t.updates.retirementKeepStable}+ </label>+ <label className="flex items-start gap-2">+ <input+ checked={workspaceChoice === 'open-preview'}+ name="retirement-workspace"+ onChange={() => setWorkspaceChoice('open-preview')}+ type="radio"+ />+ {t.updates.retirementOpenPreview}+ </label>+ <label className="flex items-start gap-2">+ <input checked={consented} onChange={event => setConsented(event.currentTarget.checked)} type="checkbox" />+ {t.updates.retirementConsent}+ </label>+ </div>+ ) : (+ <p className="text-sm">+ {retirement.state === 'complete' ? t.updates.retirementComplete : t.updates.retirementBlocked}+ </p>+ )}<div className="flex justify-end gap-2">- <Button variant="text" onClick={onLater}>{t.updates.maybeLater}</Button>- {available- ? <Button disabled={!consented} onClick={() => void applyRetirement()}>{t.updates.retirementAction}</Button>- : <Button onClick={onRetry}>{t.updates.tryAgain}</Button>}+ <Button onClick={onLater} variant="text">+ {t.updates.maybeLater}+ </Button>+ {available ? (+ <Button+ disabled={!consented || !workspaceChoice}+ onClick={() => {+ if (workspaceChoice) {+ void applyRetirement(workspaceChoice)+ }+ }}+ >+ {t.updates.retirementAction}+ </Button>+ ) : (+ <Button onClick={onRetry}>{t.updates.tryAgain}</Button>+ )}</div></div>)diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsxindex c19cb1e8878..5259039d603 100644--- a/apps/desktop/src/components/update-status.tsx+++ b/apps/desktop/src/components/update-status.tsx@@ -37,23 +37,47 @@ export interface UpdateStatusView {supported: boolean}+function retirementStatus(+ retirement: NonNullable<DesktopUpdateStatus['retirement']>,+ applying: boolean,+ supported: boolean,+ u: Translations['updates']+): UpdateStatusView {+ const available: boolean = retirement.state === 'available' || retirement.state === 'cleanup-pending'+ const line: string = applying ? u.retirementMoving : retirement.state === 'complete' ? u.retirementComplete : u.retirementTitle++ return { applying, supported, updateAvailable: false, tone: available ? 'available' : 'error', line, error: retirement.message }+}+/*** One status derivation for every "am I up to date?" surface (About page,* updates overlay). Pure so the tone/copy contract is unit-testable.*/-export function deriveUpdateStatus({- apply,- checking,- status,- target,- u-}: {+interface UpdateStatusInput {apply: UpdateApplyStatechecking: booleanstatus: DesktopUpdateStatus | nulltarget: UpdateTargetu: Translations['updates']-}): UpdateStatusView {+}++export function deriveUpdateStatus(input: UpdateStatusInput): UpdateStatusView {+ const { apply, status, target, u } = input++ if (target === 'client' && status?.retirement) {+ return retirementStatus(status.retirement, apply.applying || apply.stage === 'restart', status.supported !== false, u)+ }++ return ordinaryUpdateStatus(input)+}++function ordinaryUpdateStatus({+ apply,+ checking,+ status,+ target,+ u+}: UpdateStatusInput): UpdateStatusView {const behind = status?.behind ?? 0// behind is null when the exact count is unknowable (shallow clone): the// backend flags that case via updateAvailable instead of a number.@@ -61,14 +85,6 @@ export function deriveUpdateStatus({const supported = status?.supported !== falseconst applying = apply.applying || apply.stage === 'restart'- if (target === 'client' && status?.retirement) {- const retirement = status.retirement- const available: boolean = retirement.state === 'available' || retirement.state === 'cleanup-pending'- return { applying, supported, updateAvailable: false, tone: available ? 'available' : 'error',- line: applying ? u.retirementMoving : retirement.state === 'complete' ? u.retirementComplete : u.retirementTitle,- error: retirement.message }- }-if (!supported) {return { applying, line: status?.message ?? u.unsupportedMessage, supported, tone: 'unsupported', updateAvailable }}@@ -206,6 +222,30 @@ export function VersionHero({)}+interface UpdateActionsProps {+ retirement: boolean+ target: UpdateTarget+ u: Translations['updates']+ view: UpdateStatusView+}++function UpdateActions({ retirement, target, u, view }: UpdateActionsProps): ReactElement | null {+ if (view.applying) { return null }++ if (retirement) {+ return <Button onClick={() => openUpdateOverlayFor('client')} size="sm">{u.retirementAction}</Button>+ }++ if (!view.updateAvailable || !view.supported) { return null }++ return (+ <>+ <Button onClick={() => startActiveUpdate(target)} size="sm">{u.updateNow}</Button>+ <Button onClick={() => openUpdateOverlayFor(target)} size="sm" variant="textStrong">{u.seeWhatsNew}</Button>+ </>+ )+}+/*** The bordered update-state card (status line, last-checked age, check /* update / release-notes actions) in the About page's visual language.@@ -275,19 +315,7 @@ export function UpdateStatusCard({{checking ? u.checkingShort : u.checkNow}</Button>- {!isBackend && status?.retirement && !view.applying && (- <Button onClick={() => openUpdateOverlayFor('client')} size="sm">{u.retirementAction}</Button>- )}- {view.updateAvailable && view.supported && !view.applying && (- <>- <Button onClick={() => startActiveUpdate(target)} size="sm">- {u.updateNow}- </Button>- <Button onClick={() => openUpdateOverlayFor(target)} size="sm" variant="textStrong">- {u.seeWhatsNew}- </Button>- </>- )}+ <UpdateActions retirement={!isBackend && Boolean(status?.retirement)} target={target} u={u} view={view} />{showReleaseNotes && (<Button asChild className="ml-auto" size="sm" variant="text">diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 0f399d86770..6cd6d968d3e 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -558,7 +558,7 @@ declare global {updates: {check: (opts?: { force?: boolean }) => Promise<DesktopUpdateStatus>apply: (opts?: DesktopUpdateApplyOptions) => Promise<DesktopUpdateApplyResult>- retire: (consent: { installStable: true; removePreview: true }) => Promise<DesktopUpdateApplyResult>+ retire: (consent: DesktopRetirementConsent) => Promise<DesktopUpdateApplyResult>getBranch: () => Promise<{ branch: string }>setBranch: (name: string) => Promise<{ branch: string }>onProgress: (callback: (payload: DesktopUpdateProgress) => void) => () => void@@ -755,6 +755,12 @@ export type UpdaterMechanismClient =| 'posix-handoff'| 'manual'+export interface DesktopRetirementConsent {+ installStable: true+ removePreview: true+ workspaceChoice: 'keep-stable' | 'open-preview'+}+export interface DesktopUpdateStatus {supported: booleanretirement?: {diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex fc93d775424..61603212826 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2243,6 +2243,8 @@ export const ar = defineLocale({}},updates: {+ retirementKeepStable: 'الاحتفاظ بمساحة العمل الحالية للإصدار المستقر',+ retirementOpenPreview: 'فتح مساحة عمل هذا الإصدار التجريبي في الإصدار المستقر',channels: { stable: 'مستقر', canary: 'تجريبي' },bundleSwapPending: 'أعد التشغيل لإكمال التحديث',bundleSwapPendingDesc: 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 0785d40d8cd..bd4643b9bf1 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3083,9 +3083,11 @@ export const en: Translations = {updates: {retirementTitle: 'This preview channel has closed',- retirementBody: 'Move to the official stable app. Your local workspace stays in place. Stable must open it successfully before this preview is removed. Saved remote credentials are not copied.',+ retirementBody: 'Move to the official stable app. Both workspaces stay in place. Stable must open your chosen workspace successfully before this preview is removed. Saved remote credentials are not copied.',retirementAction: 'Move to stable',retirementConsent: 'Install or update stable and remove this preview only after stable is ready.',+ retirementKeepStable: 'Keep stable’s existing workspace',+ retirementOpenPreview: 'Open this preview workspace in stable',retirementBlocked: 'Migration paused — preview preserved',retirementMoving: 'Moving to stable…',retirementComplete: 'Stable is ready',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex a4f664089d0..7182ba75c4d 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2610,6 +2610,8 @@ export const ja = defineLocale({},updates: {+ retirementKeepStable: '安定版の既存のワークスペースを維持する',+ retirementOpenPreview: 'このプレビュー版のワークスペースを安定版で開く',channels: { stable: '安定版', canary: '先行版' },bundleSwapPending: '再起動して更新を完了',bundleSwapPendingDesc: '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 150880e0bcc..921b56f5943 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2661,6 +2661,8 @@ export interface Translations {retirementBody: stringretirementAction: stringretirementConsent: string+ retirementKeepStable: string+ retirementOpenPreview: stringretirementBlocked: stringretirementMoving: stringretirementComplete: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex f56bbe89b62..44a5cd07115 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2521,6 +2521,8 @@ export const zhHant = defineLocale({},updates: {+ retirementKeepStable: '保留穩定版現有的工作區',+ retirementOpenPreview: '在穩定版中開啟此預覽版工作區',channels: { stable: '穩定版', canary: '預覽版' },bundleSwapPending: '重新啟動以完成更新',bundleSwapPendingDesc: '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex bac6756a0b4..ffba565c213 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3238,6 +3238,8 @@ export const zh = defineLocale({},updates: {+ retirementKeepStable: '保留稳定版现有的工作区',+ retirementOpenPreview: '在稳定版中打开此预览版工作区',channels: { stable: '稳定版', canary: '预览版' },bundleSwapPending: '重启以完成更新',bundleSwapPendingDesc: '更新后的应用已安装完成,只需重启 Hermes 即可加载新版本。聊天记录和设置不会受到影响。',diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.tsindex d84c387b296..a86b0933bd0 100644--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@ -7,6 +7,7 @@ import { atom } from 'nanostores'import { connectionScoped, profileScoped } from '@/api/client'import type {+ DesktopRetirementConsent,DesktopUpdateApplyOptions,DesktopUpdateApplyResult,@@ -470,8 +471,10 @@ export async function checkUpdates({ force = false }: UpdateCheckOptions = {}):export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promise<DesktopUpdateApplyResult> {if ($updateStatus.get()?.retirement) {openUpdateOverlayFor('client')+return { ok: false, error: 'retirement-consent-required' }}+const bridge = window.hermesDesktop?.updatesif (!bridge) {@@ -577,24 +580,30 @@ export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promis}/** Only the dedicated consent view calls the retirement IPC; ordinary update stays separate. */-export async function applyRetirement(): Promise<DesktopUpdateApplyResult> {+export async function applyRetirement(workspaceChoice: DesktopRetirementConsent['workspaceChoice']): Promise<DesktopUpdateApplyResult> {const bridge = window.hermesDesktop?.updatesconst status: DesktopUpdateStatus | null = $updateStatus.get()+if (!bridge?.retire || !status?.retirement || $updateApply.get().applying) {return { ok: false, error: 'retirement-unavailable' }}+$updateApply.set({ ...IDLE, applying: true, stage: 'prepare', message: translateNow('updates.retirementMoving') })+try {- const result: DesktopUpdateApplyResult = await bridge.retire({ installStable: true, removePreview: true })+ const result: DesktopUpdateApplyResult = await bridge.retire({ installStable: true, removePreview: true, workspaceChoice })+if (result.handedOff) { return result }$updateApply.set(IDLE)$updateStatus.set({ ...status, retirement: { ...status.retirement, state: result.ok ? 'complete' : 'conflict',message: result.message ?? result.error } })+return result} catch (error) {const message: string = error instanceof Error ? error.message : String(error)$updateApply.set(IDLE)$updateStatus.set({ ...status, retirement: { ...status.retirement, state: 'conflict', message } })+return { ok: false, error: 'retirement-blocked', message }}}diff --git a/docs/stable-releases.md b/docs/stable-releases.mdindex 8d992e03737..7ceea335f64 100644--- a/docs/stable-releases.md+++ b/docs/stable-releases.md@@ -125,6 +125,17 @@ before the channel head advances.Preview a custom build, then explicitly dispatch it:+For an official release-authority remote, use the existing publisher configuration.+Fork channel administration requires a disposable allocation first; even a local+command refuses to read or write the unscoped release namespace. Dispatch the+desktop workflow with `disposable_channel` and `build_commit`, then use the exact+scoped build command in its summary. For local administration of that allocation,+carry its `R2_DISPOSABLE_RUN` and `GITHUB_REPOSITORY_ID` in the command environment,+with the configured public URL still at the unscoped root. These are test-run+inputs, not persistent application settings; the repository ID is checked against+the selected remote before credentials are read. The examples using `fork` below+assume that allocation scope is present.+```shpython scripts/release.py --channel pm-preview --build-commit my-branch --remote forkpython scripts/release.py --channel pm-preview --build-commit my-branch --remote fork --publish@@ -139,19 +150,26 @@ Conditional writes reject stale publication and permanently retired channels.Use the printed build ID and request digest with `--resume-channel-build` and`--request-sha256` to retry an admitted request rather than allocate another one.-Retirement names an official destination and immutable native qualification:+Retirement pins the current official stable build as the first receiver:```text-python scripts/release.py --retire-channel pm-preview --to stable --minimum-version VERSION --compatibility-key KEY --compatibility-sha256 SHA256 --remote fork+python scripts/release.py --retire-channel pm-preview --to stable --minimum-version VERSION --remote fork```Add `--publish` only after reviewing the dry run and the exact native acceptanceevidence. This does not rebuild stable under the preview identity or silentlyuninstall clients. Protocol-aware clients offer a consented cross-applicationhandoff; the destination must confirm readiness before preview removal. Keep-the retirement object and qualified artifacts available for offline clients.+the retirement object and pinned artifacts available for offline clients.Existing one-off builds have no retirement reader and require replacement.+The destination manifest must declare receiver support read from its packaged+stamp. The existing protected release workflow owns acceptance; there is no+separate public certification document or dependency on expiring Actions artifacts.+Native signature and identity checks, recipient consent, preserved-state preflight,+and destination readiness remain mandatory. An offline preview reaches its pinned+first receiver even after stable advances; that app then updates through stable.+Before shipping R2-only source readers, seed the existing `main` source-branchrecord and published stable/canary records through the explicit protectedbootstrap operation. Review actual accepted manifests; do not invent a nativediff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex dab404edb26..86c753687af 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -262,6 +262,19 @@ def _is_non_regular_path(path: Path) -> bool:return False+def _is_link_path(path: Path) -> bool:+ """True for symlinks and Windows junctions/reparse points — the only+ directory entries a strict walk must never descend (os.walk already+ refuses POSIX dir symlinks; this also covers junctions, which it follows)."""+ try:+ info = path.lstat()+ except OSError:+ return False+ if stat.S_ISLNK(info.st_mode):+ return True+ return os.name == "nt" and bool(getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT)++def _should_exclude(rel_path: Path) -> bool:"""Return True if *rel_path* (relative to hermes root) should be skipped."""parts = rel_path.parts@@ -274,14 +287,18 @@ def _should_exclude(rel_path: Path) -> bool:return name in _EXCLUDED_NAMES or name.startswith(_EXCLUDED_PREFIXES) or name.endswith(_EXCLUDED_SUFFIXES)-def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optional[set] = None):+def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optional[set] = None, *, strict: bool = False):"""Yield ``(abs_path, rel_path)`` for every file a full backup should hold.The one owner of the walk policy (directory pruning so os.walk never descends a multi-GBexcluded tree, the root-only ``hermes-agent`` carve-out, root runtime trees, per-file rules),shared by ``hermes backup`` and the pre-update / pre-migration path so they can never drift."""- for dirpath, dirnames, filenames in os.walk(hermes_root, followlinks=False):+ def walk_error(error: OSError) -> None:+ if strict:+ raise error++ for dirpath, dirnames, filenames in os.walk(hermes_root, followlinks=False, onerror=walk_error):rel_dir = Path(dirpath).relative_to(hermes_root)is_root = rel_dir == Path(".")kept = [@@ -290,13 +307,19 @@ def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optionaland not _in_excluded_root_dir(rel_dir / d)]if skipped_dirs is not None:skipped_dirs.update(str(rel_dir / d) for d in set(dirnames) - set(kept))- dirnames[:] = kept+ if strict:+ for name in kept:+ yield Path(dirpath) / name, rel_dir / name+ # Migration inventories links themselves; no walk may follow a junction.+ dirnames[:] = [name for name in kept if not _is_link_path(Path(dirpath) / name)]for fname in filenames:rel = rel_dir / fnamefpath = hermes_root / rel# zipfile.write() follows file symlinks, so skip links before any archive write can# copy data from outside HERMES_HOME; never archive the output zip into itself.- if _should_exclude(rel) or _is_non_regular_path(fpath):+ if _should_exclude(rel):+ continue+ if not strict and _is_non_regular_path(fpath):continuewith suppress(OSError, ValueError):if fpath.resolve() == out_path.resolve():diff --git a/hermes_cli/release_channels.py b/hermes_cli/release_channels.pyindex c34e32e727c..b38f11d66c5 100644--- a/hermes_cli/release_channels.py+++ b/hermes_cli/release_channels.py@@ -11,7 +11,7 @@ from urllib.request import HTTPRedirectHandler, Request, build_openerMAX_SEQUENCE = 2**32 - 1MAX_METADATA = 4 * 1024 * 1024-MAX_HOPS = 16+_POLICIES = ("preview", "stable-release", "canary-release", "source-branch")_RESERVED = {"con", "prn", "aux", "nul", *(f"com{i}" for i in range(1, 10)),*(f"lpt{i}" for i in range(1, 10))}@@ -151,7 +151,10 @@ def validate_request(value: object, *, repository: str | None = None,_match(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-canary\.[0-9]+)?", request.get("releaseTag"), "legacy release tag")if request.get("version") != request["releaseTag"][1:]:raise ChannelError("Legacy package version mismatch")- quad = _match(r"[0-9]+\.[0-9]+\.[0-9]+\.0", request.get("windowsVersion"), "Windows version")+ # Canary revisions encode minutes since the stable baseline; only stable+ # packages reserve revision zero.+ pattern = r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" if policy == "canary-release" else r"[0-9]+\.[0-9]+\.[0-9]+\.0"+ quad = _match(pattern, request.get("windowsVersion"), "Windows version")if any(int(part) > 65535 for part in quad.split(".")):raise ChannelError("Invalid Windows version")validate_identity(request.get("identity"))@@ -212,8 +215,10 @@ def validate_record(value: object, *, name: str | None = None, repository: str |if record["state"] == "retired":validate_name(record.get("destination"))_match(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", record.get("minimumVersion"), "retirement minimum version")- artifact_key(record.get("compatibilityKey"))- require_sha256(record.get("compatibilitySha256"))+ if _head(record.get("destinationHead")) is None:+ raise ChannelError("Retirement requires a pinned destination head")+ if type(record.get("receiverProtocol")) is not int or record["receiverProtocol"] != 1:+ raise ChannelError("Unsupported retirement receiver protocol")if _head(record.get("lastHead")) != head:raise ChannelError("Retirement last head mismatch")return record@@ -224,7 +229,7 @@ class ChannelResolution:requested: dictterminal: dictmanifest: dict | None- constraints: tuple[dict, ...] = ()+class _NoRedirect(HTTPRedirectHandler):@@ -264,51 +269,38 @@ class ChannelReader:def resolve(self, name: str) -> ChannelResolution:requested = record = self.read_record(name)- seen, retired = set(), []- while record["state"] == "retired":- if record["name"] in seen or record["destination"] in seen or record["destination"] == record["name"]:++ if record["state"] == "retired":+ if record["destination"] == name:raise ChannelError("Channel retirement cycle")- seen.add(record["name"])- if len(seen) >= MAX_HOPS:- raise ChannelError("Channel retirement hop limit exceeded")- retired.append(record)record = self.read_record(record["destination"])if record["repository"].casefold() != requested["repository"].casefold():raise ChannelError("Retirement repository authority mismatch")- constraints = tuple({"channel": item["name"], "destination": item["destination"],- "minimumVersion": item["minimumVersion"],- "compatibilityKey": item["compatibilityKey"],- "compatibilitySha256": item["compatibilitySha256"],- "qualification": decode_json(self.read_bytes(item["compatibilityKey"], item["compatibilitySha256"]))}- for item in retired)+ if record["state"] != "active" or record["policy"] != "stable-release":+ raise ChannelError("Retirement requires a directly active stable-release destination")head = record["head"]- if constraints:- # Stable may advance while a preview is offline. Migrate to the exact- # qualified build first; its own subscription can then update normally.- head = _head(constraints[0]["qualification"].get("destinationHead"))+ if requested["state"] == "retired":+ # The first receiver stays pinned even when stable advances offline.+ head = requested["destinationHead"]if head is None or record["head"] is None or head["sequence"] > record["head"]["sequence"]:- raise ChannelError("Invalid qualified retirement destination head")+ raise ChannelError("Invalid retirement destination head")manifest = None if head is None else validate_manifest(decode_json(self.read_bytes(head["manifestKey"], head["sha256"])), {**record, "head": head}, self.base_url)- for item, constraint in zip(retired, constraints):- if manifest is None:- raise ChannelError("Retirement destination has no published build")- if item["destination"] != record["name"]:- raise ChannelError("Retirement chain requires direct terminal qualification")+ if requested["state"] == "retired":+ assert manifest is not None+ if manifest.get("receiverProtocol") != requested["receiverProtocol"]:+ raise ChannelError("Stable build has no supported retirement receiver")actual = tuple(map(int, manifest["request"]["sourceVersion"].split(".")))- floor = tuple(map(int, item["minimumVersion"].split(".")))+ floor = tuple(map(int, requested["minimumVersion"].split(".")))if actual < floor:raise ChannelError("Destination does not meet retirement minimum version")- expected = {"schema": 1, "source": item["name"], "sourceHead": item["lastHead"],- "destination": record["name"], "destinationHead": head,- "minimumVersion": item["minimumVersion"]}- if any(constraint["qualification"].get(field) != value for field, value in expected.items()):- raise ChannelError("Retirement qualification does not bind source, destination and floor")- return ChannelResolution(requested, record, manifest, constraints)+ return ChannelResolution(requested, record, manifest)def validate_manifest(value: object, record: dict, base_url: str) -> dict:manifest = _schema(value)+ if "receiverProtocol" in manifest:+ _integer(manifest["receiverProtocol"], "receiver protocol", maximum=2**53 - 1)request = validate_request(manifest.get("request"), repository=record["repository"],base_url=base_url, policy=record["policy"])if request["identity"] != record["identity"]:diff --git a/hermes_cli/source_releases.py b/hermes_cli/source_releases.pyindex 7970463632b..e6c149ec346 100644--- a/hermes_cli/source_releases.py+++ b/hermes_cli/source_releases.py@@ -93,25 +93,7 @@ def resolve_source_target(channel: str, git_cmd=None, cwd=None, *, repository=Noif resolved.manifest is None:raise ValueError(f"No build published for channel {destination}")request = resolved.manifest["request"]- if resolved.requested["state"] == "retired":- # Native identity floors across intermediate channels are incomparable.- # Until qualified directly, refuse a chain rather than discard a floor.- if len(resolved.constraints) != 1:- raise ValueError("Source retirement requires direct destination qualification")- constraint = resolved.constraints[0]- qualification = constraint["qualification"]- # The reader checks the qualified manifest's digest, not today's head.- # Its immutable build identity must remain the migration target.- qualified_head = qualification.get("destinationHead")- expected = {"schema": 1, "source": channel, "sourceHead": resolved.requested["head"],- "destination": destination, "minimumVersion": constraint["minimumVersion"]}- if (constraint["channel"] != channel or constraint["destination"] != destination- or any(qualification.get(key) != value for key, value in expected.items())- or not isinstance(qualified_head, dict)- or any(qualified_head.get(key) != request[key] for key in ("buildId", "sequence"))):- raise ValueError("Source retirement qualification does not cover this destination")- if tuple(map(int, request["sourceVersion"].split("."))) < tuple(map(int, constraint["minimumVersion"].split("."))):- raise ValueError("Source retirement destination does not meet the minimum version")+commit = request["commit"]if not isinstance(commit, str) or not _SHA.fullmatch(commit):raise ValueError("Channel build has no exact source commit")diff --git a/scripts/bundles/release_artifacts.py b/scripts/bundles/release_artifacts.pyindex e5ee2ac2248..cc9be776373 100644--- a/scripts/bundles/release_artifacts.py+++ b/scripts/bundles/release_artifacts.py@@ -23,6 +23,11 @@ def sha256_file(file: Path) -> str:def stamp_matches(stamp: dict, tag: str, commit: str, *, channel_request: dict | None = None) -> None:+ if channel_request is not None and channel_request.get("receiverCandidate"):+ if (stamp.get("channelBuild") is not None or stamp.get("source") != "build"+ or stamp.get("receiverProtocol") != 1 or stamp.get("displayVersion") != channel_request["version"]):+ raise ValueError("Receiver candidate must use ordinary stable update ownership")+ tag, channel_request = channel_request["releaseTag"], Noneif channel_request is not None:if (stamp.get("source") != "channel-build" or stamp.get("channelBuild") != channel_requestor stamp.get("commit") != channel_request["commit"] or stamp.get("tag")):@@ -39,6 +44,19 @@ def single(items):return items[0]+def desktop_application(manifest: ET.Element, channel_request: dict | None) -> ET.Element:+ # CLI aliases are separate hidden Applications, not extra desktop entries.+ applications = manifest.findall("{*}Applications/{*}Application")+ visible = [app for app in applications if (+ (visual := app.find("{*}VisualElements")) is None or visual.get("AppListEntry") != "none")]+ application = single(visible)+ if channel_request is not None:+ expected = channel_request["identity"]["appNamePascal"]+ if application.get("Id") != expected or sum(app.get("Id") == expected for app in applications) != 1:+ raise ValueError("Desktop application ID differs from channel request")+ return application++def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Path,*, channel_request: dict | None = None) -> None:"""Read identities from the built packages, never from the workflow matrix."""@@ -48,13 +66,16 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Patwith zipfile.ZipFile(package) as archive:manifest = ET.fromstring(archive.read("AppxManifest.xml"))identity = manifest.find("{*}Identity")- application = single(manifest.findall("{*}Applications/{*}Application"))+ application = desktop_application(manifest, channel_request)stamp_name = single(n for n in archive.namelist() if n.replace("\\", "/").endswith("/resources/install-stamp.json"))- stamp_matches(json.loads(archive.read(stamp_name)), tag, commit, channel_request=channel_request)+ stamp = json.loads(archive.read(stamp_name))+ stamp_matches(stamp, tag, commit, channel_request=channel_request)if identity.attrib["ProcessorArchitecture"].lower() != arch:raise ValueError("MSIX architecture differs from release target")row.update(identity=identity.attrib["Name"], publisher=identity.attrib["Publisher"],applicationId=application.attrib["Id"], version=identity.attrib["Version"])+ if stamp.get("receiverProtocol") == 1:+ row["receiverProtocol"] = 1elif platform == "macos":package = single(root.glob(f"*-mac-{arch}.zip"))app = single(root.glob("mac*/*.app"))@@ -67,6 +88,8 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Patinfo = plistlib.loads(archive.read(single(n for n in archive.namelist() if re.fullmatch(r"[^/]+\.app/Contents/Info.plist", n))))stamp = json.loads(archive.read(single(n for n in archive.namelist() if re.fullmatch(r"[^/]+\.app/Contents/Resources/install-stamp.json", n))))stamp_matches(stamp, tag, commit, channel_request=channel_request)+ if stamp.get("receiverProtocol") == 1:+ row["receiverProtocol"] = 1row.update(identity=info["CFBundleIdentifier"], teamId=team.group(1), version=info["CFBundleShortVersionString"], filename=package.name)if row["version"] != (channel_request["version"] if channel_request else tag[1:]):raise ValueError("App version differs from release tag")@@ -94,6 +117,23 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Patout.write_text(json.dumps(row, sort_keys=True, indent=2) + "\n", encoding="utf-8")+def validate_windows_bundle(bundle: Path, windows: list[dict]) -> None:+ if sorted(row["arch"] for row in windows) != ["arm64", "x64"]:+ raise ValueError("Windows metadata must include both architectures")+ for field in ("identity", "publisher", "version", "applicationId"):+ if not windows[0].get(field) or windows[0][field] != windows[1].get(field):+ raise ValueError(f"Windows packages disagree on {field}")+ with zipfile.ZipFile(bundle) as archive:+ manifest = ET.fromstring(archive.read("AppxMetadata/AppxBundleManifest.xml"))+ identity = manifest.find("{*}Identity")+ if identity is None or any(identity.get(attr) != windows[0][field] for attr, field in+ (("Name", "identity"), ("Publisher", "publisher"), ("Version", "version"))):+ raise ValueError("Universal bundle identity does not match its packages")+ if sorted(p.get("Architecture", "") for p in manifest.findall("{*}Packages/{*}Package")+ if p.get("Type") == "application") != ["arm64", "x64"]:+ raise ValueError("Universal bundle must cover both architectures")++def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path,*, smoke_results: dict) -> dict:"""Bind the native metadata to files already staged by their build jobs."""@@ -124,17 +164,7 @@ def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path,universal_name = single(name for name in by_name if name.endswith(".msixbundle") and not name.startswith("Store-"))single(name for name in by_name if name.endswith(".msixbundle") and name.startswith("Store-"))windows = [r for r in rows if r["platform"] == "windows"]- if sorted(r["arch"] for r in windows) != ["arm64", "x64"]:- raise ValueError("Windows metadata must include both architectures")- for field in ("identity", "publisher", "version", "applicationId"):- if len({r[field] for r in windows}) != 1:- raise ValueError(f"Windows packages disagree on {field}")- with zipfile.ZipFile(root / universal_name) as archive:- manifest = ET.fromstring(archive.read("AppxMetadata/AppxBundleManifest.xml"))- identity = manifest.find("{*}Identity")- for attr, field in (("Name", "identity"), ("Publisher", "publisher"), ("Version", "version")):- if identity.attrib[attr] != windows[0][field]:- raise ValueError("Universal bundle identity does not match its packages")+ validate_windows_bundle(root / universal_name, windows)files = [{**row, "url": f"{public_base.rstrip('/')}/{staging_key_for(tag, name)}"}for name, row in sorted(by_name.items()) if not name.startswith("metadata-")]by_name = {item["path"]: item for item in files}diff --git a/scripts/generate_icons.py b/scripts/generate_icons.pyindex 84644beaa67..6ebd2cdb62d 100644--- a/scripts/generate_icons.py+++ b/scripts/generate_icons.py@@ -33,7 +33,7 @@ and the shared master SVGs retain the default brand.The girl's position and uniform scale are registered to the reference artwork.She renders in front of the border, clipped only to the outer rounded silhouette.-Only her bottom sliver extends to the border; the fitted face and hair stay fixed.+Only nodes near her bottom edge extend to the border; the fitted face and hair stay fixed.Standalone wordmarks remain centered and have no border.GENERATED OUTPUTS ARE NOT COMMITTED. Everything this script writes is@@ -305,6 +305,41 @@ def commit_layer(commit: str, bg: str) -> str:)+def drag_bottom_nodes(path: ET.Element, *, cutoff: float, band: float, distance: float) -> None:+ """Drag lower nodes and curve handles, tapering to zero above the bottom band."""+ y_scale, y_offset = 1.0, 0.0+ transform = path.get("transform")+ if transform:+ matrix = re.fullmatch(r"matrix\(([^)]+)\)", transform)+ if matrix is None:+ raise ValueError("bottom node edits require an axis-aligned matrix")+ _, b, c, y_scale, _, y_offset = map(float, re.split(r"[\s,]+", matrix[1].strip()))+ if b != 0 or c != 0 or y_scale <= 0:+ raise ValueError("bottom node edits require an upright axis-aligned matrix")++ # The brand exports use explicit absolute M/L/C commands. Reject other+ # commands rather than silently corrupting relative coordinates or arcs.+ tokens = re.findall(r"[A-Za-z]|[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?", path.attrib["d"])+ counts = {"M": 2, "L": 2, "C": 6, "z": 0, "Z": 0}+ index = 0+ while index < len(tokens):+ command = tokens[index]+ if command not in counts:+ raise ValueError("bottom node edits require explicit absolute M/L/C commands")+ count = counts[command]+ if index + count >= len(tokens):+ raise ValueError("incomplete SVG path command")+ for offset in range(2, count + 1, 2):+ token_index = index + offset+ raw_y = float(tokens[token_index])+ amount = min(1.0, max(0.0, (raw_y * y_scale + y_offset - cutoff) / band))+ if amount:+ weight = amount * amount * (3 - 2 * amount)+ tokens[token_index] = f"{raw_y + distance * weight / y_scale:.12g}"+ index += count + 1+ path.set("d", " ".join(tokens))++def compose_svg(art: IconArt, girl: str, bg: str) -> str:"""Full svg text: background + girl layer, in the background's nativecoordinate space (resvg scales to whatever output size is requested, so@@ -327,37 +362,23 @@ def compose_svg(art: IconArt, girl: str, bg: str) -> str:clip = ET.tostring(silhouette, encoding="unicode")box = GIRL_BOXES[bg]portrait = ET.fromstring(girl_layer(art, girl, box, align="xMidYMax"))- x, y, portrait_width, portrait_height = box- # Extrude a thin slice just above the bottom contour behind the artwork.- # Sampling above its antialiased tips avoids stretching transparent padding.- strip_height = 1- strip_top = y + portrait_height - portrait_height * 0.01- join_bottom = geometry["y"] + geometry["height"] - thickness + 4- stretch = (join_bottom - strip_top) / strip_height- bx, by, bw, bh = girl_bbox(art, girl)+ _, y, portrait_width, portrait_height = box+ _, by, bw, bh = girl_bbox(art, girl)scale = min(portrait_width / bw, portrait_height / bh)- tx = x + (portrait_width - bw * scale) / 2 - bx * scale- ty = y + portrait_height - bh * scale - by * scale- # Flatten the viewport transform: very thin nested SVG viewBoxes can be- # culled by the renderer at small icon sizes, silently losing the extension.- extension_path = ET.fromstring(girl_path(art, girl))- extension_path.attrib.pop("id", None)- join_clip = (- f'<clipPath id="icon-join"><rect x="{x}" y="{strip_top}" '- f'width="{portrait_width}" height="{join_bottom - strip_top}"/></clipPath>'- )- extension = (- '<g clip-path="url(#icon-join)">'- f'<g transform="matrix({scale} 0 0 {scale * stretch} {tx} {stretch * ty + (1 - stretch) * strip_top})">'- f'{ET.tostring(extension_path, encoding="unicode")}</g></g>'+ join_bottom = geometry["y"] + geometry["height"] - thickness + 10+ drag_bottom_nodes(+ portrait[0], cutoff=by + bh * 0.97, band=bh * 0.02,+ distance=max(0.0, join_bottom - (y + portrait_height)) / scale,)+ # Keep the fitted viewBox fixed, but let edited nodes reach into the border.+ portrait.set("overflow", "visible")badge = f" {commit_layer(art.commit, bg)}\n" if art.commit else ""return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}">\n'- f' <defs><clipPath id="icon-silhouette">{clip}</clipPath>{join_clip}</defs>\n'+ f' <defs><clipPath id="icon-silhouette">{clip}</clipPath></defs>\n'f" {inner.strip()}\n"f"{badge}"- f' <g clip-path="url(#icon-silhouette)">{extension}{ET.tostring(portrait, encoding="unicode")}</g>\n'+ f' <g clip-path="url(#icon-silhouette)">{ET.tostring(portrait, encoding="unicode")}</g>\n'"</svg>\n")diff --git a/scripts/releases/channel_build.py b/scripts/releases/channel_build.pyindex 8ba05d5743d..bf41964b292 100644--- a/scripts/releases/channel_build.py+++ b/scripts/releases/channel_build.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport hashlibimport json+import osfrom pathlib import Pathimport subprocess@@ -16,15 +17,19 @@ from scripts.releases.bundle_env import parse_assignments, validatefrom scripts.releases.channels import ChannelPublisher, R2ChannelStore-def dispatch_command(request: dict, repository: str, branch: str) -> list[str]:+def dispatch_command(request: dict, repository: str, branch: str, *, disposable_run: str = "") -> list[str]:validate_request(request, repository=repository)if not branch or branch.startswith("-"):raise ChannelError("Missing repository default branch")digest = hashlib.sha256(canonical_json(request)).hexdigest()- return ["gh", "workflow", "run", commit_build.WORKFLOW, "--repo", repository, "--ref", branch,+ command = ["gh", "workflow", "run", commit_build.WORKFLOW, "--repo", repository, "--ref", branch,"-f", "channel_build=" + request["buildId"], "-f", "channel_request_sha256=" + digest,"-f", "tag=", "-f", "upload_release=false", "-f", "termux_only=false","-f", "termux_upgrade_from_tag="]+ if disposable_run:+ from scripts.releases.r2_scope import require_run+ command += ["-f", "disposable_run=" + require_run(disposable_run)]+ return commanddef prepare_build(*, name: str, revision: str, remote: str, repo: Path, repository: str,@@ -55,7 +60,8 @@ def prepare_build(*, name: str, revision: str, remote: str, repo: Path, repositoreturn resultpublisher.create(name)request = publisher.allocate(name, commit, version, bundle_env, controller_commit)- command = dispatch_command(request, repository, default_branch)+ command = dispatch_command(request, repository, default_branch,+ disposable_run=os.environ.get("R2_DISPOSABLE_RUN", ""))print(f"Admitted build {request['buildId']}; request SHA256 {hashlib.sha256(canonical_json(request)).hexdigest()}")dispatch(command)return {**result, "request": request, "command": command}@@ -70,7 +76,8 @@ def resume_build(build_id: str, digest: str, *, publisher: ChannelPublisher,publisher._preview("allocate", current[0])if current[0]["identity"] != request["identity"]:raise ChannelError("Request channel identity mismatch")- command = dispatch_command(request, publisher.repository, default_branch)+ command = dispatch_command(request, publisher.repository, default_branch,+ disposable_run=os.environ.get("R2_DISPOSABLE_RUN", ""))if publish:dispatch(command)return {"request": request, "command": command}@@ -89,20 +96,21 @@ def maintainer_authorizer(repository: str):def configured_publisher(repository: str) -> ChannelPublisher:- from scripts.releases.channel_qualification import configured_verifier-- store = R2ChannelStore(*r2.credentials())- base = r2.public_base_url()- # Resolve evidence policy lazily: listing and preview allocation do not need- # qualification API calls, and CLI parsing must not import this dependency.+ from scripts.releases.r2_scope import R2Scope, channel_public_base+ validate_repository(repository)+ scope = R2Scope.configured(repository)+ if scope.prefix:+ actual_id = commit_build.output(["gh", "api", f"repos/{repository}", "--jq", ".id"])+ if actual_id != os.environ.get("GITHUB_REPOSITORY_ID"):+ raise ChannelError("Disposable namespace belongs to another repository")+ base = channel_public_base()+ store = R2ChannelStore(*r2.credentials(), scope=scope)def verify_build(request: dict, manifest: dict) -> bool:- return configured_verifier(store, repository, base).verify_build(request, manifest)-- def verify_retirement(source: dict, target: dict, qualification: dict) -> bool:- return configured_verifier(store, repository, base).verify_retirement(source, target, qualification)+ from scripts.releases.channel_releases import verify_bootstrap+ return verify_bootstrap(request, manifest, base, repository)return ChannelPublisher(store, repository, base, authorize=maintainer_authorizer(repository),- verify_build=verify_build, verify_retirement=verify_retirement)+ verify_build=verify_build)def cmd_channel(args) -> None:@@ -121,7 +129,6 @@ def cmd_channel(args) -> None:dispatch=lambda command: subprocess.run(command, cwd=release.REPO_ROOT, check=True, timeout=60)),"bootstrap_channels": lambda: _bootstrap_file(publisher, Path(args.bootstrap_channels), args.publish),"retire_channel": lambda: publisher.retire(args.retire_channel, args.to, args.minimum_version,- args.compatibility_key, args.compatibility_sha256,publish=args.publish),"channel": lambda: prepare_build(name=args.channel, revision=args.build_commit, remote=remote, repo=release.REPO_ROOT,@@ -155,9 +162,7 @@ def add_arguments(parser) -> None:parser.add_argument("--channels", action="store_true", help="List authenticated R2 channel records")parser.add_argument("--retire-channel", type=validate_name, metavar="NAME", help="Permanently retire a preview channel")parser.add_argument("--to", type=validate_name, metavar="NAME", help="Retirement destination channel")- parser.add_argument("--minimum-version", metavar="X.Y.Z", help="Qualified destination version floor")- parser.add_argument("--compatibility-key", help="Immutable retirement qualification object key")- parser.add_argument("--compatibility-sha256", type=require_sha256, help="Exact retirement qualification digest")+ parser.add_argument("--minimum-version", metavar="X.Y.Z", help="Destination version floor")parser.add_argument("--bootstrap-channels", metavar="JSON", help="Preview protected channel bootstrap from accepted release facts")@@ -165,7 +170,7 @@ def validate_arguments(parser, args) -> bool:selected = [key for key in ("channel", "channels", "retire_channel", "bootstrap_channels", "resume_channel_build") if getattr(args, key)]if bool(args.resume_channel_build) != bool(args.request_sha256):parser.error("--resume-channel-build and --request-sha256 are required together")- retirement = (args.to, args.minimum_version, args.compatibility_key, args.compatibility_sha256)+ retirement = (args.to, args.minimum_version)if any(retirement) and not args.retire_channel:parser.error("Retirement options require --retire-channel")if len(selected) > 1:@@ -177,7 +182,7 @@ def validate_arguments(parser, args) -> bool:if args.channel and args.build_commit is None:parser.error("--channel requires --build-commit")if args.retire_channel and not all(retirement):- parser.error("--retire-channel requires --to, --minimum-version, --compatibility-key and --compatibility-sha256")+ parser.error("--retire-channel requires --to and --minimum-version")if ((not args.channel and args.build_commit) or any((args.bump, args.canary, args.prune_canaries,args.first_release, args.date, args.output, args.no_changelog))):parser.error("Channel operations cannot be combined with release/tag operations")diff --git a/scripts/releases/channel_publish.py b/scripts/releases/channel_publish.pyindex 1b7abee4330..135d9af34f9 100644--- a/scripts/releases/channel_publish.py+++ b/scripts/releases/channel_publish.py@@ -2,14 +2,11 @@from __future__ import annotationsimport argparse-import base64import hashlibimport jsonimport osfrom pathlib import Pathimport tempfile-import xml.etree.ElementTree as ET-import zipfilefrom hermes_cli.release_channels import ChannelReader, build_prefix, canonical_json, decode_json, require_sha256, validate_requestfrom scripts.releases import commit_build, handoff, r2@@ -39,19 +36,38 @@ def require_success(needs: dict) -> None:raise ValueError("Channel publication requires successful jobs: " + ", ".join(failed))+def receiver_request(request: dict) -> bool:+ """An explicit marker is never sufficient without the physical CI scope."""+ if not request.get("receiverCandidate"):+ return False+ from scripts.releases.channel_releases import product_identity+ from scripts.releases.r2_scope import R2Scope, channel_public_base+ scope = R2Scope.configured()+ if (request["receiverCandidate"] is not True or not scope.prefix+ or request["publicBase"] != channel_public_base()+ or request["identity"] != product_identity(request.get("releaseTag", ""))+ or request.get("releaseTag") != "v" + request["version"]+ or request.get("channel") != "stable" or request.get("bundleEnv") != {}):+ raise ValueError("Receiver candidate escaped disposable official identity admission")+ validate_request(request, policy="stable-release")+ return True++def admit(request: dict, env: dict[str, str]) -> dict[str, str]:if (env.get("BUILD_COMMIT") or env.get("TAG") or env.get("RELEASE_PHASE")or env.get("TERMUX_UPGRADE_FROM_TAG") or env.get("TERMUX_ONLY") == "true"or env.get("UPLOAD_RELEASE", "false") != "false"or env.get("BUNDLE_ENV_JSON", "") not in ("", "{}")):raise ValueError("Channel requests cannot select one-off, release, Termux or bundle overrides")+ validate_request(request, repository=env.get("GITHUB_REPOSITORY"))admitted = commit_build.admit({**env, "BUILD_COMMIT": request["commit"],"BUNDLE_ENV_JSON": json.dumps(request["bundleEnv"])})if admitted["payload-version"] != request["sourceVersion"]:raise ValueError("Channel request source version differs from admitted commit")if request.get("controllerCommit", env.get("GITHUB_SHA")) != env.get("GITHUB_SHA"):raise ValueError("Channel request controller differs from trusted workflow revision")- return {"sha": request["commit"], "channel": request["channel"], "payload-version": request["version"]}+ return {"sha": request["commit"], "channel": request["channel"], "payload-version": request["version"],+ "receiver-candidate": str(receiver_request(request)).lower()}def _metadata(root: Path, request: dict, platform: str, arch: str) -> dict:@@ -71,7 +87,7 @@ def _metadata(root: Path, request: dict, platform: str, arch: str) -> dict:def assemble(request: dict, root: Path, *, needs: dict) -> tuple[dict, list[Path]]:"""Consume downloaded receipts; derive immutable feeds without another build."""- from scripts.bundles.release_artifacts import single, write_appinstaller+ from scripts.bundles.channel_artifacts import assemble as assemble_nativerequire_success(needs)validate_request(request)@@ -101,60 +117,41 @@ def assemble(request: dict, root: Path, *, needs: dict) -> tuple[dict, list[Pathif file.stat().st_size != row["size"] or r2.file_sha256(file) != row["sha256"]:raise ValueError("Channel artifact differs from its receipt")files[row["path"]] = row- name = request["identity"]["artifactNamePascal"]- bundle_name = f"{name}-{request['windowsVersion']}-win.msixbundle"- if bundle_name not in files:- raise ValueError("Missing Windows universal bundle")- windows = [_metadata(root, request, "win32", arch) for arch in ("arm64", "x64")]- for field in ("publisher", "version", "identity", "applicationId"):- if not windows[0].get(field) or windows[0][field] != windows[1].get(field):- raise ValueError(f"Windows native metadata disagrees on {field}")- with zipfile.ZipFile(root / bundle_name) as archive:- manifest = ET.fromstring(archive.read("AppxMetadata/AppxBundleManifest.xml"))- native = manifest.find("{*}Identity")- for attr, field in (("Name", "identity"), ("Publisher", "publisher"), ("Version", "version")):- if native is None or native.get(attr) != windows[0][field]:- raise ValueError("Windows universal envelope differs from native metadata")- architectures = sorted(p.get("Architecture", "") for p in manifest.findall("{*}Packages/{*}Package")- if p.get("Type") == "application")- if architectures != ["arm64", "x64"]:- raise ValueError("Universal bundle must contain both native architectures")- descriptor = root / "win32" / "stable.appinstaller"- base = request["publicBase"]- write_appinstaller(descriptor, identity=windows[0]["identity"], publisher=windows[0]["publisher"],- version=request["windowsVersion"], self_uri=f"{base}/{prefix}win32/stable.appinstaller",- artifact_uri=f"{base}/{prefix}{bundle_name}", update_policy="pinned")- packages = []- mac_files = []- for platform in ("darwin", "win32"):- for arch in ("arm64", "x64"):- metadata = _metadata(root, request, platform, arch)- filename = f"{name}-{request['version']}-mac-{arch}.zip" if platform == "darwin" else bundle_name- row = files[filename]- signing_field = "teamId" if platform == "darwin" else "publisher"- if not metadata.get(signing_field):- raise ValueError("Missing native signing identity")- packages.append({"platform": platform, "arch": arch, "variant": "bundled",- "version": metadata["version"], "identity": metadata["identity"],- signing_field: metadata[signing_field],- "artifact": {"key": prefix + filename, "sha256": row["sha256"], "size": row["size"]},- "feed": {"key": prefix + ("darwin/stable-mac.yml" if platform == "darwin"- else "win32/stable.appinstaller"), "channel": "stable"}})- if platform == "darwin":- for extension in ("zip", "dmg"):- artifact = f"{name}-{request['version']}-mac-{arch}.{extension}"- if artifact not in files or artifact + ".blockmap" not in files:- raise ValueError("Missing macOS native package or blockmap")- with (root / artifact).open("rb") as stream:- sha512 = base64.b64encode(hashlib.file_digest(stream, "sha512").digest()).decode("ascii")- mac_files.append({"url": base + "/" + prefix + artifact, "sha512": sha512, "size": files[artifact]["size"]})- # JSON is valid YAML. A neutral filename avoids electron-updater prerelease-name parsing.- feed = root / "darwin" / "stable-mac.yml"- feed.parent.mkdir(parents=True, exist_ok=True)- first_zip = single(f for f in mac_files if f["url"].endswith("-arm64.zip"))- feed.write_text(json.dumps({"version": request["version"], "files": mac_files,- "path": first_zip["url"], "sha512": first_zip["sha512"]}, indent=2) + "\n", encoding="utf-8")- return {"schema": 1, "request": request, "packages": packages}, [feed, descriptor]+ rows = [_metadata(root, request, platform, arch)+ for platform in ("darwin", "win32") for arch in ("arm64", "x64")]+ return assemble_native(request, {"files": files, "packages": rows}, root, artifact_prefix=prefix)+++def publish_receiver(request: dict, root: Path, *, needs: dict, publisher) -> dict:+ from scripts.releases.channel_disposable import require_receiver_scope+ from hermes_cli.release_channels import channel_key, validate_manifest++ require_receiver_scope(publisher)+ if not receiver_request(request) or publisher.request(request["buildId"]) != request:+ raise ValueError("Receiver request admission mismatch")+ current = publisher._read(request["channel"])+ if current is None or current[0].get("testOnly") is not True or current[0]["state"] != "active":+ raise ValueError("Receiver requires a test-only active stable record")+ handoff.fetch_channel_build(request, list(NATIVE_LEGS), root, public_base=request["publicBase"])+ manifest, feeds = assemble(request, root, needs=needs)+ prefix = build_prefix(request["buildId"])+ validate_manifest(manifest, {**current[0], "head": None}, publisher.public_base)+ if manifest.get("receiverProtocol") != 1:+ raise ValueError("Candidate packages have no retirement receiver")+ for file in feeds:+ key = prefix + file.relative_to(root).as_posix()+ r2.put(tag="", key=key, file=str(file), key_is_full=True, immutable=True)+ if publisher.reader.read_bytes(key) != file.read_bytes():+ raise ValueError("Receiver feed readback mismatch")+ publisher._write(prefix + "build.json", manifest)+ head = {"buildId": request["buildId"], "sequence": request["sequence"], "manifestKey": prefix + "build.json",+ "sha256": hashlib.sha256(canonical_json(manifest)).hexdigest()}+ # S becomes the initial disposable destination. T is immutable but deliberately+ # unpromoted until the actual handoff chat asks the lifecycle controller to advance.+ if request["sequence"] == 1 and current[0]["head"] is None:+ publisher._write(channel_key(request["channel"]), {**current[0], "head": head,+ "revision": current[0]["revision"] + 1}, current[1])+ return {"head": head, "manifest": manifest}def publish(request: dict, root: Path, *, needs: dict, publisher) -> dict:@@ -180,20 +177,27 @@ def publish(request: dict, root: Path, *, needs: dict, publisher) -> dict:def main(argv: list[str] | None = None) -> None:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("command", choices=["request", "admit", "publish"])+ parser.add_argument("command", choices=["request", "admit", "publish", "receiver-publish"])parser.add_argument("--build-id", default=os.environ.get("CHANNEL_BUILD", ""))parser.add_argument("--request-sha256", default=os.environ.get("CHANNEL_REQUEST_SHA256", ""))- parser.add_argument("--public-base", default=os.environ.get("CLOUDFLARE_R2_PUBLIC_URL", ""))+ parser.add_argument("--public-base", help="Expected public authority (not an override in disposable CI)")+ parser.add_argument("--disposable-run", help="Controller run-id-attempt; propagated to R2 object scope")parser.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY", ""))parser.add_argument("--out", type=Path)parser.add_argument("--root", type=Path)args = parser.parse_args(argv)+ from scripts.releases.r2_scope import channel_public_base, require_run+ if args.disposable_run is not None:+ os.environ["R2_DISPOSABLE_RUN"] = require_run(args.disposable_run)+ args.public_base = channel_public_base(args.public_base)request = read_request(args.build_id, args.request_sha256, args.public_base, args.repository)if args.command == "admit":values = admit(request, dict(os.environ))+ values["public-root"] = os.environ["CLOUDFLARE_R2_PUBLIC_URL"]+ values["public-base"] = args.public_basewith Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as stream:stream.write("".join(f"{key}={value}\n" for key, value in values.items()))- elif args.command == "publish":+ elif args.command in {"publish", "receiver-publish"}:from scripts.releases.channels import ChannelPublisher, R2ChannelStoreneeds = json.loads(os.environ.get("RELEASE_NEEDS", "{}"))require_success(needs)@@ -211,7 +215,11 @@ def main(argv: list[str] | None = None) -> None:publisher = ChannelPublisher(R2ChannelStore(*r2.credentials()), args.repository, args.public_base,authorize=authorize, verify_build=qualified)- if args.root:+ if args.command.startswith("receiver-"):+ if args.root is None:+ parser.error("receiver publication requires --root")+ result = publish_receiver(request, args.root, needs=needs, publisher=publisher)+ elif args.root:root = args.rootresult = publish(request, args.root, needs=needs, publisher=publisher)else:diff --git a/scripts/releases/channel_qualification.py b/scripts/releases/channel_qualification.pydeleted file mode 100644index 9775e8c9cca..00000000000--- a/scripts/releases/channel_qualification.py+++ /dev/null@@ -1,280 +0,0 @@-"""Release-admin evidence verifier. R2 assertions alone never authorize retirement.--The trusted controller uploads receipt.json as an immutable Actions artifact.-We compare those bytes with the digest-pinned R2 copy, then bind every claim to-native packages and the successful default-branch workflow that produced it.-"""-from __future__ import annotations--import hashlib-import io-import subprocess-from urllib.parse import quote-from urllib.request import Request, urlopen-import zipfile--from hermes_cli.release_channels import (- ChannelError, ChannelReader, artifact_key, build_prefix, canonical_json,- decode_json, public_base, require_commit, require_sha256, validate_manifest,- validate_record, validate_repository,-)--RETIREMENT_ASSERTIONS = (- "nativeIdentityVerified", "sourceChatCompleted", "destinationChatCompleted",- "statePreserved", "automaticActivation", "previewRemoved", "ownedLaunchersRemoved",- "stableSubscription", "stableUpdateCompleted", "stableUpdateChatCompleted",-)-SUPPORTED = {(p, a) for p in ("darwin", "win32") for a in ("arm64", "x64")}-MAX_EVIDENCE = 4 * 1024 * 1024---def _require(condition: bool, reason: str) -> None:- if not condition:- raise ChannelError(reason)---def _positive(value: object) -> int:- _require(type(value) is int and value > 0, "Invalid Actions evidence ID")- return value---class GitHubEvidence:- """gh owns production credentials. The explicit HTTP endpoint is for fixtures."""- def __init__(self, *, api_base: str | None = None):- self.api_base = public_base(api_base) if api_base else None-- def read(self, endpoint: str) -> bytes:- try:- if self.api_base:- with urlopen(Request(self.api_base + "/" + endpoint), timeout=30) as response:- body = response.read(MAX_EVIDENCE + 1)- else:- body = subprocess.check_output(["gh", "api", endpoint], stdin=subprocess.DEVNULL, timeout=60)- except (OSError, subprocess.SubprocessError) as exc:- raise ChannelError("GitHub qualification evidence unavailable") from exc- _require(len(body) <= MAX_EVIDENCE, "Actions evidence exceeds size limit")- return body-- def json(self, endpoint: str) -> dict:- return decode_json(self.read(endpoint))-- def receipt(self, repository: str, proof: dict, expected: bytes, *, controller: str,- branch: str, workflow: str, artifact_name: str) -> dict:- run_id, attempt, artifact_id = (_positive(proof.get(k)) for k in ("runId", "runAttempt", "artifactId"))- prefix = f"repos/{repository}/actions"- run = self.json(f"{prefix}/runs/{run_id}")- facts = {"id": run_id, "run_attempt": attempt, "status": "completed", "conclusion": "success",- "head_sha": controller, "head_branch": branch, "event": "workflow_dispatch", "path": workflow}- _require(all(run.get(k) == v for k, v in facts.items()), "Untrusted or unsuccessful qualification workflow run")- _require(all(isinstance(run.get(k), dict) and run[k].get("full_name", "").casefold() == repository.casefold()- for k in ("repository", "head_repository")), "Qualification workflow repository mismatch")- artifact = self.json(f"{prefix}/artifacts/{artifact_id}")- _require(artifact.get("id") == artifact_id and artifact.get("expired") is False- and artifact.get("name") == artifact_name, "Wrong or expired Actions receipt artifact")- binding = artifact.get("workflow_run", {})- _require(binding.get("id") == run_id and binding.get("head_sha") == controller,- "Actions artifact is not from the qualified controller run")- archive = self.read(f"{prefix}/artifacts/{artifact_id}/zip")- _require(artifact.get("digest") == "sha256:" + hashlib.sha256(archive).hexdigest(),- "Actions artifact digest mismatch")- try:- with zipfile.ZipFile(io.BytesIO(archive)) as zipped:- _require(zipped.namelist() == ["receipt.json"], "Actions artifact must contain only receipt.json")- _require(zipped.getinfo("receipt.json").file_size <= MAX_EVIDENCE, "Actions receipt exceeds size limit")- body = zipped.read("receipt.json")- except (zipfile.BadZipFile, RuntimeError) as exc:- raise ChannelError("Invalid Actions receipt archive") from exc- _require(body == expected, "R2 receipt differs from trusted Actions artifact")- receipt = decode_json(body)- _require(receipt.get("repository") == repository and receipt.get("controllerCommit") == controller- and receipt.get("runId") == run_id and receipt.get("runAttempt") == attempt,- "Receipt controller/run binding mismatch")- return receipt---class QualificationVerifier:- def __init__(self, store, repository: str, base_url: str, controller_commit: str,- default_branch: str, *, github: GitHubEvidence | None = None):- self.store = store- self.repository = validate_repository(repository)- self.base_url = public_base(base_url)- self.reader = ChannelReader(base_url, repository)- self.controller = require_commit(controller_commit)- self.branch = default_branch- self.github = github or GitHubEvidence()-- def verify_build(self, request: dict, manifest: dict) -> bool:- from scripts.releases.stable import validate_candidates-- _require(manifest.get("request") == request, "Build request binding mismatch")- tag = request.get("releaseTag")- _require(isinstance(tag, str), "Admin bootstrap requires accepted protected release metadata")- # Canary publication remains owned by its existing workflow, not stable bootstrap.- _require("-" not in tag, "Stable bootstrap cannot admit a canary as stable")- record = {"name": request["channel"], "repository": self.repository, "policy": "stable-release",- "identity": request["identity"], "head": None}- validate_manifest(manifest, record, self.base_url)- qualification = manifest.get("releaseQualification", {})- candidate_ref = qualification.get("candidate", {})- _require(candidate_ref.get("key") == f"releases/tag/{tag}/release-candidates.json",- "Bootstrap must reuse the accepted release candidate")- candidate = self._object(candidate_ref["key"], require_sha256(candidate_ref.get("sha256")))- try:- rows = validate_candidates(candidate, tag, request["commit"], self.base_url)- except ValueError as exc:- raise ChannelError(str(exc)) from exc- _require({(p["platform"], p["arch"]) for p in manifest["packages"]} == SUPPORTED,- "Bootstrap requires every native release platform")- for package in manifest["packages"]:- platform = "macos" if package["platform"] == "darwin" else "windows"- admitted = rows[f"{platform}/{package['arch']}"]- signing = "teamId" if platform == "macos" else "publisher"- _require(all(admitted.get(k) == package.get(k) for k in ("identity", "version", signing))- and admitted["artifact"]["url"] == self.base_url + "/" + package["artifact"]["key"]- and admitted["artifact"]["sha256"] == package["artifact"]["sha256"],- "Bootstrap package differs from accepted stable candidate")- if platform == "windows":- _require(admitted["applicationId"] == request["identity"]["appNamePascal"],- "Bootstrap native application identity mismatch")- release = self.github.json(f"repos/{self.repository}/releases/tags/{quote(tag, safe='')}")- _require(release.get("tag_name") == tag and release.get("draft") is False- and release.get("prerelease") is False and bool(release.get("published_at")),- "Bootstrap destination is not a published stable release")- _require(self.github.json(f"repos/{self.repository}/commits/{quote(tag, safe='')}").get("sha") == request["commit"],- "Published release commit differs from bootstrap")- comparison = self.github.json(f"repos/{self.repository}/compare/{request['commit']}...{self.controller}")- _require(comparison.get("status") in ("ahead", "identical")- and comparison.get("merge_base_commit", {}).get("sha") == request["commit"],- "Published stable controller is not admitted on the default branch")- receipt = self._proof(qualification.get("proof"), workflow=".github/workflows/stable-release.yml",- artifact_name="channel-qualification", controller=request["commit"], branch=tag)- content = {"schema": 1, "request": request, "packages": manifest["packages"]}- facts = {"schema": 1, "kind": "channel-release", "tag": tag, "commit": request["commit"],- "manifestSha256": hashlib.sha256(canonical_json(content)).hexdigest(),- "candidateSha256": candidate_ref["sha256"]}- _require(all(receipt.get(k) == v for k, v in facts.items()), "Release qualification binding mismatch")- _require(all(receipt.get("assertions", {}).get(k) is True for k in ("nativeSmoke", "nativeUpgrade", "releaseGate")),- "Missing native stable release acceptance")- return True-- def _object(self, key: str, digest: str | None = None) -> dict:- artifact_key(key)- if digest is not None:- require_sha256(digest)- found = self.store.get(key)- _require(found is not None, "Missing immutable qualification object")- raw = found[0]- _require(digest is None or hashlib.sha256(raw).hexdigest() == digest, "Qualification object digest mismatch")- return decode_json(raw)-- def _manifest(self, record: dict, head: dict) -> dict:- return validate_manifest(self._object(head["manifestKey"], head["sha256"]),- {**record, "head": head}, self.reader.base_url)-- def _proof(self, proof: dict, *, workflow: str, artifact_name: str,- controller: str | None = None, branch: str | None = None) -> dict:- _require(isinstance(proof, dict), "Missing native qualification proof")- key = artifact_key(proof.get("key"))- _require(key.startswith("releases/qualifications/"), "Receipt is outside immutable qualification namespace")- body = self.reader.read_bytes(key, require_sha256(proof.get("sha256")))- return self.github.receipt(self.repository, proof, body, controller=controller or self.controller,- branch=branch or self.branch, workflow=workflow, artifact_name=artifact_name)-- def _cohorts(self, source: dict) -> dict[str, tuple[dict, dict]]:- """No publication ledger exists: conservatively cover all complete builds <= head.-- Failed requests without build.json are not installable. Fully assembled but- unpublished builds are included rather than silently losing an old cohort.- """- _require(source.get("head") is not None, "Cannot qualify an unpublished source")- result = {}- for key in self.store.keys("releases/channel-builds/"):- if not key.endswith("/build.json"):- continue- value = self._object(key)- request = value.get("request", {})- if request.get("channel") != source["name"]:- continue- _require(request.get("identity") == source["identity"], "Source cohort identity changed")- _require(type(request.get("sequence")) is int, "Invalid source cohort sequence")- if request["sequence"] > source["head"]["sequence"]:- continue- head = {"buildId": request.get("buildId"), "sequence": request["sequence"],- "manifestKey": key, "sha256": hashlib.sha256(self.store.get(key)[0]).hexdigest()}- _require(key == build_prefix(head["buildId"]) + "build.json", "Cohort manifest key mismatch")- result[head["buildId"]] = (head, self._manifest(source, head))- _require(source["head"]["buildId"] in result, "Source head missing from cohort coverage")- return result-- @staticmethod- def _native(manifest: dict, platform: str, arch: str) -> dict:- matches = [p for p in manifest["packages"] if (p["platform"], p["arch"]) == (platform, arch)]- _require(len(matches) == 1, "Missing supported native package")- return matches[0]-- @staticmethod- def _side(record: dict, head: dict, manifest: dict, package: dict) -> dict:- return {"channel": record["name"], "head": head, "commit": manifest["request"]["commit"],- "identity": package["identity"], "artifactSha256": package["artifact"]["sha256"]}-- def verify_retirement(self, source: dict, target: dict, qualification: dict) -> bool:- validate_record(source, repository=self.repository)- validate_record(target, repository=self.repository)- _require(source["policy"] == "preview" and target["policy"] == "stable-release"- and target["state"] == "active", "Unsupported native retirement policy")- expected = {"schema": 1, "source": source["name"], "sourceHead": source["head"],- "destination": target["name"], "destinationHead": target["head"], "receiverProtocol": 1}- _require(all(qualification.get(k) == v for k, v in expected.items()), "Qualification head binding mismatch")- destination = self._manifest(target, target["head"])- cohorts = self._cohorts(source)- coverage = qualification.get("coverage")- _require(isinstance(coverage, list) and bool(coverage), "Missing per-platform native coverage")- platforms = {(p["platform"], p["arch"]) for _, m in cohorts.values() for p in m["packages"]}- _require(platforms <= SUPPORTED and len(coverage) == len(platforms), "Incomplete native platform coverage")- seen = set()- for row in coverage:- platform, arch = row.get("platform"), row.get("arch")- _require((platform, arch) in platforms - seen, "Duplicate or unsupported native coverage")- seen.add((platform, arch))- package = self._native(destination, platform, arch)- _require(row.get("destinationIdentity") == package["identity"], "Destination native identity mismatch")- entries = row.get("cohorts", [])- needed = {k for k, (_, m) in cohorts.items() if any((p["platform"], p["arch"]) == (platform, arch) for p in m["packages"])}- _require(isinstance(entries, list) and len(entries) == len(needed), "Missing source cohort coverage")- covered = set()- for entry in entries:- build_id = entry.get("buildId")- _require(build_id in needed - covered, "Unknown or duplicate source cohort")- covered.add(build_id)- head, manifest = cohorts[build_id]- native = self._native(manifest, platform, arch)- _require(entry.get("commit") == manifest["request"]["commit"]- and row.get("sourceIdentity") == native["identity"], "Source cohort commit or identity mismatch")- scenarios = set()- for proof in entry.get("proofs", []):- # The stable state also lives inside the independently authenticated receipt.- receipt = self._proof(proof, workflow=".github/workflows/install-e2e.yml",- artifact_name="channel-qualification")- facts = {"schema": 1, "kind": "channel-retirement", "platform": platform, "arch": arch,- "variant": "bundled", "receiverProtocol": 1, "minimumVersion": qualification.get("minimumVersion"),- "source": self._side(source, head, manifest, native),- "destination": self._side(target, target["head"], destination, package)}- _require(all(receipt.get(k) == v for k, v in facts.items()), "Native acceptance receipt target mismatch")- assertions = receipt.get("assertions", {})- _require(all(assertions.get(k) is True for k in RETIREMENT_ASSERTIONS), "Incomplete native lifecycle acceptance")- scenario = receipt.get("scenario", {})- _require(scenario.get("home") in ("shared", "distinct") and scenario.get("route") in ("direct", "via-update"),- "Invalid native lifecycle scenario")- scenarios.add((scenario.get("route"), scenario.get("stable")))- _require({("direct", "absent"), ("direct", "running")} <= scenarios,- "Every cohort needs direct retirement with absent and running stable")- return True---def configured_verifier(store, repository: str, base_url: str) -> QualificationVerifier:- github = GitHubEvidence()- repository = validate_repository(repository)- branch = github.json(f"repos/{repository}").get("default_branch")- _require(isinstance(branch, str) and bool(branch), "Repository has no default controller branch")- controller = github.json(f"repos/{repository}/commits/{quote(branch, safe='')}").get("sha")- return QualificationVerifier(store, repository, base_url, controller, branch, github=github)diff --git a/scripts/releases/channel_releases.py b/scripts/releases/channel_releases.pyindex 6f8da53278c..ba556184088 100644--- a/scripts/releases/channel_releases.py+++ b/scripts/releases/channel_releases.py@@ -2,25 +2,23 @@from __future__ import annotationsimport argparse-import base64import hashlibimport jsonimport osfrom pathlib import Pathimport subprocessimport tempfile-import xml.etree.ElementTree as ET-import zipfilefrom hermes_cli.release_channels import (- ChannelError, build_prefix, canonical_json, validate_identity, validate_manifest,+ ChannelError, build_prefix, canonical_json, validate_identity,)+from scripts.bundles.channel_artifacts import assemblefrom scripts.releases import handoff, r2, stablefrom scripts.releases.channels import ChannelPublisher, R2ChannelStoreNATIVE_LEGS = ("darwin-arm64", "darwin-x64", "win32-arm64", "win32-x64", "windows-universal")-STABLE_NEEDS = ("admit", "ci", "docker", "acceptance", "candidates", "publication", "promote-docker", "promote-bundles")-CANARY_NEEDS = ("build-win32", "build-darwin", "build-linux", "builds-table", "assemble-win32-bundle",+STABLE_NEEDS = ("admit", "ci", "docker", "acceptance", "candidates", "publication", "promote-docker", "promote-bundles", "windows-packaged", "macos-packaged")+CANARY_NEEDS = ("validate", "build-win32", "build-darwin", "build-linux", "builds-table", "assemble-win32-bundle","smoke-darwin", "smoke-win32", "smoke-win32-universal", "publish-win32-updater", "publish-darwin-updater")@@ -75,67 +73,11 @@ def read_native_receipts(root: Path, tag: str, commit: str) -> dict:return {"packages": rows, "files": files}-def assemble(request: dict, native: dict, root: Path) -> tuple[dict, list[Path]]:- from scripts.bundles.release_artifacts import single, write_appinstaller-- files = native["files"]- tag_prefix = f"releases/tag/{request['releaseTag']}/"- prefix = build_prefix(request["buildId"])- base = request["publicBase"]- windows = [row for row in native["packages"] if row["platform"] == "windows"]- for field in ("identity", "publisher", "version", "applicationId"):- if len(windows) != 2 or not windows[0].get(field) or windows[0][field] != windows[1].get(field):- raise ChannelError(f"Windows native metadata disagrees on {field}")- if windows[0]["applicationId"] != request["identity"]["appNamePascal"]:- raise ChannelError("Windows application identity mismatch")- bundle_name = single(name for name in files if name.endswith(".msixbundle") and not name.startswith("Store-"))- with zipfile.ZipFile(root / bundle_name) as archive:- envelope = ET.fromstring(archive.read("AppxMetadata/AppxBundleManifest.xml"))- identity = envelope.find("{*}Identity")- if identity is None or any(identity.get(attr) != windows[0][field] for attr, field in- (("Name", "identity"), ("Publisher", "publisher"), ("Version", "version"))):- raise ChannelError("Universal bundle differs from native metadata")- if sorted(p.get("Architecture", "") for p in envelope.findall("{*}Packages/{*}Package")- if p.get("Type") == "application") != ["arm64", "x64"]:- raise ChannelError("Universal bundle must cover both architectures")- descriptor = root / "win32" / "stable.appinstaller"- write_appinstaller(descriptor, identity=windows[0]["identity"], publisher=windows[0]["publisher"],- version=windows[0]["version"], self_uri=f"{base}/{prefix}win32/stable.appinstaller",- artifact_uri=f"{base}/{tag_prefix}{bundle_name}", update_policy="pinned")- packages, mac_files = [], []- for row in native["packages"]:- mac = row["platform"] == "macos"- filename = row["filename"] if mac else bundle_name- receipt = files.get(filename)- if receipt is None or not (root / filename).is_file():- raise ChannelError("Missing receipt-bound native artifact")- signing = "teamId" if mac else "publisher"- packages.append({"platform": "darwin" if mac else "win32", "arch": row["arch"], "variant": "bundled",- "identity": row["identity"], "version": row["version"], signing: row.get(signing),- "artifact": {"key": tag_prefix + filename, "sha256": receipt["sha256"], "size": receipt["size"]},- "feed": {"key": prefix + ("darwin/stable-mac.yml" if mac else "win32/stable.appinstaller"),- "channel": "stable"}})- if mac:- for name in (filename, filename.removesuffix(".zip") + ".dmg"):- if any(item not in files or not (root / item).is_file() for item in (name, name + ".blockmap")):- raise ChannelError("Missing receipt-bound macOS package or blockmap")- with (root / name).open("rb") as stream:- digest = base64.b64encode(hashlib.file_digest(stream, "sha512").digest()).decode("ascii")- mac_files.append({"url": f"{base}/{tag_prefix}{name}", "sha512": digest, "size": files[name]["size"]})- feed = root / "darwin" / "stable-mac.yml"- feed.parent.mkdir(parents=True, exist_ok=True)- first = single(row for row in mac_files if row["url"].endswith("-arm64.zip"))- feed.write_bytes(canonical_json({"version": request["version"], "files": mac_files,- "path": first["url"], "sha512": first["sha512"]}))- manifest = {"schema": 1, "request": request, "packages": packages}- record = {"name": request["channel"], "repository": request["repository"], "identity": request["identity"],- "policy": "canary-release" if "-canary." in request["releaseTag"] else "stable-release", "head": None}- validate_manifest(manifest, record, base)- return manifest, [feed, descriptor]--def match_accepted_packages(manifest: dict, accepted: dict) -> None:by_target = {(row["platform"], row["arch"]): row for row in accepted["packages"]}+ if {(row["platform"], row["arch"]) for row in manifest["packages"]} != {+ (platform, arch) for platform in ("darwin", "win32") for arch in ("arm64", "x64")}:+ raise ChannelError("Protected manifest must include every native target")for package in manifest["packages"]:platform = "macos" if package["platform"] == "darwin" else "windows"row = by_target.get((platform, package["arch"]), {})@@ -144,6 +86,11 @@ def match_accepted_packages(manifest: dict, accepted: dict) -> None:or row.get("artifact") != {"url": manifest["request"]["publicBase"] + "/" + package["artifact"]["key"],"sha256": package["artifact"]["sha256"]}):raise ChannelError("Protected package differs from the accepted release")+ if platform == "windows" and row.get("applicationId") != manifest["request"]["identity"]["appNamePascal"]:+ raise ChannelError("Protected application ID differs from the accepted release")+ if manifest.get("receiverProtocol") == 1 and any(+ row.get("receiverProtocol") != 1 for row in accepted["packages"] if row["platform"] in ("windows", "macos")):+ raise ChannelError("Accepted packages do not declare retirement receiver support")def admit_transaction(policy: str, env: dict, *, run=stable.output) -> tuple[str, str]:@@ -207,10 +154,72 @@ def accepted_stable(publisher: ChannelPublisher, env: dict, tag: str, commit: streturn candidate+def verify_bootstrap(request: dict, manifest: dict, base: str, repository: str) -> bool:+ """Bootstrap from published release outputs, never caller attestations."""+ from hermes_cli.release_channels import ChannelReader, decode_json+ tag = request.get("releaseTag", "")+ if not tag or manifest.get("request") != request:+ raise ChannelError("Bootstrap requires published release metadata")+ canary = "-canary." in tag+ reader = ChannelReader(base, repository)+ if canary:+ verify_canary_outputs(request, manifest, reader)+ else:+ candidate = decode_json(reader.read_bytes(f"releases/tag/{tag}/release-candidates.json"))+ stable.validate_candidates(candidate, tag, request["commit"], base)+ if decode_json(reader.read_bytes("releases/stable/release-candidates.json")) != candidate:+ raise ChannelError("Bootstrap must use the current accepted stable transaction")+ match_accepted_packages(manifest, candidate)+ identity = product_identity(tag)+ if any(request["identity"][key] != value for key, value in identity.items() if key != "token"):+ raise ChannelError("Bootstrap must retain official native identity")+ release = json.loads(stable.output(["gh", "api", f"repos/{repository}/releases/tags/{tag}"]))+ commit = stable.output(["gh", "api", f"repos/{repository}/commits/{tag}", "--jq", ".sha"])+ if (release.get("draft") is not False or release.get("prerelease") is not canary+ or not release.get("published_at") or commit != request["commit"]):+ raise ChannelError("Bootstrap requires the published release")+ return True+++def verify_canary_outputs(request: dict, manifest: dict, reader) -> None:+ """Canary has native promoted feeds, not stable's candidate transaction."""+ import xml.etree.ElementTree as ET++ from scripts.releases.darwin import parse_mac_feed+ tag, base = request["releaseTag"], request["publicBase"]+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ handoff.fetch(tag, request["commit"], list(NATIVE_LEGS), root,+ ["metadata-*.json", "*.zip", "*.dmg", "*.blockmap", "*.msixbundle"], public_base=base)+ expected, feeds = assemble(request, read_native_receipts(root, tag, request["commit"]), root,+ artifact_prefix=f"releases/tag/{tag}/")+ if manifest != expected:+ raise ChannelError("Canary bootstrap differs from receipt-bound native packages")+ live = parse_mac_feed(reader.read_bytes("releases/darwin/canary/canary-mac.yml").decode())+ pinned = parse_mac_feed(feeds[0].read_text(encoding="utf-8-sig"))+ files = [{**entry, "url": base + entry["url"] if entry["url"].startswith("/releases/") else entry["url"]}+ for entry in live["files"]]+ if live["version"] != request["version"] or sorted(files, key=lambda x: x["url"]) != sorted(pinned["files"], key=lambda x: x["url"]):+ raise ChannelError("Canary macOS feed has not promoted these packages")+ descriptor = ET.fromstring(reader.read_bytes("releases/win32/canary/canary.appinstaller"))+ bundle = descriptor.find("{*}MainBundle")+ native = next(p for p in manifest["packages"] if p["platform"] == "win32")+ if bundle is None or any(bundle.get(k) != v for k, v in {+ "Name": native["identity"], "Publisher": native["publisher"], "Version": native["version"]}.items()):+ raise ChannelError("Canary Windows feed has not promoted these packages")+ uri = bundle.get("Uri", "")+ if not uri.startswith(base + "/releases/win32/canary/"):+ raise ChannelError("Canary Windows feed archive mismatch")+ r2.download_public_object(base, uri.removeprefix(base + "/"), root / "promoted.msixbundle",+ expected_size=native["artifact"]["size"], expected_sha256=native["artifact"]["sha256"])++def publish_release(policy: str, env: dict, root: Path) -> dict:from scripts.releases.commit_build import version_attag, commit = admit_transaction(policy, env)+ if env.get("R2_DISPOSABLE_RUN"):+ raise ChannelError("Disposable receiver builds cannot enter production release publication")publisher = ChannelPublisher(R2ChannelStore(*r2.credentials()), env["GITHUB_REPOSITORY"],r2.public_base_url(), authorize=lambda action, record: admit_transaction(policy, env))name = select_channel(publisher, policy)@@ -237,7 +246,7 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:request = publisher.allocate_protected(name, commit, version_at(None, commit), release_tag=tag,version=tag[1:], windows_version=windows["version"],identity=identity, policy=policy, release_gate=release_gate)- manifest, feeds = assemble(request, native, root)+ manifest, feeds = assemble(request, native, root, artifact_prefix=f"releases/tag/{tag}/")if accepted is not None:match_accepted_packages(manifest, accepted)prefix = build_prefix(request["buildId"])@@ -250,9 +259,11 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:def qualified(pinned: dict, actual: dict) -> bool:# Rehash local receipt-bound bytes rather than trusting caller-supplied claims.- expected, _ = assemble(pinned, read_native_receipts(root, tag, commit), root)+ expected, _ = assemble(pinned, read_native_receipts(root, tag, commit), root,+ artifact_prefix=f"releases/tag/{tag}/")if accepted is not None:match_accepted_packages(expected, accepted)+return pinned == request and actual == expectedpublisher.verify_build = qualified@@ -262,9 +273,14 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:def main(argv: list[str] | None = None) -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("role", choices=("stable", "canary"), help="Protected release policy, not a channel name")++ parser.add_argument("--root", type=Path)args = parser.parse_args(argv)- with tempfile.TemporaryDirectory() as directory:- result = publish_release(args.role + "-release", dict(os.environ), Path(directory))+ if args.root:+ result = publish_release(args.role + "-release", dict(os.environ), args.root)+ else:+ with tempfile.TemporaryDirectory() as directory:+ result = publish_release(args.role + "-release", dict(os.environ), Path(directory))print(json.dumps(result, sort_keys=True))diff --git a/scripts/releases/channels.py b/scripts/releases/channels.pyindex fcdb4d5afb6..6d397ca1584 100644--- a/scripts/releases/channels.py+++ b/scripts/releases/channels.py@@ -24,11 +24,13 @@ class PublicVisibilityError(ChannelError):class R2ChannelStore:- def __init__(self, creds: dict, base: str, bucket: str):+ def __init__(self, creds: dict, base: str, bucket: str, *, scope=None):+ from scripts.releases.r2_scope import R2Scopeself.creds, self.base, self.bucket = creds, base.rstrip("/"), bucket+ self.scope = R2Scope.configured() if scope is None else scopedef get(self, key: str) -> tuple[bytes, str] | None:- url = f"{self.base}/{self.bucket}/{r2.encode_key_path(artifact_key(key))}"+ url = self.scope.object_url(self.base, self.bucket, artifact_key(key))try:response = r2.signed_request("GET", url, creds=self.creds, now=r2.amz_timestamp())except r2.R2RequestError as exc:@@ -44,7 +46,7 @@ class R2ChannelStore:return body, etagdef put(self, key: str, body: bytes, etag: str | None = None) -> None:- url = f"{self.base}/{self.bucket}/{r2.encode_key_path(artifact_key(key))}"+ url = self.scope.object_url(self.base, self.bucket, artifact_key(key))condition = {"If-Match": etag} if etag is not None else {"If-None-Match": "*"}condition["Cache-Control"] = r2.cache_control_for(key) or "no-store"try:@@ -65,15 +67,16 @@ class R2ChannelStore:def keys(self, prefix: str) -> list[str]:keys, seen = [], set()+ prefix = self.scope.listing_prefix(prefix)token = Nonewhile True:params = {"list-type": "2", "max-keys": "1000", "prefix": prefix}if token is not None:params["continuation-token"] = token- url = f"{self.base}/{self.bucket}?{r2.canonical_query(params)}"+ url = f"{self.scope.bucket_url(self.base, self.bucket)}?{r2.canonical_query(params)}"response = r2.signed_request("GET", url, creds=self.creds, now=r2.amz_timestamp())page = r2.parse_list_xml(response.text())- keys.extend(page["keys"])+ keys.extend(self.scope.logical_key(key) for key in page["keys"])if not page["truncated"]:return keystoken = page["nextToken"]@@ -93,14 +96,14 @@ def preview_identity(name: str, token: str) -> dict:class ChannelPublisher:def __init__(self, store: R2ChannelStore, repository: str, public_base: str,- authorize, verify_build=None, verify_retirement=None):+ authorize, verify_build=None):self.store = storeself.repository = validate_repository(repository)self.public_base = validate_public_base(public_base)self.reader = ChannelReader(self.public_base, self.repository)self.authorize = authorizeself.verify_build = verify_build- self.verify_retirement = verify_retirement+def _read(self, name: str) -> tuple[dict, str] | None:value = self.store.get(channel_key(name))@@ -376,7 +379,7 @@ class ChannelPublisher:raise ChannelConflict("Channel promotion remained contended")def retire(self, name: str, destination: str, minimum_version: str,- compatibility_key: str, compatibility_sha256: str, *, publish: bool = True) -> dict:+ *, publish: bool = True) -> dict:validate_name(destination)if name == destination:raise ChannelError("Channel retirement cycle")@@ -391,25 +394,20 @@ class ChannelPublisher:target, target_etag = target_read# Do not discard incomparable intermediate identity floors.if target["state"] != "active" or target["policy"] != "stable-release" or target["head"] is None:- raise ChannelError("Retirement requires a directly qualified active stable-release destination")- qualification = decode_json(self.reader.read_bytes(compatibility_key, compatibility_sha256))- expected = {"schema": 1, "source": name, "sourceHead": record["head"],- "destination": destination, "destinationHead": target["head"], "minimumVersion": minimum_version}- if any(qualification.get(field) != value for field, value in expected.items()):- raise ChannelError("Retirement qualification does not cover current heads and floor")+ raise ChannelError("Retirement requires a directly active stable-release destination")target_raw = self.reader.read_bytes(target["head"]["manifestKey"], target["head"]["sha256"])manifest = validate_manifest(decode_json(target_raw), target, self.public_base)retired = {**record, "state": "retired", "revision": record["revision"] + 1,"destination": destination, "minimumVersion": minimum_version,- "compatibilityKey": compatibility_key, "compatibilitySha256": compatibility_sha256,+ "destinationHead": target["head"], "receiverProtocol": 1,"lastHead": record["head"]}validate_record(retired)if tuple(map(int, manifest["request"]["sourceVersion"].split("."))) < tuple(map(int, minimum_version.split("."))):raise ChannelError("Destination does not meet minimum version")- if self.verify_retirement is None or self.verify_retirement(record, target, qualification) is not True:- raise ChannelError("Retirement requires signed cohort compatibility qualification")+ if manifest.get("receiverProtocol") != 1:+ raise ChannelError("Stable release does not declare retirement receiver support")if self._read(destination) != (target, target_etag):- raise ChannelConflict("Retirement destination changed; re-qualify")+ raise ChannelConflict("Retirement destination changed; review the new target before retrying")if publish:self._write(channel_key(name), retired, etag)return retireddiff --git a/scripts/releases/r2.py b/scripts/releases/r2.pyindex 5848e972ff4..0b6b574e3e1 100644--- a/scripts/releases/r2.py+++ b/scripts/releases/r2.py@@ -14,6 +14,8 @@ from datetime import datetime, timezonefrom typing import Callable, Iterable, castfrom urllib.parse import quote, urlparse+from scripts.releases.r2_scope import R2Scope+REGION = "auto"SERVICE = "s3"EMPTY_SHA = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"@@ -322,7 +324,7 @@ def download_object(creds: dict[str, str], base: str, bucket: str, key: str, file: Path, now: str,*, expected_size: int, expected_sha256: str,) -> None:- url = f"{base}/{bucket}/{encode_key_path(key)}"+ url = R2Scope.configured().object_url(base, bucket, key)parsed = urlparse(url)def headers(attempt: int) -> dict[str, str]:return r2_headers("GET", parsed.netloc, parsed.path, "", EMPTY_SHA,@@ -506,9 +508,9 @@ DEFAULT_PUBLIC_URL = "https://hermes-assets.nousresearch.com"def public_base_url(explicit: str | None = None) -> str:- return (+ return R2Scope.configured().public_base(explicit or os.environ.get("CLOUDFLARE_R2_PUBLIC_URL") or DEFAULT_PUBLIC_URL- ).rstrip("/")+ )def public_url_for(base_url: str, key: str) -> str:@@ -564,6 +566,7 @@ def required_env(name: str) -> str:def credentials() -> tuple[dict[str, str], str, str]:"""(creds, base, bucket) from the R2 env vars. No secrets are printed."""+ R2Scope.configured() # Fail closed before exposing an unscoped fork transport.creds = {"access_key_id": required_env("CLOUDFLARE_R2_ACCESS_KEY_ID"),"secret_key": required_env("CLOUDFLARE_R2_SECRET_ACCESS_KEY"),@@ -616,7 +619,7 @@ def put_object(if cache_control:extra["Cache-Control"] = cache_control- url = f"{base}/{bucket}/{encode_key_path(key)}"+ url = R2Scope.configured().object_url(base, bucket, key)last_error: Exception | None = Noneresponse: Response | None = Nonefor _ in range(3):@@ -762,6 +765,8 @@ def list_objects(if creds is None:creds, base, bucket = credentials()assert creds is not None and base is not None and bucket is not None+ scope = R2Scope.configured()+ prefix = scope.listing_prefix(prefix)keys: list[str] = []last_modified: dict[str, int] = {}token: str | None = None@@ -772,7 +777,7 @@ def list_objects(if token:params["continuation-token"] = tokenquery = canonical_query(params)- url = f"{base}/{bucket}?{query}"+ url = f"{scope.bucket_url(base, bucket)}?{query}"if fetcher is not None:response = fetcher(method="GET", url=url, body_hash=EMPTY_SHA)if response.status >= 400:@@ -785,7 +790,8 @@ def list_objects(if not parsed["truncated"] or not parsed["nextToken"]:breaktoken = parsed["nextToken"]- return {"keys": keys, "lastModified": last_modified}+ return {"keys": [scope.logical_key(key) for key in keys],+ "lastModified": {scope.logical_key(key): value for key, value in last_modified.items()}}def get_object(@@ -793,7 +799,7 @@ def get_object(fetcher: Callable[..., Response] | None = None,) -> str | None:"""GET one object's body, or None when it does not exist / cannot be read."""- url = f"{base}/{bucket}/{encode_key_path(key)}"+ url = R2Scope.configured().object_url(base, bucket, key)response = (fetcher(method="GET", url=url, body_hash=EMPTY_SHA)if fetcher is not None@@ -960,7 +966,7 @@ def prune(if dry_run:print(f"(dry-run) would delete r2:{key}")continue- url = f"{base}/{bucket}/{encode_key_path(key)}"+ url = R2Scope.configured().object_url(base, bucket, key)response = (fetcher(method="DELETE", url=url, body_hash=EMPTY_SHA)if fetcher is not Nonediff --git a/tests/ci/test_channel_build_publication.py b/tests/ci/test_channel_build_publication.pyindex 81035d2a827..068cefe58bf 100644--- a/tests/ci/test_channel_build_publication.py+++ b/tests/ci/test_channel_build_publication.py@@ -32,9 +32,20 @@ def request_for(base):@pytest.fixture-def staged_channel(tmp_path, r2_server):+def staged_channel(tmp_path, r2_server, request, monkeypatch):+ from scripts.releases.r2_scope import R2Scopebase = f"http://127.0.0.1:{r2_server.server_port}/hermes-releases"- request = request_for(base)+ if getattr(request, "param", ""):+ monkeypatch.setenv("R2_DISPOSABLE_RUN", "98765-1" if request.param == "receiver" else request.param)+ monkeypatch.setenv("GITHUB_REPOSITORY_ID", "12345")+ monkeypatch.setenv("CLOUDFLARE_R2_PUBLIC_URL", base)+ scope = R2Scope.configured()+ receiver = getattr(request, "param", "") == "receiver"+ request = request_for(scope.public_base(base))+ if receiver:+ from scripts.releases.channel_releases import product_identity+ request.update(channel="stable", receiverCandidate=True, releaseTag="v0.0.7",+ identity=product_identity("v0.0.7"), bundleEnv={})_origin, clone = _seed_repo(tmp_path)request.update(commit=_git("rev-parse", "HEAD", cwd=clone), sourceVersion="0.1.2")build = tmp_path / "build"@@ -46,8 +57,11 @@ def staged_channel(tmp_path, r2_server):metadata = {"platform": native, "arch": arch, "commit": request["commit"], "request": request,"identity": request["identity"]["appId" if platform == "darwin" else "msixAppIdWithOrg"],"version": request["version" if platform == "darwin" else "windowsVersion"]}+ if receiver:+ metadata["receiverProtocol"] = 1if platform == "darwin":metadata["teamId"] = "ABCDEFGHIJ"+ metadata["filename"] = f"{name}-0.0.7-mac-{arch}.zip"files = [f"{name}-0.0.7-mac-{arch}.{suffix}" for suffix in ("zip", "dmg", "zip.blockmap", "dmg.blockmap")]for file in files:(build / file).write_bytes(f"native transport fixture, not signed: {file}".encode())@@ -71,7 +85,7 @@ def staged_channel(tmp_path, r2_server):+ '<Package Type="application" Architecture="x64"/></Packages></Bundle>')handoff.stage_channel_build(request, "windows-universal", build, [bundle_name])prefix = handoff.channel_prefix(request)- r2_server.store[prefix + "request.json"] = (canonical_json(request), '"request"')+ r2_server.store[scope.key(prefix + "request.json")] = (canonical_json(request), '"request"')return request, build@@ -122,6 +136,32 @@ def test_channel_handoff_binds_full_request_and_feed_bytes(tmp_path, r2_server,channel_publish.assemble(request, fetched, needs=needs)[email protected]("staged_channel", ["receiver"], indirect=True)+def test_scoped_receiver_publication_preserves_existing_head_and_requires_smoke(tmp_path, r2_server, staged_channel):+ from scripts.releases.channels import ChannelPublisher, R2ChannelStore+ from scripts.releases.r2_scope import R2Scope+ request, _ = staged_channel+ scope = R2Scope.configured()+ previous = {"buildId": "b" * 32, "sequence": 1,+ "manifestKey": "releases/channel-builds/" + "b" * 32 + "/build.json", "sha256": "e" * 64}+ record = {"schema": 1, "name": "stable", "repository": request["repository"], "policy": "stable-release",+ "state": "active", "revision": 1, "nextSequence": 8, "identity": request["identity"],+ "testOnly": True, "head": previous}+ key = scope.key("releases/channels/stable.json")+ r2_server.store[key] = (canonical_json(record), '"record"')+ publisher = ChannelPublisher(R2ChannelStore(*r2.credentials()), request["repository"], request["publicBase"],+ authorize=lambda *_: pytest.fail("Receiver must not enter production promotion"))+ before = dict(r2_server.store)+ with pytest.raises(ValueError, match="successful jobs"):+ channel_publish.publish_receiver(request, tmp_path / "rejected", needs={}, publisher=publisher)+ assert r2_server.store == before+ result = channel_publish.publish_receiver(request, tmp_path / "receiver", publisher=publisher,+ needs={job: {"result": "success"} for job in channel_publish.REQUIRED_JOBS})+ assert result["manifest"]["receiverProtocol"] == 1+ assert json.loads(publisher.reader.read_bytes(result["head"]["manifestKey"], result["head"]["sha256"])) == result["manifest"]+ assert json.loads(r2_server.store[key][0])["head"] == previous++def workflow_step(workflow, job, name):doc = hermes_yaml.safe_load((ROOT / ".github/workflows" / workflow).read_text(encoding="utf-8"))return next(step["run"] for step in doc["jobs"][job]["steps"] if step.get("name") == name)@@ -208,9 +248,12 @@ def test_workflow_promotion_missing_native_gate_does_not_write(tmp_path, r2_serv@pytest.mark.platforms("posix")[email protected]("staged_channel", ["", "98765-1"], indirect=True)def test_real_publication_cas_and_manifest_summary(tmp_path, r2_server, staged_channel):request, _ = staged_channel- channel_key = f"releases/channels/{request['channel']}.json"+ from scripts.releases.r2_scope import R2Scope+ scope = R2Scope.configured()+ channel_key = scope.key(f"releases/channels/{request['channel']}.json")record = {"schema": 1, "name": request["channel"], "repository": request["repository"],"policy": "preview", "state": "active", "revision": 1, "nextSequence": 8,"identity": request["identity"], "head": None}@@ -223,7 +266,12 @@ def test_real_publication_cas_and_manifest_summary(tmp_path, r2_server, staged_c"DEFAULT_BRANCH": "main", "GITHUB_REF": "refs/heads/main", "GITHUB_EVENT_NAME": "workflow_dispatch","GITHUB_WORKFLOW_REF": "fixture/repo/.github/workflows/desktop-bundled-release.yml@refs/heads/main","GITHUB_SHA": request["commit"], "GITHUB_ACTOR": "fixture", "GITHUB_TRIGGERING_ACTOR": "fixture"}- prefix = handoff.channel_prefix(request)+ prefix = scope.prefix + handoff.channel_prefix(request)+ if scope.prefix:+ env["CLOUDFLARE_R2_PUBLIC_URL"] = os.environ["CLOUDFLARE_R2_PUBLIC_URL"]+ env["GITHUB_ACTIONS"] = "true"+ # A production sentinel makes accidental writes outside scope observable.+ r2_server.store["releases/channels/stable.json"] = (b"production sentinel", '"production"')artifact_key = prefix + request["identity"]["artifactNamePascal"] + "-0.0.7-mac-x64.zip"saved = r2_server.store[artifact_key]r2_server.store[artifact_key] = (b"damaged artifact", '"damaged"')@@ -235,7 +283,7 @@ def test_real_publication_cas_and_manifest_summary(tmp_path, r2_server, staged_cresult = run_shell(tmp_path, r2_server, script, env, cwd=tmp_path / "clone")assert result.returncode == 0, result.stdout + result.stderrstored = json.loads(r2_server.store[channel_key][0])- manifest_key = handoff.channel_prefix(request) + "build.json"+ manifest_key = scope.key(handoff.channel_prefix(request) + "build.json")raw = r2_server.store[manifest_key][0]assert stored["head"]["sha256"] == hashlib.sha256(raw).hexdigest()manifest = json.loads(raw)@@ -245,10 +293,20 @@ def test_real_publication_cas_and_manifest_summary(tmp_path, r2_server, staged_cassert request["publicBase"] + "/" + package["artifact"]["key"] in summaryputs = [path for method, path, _ in r2_server.requests if method == "PUT"]assert puts[-1].endswith(channel_key)+ if scope.prefix:+ assert all(path.startswith("/hermes-releases/" + scope.prefix) for path in puts)+ assert r2_server.store["releases/channels/stable.json"][0] == b"production sentinel"+ smoke_env = {**env, "SMOKE_ROOT": str(tmp_path / "scoped-smoke"), "PUBLIC_BASE": request["publicBase"],+ "RELEASE_TAG": "", "RELEASE_COMMIT": request["commit"], "COMMIT_BUILD": "false",+ "PLATFORM": "win32", "ARCH": "x64", "FORMAT": "msix", "GITHUB_OUTPUT": str(tmp_path / "smoke-output")}+ fetch = workflow_step("desktop-bundle-smoke.yml", "windows", "Fetch one exact downloadable artifact")+ result = run_shell(tmp_path, r2_server, fetch, smoke_env)+ assert result.returncode == 0, result.stdout + result.stderr+ evidence = json.loads((tmp_path / "scoped-smoke/out/download.json").read_text())+ assert evidence["request"] == request# A retired publisher can stage immutable diagnostics, but never revive its pointer.retired = {**stored, "state": "retired", "destination": "stable", "minimumVersion": "1.2.3",- "lastHead": stored["head"], "compatibilityKey": "releases/qualification/example.json",- "compatibilitySha256": "d" * 64}+ "lastHead": stored["head"], "destinationHead": stored["head"], "receiverProtocol": 1}r2_server.store[channel_key] = (canonical_json(retired), '"retired"')result = run_shell(tmp_path, r2_server, script, env, cwd=tmp_path / "clone")assert result.returncode != 0 and "Retired" in result.stderr@@ -287,8 +345,10 @@ def test_channel_windows_record_stage_and_assembly_handoff_shell(tmp_path, r2_seassert result.returncode == 0, result.stdout + result.stderrassert sorted(p.name for p in release.glob("*.msix")) == sorted(p.name for p in build.glob("*.msix"))# Native admission validates package stamps before the stage can claim completion.+ with zipfile.ZipFile(release / filename) as package:+ manifest = package.read('AppxManifest.xml')with zipfile.ZipFile(release / filename, "w") as package:- package.writestr("AppxManifest.xml", '<Package><Identity Name="Wrong" Publisher="CN=Fixture" Version="0.0.7.0" ProcessorArchitecture="x64"/><Applications><Application Id="App"/></Applications></Package>')+ package.writestr("AppxManifest.xml", manifest)package.writestr("app/resources/install-stamp.json", json.dumps({"source": "commit-build", "commit": request["commit"]}))before = dict(r2_server.store)result = run_shell(tmp_path, r2_server, script, env)@@ -300,6 +360,86 @@ def test_channel_windows_record_stage_and_assembly_handoff_shell(tmp_path, r2_seassert result.returncode == expected[email protected]("posix")+def test_disposable_controller_allocates_then_separate_admission(tmp_path):+ from tests.scripts.test_release_channels import object_server+ _origin, clone = _seed_repo(tmp_path)+ commit = _git("rev-parse", "HEAD", cwd=clone)+ with object_server() as (url, objects, headers, requests, faults):+ # run_shell redirects only the R2 network endpoint; the controller,+ # permission CLI, pushed Git source and both workflow scripts run for real.+ from types import SimpleNamespace+ server = SimpleNamespace(server_port=int(url.rsplit(":", 1)[1]))+ env = {"DISPOSABLE_CHANNEL": "native-preview", "BUILD_COMMIT": commit,+ "CLOUDFLARE_R2_BUCKET": "bucket", "CLOUDFLARE_R2_PUBLIC_URL": url + "/bucket",+ "CLOUDFLARE_R2_ACCOUNT_ID": "loopback", "CLOUDFLARE_R2_ACCESS_KEY_ID": "fixture",+ "CLOUDFLARE_R2_SECRET_ACCESS_KEY": "fixture", "GITHUB_REPOSITORY": "fixture/repo",+ "GITHUB_REPOSITORY_ID": "12345", "GITHUB_RUN_ID": "98765", "GITHUB_RUN_ATTEMPT": "1",+ "GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "workflow_dispatch",+ "GITHUB_REF": "refs/heads/main", "DEFAULT_BRANCH": "main", "GITHUB_SHA": commit,+ "GITHUB_WORKFLOW_REF": "fixture/repo/.github/workflows/desktop-bundled-release.yml@refs/heads/main",+ "GITHUB_ACTOR": "fixture", "GITHUB_TRIGGERING_ACTOR": "fixture", "UPLOAD_RELEASE": "false",+ "GITHUB_STEP_SUMMARY": str(tmp_path / "allocation.md"), "BUNDLE_ENV_JSON": "{}"}+ script = workflow_step("desktop-bundled-release.yml", "allocate-disposable", "Probe scoped storage and allocate without dispatching")+ objects["releases/channels/stable.json"] = b"production sentinel"+ result = run_shell(tmp_path, server, script, env, cwd=clone)+ assert result.returncode == 0, result.stdout + result.stderr+ allocation = json.loads(result.stdout)+ request = allocation["request"]+ assert request["publicBase"] == url + "/bucket/ci-disposable/12345/98765-1"+ assert allocation["storagePrefix"] == "ci-disposable/12345/98765-1/"+ assert "disposable_run=98765-1" in allocation["command"]+ assert "channel_build=" + request["buildId"] in allocation["command"]+ assert objects["releases/channels/stable.json"] == b"production sentinel"+ assert all(key.startswith(allocation["storagePrefix"]) for method, key in requests if method == "PUT")+ before = dict(objects)+ for change in ({"R2_DISPOSABLE_RUN": "98765-1"}, {"DISPOSABLE_CHANNEL": "stable"},+ {"GITHUB_REF": "refs/heads/other"}, {"GITHUB_ACTOR": "", "GITHUB_TRIGGERING_ACTOR": ""}):+ failed = run_shell(tmp_path, server, script, {**env, **change}, cwd=clone)+ assert failed.returncode != 0+ assert objects == before+ admit_env = {**env, "DISPOSABLE_CHANNEL": "", "BUILD_COMMIT": "", "TAG": "",+ "R2_DISPOSABLE_RUN": allocation["disposableRun"], "CHANNEL_BUILD": request["buildId"],+ "CHANNEL_REQUEST_SHA256": allocation["requestSha256"], "GITHUB_OUTPUT": str(tmp_path / "admitted")}+ admission = workflow_step("desktop-bundled-release.yml", "validate", "Validate tag shape, pyproject lockstep, and ancestry on origin/main")+ result = run_shell(tmp_path, server, admission, admit_env, cwd=clone)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "public-base=" + request["publicBase"] in (tmp_path / "admitted").read_text()+ for change in ({"R2_DISPOSABLE_RUN": ""}, {"GITHUB_REPOSITORY_ID": ""},+ {"CLOUDFLARE_R2_PUBLIC_URL": ""}, {"R2_DISPOSABLE_RUN": "../escape"},+ {"R2_DISPOSABLE_RUN": "98765-2"}, {"CHANNEL_REQUEST_SHA256": "f" * 64}):+ failed = run_shell(tmp_path, server, admission, {**admit_env, **change}, cwd=clone)+ assert failed.returncode != 0+ assert objects == before++[email protected]("posix")+def test_receiver_allocation_uses_official_identity_only_inside_scope(tmp_path):+ from tests.scripts.test_release_channels import object_server, publisher+ from scripts.releases.channel_disposable import allocate_receivers+ from scripts.releases.channel_releases import product_identity+ from scripts.releases.r2_scope import R2Scope++ with object_server() as (url, objects, *_):+ pub = publisher(url)+ with pytest.raises(ValueError, match="disposable"):+ allocate_receivers(pub, "a" * 40, "1.2.3", "a" * 40)+ scope = R2Scope("ci-disposable/12345/17-1/")+ pub.store.scope = scope+ pub.public_base += "/" + scope.prefix.rstrip("/")+ from hermes_cli.release_channels import ChannelReader+ pub.reader = ChannelReader(pub.public_base, pub.repository)+ receivers = allocate_receivers(pub, "a" * 40, "1.2.3", "a" * 40)+ assert set(receivers) == {"S", "T"}+ for slot, request in receivers.items():+ assert request["receiverCandidate"] is True+ assert request["identity"] == product_identity("v" + request["version"])+ assert request["publicBase"] == pub.public_base+ assert request["controllerCommit"] == "a" * 40+ assert receivers["T"]["sequence"] > receivers["S"]["sequence"]+ assert pub._read("stable")[0]["head"] is None++def test_pinned_xml_retains_legacy_automatic_policy(tmp_path):from scripts.bundles.release_artifacts import write_appinstallerfor policy in ("automatic", "pinned"):diff --git a/tests/ci/test_desktop_release_tag_admission.py b/tests/ci/test_desktop_release_tag_admission.pyindex 44396258848..a048fb3c3ad 100644--- a/tests/ci/test_desktop_release_tag_admission.py+++ b/tests/ci/test_desktop_release_tag_admission.py@@ -66,16 +66,21 @@ def test_signing_jobs_pin_source_and_controller_revisions_not_mutable_tags():continueref = step.get("with", {}).get("ref")expected = "${{ needs.validate.outputs.sha }}"- if name == "publish-channel" or step.get("if") == "inputs.channel_build != ''":+ if name in {"publish-channel", "allocate-disposable"} or step.get("if") == "inputs.channel_build != ''":expected = "${{ github.sha }}"+ elif name == "validate":+ expected = "${{ (inputs.build_commit != '' || inputs.channel_build != '') && github.sha || inputs.tag }}"elif name == "assemble-win32-bundle":expected = "${{ inputs.channel_build != '' && github.sha || needs.validate.outputs.sha }}"assert ref == expected, (f"signing job {name!r} checks out {ref!r} — it must check out ""the admitted source or explicitly selected trusted controller, never a mutable tag")- # jobs that need the SHA must actually need validate+ # The admission and allocation controllers do not consume a prior admission.for name, job in privileged.items():+ if name in {"validate", "allocate-disposable"}:+ assert not job.get("needs")+ continueneeds = job.get("needs") or []needs = [needs] if isinstance(needs, str) else needsassert "validate" in needs, f"signing job {name!r} reads needs.validate.outputs.sha but does not need validate"diff --git a/tests/ci/test_protected_canary_publication.py b/tests/ci/test_protected_canary_publication.pyindex eb22068a815..e4eaea7dc9c 100644--- a/tests/ci/test_protected_canary_publication.py+++ b/tests/ci/test_protected_canary_publication.py@@ -47,6 +47,13 @@ def canary(tmp_path, r2_server, monkeypatch):(desktop / "product-identity.cjs").symlink_to(ROOT / "apps/desktop/product-identity.cjs")monkeypatch.chdir(clone)identity = channel_releases.product_identity(tag)+ minutes = subprocess.check_output([+ "node", "--input-type=module", "-e",+ f"import {{canaryBuildMinutesFor}} from {json.dumps((ROOT / 'scripts/msix-shared.mjs').as_uri())};"+ f"console.log(canaryBuildMinutesFor({json.dumps(tag)}, Date.UTC(2026, 8, 13) / 1000))",+ ], text=True).strip()+ windows_version = tag[1:].split("-", 1)[0] + "." + minutes+ assert windows_version == "0.1.3.10"tools = tmp_path / "tools"tools.mkdir()driver = tools / "driver.py"@@ -80,7 +87,7 @@ def canary(tmp_path, r2_server, monkeypatch):codesign.chmod(0o755)base = f"http://127.0.0.1:{r2_server.server_port}/hermes-releases"env = {**os.environ, "PATH": str(tools) + os.pathsep + os.environ["PATH"],- "FIXTURE_RELEASE": str(release_state), "GITHUB_ACTIONS": "true",+ "FIXTURE_RELEASE": str(release_state), "FIXTURE_WINDOWS_VERSION": windows_version, "GITHUB_ACTIONS": "true","GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REPOSITORY": "NousResearch/hermes-agent","GITHUB_WORKFLOW_REF": "NousResearch/hermes-agent/.github/workflows/desktop-bundled-release.yml@refs/heads/main","RELEASE_TAG": tag, "TAG": tag, "HERMES_PAYLOAD_TAG": tag,@@ -103,7 +110,7 @@ def native_leg(root, identity, env, platform, arch):artifact = identity["artifactNamePascal"]if platform == "win32":with zipfile.ZipFile(root / f"{artifact}-{version}-win-{arch}.msix", "w") as package:- package.writestr("AppxManifest.xml", f'<Package><Identity Name="{identity["msixAppIdWithOrg"]}" Publisher="CN=Fixture" Version="0.1.3.10" ProcessorArchitecture="{arch}"/><Applications><Application Id="{identity["appNamePascal"]}"/><Application Id="CLI"><VisualElements AppListEntry="none"/></Application></Applications></Package>')+ package.writestr("AppxManifest.xml", f'<Package><Identity Name="{identity["msixAppIdWithOrg"]}" Publisher="CN=Fixture" Version="{env["FIXTURE_WINDOWS_VERSION"]}" ProcessorArchitecture="{arch}"/><Applications><Application Id="{identity["appNamePascal"]}"/><Application Id="CLI"><VisualElements AppListEntry="none"/></Application></Applications></Package>')package.writestr("app/resources/install-stamp.json", json.dumps(stamp))else:name = f"{artifact}-{version}-mac-{arch}"@@ -111,32 +118,46 @@ def native_leg(root, identity, env, platform, arch):with zipfile.ZipFile(root / f"{name}.zip", "w") as package:package.writestr(f"{artifact}.app/Contents/Info.plist", plistlib.dumps({"CFBundleIdentifier": identity["appId"], "CFBundleShortVersionString": version}))package.writestr(f"{artifact}.app/Contents/Resources/install-stamp.json", json.dumps(stamp))+ (root / "canary-mac.yml").write_text(json.dumps({"version": version}))for suffix in ("dmg", "dmg.blockmap", "zip.blockmap"):(root / f"{name}.{suffix}").write_bytes(b"unsigned transport fixture")@pytest.mark.parametrize("platform", ["win32", "darwin"])-def test_canary_metadata_is_recorded_and_receipt_bound(canary, r2_server, platform):- clone, identity, env, run = canary[email protected]("variant,phase,commit_build", [+ ("bundled", "", False), ("bundled", "candidate", False),+ ("light", "", False), ("bundled", "", True),+])+def test_canary_metadata_is_recorded_and_receipt_bound(canary, r2_server, platform, variant, phase, commit_build):+ clone, identity, original_env, run = canary+ env = {**original_env, "HERMES_DESKTOP_VARIANT": variant, "RELEASE_PHASE": phase}+ if phase == "candidate":+ env["RELEASE_TAG"] = env["HERMES_PAYLOAD_TAG"] = "v0.1.2"+ env["FIXTURE_WINDOWS_VERSION"] = "0.1.2.0"+ if commit_build:+ env["RELEASE_TAG"] = env["HERMES_PAYLOAD_TAG"] = ""+ env["HERMES_BUILD_COMMIT"] = env["RELEASE_COMMIT"]root = clone / "apps/desktop/release"native_leg(root, identity, env, platform, "x64")name = "Stage Windows packages to R2" if platform == "win32" else "Stage macOS packages and feed inputs to R2"script = step_script(f"build-{platform}-release", name)- result = run(script, TARGET=f"{platform}-x64")+ result = run(script, **env, TARGET=f"{platform}-x64")assert result.returncode == 0, result.stdout + result.stderr- prefix = f"releases/tag/{env['RELEASE_TAG']}/"+ prefix = f"releases/commit/{env['RELEASE_COMMIT']}/" if commit_build else f"releases/tag/{env['RELEASE_TAG']}/"receipt = json.loads(r2_server.store[prefix + handoff.receipt_name(f"{platform}-x64")][0])metadata_name = f"metadata-{'windows' if platform == 'win32' else 'macos'}-x64.json"+ if variant == "light" or commit_build:+ assert not any(row["path"].startswith("metadata-") for row in receipt["files"])+ returnentry = next(row for row in receipt["files"] if row["path"] == metadata_name)body = r2_server.store[prefix + metadata_name][0]metadata = json.loads(body)assert entry["sha256"] == hashlib.sha256(body).hexdigest()assert metadata["commit"] == env["RELEASE_COMMIT"] and metadata["tag"] == env["RELEASE_TAG"]- assert metadata["version"] == ("0.1.3.10" if platform == "win32" else env["RELEASE_TAG"][1:])+ assert metadata["version"] == (env["FIXTURE_WINDOWS_VERSION"] if platform == "win32" else env["RELEASE_TAG"][1:])-def test_published_canary_workflow_advances_only_after_every_gate(canary, r2_server):- clone, identity, env, run = canary+def stage_canary(clone, identity, env, run):root = clone / "apps/desktop/release"# Stage independent per-architecture job workspaces through the actual shell.import shutil@@ -146,19 +167,28 @@ def test_published_canary_workflow_advances_only_after_every_gate(canary, r2_sershutil.rmtree(root)native_leg(root, identity, env, platform, arch)name = "Stage Windows packages to R2" if platform == "win32" else "Stage macOS packages and feed inputs to R2"- result = run(step_script(f"build-{platform}-release", name), TARGET=f"{platform}-{arch}")+ result = run(step_script(f"build-{platform}-release", name), **env, TARGET=f"{platform}-{arch}")assert result.returncode == 0, result.stdout + result.stderr- bundle = root / f"{identity['artifactNamePascal']}-0.1.3.10-win.msixbundle"+ bundle = root / f"{identity['artifactNamePascal']}-{env['FIXTURE_WINDOWS_VERSION']}-win.msixbundle"with zipfile.ZipFile(bundle, "w") as package:- package.writestr("AppxMetadata/AppxBundleManifest.xml", f'<Bundle><Identity Name="{identity["msixAppIdWithOrg"]}" Publisher="CN=Fixture" Version="0.1.3.10"/><Packages><Package Type="application" Architecture="arm64"/><Package Type="application" Architecture="x64"/></Packages></Bundle>')- result = run('python -m scripts.releases.handoff stage --tag "$RELEASE_TAG" --commit "$RELEASE_COMMIT" --name windows-universal --root apps/desktop/release --include "*.msixbundle"')+ package.writestr("AppxMetadata/AppxBundleManifest.xml", f'<Bundle><Identity Name="{identity["msixAppIdWithOrg"]}" Publisher="CN=Fixture" Version="{env["FIXTURE_WINDOWS_VERSION"]}"/><Packages><Package Type="application" Architecture="arm64"/><Package Type="application" Architecture="x64"/></Packages></Bundle>')+ result = run('python -m scripts.releases.handoff stage --tag "$RELEASE_TAG" --commit "$RELEASE_COMMIT" --name windows-universal --root apps/desktop/release --include "*.msixbundle"', **env)assert result.returncode == 0, result.stdout + result.stderr+ return bundle+++def test_published_canary_workflow_advances_only_after_every_gate(canary, r2_server, monkeypatch, tmp_path):+ clone, identity, env, run = canary+ bundle = stage_canary(clone, identity, env, run)script = step_script("publish-canary", "Advance protected canary head from the published release")before = dict(r2_server.store)- for job in channel_releases.CANARY_NEEDS:- for outcome in ("failure", "skipped", "cancelled"):+ for job in workflow_job("publish-canary")["needs"]:+ for outcome in ("failure", "skipped", "cancelled", None):needs = json.loads(env["RELEASE_NEEDS"])- needs[job] = {"result": outcome}+ if outcome is None:+ del needs[job]+ else:+ needs[job] = {"result": outcome}result = run(script, RELEASE_NEEDS=json.dumps(needs))assert result.returncode != 0 and job in result.stderrassert r2_server.store == before@@ -170,15 +200,85 @@ def test_published_canary_workflow_advances_only_after_every_gate(canary, r2_serassert result.returncode != 0 and "published" in result.stderrassert r2_server.store == beforerelease.write_text(json.dumps(published))- result = run(script)- assert result.returncode == 0, result.stdout + result.stderr+ prefix = f"releases/tag/{env['RELEASE_TAG']}/"+ for key in (prefix + "metadata-windows-arm64.json", prefix + bundle.name):+ saved = r2_server.store.pop(key)+ missing = dict(r2_server.store)+ result = run(script)+ assert result.returncode != 0+ assert r2_server.store == missing+ r2_server.store[key] = (b"corrupt", '"corrupt"')+ corrupted = dict(r2_server.store)+ result = run(script)+ assert result.returncode != 0 and "checksum mismatch" in result.stderr+ assert r2_server.store == corrupted+ r2_server.store[key] = saved+ assert r2_server.store == before+ # Replay all final publication shell in its declared order, including edit+ # followed by the controller's independent published-release read-back.+ release.write_text(json.dumps({**published, "isDraft": True}))+ for step in workflow_job("publish-canary")["steps"]:+ if "run" in step:+ result = run(step["run"])+ assert result.returncode == 0, result.stdout + result.stderrresolved = ChannelReader(env["CLOUDFLARE_R2_PUBLIC_URL"], repository=env["GITHUB_REPOSITORY"]).resolve("canary")+ assert resolved.manifest is not Noneassert resolved.manifest["request"]["windowsVersion"] == "0.1.3.10"assert resolved.manifest["request"]["commit"] == env["RELEASE_COMMIT"]assert len(resolved.manifest["packages"]) == 4+ # Bootstrap reads actual receipt-bound artifacts and the promoted native feeds,+ # rather than asking canary for a stable-only candidate manifest.+ from scripts.bundles.release_artifacts import write_appinstaller+ from scripts.releases import stable+ from hermes_cli.release_channels import canonical_json+ mac = resolved.manifest["packages"][0]+ mac_feed = json.loads(r2_server.store[mac["feed"]["key"]][0])+ for entry in mac_feed["files"]:+ entry["url"] = entry["url"].removeprefix(env["CLOUDFLARE_R2_PUBLIC_URL"])+ mac_feed["path"] = mac_feed["path"].removeprefix(env["CLOUDFLARE_R2_PUBLIC_URL"])+ r2_server.store["releases/darwin/canary/canary-mac.yml"] = (canonical_json(mac_feed), '"feed"')+ win = next(p for p in resolved.manifest["packages"] if p["platform"] == "win32")+ promoted_key = "releases/win32/canary/" + bundle.name+ r2_server.store[promoted_key] = r2_server.store[win["artifact"]["key"]]+ descriptor = tmp_path / "canary.appinstaller"+ write_appinstaller(descriptor, identity=win["identity"], publisher=win["publisher"], version=win["version"],+ self_uri=env["CLOUDFLARE_R2_PUBLIC_URL"] + "/releases/win32/canary/canary.appinstaller",+ artifact_uri=env["CLOUDFLARE_R2_PUBLIC_URL"] + "/" + promoted_key)+ r2_server.store["releases/win32/canary/canary.appinstaller"] = (descriptor.read_bytes(), '"feed"')+ monkeypatch.setattr(stable, "output", lambda args: env["RELEASE_COMMIT"] if "/commits/" in args[2]+ else json.dumps({"draft": False, "prerelease": True, "published_at": "fixture-published"}))+ assert channel_releases.verify_bootstrap(resolved.manifest["request"], resolved.manifest,+ env["CLOUDFLARE_R2_PUBLIC_URL"], env["GITHUB_REPOSITORY"])+ saved_feed = r2_server.store["releases/darwin/canary/canary-mac.yml"]+ bad = json.loads(saved_feed[0]); bad["version"] = "9.0.0"+ r2_server.store["releases/darwin/canary/canary-mac.yml"] = (canonical_json(bad), '"bad"')+ with pytest.raises(ValueError, match="promoted"):+ channel_releases.verify_bootstrap(resolved.manifest["request"], resolved.manifest,+ env["CLOUDFLARE_R2_PUBLIC_URL"], env["GITHUB_REPOSITORY"])+ r2_server.store["releases/darwin/canary/canary-mac.yml"] = saved_feedafter = dict(r2_server.store)assert run(script).returncode == 0assert r2_server.store == after+ # A later canary really advances the existing head and native quad, rather+ # than merely succeeding at the empty-channel bootstrap case.+ newer_tag = "v0.1.3-canary.20260913001100"+ _git("tag", newer_tag, cwd=clone)+ _git("push", "origin", newer_tag, cwd=clone)+ newer = {**env, "RELEASE_TAG": newer_tag, "HERMES_PAYLOAD_TAG": newer_tag,+ "FIXTURE_WINDOWS_VERSION": "0.1.3.11"}+ stage_canary(clone, identity, newer, run)+ release.write_text(json.dumps({**published, "tagName": newer_tag}))+ result = run(script, **newer)+ assert result.returncode == 0, result.stdout + result.stderr+ advanced = ChannelReader(env["CLOUDFLARE_R2_PUBLIC_URL"], repository=env["GITHUB_REPOSITORY"]).resolve("canary")+ assert advanced.manifest is not None+ assert advanced.manifest["request"]["windowsVersion"] == "0.1.3.11"+ assert advanced.terminal["head"]["sequence"] > resolved.terminal["head"]["sequence"]+ after = dict(r2_server.store)+ release.write_text(json.dumps(published))+ result = run(script)+ assert result.returncode != 0 and "stale" in result.stderr+ assert r2_server.store == after# A moved published tag must not retarget the accepted release, even on retry._git("commit", "--allow-empty", "-m", "new source", cwd=clone)_git("tag", "-f", env["RELEASE_TAG"], cwd=clone)diff --git a/tests/hermes_cli/test_backup_zip_serialization.py b/tests/hermes_cli/test_backup_zip_serialization.pyindex 9c945c1148e..341148dfb18 100644--- a/tests/hermes_cli/test_backup_zip_serialization.py+++ b/tests/hermes_cli/test_backup_zip_serialization.py@@ -48,3 +48,40 @@ def test_zip_captures_live_wal_and_cleans_failed_staging(tmp_path, monkeypatch,monkeypatch.setattr(zipfile.ZipFile, "write", refuse_write)run()assert sorted(output.iterdir()) == [archive], "a failed write must not leak a private database snapshot"+++def test_strict_migration_snapshot_preserves_full_inventory_and_reports_read_failures(tmp_path, monkeypatch):+ from hermes_cli.backup_migration import snapshot_migration_home++ home = tmp_path / 'home'+ home.mkdir()+ monkeypatch.setenv('HERMES_HOME', str(home))+ for relative in ['skills/custom/SKILL.md', 'profiles/work/sessions/transcript.jsonl', 'cache/images/photo.png']:+ file = home / relative+ file.parent.mkdir(parents=True, exist_ok=True)+ file.write_text(relative)+ (home / 'models').mkdir()+ (home / 'models/regenerable').write_text('not a migration payload')+ with closing(sqlite3.connect(home / 'state.db')) as writer:+ writer.executescript("PRAGMA journal_mode=WAL; CREATE TABLE witness(value); INSERT INTO witness VALUES ('WAL')")+ snapshot = tmp_path / 'snapshot'+ snapshot_migration_home(home, snapshot)+ with closing(sqlite3.connect(snapshot / 'state.db')) as reader:+ assert reader.execute('SELECT value FROM witness').fetchall() == [('WAL',)]+ assert (snapshot / 'skills/custom/SKILL.md').read_text() == 'skills/custom/SKILL.md'+ assert (snapshot / 'profiles/work/sessions/transcript.jsonl').exists()+ assert (snapshot / 'cache/images/photo.png').exists()+ assert not (snapshot / 'models').exists()+ assert not (snapshot / 'state.db-wal').exists()++ original = Path.open++ def unreadable(self, *args, **kwargs):+ if self == home / 'skills/custom/SKILL.md':+ raise PermissionError('source became unreadable')+ return original(self, *args, **kwargs)++ monkeypatch.setattr(Path, 'open', unreadable)+ with pytest.raises(PermissionError, match='unreadable'):+ snapshot_migration_home(home, tmp_path / 'failed-snapshot')+ assert (snapshot / 'skills/custom/SKILL.md').exists()diff --git a/tests/hermes_cli/test_release_channels.py b/tests/hermes_cli/test_release_channels.pyindex 3ae211422d5..082148f157d 100644--- a/tests/hermes_cli/test_release_channels.py+++ b/tests/hermes_cli/test_release_channels.py@@ -17,7 +17,7 @@ object_server, publisher = _fixture.object_server, _fixture.publisherdef seed_manifest(pub, request, objects):from hermes_cli.release_channels import build_prefix, canonical_jsonkey = build_prefix(request["buildId"]) + "build.json"- manifest = {"schema": 1, "request": request, "packages": [{"platform": "darwin", "arch": "arm64", "variant": "bundled",+ manifest = {"schema": 1, "receiverProtocol": 1, "request": request, "packages": [{"platform": "darwin", "arch": "arm64", "variant": "bundled","artifact": {"key": build_prefix(request["buildId"]) + "darwin/package.zip", "sha256": "f" * 64, "size": 123},"version": request["version"], "identity": request["identity"]["appId"], "teamId": "ABCDEFGHIJ","feed": {"key": build_prefix(request["buildId"]) + "darwin/stable-mac.yml", "channel": "stable"}}]}@@ -38,23 +38,23 @@ def test_resolve_verifies_exact_manifest_and_preserves_retirement_constraints():for name in ("old-preview", "next-preview"):pub.create(name)request = pub.allocate("next-preview", "a" * 40, "1.2.3")+ request.update(version="1.2.3", windowsVersion="1.2.3.0", releaseTag="v1.2.3")manifest, record = seed_manifest(pub, request, objects)+ record["policy"] = "stable-release"+ objects["releases/channels/next-preview.json"] = canonical_json(record)reader = ChannelReader(url + "/bucket", repository="example/hermes-agent")assert reader.resolve("next-preview").manifest == manifestold = pub._read("old-preview")[0]- qualification = {"schema": 1, "source": "old-preview", "sourceHead": None, "destination": "next-preview",- "destinationHead": record["head"], "minimumVersion": "1.0.0"}- raw = canonical_json(qualification)- objects["releases/channel-builds/" + request["buildId"] + "/retirement.json"] = rawold.update(state="retired", destination="next-preview", minimumVersion="1.0.0",- compatibilityKey="releases/channel-builds/" + request["buildId"] + "/retirement.json",- compatibilitySha256=hashlib.sha256(raw).hexdigest(), lastHead=None)+ destinationHead=record["head"], receiverProtocol=1, lastHead=None)objects["releases/channels/old-preview.json"] = canonical_json(old)resolved = reader.resolve("old-preview")assert resolved.requested == old and resolved.terminal == record- assert resolved.constraints[0]["minimumVersion"] == "1.0.0"+ assert resolved.requested["minimumVersion"] == "1.0.0"# Retirement pins the qualified destination, not an unqualified later head.- newer = pub.allocate("next-preview", "b" * 40, "1.3.0")+ newer = dict(request, buildId="f" * 32, sequence=2, sourceVersion="1.3.0", version="1.3.0", windowsVersion="1.3.0.0", releaseTag="v1.3.0")+ record["nextSequence"] = 3+ objects["releases/channels/next-preview.json"] = canonical_json(record)seed_manifest(pub, newer, objects)after_advance = reader.resolve("old-preview")assert after_advance.manifest == manifest@@ -93,7 +93,7 @@ def test_reader_rejects_cycles_identity_substitution_and_cross_authority():reader.resolve("alpha")record["repository"] = "example/hermes-agent"record.update(state="retired", destination="alpha", minimumVersion="1.0.0", lastHead=record["head"],- compatibilityKey="releases/retirement.json", compatibilitySha256="a" * 64)+ destinationHead=record["head"], receiverProtocol=1)objects["releases/channels/alpha.json"] = canonical_json(record)with pytest.raises(ChannelError, match="cycle"):reader.resolve("alpha")@@ -109,7 +109,7 @@ def test_legacy_bootstrap_uses_real_archive_keys_and_source_main_has_no_bundle()for name, policy, tag in [("stable", "stable-release", "v2.0.0"), ("canary", "canary-release", "v2.1.0-canary.20260913000100")]:legacy = deepcopy(manifest)legacy["request"].update(channel=name, buildId=("a" if name == "stable" else "b") * 32,- releaseTag=tag, version=tag[1:], windowsVersion="2.0.0.0")+ releaseTag=tag, version=tag[1:], windowsVersion="2.0.0.0" if name == "stable" else "2.1.0.10")legacy["packages"][0].update(version=tag[1:])legacy["packages"][0]["artifact"]["key"] = f"releases/tag/{tag}/actual.zip"legacy["packages"][0]["feed"]["key"] = f"releases/tag/{tag}/stable-mac.yml"@@ -120,6 +120,13 @@ def test_legacy_bootstrap_uses_real_archive_keys_and_source_main_has_no_bundle()pub.bootstrap(record, legacy, publish=True)assert pub.reader.resolve(name).manifest == legacyassert pub.request(legacy["request"]["buildId"]) == legacy["request"]+ from hermes_cli.release_channels import validate_request+ invalid_versions = ["2.1.0.65536", "65536.1.0.0", "2.1.0.-1", "2.1.0.1.0", "2.1.0.x"]+ if policy == "stable-release":+ invalid_versions.append("2.0.0.10")+ for windows_version in invalid_versions:+ with pytest.raises(ChannelError, match="Windows version"):+ validate_request(dict(legacy["request"], windowsVersion=windows_version), policy=policy)with pytest.raises(ChannelError, match="Protected"):pub.promote(legacy["request"]["buildId"])with pytest.raises(ChannelError, match="Protected"):@@ -158,14 +165,12 @@ def test_malformed_record_and_unqualified_retirement_never_resolve():objects["releases/channels/preview.json"] = canonical_json(record)pub.create("destination")request = pub.allocate("destination", "a" * 40, "1.0.0")+ request.update(version="1.0.0", windowsVersion="1.0.0.0", releaseTag="v1.0.0")_, target = seed_manifest(pub, request, objects)- qualification = {"schema": 1, "source": "preview", "sourceHead": None,- "destination": "destination", "destinationHead": target["head"], "minimumVersion": "2.0.0"}- raw = canonical_json(qualification)- key = "releases/channel-builds/" + request["buildId"] + "/retirement.json"- objects[key] = raw+ target["policy"] = "stable-release"+ objects["releases/channels/destination.json"] = canonical_json(target)record.update(state="retired", destination="destination", minimumVersion="2.0.0", lastHead=None,- compatibilityKey=key, compatibilitySha256=hashlib.sha256(raw).hexdigest())+ destinationHead=target["head"], receiverProtocol=1)objects["releases/channels/preview.json"] = canonical_json(record)with pytest.raises(ChannelError, match="minimum version"):pub.reader.resolve("preview")diff --git a/tests/hermes_cli/test_source_channel_integration.py b/tests/hermes_cli/test_source_channel_integration.pyindex 64803c7c534..dee44722882 100644--- a/tests/hermes_cli/test_source_channel_integration.py+++ b/tests/hermes_cli/test_source_channel_integration.py@@ -64,13 +64,7 @@ def reader_result(source, name, destination=None, repository="NousResearch/hermestate="retired" if destination else "active", destination=destination)terminal = record(destination or name, repository=repository)terminal["head"] = {"buildId": "build-fixture", "sequence": 1}- constraints = ()- if destination:- qualification = {"schema": 1, "source": name, "sourceHead": requested["head"],- "destination": destination, "destinationHead": terminal["head"], "minimumVersion": "1.0.0"}- constraints = ({"channel": name, "destination": destination, "minimumVersion": "1.0.0",- "qualification": qualification},)- return SimpleNamespace(requested=requested, terminal=terminal, constraints=constraints, manifest={+ return SimpleNamespace(requested=requested, terminal=terminal, manifest={"schema": 1, "request": {"buildId": "build-fixture", "channel": terminal["name"],"sequence": 1, "repository": repository, "commit": source.commits[1],"sourceVersion": "1.2.3", "version": "0.0.1", "identity": {}, "bundleEnv": {},@@ -226,7 +220,7 @@ def publish_channel_build(channel_archive, name, build_id, commit, *, sequence=1"identity": identity, "bundleEnv": {}, "publicBase": base}if stable:request["releaseTag"] = "v" + version- manifest = {"schema": 1, "request": request, "packages": [{+ manifest = {"schema": 1, "receiverProtocol": 1, "request": request, "packages": [{"platform": "darwin", "arch": "arm64", "variant": "bundled","artifact": {"key": prefix + "fixture.zip", "size": 1, "sha256": "d" * 64},"identity": identity["appId"], "version": version, "teamId": "ABCDEFGHIJ",@@ -266,31 +260,24 @@ def test_real_http_reader_resolves_tagless_build_through_cli(source, monkeypatch@pytest.fixturedef retired_channel_archive(source, channel_archive):- from hashlib import sha256from hermes_cli.release_channels import canonical_jsonarchive, _ = channel_archivename = "offline-preview"preview = publish_channel_build(channel_archive, name, "a" * 32, source.commits[0])qualified = publish_channel_build(channel_archive, "stable", "b" * 32, source.commits[1], stable=True)- qualification = {"schema": 1, "source": name, "sourceHead": preview["head"],- "destination": "stable", "destinationHead": qualified["head"], "minimumVersion": "1.0.0"}- body = canonical_json(qualification)- key = "releases/channel-builds/" + preview["head"]["buildId"] + "/retirement.json"- (archive / key).write_bytes(body)retired = dict(preview, state="retired", destination="stable", minimumVersion="1.0.0",- compatibilityKey=key, compatibilitySha256=sha256(body).hexdigest(), lastHead=preview["head"])+ destinationHead=qualified["head"], receiverProtocol=1, lastHead=preview["head"])(archive / f"releases/channels/{name}.json").write_bytes(canonical_json(retired))publish_channel_build(channel_archive, "stable", "c" * 32, source.commits[2], sequence=2, stable=True)set_install_channel(name, source.root)return SimpleNamespace(archive=archive, name=name, retired=retired,- qualified=qualified, qualification=qualification)+ qualified=qualified)@pytest.mark.parametrize("fault", [None, "binding", "manifest"])def test_offline_retirement_uses_qualified_build_before_current_stable(source, monkeypatch, retired_channel_archive, fault):- from hashlib import sha256from hermes_cli import source_checkfrom hermes_cli.release_channels import canonical_json@@ -304,10 +291,7 @@ def test_offline_retirement_uses_qualified_build_before_current_stable(monkeypatch.setattr(update_cmd, "run_completion", completion)monkeypatch.setattr(update_cmd, "_write_fleet_restart_pending_marker", lambda **kw: None)if fault == "binding":- fixture.qualification["source"] = "wrong-preview"- body = canonical_json(fixture.qualification)- (fixture.archive / fixture.retired["compatibilityKey"]).write_bytes(body)- fixture.retired["compatibilitySha256"] = sha256(body).hexdigest()+ fixture.retired["destinationHead"]["sequence"] += 1(fixture.archive / f"releases/channels/{fixture.name}.json").write_bytes(canonical_json(fixture.retired))elif fault == "manifest":path = fixture.archive / fixture.qualified["head"]["manifestKey"]@@ -477,21 +461,20 @@ def test_changed_checkout_cannot_repin_selected_channel_during_apply(source, monassert saved(source)["channel"] == "preview"[email protected]("fault", ["floor", "qualification", "build", "chain", "missing"])-def test_source_retirement_does_not_discard_compatibility_constraints(source, monkeypatch, fault):- resolved = reader_result(source, "preview", "stable")- constraint = resolved.constraints[0][email protected]("fault", ["floor", "protocol", "build", "chain", "missing"])+def test_source_retirement_rejects_invalid_archive_constraints(source, retired_channel_archive, fault):+ from hermes_cli.release_channels import canonical_json+ fixture = retired_channel_archiveif fault == "floor":- constraint["minimumVersion"] = "9.0.0"- constraint["qualification"]["minimumVersion"] = "9.0.0"- elif fault == "qualification":- constraint["qualification"]["source"] = "another-preview"+ fixture.retired["minimumVersion"] = "9.0.0"+ elif fault == "protocol":+ fixture.retired["receiverProtocol"] = 2elif fault == "build":- resolved.manifest["request"]["buildId"] = "another-build"+ fixture.retired["destinationHead"]["buildId"] = "f" * 32elif fault == "chain":- constraint["destination"] = "intermediate"+ fixture.retired["destination"] = fixture.nameelse:- resolved.constraints = ()- install_reader(monkeypatch, resolved)- with pytest.raises(ValueError, match="retirement|Retirement"):- source_releases.resolve_source_target("preview", ["git"], source.root)+ del fixture.retired["destinationHead"]+ (fixture.archive / f"releases/channels/{fixture.name}.json").write_bytes(canonical_json(fixture.retired))+ with pytest.raises(ValueError):+ source_releases.resolve_source_target(fixture.name, ["git"], source.root)diff --git a/tests/install/e2e-assets/bundle-smoke-metadata.mjs b/tests/install/e2e-assets/bundle-smoke-metadata.mjsindex 9e76bb6c7e7..8a32c0d789e 100644--- a/tests/install/e2e-assets/bundle-smoke-metadata.mjs+++ b/tests/install/e2e-assets/bundle-smoke-metadata.mjs@@ -36,10 +36,13 @@ export function bundleIdentity(commit, tag = '', channelRequest = null) {applicationId: identity.appNamePascal, publisher: OUT_OF_STORE_PUBLISHER }}+/** @param {object} stamp+ * @param {{commit: string, tag?: string, platform: string,+ * channelRequest?: import('../../../apps/desktop/electron/install-stamp.js').ChannelBuildRequest | null}} options */export function verifyBundleStamp(stamp, { commit, tag = '', platform, channelRequest = null }) {if (!['darwin', 'win32'].includes(platform)) throw new Error('Unsupported native platform')const request = channelRequest === null ? null : admitChannelRequest(channelRequest, commit, tag)- const expected = { commit, tag: tag || null, payload: 'bundled', distribution: 'desktop-app', dirty: false,+ const expected = { commit, tag: request?.receiverCandidate ? request.releaseTag : tag || null, payload: 'bundled', distribution: 'desktop-app', dirty: false,updateMechanism: tag || request ? { darwin: 'electron-updater', win32: 'app-installer' }[platform] : 'external' }if (!tag && !request) Object.assign(expected, { source: 'commit-build', branch: null })for (const [key, value] of Object.entries(expected)) {diff --git a/tests/install/e2e-assets/channel-retirement-manifest.cjs b/tests/install/e2e-assets/channel-retirement-manifest.cjsindex 446393f2f32..c3a66878b8f 100644--- a/tests/install/e2e-assets/channel-retirement-manifest.cjs+++ b/tests/install/e2e-assets/channel-retirement-manifest.cjs@@ -1,52 +1,149 @@'use strict'-// Native journey inputs are exact archived builds, not a relaxed OLD/NEW manifest.+// Cross-identity journey input only; ordinary bundle validation stays strict.const { createHash } = require('node:crypto')const { isDeepStrictEqual } = require('node:util')+const semver = require('semver')-function validateJourney(input, platform, arch) {+/** @typedef {import('../../../apps/desktop/electron/updater/channel-protocol.ts').ChannelManifest} Manifest */+/** @typedef {{manifest: Manifest, head: import('../../../apps/desktop/electron/updater/channel-protocol.ts').ChannelHead,+ * package: import('../../../apps/desktop/electron/updater/channel-protocol.ts').ChannelPackage, artifactPath?: string}} Side */+/** @typedef {{schema: 1, platform: 'darwin'|'win32', arch: 'arm64'|'x64', repository: string,+ * controllerCommit: string, route: 'direct'|'via-update', stable: 'absent'|'running', home: 'shared',+ * minimumVersion: string, A: Side, B?: Side, S: Side, T: Side}} Journey */++const SHA256 = /^[a-f0-9]{64}$/+const COMMIT = /^[a-f0-9]{40}$/+const SLUG = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/++function archiveBase(value) {+ const url = new URL(value)+ if (!['https:', 'http:'].includes(url.protocol) ||+ (url.protocol === 'http:' && url.hostname !== '127.0.0.1') ||+ url.username || url.password || url.search || url.hash ||+ /[%\\;\s]/.test(value) || value.endsWith('/') ||+ value.split('/').some(part => part === '.' || part === '..')) {+ throw new Error('Archive must use canonical HTTPS or explicit loopback without credentials')+ }+ return value+}++function objectKey(key) {+ if (!/^releases\/[A-Za-z0-9_./+-]+$/.test(key) || key.split('/').some(part =>+ !part || part === '.' || part === '..' || part.endsWith('.') || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) {+ throw new Error('Invalid immutable object key')+ }+ return key+}+++function validateScenario(input, platform, arch) {if (input.schema !== 1 || input.platform !== platform || input.arch !== arch ||!['darwin', 'win32'].includes(platform) || !['arm64', 'x64'].includes(arch)) {throw new Error('Native journey platform/architecture mismatch')}- if (!/^[a-f0-9]{40}$/.test(input.controllerCommit) || !/^[\w-]+\/[\w.-]+$/.test(input.repository)) {+ if (!COMMIT.test(input.controllerCommit) || !/^[\w-]+\/[\w.-]+$/.test(input.repository)) {throw new Error('Missing controller authority')}- if (!['direct', 'via-update'].includes(input.route) || !['absent', 'running'].includes(input.stable)) {- throw new Error('Unsupported journey scenario')- }- for (const name of ['A', 'S', ...(input.route === 'via-update' ? ['B'] : []), ...(input.T ? ['T'] : [])]) {- const side = input[name]- const request = side?.manifest?.request- const head = side?.head- if (!request || !head || !/^[a-f0-9]{32}$/.test(request.buildId) || !/^[a-f0-9]{40}$/.test(request.commit) ||- request.repository !== input.repository || head.buildId !== request.buildId || head.sequence !== request.sequence ||- head.manifestKey !== `releases/channel-builds/${request.buildId}/build.json` || !/^[a-f0-9]{64}$/.test(head.sha256)) {- throw new Error(`Invalid ${name} immutable build binding`)- }- const url = new URL(request.publicBase)- if (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === '127.0.0.1')) {- throw new Error('Journey archive must use HTTPS or explicit loopback')- }- const packages = side.manifest.packages.filter(p => p.platform === platform && p.arch === arch && p.variant === 'bundled')- if (packages.length !== 1) throw new Error(`Missing ${name} native package`)- const pkg = packages[0]- if (pkg.identity !== request.identity[platform === 'darwin' ? 'appId' : 'msixAppIdWithOrg'] ||- pkg.version !== request[platform === 'darwin' ? 'version' : 'windowsVersion'] ||- !/^[a-f0-9]{64}$/.test(pkg.artifact.sha256) || !Number.isSafeInteger(pkg.artifact.size) || pkg.artifact.size <= 0) {- throw new Error(`Invalid ${name} native artifact`)- }- side.package = pkg- }- if (input.A.package.identity === input.S.package.identity || input.S.manifest.request.releaseTag !== `v${input.S.manifest.request.version}`) {- throw new Error('Retirement must enter a distinct stable release identity')+ if (!['direct', 'via-update'].includes(input.route) || !['absent', 'running'].includes(input.stable) ||+ input.home !== 'shared') throw new Error('Unsupported journey scenario')+ if ((input.route === 'direct') !== (input.B === undefined)) throw new Error('B is required only for via-update')+ if (!semver.valid(input.minimumVersion) || semver.prerelease(input.minimumVersion)) throw new Error('Invalid stable version floor')+}++function validateBinding(side, name, repository) {+ const request = side?.manifest?.request+ const head = side?.head+ if (!request || !head || side.manifest.schema !== 1 || request.schema !== 1 ||+ !/^[a-f0-9]{32}$/.test(request.buildId) || !COMMIT.test(request.commit) ||+ request.repository !== repository || !Number.isSafeInteger(request.sequence) || request.sequence < 1) {+ throw new Error(`Invalid ${name} immutable build binding`)+ }+ if (head.buildId !== request.buildId || head.sequence !== request.sequence ||+ head.manifestKey !== `releases/channel-builds/${request.buildId}/build.json` || !SHA256.test(head.sha256)) {+ throw new Error(`Invalid ${name} immutable head binding`)+ }+ if (!SLUG.test(request.channel) || request.channel.length > 32) throw new Error('Invalid channel name')+ archiveBase(request.publicBase)+ return request+}++function validatePackage(side, request, platform, arch) {+ const packages = side.manifest.packages.filter(p => p.platform === platform && p.arch === arch && p.variant === 'bundled')+ if (packages.length !== 1) throw new Error('Missing unique native package')+ const pkg = packages[0]+ const darwin = platform === 'darwin'+ if (pkg.identity !== request.identity[darwin ? 'appId' : 'msixAppIdWithOrg'] ||+ pkg.version !== request[darwin ? 'version' : 'windowsVersion'] ||+ !SHA256.test(pkg.artifact.sha256) || !Number.isSafeInteger(pkg.artifact.size) || pkg.artifact.size <= 0) {+ throw new Error('Invalid native artifact')}- if (input.B && (input.A.package.identity !== input.B.package.identity || input.B.head.sequence <= input.A.head.sequence)) {- throw new Error('A to B must advance within one preview identity')+ const signer = darwin ? pkg.teamId : pkg.publisher+ if (!signer || (darwin && !/^[A-Z0-9]{10}$/.test(signer))) throw new Error('Missing native signing identity')+ const prefixes = [`releases/channel-builds/${request.buildId}/`]+ if (request.releaseTag) prefixes.push(`releases/tag/${request.releaseTag}/`)+ for (const key of [pkg.artifact.key, pkg.feed.key]) {+ if (!prefixes.some(prefix => objectKey(key).startsWith(prefix))) throw new Error('Artifact/feed outside immutable build')}- if (input.T && (input.S.package.identity !== input.T.package.identity || input.T.head.sequence <= input.S.head.sequence)) {- throw new Error('S to T must advance within stable identity')+ if (pkg.feed.channel !== 'stable' || !pkg.feed.key.endsWith(darwin ? '/stable-mac.yml' : '.appinstaller')) {+ throw new Error('Invalid immutable native feed')}- return input+ return { ...side, package: pkg }+}++function validatePreview(side, platform) {+ const request = side.manifest.request+ const version = platform === 'darwin' ? `0.0.${request.sequence}`+ : `0.${Math.floor(request.sequence / 65536)}.${request.sequence % 65536}.0`+ if (request.releaseTag || request.sequence > 0xffffffff || side.package.version !== version) {+ throw new Error('Preview package must use its allocated native sequence')+ }+}++function validateStable(side) {+ const request = side.manifest.request+ if (!semver.valid(request.version) || semver.prerelease(request.version) || request.releaseTag !== `v${request.version}`) {+ throw new Error('Destination must be a stable release')+ }+ if (request.channel !== 'stable' || side.manifest.receiverProtocol !== 1) throw new Error('Missing stable receiver support')+}++function assertAdvance(before, after, description) {+ if (before.manifest.request.channel !== after.manifest.request.channel ||+ !isDeepStrictEqual(before.manifest.request.identity, after.manifest.request.identity) ||+ after.head.sequence <= before.head.sequence) throw new Error(`${description} must advance within one identity`)+ const left = before.package.version.split('.').map(Number)+ const right = after.package.version.split('.').map(Number)+ if (left.length !== right.length || [...left, ...right].some(n => !Number.isSafeInteger(n) || n < 0)) {+ throw new Error('Native versions must be numeric')+ }+ const index = left.findIndex((n, i) => n !== right[i])+ if (index < 0 || right[index] <= left[index]) throw new Error(`${description} native version did not advance`)+}++function validateJourney(input, platform, arch) {+ validateScenario(input, platform, arch)+ const journey = { ...input }+ for (const name of ['A', 'S', 'T', ...(input.route === 'via-update' ? ['B'] : [])]) {+ const request = validateBinding(input[name], name, input.repository)+ journey[name] = validatePackage(input[name], request, platform, arch)+ if (request.publicBase !== input.A.manifest.request.publicBase) throw new Error('Journey archive authority differs')+ }+ validatePreview(journey.A, platform)+ if (journey.B) validatePreview(journey.B, platform)+ validateStable(journey.S)+ validateStable(journey.T)+ if (journey.A.package.identity === journey.S.package.identity ||+ journey.A.manifest.request.channel === journey.S.manifest.request.channel || journey.A.manifest.request.releaseTag) {+ throw new Error('Retirement must enter a distinct stable release identity')+ }+ const signer = platform === 'darwin' ? 'teamId' : 'publisher'+ for (const name of ['S', 'T', ...(journey.B ? ['B'] : [])]) {+ if (journey[name].package[signer] !== journey.A.package[signer]) throw new Error('Journey signing authority differs')+ }+ if (journey.B) assertAdvance(journey.A, journey.B, 'A to B')+ assertAdvance(journey.S, journey.T, 'S to T')+ if (semver.lt(journey.S.manifest.request.sourceVersion, input.minimumVersion)) throw new Error('Stable is below compatibility floor')+ return journey}function verifyBytes(bytes, expected) {@@ -57,9 +154,7 @@ function verifyBytes(bytes, expected) {function verifyManifest(bytes, side) {if (createHash('sha256').update(bytes).digest('hex') !== side.head.sha256 ||- !isDeepStrictEqual(JSON.parse(bytes.toString('utf8')), side.manifest)) {- throw new Error('Archived manifest differs from journey')- }+ !isDeepStrictEqual(JSON.parse(bytes.toString('utf8')), side.manifest)) throw new Error('Archived manifest differs from journey')}-module.exports = { validateJourney, verifyBytes, verifyManifest }+module.exports = { archiveBase, objectKey, validateJourney, verifyBytes, verifyManifest }diff --git a/tests/install/e2e-assets/channel-retirement-manifest.test.cjs b/tests/install/e2e-assets/channel-retirement-manifest.test.cjsindex 8d774915af9..fdb153589ca 100644--- a/tests/install/e2e-assets/channel-retirement-manifest.test.cjs+++ b/tests/install/e2e-assets/channel-retirement-manifest.test.cjs@@ -1,41 +1,143 @@const { test } = require('node:test')const assert = require('node:assert/strict')-const { createHash } = require('node:crypto')+const { createHash, createHmac } = require('node:crypto')+const http = require('node:http')+const fs = require('node:fs/promises')+const os = require('node:os')+const path = require('node:path')const { validateJourney, verifyBytes, verifyManifest } = require('./channel-retirement-manifest.cjs')-function fixture() {- function side(buildId, identity, sequence, releaseTag) {- const request = { buildId, sequence, commit: 'a'.repeat(40), repository: 'example/hermes',- publicBase: 'http://127.0.0.1:9876', version: releaseTag ? '1.0.0' : `0.0.${sequence}`,- releaseTag, identity: { appId: identity } }- const manifest = { request, packages: [{ platform: 'darwin', arch: 'arm64', variant: 'bundled',- identity, version: request.version, artifact: { sha256: 'f'.repeat(64), size: 5 } }] }- const body = Buffer.from(JSON.stringify(manifest))- return { manifest, head: { buildId, sequence, manifestKey: `releases/channel-builds/${buildId}/build.json`,- sha256: createHash('sha256').update(body).digest('hex') } }+const digest = bytes => createHash('sha256').update(bytes).digest('hex')+// Protocol fixtures only. These bytes are never installed or called native proof.+function fixture(base = 'https://archive.example.test/disposable') {+ const objects = new Map()+ function put(key, value) {+ const bytes = Buffer.isBuffer(value) ? value : Buffer.from(JSON.stringify(value))+ objects.set('/disposable/' + key, bytes)+ return { key, sha256: digest(bytes), size: bytes.length }}- return { schema: 1, platform: 'darwin', arch: 'arm64', repository: 'example/hermes', controllerCommit: 'b'.repeat(40),- route: 'direct', stable: 'absent', A: side('a'.repeat(32), 'preview.app', 1), S: side('b'.repeat(32), 'stable.app', 2, 'v1.0.0') }+ function side(id, nativeIdentity, sequence, version, channel, releaseTag) {+ const buildId = id.repeat(32)+ const identity = { appId: nativeIdentity, appNamePascal: nativeIdentity === 'preview.app' ? 'Preview' : 'Stable' }+ const request = { schema: 1, buildId, sequence, commit: id.repeat(40), repository: 'example/hermes', channel,+ publicBase: base, version, sourceVersion: version, identity }+ if (releaseTag) request.releaseTag = releaseTag+ const prefix = `releases/channel-builds/${buildId}/`+ const artifact = put(prefix + 'app.zip', Buffer.from(`not a native package: ${id}`))+ const manifest = { schema: 1, request, packages: [{ platform: 'darwin', arch: 'arm64', variant: 'bundled',+ identity: nativeIdentity, version, teamId: 'ABCDEFGHIJ', artifact, feed: { key: prefix + 'stable-mac.yml', channel: 'stable' } }] }+ if (releaseTag) manifest.receiverProtocol = 1+ const ref = put(prefix + 'build.json', manifest)+ return { manifest, head: { buildId, sequence, manifestKey: ref.key, sha256: ref.sha256 } }+ }+ const journey = { schema: 1, platform: 'darwin', arch: 'arm64', repository: 'example/hermes', controllerCommit: 'f'.repeat(40),+ route: 'via-update', stable: 'running', home: 'shared', minimumVersion: '1.0.0',+ A: side('a', 'preview.app', 1, '0.0.1', 'test-preview'), B: side('b', 'preview.app', 2, '0.0.2', 'test-preview'),+ S: side('c', 'stable.app', 1, '1.0.0', 'stable', 'v1.0.0'), T: side('d', 'stable.app', 2, '1.1.0', 'stable', 'v1.1.0') }+ return { journey, objects }}-test('retirement validates cross-identity artifacts without relaxing ordinary update identity', () => {- assert.equal(validateJourney(fixture(), 'darwin', 'arm64').S.package.identity, 'stable.app')- const bad = fixture()- bad.S.manifest.request.identity.appId = 'preview.app'- bad.S.manifest.packages[0].identity = 'preview.app'- assert.throws(() => validateJourney(bad, 'darwin', 'arm64'), /distinct/)- assert.throws(() => validateJourney(fixture(), 'win32', 'arm64'), /platform/)- const wrongHead = fixture()- wrongHead.A.head.buildId = 'e'.repeat(32)- assert.throws(() => validateJourney(wrongHead, 'darwin', 'arm64'), /binding/)+test('lifecycle inputs bind distinct identities, native ordering and receiver support', () => {+ const { journey } = fixture()+ const validated = validateJourney(journey, 'darwin', 'arm64')+ assert.equal(validated.S.package.identity, 'stable.app')+ assert.equal(journey.S.package, undefined, 'validation must not mutate the signed input')+ const direct = structuredClone(journey)+ direct.route = 'direct'; delete direct.B+ validateJourney(direct, 'darwin', 'arm64')+ const cases = [+ [j => { delete j.T }, /binding/],+ [j => { delete j.S.manifest.receiverProtocol }, /receiver/],+ [j => { j.T.manifest.request.version = j.S.manifest.request.version; j.T.manifest.request.releaseTag = 'v1.0.0'; j.T.manifest.packages[0].version = j.S.manifest.request.version }, /native version/],+ [j => { j.B.manifest.request.identity.extra = 'different' }, /identity/],+ [j => { j.S.head.buildId = 'e'.repeat(32) }, /binding/],+ [j => { j.S.manifest.request.publicBase = 'https://another.example' }, /authority/],+ [j => { j.S.manifest.packages[0].artifact.key = 'releases/../foreign.zip' }, /object key/],+ [j => { j.S.manifest.packages[0].teamId = '0123456789' }, /signing/],+ [j => { j.home = 'invented' }, /scenario/],+ ]+ for (const [mutate, error] of cases) {+ const bad = structuredClone(journey); mutate(bad)+ assert.throws(() => validateJourney(bad, 'darwin', 'arm64'), error)+ }+ assert.throws(() => validateJourney(journey, 'win32', 'arm64'), /platform/)+ // Platform is manifest data here, not a mocked native host.+ const windows = structuredClone(journey)+ windows.platform = 'win32'+ for (const name of ['A', 'B', 'S', 'T']) {+ const side = windows[name]+ const request = side.manifest.request+ const pkg = side.manifest.packages[0]+ request.identity.msixAppIdWithOrg = pkg.identity+ request.windowsVersion = request.releaseTag ? `${request.version}.0` : `0.0.${request.sequence}.0`+ pkg.version = request.windowsVersion+ pkg.platform = 'win32'; pkg.publisher = 'CN=Test fixture'+ pkg.artifact.key = pkg.artifact.key.replace('.zip', '.msixbundle')+ pkg.feed.key = pkg.feed.key.replace('stable-mac.yml', 'update.appinstaller')+ }+ validateJourney(windows, 'win32', 'arm64')+ windows.T.manifest.packages[0].publisher = 'CN=Foreign fixture'+ assert.throws(() => validateJourney(windows, 'win32', 'arm64'), /signing/)+ const body = Buffer.from(JSON.stringify(journey.A.manifest))+ verifyManifest(body, journey.A)+ verifyBytes(body, { size: body.length, sha256: digest(body) })+ assert.throws(() => verifyManifest(Buffer.from('{}'), journey.A), /manifest/)+ assert.throws(() => verifyBytes(body, { size: body.length + 1, sha256: digest(body) }), /hash/)+})++test('staging uses real HTTP bytes, refuses tampering and never emits native receipts', async () => {+ const { stageJourney } = await import('./channel-retirement-inputs.mjs')+ let objects = new Map()+ const server = http.createServer((req, res) => {+ const bytes = objects.get(req.url)+ res.writeHead(bytes ? 200 : 404); res.end(bytes || 'missing')+ })+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'retirement-inputs-'))+ try {+ const fixtureData = fixture(`http://127.0.0.1:${server.address().port}/disposable`)+ objects = fixtureData.objects+ const bytes = Buffer.from(JSON.stringify(fixtureData.journey))+ const manifest = path.join(root, 'input.json'); await fs.writeFile(manifest, bytes)+ const options = { manifest, manifestSha256: digest(bytes), platform: 'darwin', arch: 'arm64', out: path.join(root, 'staged') }+ const staged = JSON.parse(await fs.readFile(await stageJourney(options)))+ for (const name of ['A', 'B', 'S', 'T']) {+ const downloaded = await fs.readFile(staged[name].artifactPath)+ assert.equal(digest(downloaded), staged[name].package.artifact.sha256)+ }+ await assert.rejects(fs.access(path.join(options.out, 'receipt.json')), /ENOENT/)+ await assert.rejects(stageJourney(options), /EEXIST/)+ await assert.rejects(stageJourney({ ...options, manifestSha256: '0'.repeat(64) }), /Journey SHA256/)+ const key = '/disposable/' + fixtureData.journey.S.head.manifestKey+ objects.set(key, Buffer.from('{}'))+ await assert.rejects(stageJourney({ ...options, out: path.join(root, 'tampered') }), /SHA256 mismatch/)+ await assert.rejects(fs.access(path.join(root, 'tampered', 'journey-inputs.json')), /ENOENT/)+ } finally {+ await new Promise(resolve => server.close(resolve))+ await fs.rm(root, { recursive: true, force: true })+ }})-test('archive and manifest checks bind exact bytes, not artifact filenames', () => {- const bytes = Buffer.from('native package fixture')- const expected = { size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }- verifyBytes(bytes, expected)- assert.throws(() => verifyBytes(Buffer.concat([bytes, Buffer.from('!')]), expected), /hash/)- const side = fixture().A- verifyManifest(Buffer.from(JSON.stringify(side.manifest)), side)- assert.throws(() => verifyManifest(Buffer.from('{}'), side), /manifest/)+test('journal observations require exact pinned receiver and authenticated readiness', async () => {+ const { completedJournal } = await import('./channel-retirement-macos.mjs')+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'retirement-journal-'))+ const id = 'a'.repeat(32), token = 'b'.repeat(64), sha256 = 'c'.repeat(64)+ const dir = path.join(root, id), file = path.join(dir, 'journal.json')+ const request = { id, token, source: { appPath: '/preview', removalRoots: ['/preview'] },+ destination: { appPath: '/stable', commit: 'd'.repeat(40) }, destinationManifestSha256: sha256 }+ const requestDigest = digest(JSON.stringify(request))+ const ready = { id, requestDigest, pid: 123, executable: '/stable/bin', home: '/home/fixture',+ commit: request.destination.commit, connectionId: 'local', profile: 'default' }+ const record = { request, requestDigest, stage: 'complete', state: { selectedHome: ready.home },+ ready: { ...ready, mac: createHmac('sha256', Buffer.from(token, 'hex')).update(JSON.stringify(ready)).digest('hex') } }+ try {+ await fs.mkdir(dir)+ await fs.mkdir(path.join(root, 'e'.repeat(32)))+ await fs.writeFile(file, JSON.stringify(record))+ assert.equal(completedJournal(root, '/preview', '/stable', sha256).pid, 123)+ assert.throws(() => completedJournal(root, '/preview', '/stable', '0'.repeat(64)), /Assertion/)+ record.ready.pid+++ await fs.writeFile(file, JSON.stringify(record))+ assert.throws(() => completedJournal(root, '/preview', '/stable', sha256), /Assertion/)+ } finally { await fs.rm(root, { recursive: true, force: true }) }})diff --git a/tests/install/e2e-assets/channel-retirement-native-ui.ps1 b/tests/install/e2e-assets/channel-retirement-native-ui.ps1deleted file mode 100644index 50898f54a05..00000000000--- a/tests/install/e2e-assets/channel-retirement-native-ui.ps1+++ /dev/null@@ -1,22 +0,0 @@-# Operate the already-running destination's real UI. Never activate/launch it.-param([Parameter(Mandatory=$true)][int]$ProcessId, [Parameter(Mandatory=$true)][string]$Prompt)-$ErrorActionPreference = 'Stop'-Set-StrictMode -Version Latest-Add-Type -AssemblyName UIAutomationClient-Add-Type -AssemblyName UIAutomationTypes-Add-Type -AssemblyName System.Windows.Forms-$process = Get-Process -Id $ProcessId -ErrorAction Stop-if ($process.MainWindowHandle -eq 0) { throw 'Destination has no real visible window' }-$root = [System.Windows.Automation.AutomationElement]::RootElement-$condition = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ProcessIdProperty, $ProcessId)-$window = $root.FindFirst([System.Windows.Automation.TreeScope]::Children, $condition)-if (-not $window) { throw 'Destination window unavailable to UI Automation' }-$edits = $window.FindAll([System.Windows.Automation.TreeScope]::Descendants,- (New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ControlTypeProperty, [System.Windows.Automation.ControlType]::Edit)))-$editable = @($edits | Where-Object { $_.Current.IsEnabled -and -not $_.Current.IsOffscreen })-if ($editable.Count -ne 1) { throw 'Cannot identify a unique visible chat composer; refusing guessed keystrokes' }-$editable[0].SetFocus()-$pattern = $null-if (-not $editable[0].TryGetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern, [ref]$pattern)) { throw 'Composer does not expose native text input' }-$pattern.SetValue($Prompt)-[System.Windows.Forms.SendKeys]::SendWait('{ENTER}')diff --git a/tests/install/e2e-assets/mac-bundled-manifest.cjs b/tests/install/e2e-assets/mac-bundled-manifest.cjsindex 45507814612..90ee2685859 100644--- a/tests/install/e2e-assets/mac-bundled-manifest.cjs+++ b/tests/install/e2e-assets/mac-bundled-manifest.cjs@@ -5,6 +5,10 @@ function channelStampAssertions(stamp, request) {const expected = { channelBuild: request, commit: request.commit, tag: null, source: 'channel-build',branch: null, dirty: false, baseVersion: request.sourceVersion,displayVersion: `${request.sourceVersion} (${request.channel} #${request.sequence}, ${request.commit.slice(0, 7)})` }+ if (request.receiverCandidate) Object.assign(expected, {+ channelBuild: undefined, tag: request.releaseTag, source: 'build',+ displayVersion: request.version, receiverProtocol: 1,+ })return Object.entries(expected).filter(([key, value]) => !isDeepStrictEqual(stamp?.[key], value)).map(([key]) => `stamp.${key} disagrees with admitted channel request`)}diff --git a/tests/install/macos-bundled-e2e.sh b/tests/install/macos-bundled-e2e.shindex 3c4bebc01ce..0295aef9fe6 100644--- a/tests/install/macos-bundled-e2e.sh+++ b/tests/install/macos-bundled-e2e.sh@@ -39,6 +39,7 @@set -euo pipefailPHASE="all"+RETIREMENT_WORK=""MANIFEST_URL=""ARCH="arm64"UPDATE_WATCH_TIMEOUT_MS=900000@@ -51,6 +52,9 @@ while [ "$#" -gt 0 ]; do--manifest-url)[ "$#" -ge 2 ] || { echo 'error: --manifest-url needs a value' >&2; exit 1; }MANIFEST_URL="$2"; shift 2 ;;+ --retirement-work)+ [ "$#" -ge 2 ] || { echo 'error: --retirement-work needs a value' >&2; exit 1; }+ RETIREMENT_WORK="$2"; shift 2 ;;--arch)[ "$#" -ge 2 ] || { echo 'error: --arch needs a value' >&2; exit 1; }ARCH="$2"; shift 2 ;;@@ -71,6 +75,13 @@ export TS_BASE=$SECONDSNODE_BIN="${HERMES_E2E_NODE:-$(command -v node)}"export HERMES_E2E_NODE="$NODE_BIN"+# OS activation does not inherit the ordinary journey's sandbox overrides.+# Retirement uses the unused natural home of this disposable hosted account.+if [ "$PHASE" = retirement ]; then+ [ -n "$RETIREMENT_WORK" ] || { echo 'error: retirement requires controller work directory' >&2; exit 1; }+ exec "$NODE_BIN" "$REPO_ROOT/tests/install/channel-retirement-e2e.mjs" --work "$RETIREMENT_WORK" --arch "$ARCH"+fi+WORK_ROOT="${HERMES_E2E_WORKROOT:-${RUNNER_TEMP:-${TMPDIR:-/tmp}}/hermes-bundled-e2e}"LOG_DIR="${HERMES_E2E_LOG_DIR:-$WORK_ROOT/logs}"HOME_SANDBOX="$WORK_ROOT/home"diff --git a/tests/install/windows-bundled-e2e.ps1 b/tests/install/windows-bundled-e2e.ps1index 1395e2a7b37..947f09c3c94 100644--- a/tests/install/windows-bundled-e2e.ps1+++ b/tests/install/windows-bundled-e2e.ps1@@ -1,6 +1,7 @@# Native package replacement acceptance. Never run on a developer desktop.param(- [Parameter(Mandatory=$true)][string]$ManifestUrl,+ [string]$ManifestUrl,+ [string]$RetirementWork,[ValidateSet('x64','arm64')][string]$Arch = 'x64')$ErrorActionPreference = 'Stop'@@ -8,6 +9,13 @@ Set-StrictMode -Version Latestif ($env:GITHUB_ACTIONS -ne 'true' -or $env:OS -ne 'Windows_NT') { throw 'Disposable Windows Actions runner required' }$Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..'))$Assets = Join-Path $PSScriptRoot 'e2e-assets'+if ($RetirementWork) {+ # Keep natural HOME/AppData for OS-activated receivers and distinct locks.+ & node (Join-Path $PSScriptRoot 'channel-retirement-e2e.mjs') --work $RetirementWork --arch $Arch+ if ($LASTEXITCODE -ne 0) { throw 'Native retirement journey failed' }+ return+}+if (-not $ManifestUrl) { throw 'ManifestUrl is required for ordinary package updates' }$Work = Join-Path $env:RUNNER_TEMP 'hermes-bundled-update'if (Test-Path $Work) { throw "Refusing to reuse $Work" }$Proof = Join-Path $Work 'proof'diff --git a/tests/scripts/test_channel_qualification.py b/tests/scripts/test_channel_qualification.pydeleted file mode 100644index e991cceab81..00000000000--- a/tests/scripts/test_channel_qualification.py+++ /dev/null@@ -1,234 +0,0 @@-"""Qualification uses real HTTP bytes and a real Git controller, never a true callback."""-from __future__ import annotations--from contextlib import contextmanager-from copy import deepcopy-import hashlib-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer-import io-import json-import subprocess-from threading import Thread-import zipfile--import pytest--from hermes_cli.release_channels import canonical_json, ChannelError-from test_release_channels import object_server, publisher, put_build---def digest(body):- return hashlib.sha256(body).hexdigest()---@contextmanager-def github_server():- responses = {}- calls = []-- class Handler(BaseHTTPRequestHandler):- def log_message(self, *args):- pass-- def do_GET(self):- calls.append(self.path)- body = responses.get(self.path)- if isinstance(body, dict):- body = canonical_json(body)- self.send_response(200 if body is not None else 404)- self.end_headers()- self.wfile.write(body or b"missing")-- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)- thread = Thread(target=server.serve_forever, daemon=True)- thread.start()- try:- yield f"http://127.0.0.1:{server.server_port}", responses, calls- finally:- server.shutdown()- server.server_close()- thread.join()---def git_controller(tmp_path):- repo = tmp_path / "controller"- repo.mkdir()- def git(*args):- return subprocess.check_output(["git", "-C", str(repo), *args], text=True, stdin=subprocess.DEVNULL).strip()- git("init", "-b", "main")- git("config", "user.name", "Fixture")- git("config", "user.email", "[email protected]")- (repo / "controller").write_text("trusted workflow fixture", encoding="utf-8")- git("add", "controller")- git("commit", "-m", "controller")- return git("rev-parse", "HEAD")---def evidence(objects, responses, receipt, *, run_id=17, artifact_id=23):- body = canonical_json(receipt)- key = f"releases/qualifications/{digest(body)}.json"- objects[key] = body- archive = io.BytesIO()- with zipfile.ZipFile(archive, "w") as bundle:- bundle.writestr("receipt.json", body)- zipped = archive.getvalue()- repository = receipt["repository"]- prefix = f"/repos/{repository}"- responses[f"{prefix}/actions/runs/{run_id}"] = {- "id": run_id, "run_attempt": 1, "status": "completed", "conclusion": "success",- "event": "workflow_dispatch", "head_branch": "main", "head_sha": receipt["controllerCommit"],- "path": ".github/workflows/install-e2e.yml", "repository": {"full_name": repository},- "head_repository": {"full_name": repository},- }- responses[f"{prefix}/actions/artifacts/{artifact_id}"] = {- "id": artifact_id, "expired": False, "name": "channel-qualification",- "digest": "sha256:" + digest(zipped), "workflow_run": {"id": run_id, "head_sha": receipt["controllerCommit"]},- }- responses[f"{prefix}/actions/artifacts/{artifact_id}/zip"] = zipped- return {"key": key, "sha256": digest(body), "runId": run_id, "runAttempt": 1, "artifactId": artifact_id}---def test_retirement_verifier_binds_native_receipts_to_trusted_successful_run(tmp_path):- from scripts.releases.channel_qualification import QualificationVerifier, GitHubEvidence, RETIREMENT_ASSERTIONS-- controller = git_controller(tmp_path)- with object_server() as (url, objects, *_), github_server() as (api_url, responses, calls):- pub = publisher(url)- pub.create("preview")- request = pub.allocate("preview", "a" * 40, "1.0.0", controller_commit=controller)- source_manifest = put_build(objects, request)- source = pub._read("preview")[0]- source["head"] = {"buildId": request["buildId"], "sequence": 1,- "manifestKey": f"releases/channel-builds/{request['buildId']}/build.json",- "sha256": digest(canonical_json(source_manifest))}- objects["releases/channels/preview.json"] = canonical_json(source)- target = deepcopy(source)- target.update(name="stable", policy="stable-release")- stable_request = {**request, "channel": "stable", "buildId": "b" * 32,- "releaseTag": "v2.0.0", "sourceVersion": "2.0.0", "version": "2.0.0", "windowsVersion": "2.0.0.0"}- stable_request["identity"] = {**request["identity"], "appId": "com.nousresearch.hermes-bundled"}- target["identity"] = stable_request["identity"]- stable_manifest = put_build(objects, stable_request)- target["head"] = {"buildId": stable_request["buildId"], "sequence": 1,- "manifestKey": f"releases/channel-builds/{stable_request['buildId']}/build.json",- "sha256": digest(canonical_json(stable_manifest))}- objects["releases/channels/stable.json"] = canonical_json(target)- qualification = {"schema": 1, "source": "preview", "sourceHead": source["head"], "destination": "stable",- "destinationHead": target["head"], "minimumVersion": "2.0.0", "receiverProtocol": 1, "coverage": []}- refs = []- for i, state in enumerate(("absent", "running")):- receipt = {"schema": 1, "kind": "channel-retirement", "repository": pub.repository,- "controllerCommit": controller, "runId": 17 + i, "runAttempt": 1,- "platform": "darwin", "arch": "arm64", "variant": "bundled", "receiverProtocol": 1,- "source": {"channel": "preview", "head": source["head"], "commit": request["commit"],- "identity": source_manifest["packages"][0]["identity"],- "artifactSha256": source_manifest["packages"][0]["artifact"]["sha256"]},- "destination": {"channel": "stable", "head": target["head"], "commit": stable_request["commit"],- "identity": stable_manifest["packages"][0]["identity"],- "artifactSha256": stable_manifest["packages"][0]["artifact"]["sha256"]},- "minimumVersion": "2.0.0", "scenario": {"route": "direct", "stable": state, "home": "shared"},- "assertions": dict.fromkeys(RETIREMENT_ASSERTIONS, True)}- refs.append(evidence(objects, responses, receipt, run_id=17 + i, artifact_id=23 + i))- qualification["coverage"] = [{"platform": "darwin", "arch": "arm64", "sourceIdentity": receipt["source"]["identity"],- "destinationIdentity": receipt["destination"]["identity"],- "cohorts": [{"buildId": request["buildId"], "commit": request["commit"], "proofs": refs}]}]- verifier = QualificationVerifier(pub.store, pub.repository, pub.public_base, controller, "main",- github=GitHubEvidence(api_base=api_url))- pub.verify_retirement = verifier.verify_retirement- key = "releases/qualifications/retirement.json"- objects[key] = canonical_json(qualification)- assert pub.retire("preview", "stable", "2.0.0", key, digest(objects[key]), publish=False)["state"] == "retired"- assert calls and pub._read("preview")[0]["state"] == "active"- run = responses[f"/repos/{pub.repository}/actions/runs/17"]- for field, wrong in (("conclusion", "failure"), ("head_sha", "c" * 40), ("path", ".github/workflows/untrusted.yml"),- ("event", "pull_request"), ("head_repository", {"full_name": "attacker/fork"})):- saved = run[field]- run[field] = wrong- with pytest.raises(ChannelError):- verifier.verify_retirement(source, target, qualification)- run[field] = saved- bad = deepcopy(qualification)- bad["coverage"][0]["cohorts"][0]["commit"] = "d" * 40- with pytest.raises(ChannelError):- verifier.verify_retirement(source, target, bad)- # Every complete source cohort is required, including an older offline install.- older = {**request, "buildId": "9" * 32}- put_build(objects, older)- with pytest.raises(ChannelError, match="cohort"):- verifier.verify_retirement(source, target, qualification)- del objects[f"releases/channel-builds/{older['buildId']}/build.json"]- # An R2 author cannot change the acceptance assertions, even with an updated R2 hash.- forged = json.loads(objects[refs[0]["key"]])- forged["assertions"]["previewRemoved"] = False- forged_ref = {**refs[0], "sha256": digest(canonical_json(forged))}- objects[forged_ref["key"]] = canonical_json(forged)- bad = deepcopy(qualification)- bad["coverage"][0]["cohorts"][0]["proofs"][0] = forged_ref- with pytest.raises(ChannelError):- verifier.verify_retirement(source, target, bad)--def test_stable_bootstrap_requires_accepted_candidate_and_published_release(tmp_path):- from scripts.releases.channel_qualification import QualificationVerifier, GitHubEvidence- from scripts.releases.channels import preview_identity-- controller = git_controller(tmp_path)- repository = "example/hermes-agent"- archive_base = "https://archive.example.invalid"- with object_server() as (url, objects, *_), github_server() as (api_url, responses, calls):- pub = publisher(url)- verifier = QualificationVerifier(pub.store, repository, archive_base, controller, "main",- github=GitHubEvidence(api_base=api_url))- # Only the transport endpoint changes; candidate URLs retain their HTTPS authority.- verifier.reader = pub.reader- identity = {**preview_identity("stable", "a" * 16), "appId": "com.nousresearch.hermes-bundled",- "msixAppIdWithOrg": "NousResearch.HermesBundled", "appNamePascal": "HermesBundled"}- request = {"schema": 1, "buildId": "f" * 32, "channel": "stable", "repository": repository,- "sequence": 1, "commit": controller, "controllerCommit": controller, "sourceVersion": "2.0.0",- "releaseTag": "v2.0.0", "version": "2.0.0", "windowsVersion": "2.0.0.0",- "identity": identity, "bundleEnv": {}, "publicBase": archive_base}- packages, candidates = [], []- for platform, arch in ((p, a) for p in ("darwin", "win32") for a in ("arm64", "x64")):- mac = platform == "darwin"- name = f"{platform}-{arch}." + ("zip" if mac else "msixbundle")- key = f"releases/tag/v2.0.0/{name}"- native = identity["appId" if mac else "msixAppIdWithOrg"]- signing = {"teamId": "ABCDEFGHIJ"} if mac else {"publisher": "CN=Nous Research"}- package = {"platform": platform, "arch": arch, "variant": "bundled", "identity": native,- "version": "2.0.0" if mac else "2.0.0.0", **signing,- "artifact": {"key": key, "sha256": "e" * 64, "size": 100},- "feed": {"key": f"releases/tag/v2.0.0/{platform}/stable", "channel": "stable"}}- packages.append(package)- candidates.append({**package, "platform": "macos" if mac else "windows", "tag": "v2.0.0",- "commit": request["commit"], "applicationId": "HermesBundled",- "artifact": {"url": archive_base + "/" + key, "sha256": "e" * 64}})- candidate = {"schema": 2, "tag": "v2.0.0", "commit": request["commit"], "packages": candidates,- "smoke_results": {k: {"result": "success"} for k in- ("smoke-darwin", "smoke-win32", "smoke-win32-universal")}}- key = "releases/tag/v2.0.0/release-candidates.json"- objects[key] = canonical_json(candidate)- manifest = {"schema": 1, "request": request, "packages": packages}- receipt = {"schema": 1, "kind": "channel-release", "repository": repository,- "controllerCommit": controller, "runId": 17, "runAttempt": 1,- "manifestSha256": digest(canonical_json(manifest)), "candidateSha256": digest(objects[key]),- "tag": "v2.0.0", "commit": request["commit"],- "assertions": {"nativeSmoke": True, "nativeUpgrade": True, "releaseGate": True}}- proof = evidence(objects, responses, receipt)- responses[f"/repos/{repository}/actions/runs/17"]["path"] = ".github/workflows/stable-release.yml"- responses[f"/repos/{repository}/releases/tags/v2.0.0"] = {- "tag_name": "v2.0.0", "draft": False, "prerelease": False, "published_at": "2026-01-01T00:00:00Z"}- responses[f"/repos/{repository}/commits/v2.0.0"] = {"sha": request["commit"]}- responses[f"/repos/{repository}/compare/{controller}...{controller}"] = {"status": "identical", "merge_base_commit": {"sha": controller}}- responses[f"/repos/{repository}/actions/runs/17"]["head_branch"] = "v2.0.0"- manifest["releaseQualification"] = {"candidate": {"key": key, "sha256": digest(objects[key])}, "proof": proof}- assert verifier.verify_build(request, manifest) is True- for mutate in (lambda m: m["packages"][0]["artifact"].update(sha256="b" * 64),- lambda m: m["packages"][0].update(identity="attacker.app"),- lambda m: m["request"].update(commit="b" * 40)):- bad = deepcopy(manifest)- mutate(bad)- with pytest.raises(ChannelError):- verifier.verify_build(bad["request"], bad)- responses[f"/repos/{repository}/releases/tags/v2.0.0"]["draft"] = True- with pytest.raises(ChannelError):- verifier.verify_build(request, manifest)-diff --git a/tests/scripts/test_icon_generation_exit.py b/tests/scripts/test_icon_generation_exit.pyindex 32a31b7a766..9f279e59470 100644--- a/tests/scripts/test_icon_generation_exit.py+++ b/tests/scripts/test_icon_generation_exit.py@@ -100,7 +100,7 @@ def test_icon_portrait_overlays_border_inside_outer_silhouette(monkeypatch, platspec.loader.exec_module(module)art = SimpleNamespace(backgrounds=source / "assets/backgrounds", colors=colors, commit="0123456",- bboxes={girl: (0, 0, 100, 90)}, paths={girl: '<path d="M0 0H100V90H0Z"/>'},+ bboxes={girl: (0, 0, 100, 90)}, paths={girl: '<path d="M 0 0 L 100 0 L 100 90 L 0 90 z"/>'},)name = f"squircle-{platform}{appearance}.svg"ns = {"svg": "http://www.w3.org/2000/svg"}@@ -126,26 +126,27 @@ def test_icon_portrait_overlays_border_inside_outer_silhouette(monkeypatch, plat)group = result[-1]portrait = group[-1]+ assert len(group) == 1, "extend the existing contour, not a duplicate strip"assert portrait is not None and group is not Noneassert portrait.get("preserveAspectRatio") == "xMidYMax meet"assert tuple(float(portrait.attrib[key]) for key in ("x", "y", "width", "height")) == module.GIRL_BOXES[name]clip_path = result.find("svg:defs/svg:clipPath", ns)assert clip_path is not Noneassert group.get("clip-path") == f"url(#{clip_path.attrib['id']})"- extension = group[0]- assert extension is not portrait- join_clip = result.find("svg:defs/svg:clipPath[@id='icon-join']/svg:rect", ns)- assert join_clip is not None- strip_x, strip_y, strip_width, strip_height = (- float(join_clip.attrib[key]) for key in ("x", "y", "width", "height")- )- px, py, pw, ph = module.GIRL_BOXES[name]- assert (strip_x, strip_width) == (px, pw)- assert 0 < py + ph - strip_y < ph / 50- assert strip_y + strip_height > y + height - thickness- assert strip_y + strip_height < y + height- assert extension.get("clip-path") == "url(#icon-join)"- extension_ink = extension.find("svg:g/svg:path", ns)- portrait_ink = portrait.find("svg:path", ns)- assert extension_ink is not None and portrait_ink is not None- assert extension_ink.get("d") == portrait_ink.get("d")+ assert portrait.get("overflow") == "visible"+ assert len(result.findall(".//svg:path", ns)) == 2 # one badge and one portrait+++def test_bottom_node_drag_preserves_upper_geometry_and_path_transform(monkeypatch):+ monkeypatch.setitem(sys.modules, "resvg_py", ModuleType("resvg_py"))+ script = Path(__file__).resolve().parents[2] / "scripts/generate_icons.py"+ spec = importlib.util.spec_from_file_location("icon_nodes_under_test", script)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ path = ET.fromstring('<path transform="matrix(2,0,0,2,10,-100)" d="M 0 0 C 0 90 10 98 20 100 L 0 100 z"/>')+ module.drag_bottom_nodes(path, cutoff=80, band=20, distance=10)+ assert path.get("transform") == "matrix(2,0,0,2,10,-100)"+ assert path.get("d") == "M 0 0 C 0 90 10 102.48 20 105 L 0 105 z"+ with pytest.raises(ValueError, match="absolute M/L/C"):+ module.drag_bottom_nodes(ET.fromstring('<path d="m 0 0 l 1 1"/>'), cutoff=0, band=1, distance=1)diff --git a/tests/scripts/test_release_artifacts.py b/tests/scripts/test_release_artifacts.pyindex 237df7f8b00..9080036b6ee 100644--- a/tests/scripts/test_release_artifacts.py+++ b/tests/scripts/test_release_artifacts.py@@ -32,10 +32,10 @@ def test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_ppackage = root / 'Product-win-x64.msix'manifest = '<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"><Identity Name="Product" Publisher="CN=Test" Version="1.2.3.0" ProcessorArchitecture="x64"/><Applications><Application Id="App"/></Applications></Package>'- def write_package(sha):+ def write_package(sha, receiver=None):with zipfile.ZipFile(package, 'w') as archive:archive.writestr('AppxManifest.xml', manifest)- archive.writestr('app/resources/install-stamp.json', json.dumps({'tag': tag, 'commit': sha}))+ archive.writestr('app/resources/install-stamp.json', json.dumps({'tag': tag, 'commit': sha, 'receiverProtocol': receiver}))write_package(commit)out = root / 'metadata-windows-x64.json'@@ -47,6 +47,10 @@ def test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_passert metadata['publisher'] == 'CN=Test'assert metadata['applicationId'] == 'App'assert package.read_bytes() == original+ assert 'receiverProtocol' not in metadata+ write_package(commit, receiver=1)+ record('windows', 'x64', root, tag, commit, out)+ assert json.loads(out.read_text())['receiverProtocol'] == 1write_package('b' * 40)with pytest.raises(ValueError, match='provenance'):record('windows', 'x64', root, tag, commit, tmp_path / 'bad.json')@@ -98,7 +102,7 @@ def staged_candidate(tmp_path, r2_server, https_origin):handoff.stage(tag, commit, handoff_name, built, includes)bundle = built / 'Product-win.msixbundle'with zipfile.ZipFile(bundle, 'w') as archive:- archive.writestr('AppxMetadata/AppxBundleManifest.xml', '<Bundle><Identity Name="Product" Publisher="CN=Test" Version="1.2.3.0"/></Bundle>')+ archive.writestr('AppxMetadata/AppxBundleManifest.xml', '<Bundle><Identity Name="Product" Publisher="CN=Test" Version="1.2.3.0"/><Packages><Package Type="application" Architecture="arm64"/><Package Type="application" Architecture="x64"/></Packages></Bundle>')(built / 'Store-Product-win.msixbundle').write_bytes(b'Store bundle transport fixture')handoff.stage(tag, commit, 'windows-universal', built, ['*.msixbundle'])fetched = tmp_path / 'fetched'@@ -115,6 +119,34 @@ def staged_candidate(tmp_path, r2_server, https_origin):return manifest, fetched, base+def test_bootstrap_reuses_published_candidate_and_rejects_substitution(staged_candidate, r2_server, monkeypatch):+ from scripts.releases import channel_releases+ candidate, _, base = staged_candidate+ request = {'releaseTag': candidate['tag'], 'commit': candidate['commit'], 'publicBase': base,+ 'identity': {'token': 'a' * 16, 'appNamePascal': 'App'}}+ packages = []+ for row in candidate['packages']:+ if row['platform'] == 'termux':+ continue+ packages.append({**row, 'platform': 'darwin' if row['platform'] == 'macos' else 'win32',+ 'artifact': {'key': row['artifact']['url'].removeprefix(base + '/'),+ 'sha256': row['artifact']['sha256']}})+ manifest = {'request': request, 'packages': packages}+ monkeypatch.setattr(channel_releases, 'product_identity', lambda tag: request['identity'])+ published = {'draft': False, 'prerelease': False, 'published_at': 'fixture-published'}+ monkeypatch.setattr(channel_releases.stable, 'output', lambda args: candidate['commit']+ if '/commits/' in args[2] else json.dumps(published))+ r2_server.store['releases/stable/release-candidates.json'] = r2_server.store[f"releases/tag/{candidate['tag']}/release-candidates.json"]+ assert channel_releases.verify_bootstrap(request, manifest, base, 'fixture/repo')+ substituted = copy.deepcopy(manifest)+ substituted['packages'][0]['artifact']['sha256'] = 'f' * 64+ with pytest.raises(ValueError, match='accepted'):+ channel_releases.verify_bootstrap(request, substituted, base, 'fixture/repo')+ published['draft'] = True+ with pytest.raises(ValueError, match='published'):+ channel_releases.verify_bootstrap(request, manifest, base, 'fixture/repo')++def test_assemble_rejects_missing_and_changed_receipts(tmp_path, staged_candidate):from scripts.bundles.release_artifacts import assemblediff --git a/tests/scripts/test_release_build_commit.py b/tests/scripts/test_release_build_commit.pyindex 374ebf10a22..df8a0b577f9 100644--- a/tests/scripts/test_release_build_commit.py+++ b/tests/scripts/test_release_build_commit.py@@ -32,7 +32,7 @@ def fixture_repo(tmp_path):for relative in ('scripts/release.py', 'scripts/releases/commit_build.py','scripts/releases/bundle_env.py','scripts/releases/channel_build.py', 'scripts/releases/channels.py',- 'scripts/releases/r2.py', 'scripts/release-content-types.json',+ 'scripts/releases/r2.py', 'scripts/releases/r2_scope.py', 'scripts/release-content-types.json','hermes_cli/__init__.py', 'hermes_cli/update_channel.py','hermes_cli/release_channels.py','hermes_cli/runtime_paths.py', 'hermes_constants.py'):diff --git a/tests/scripts/test_release_channel_build.py b/tests/scripts/test_release_channel_build.pyindex 5aa7def0372..92ad126e97d 100644--- a/tests/scripts/test_release_channel_build.py+++ b/tests/scripts/test_release_channel_build.py@@ -73,6 +73,27 @@ def test_missing_controller_branch_is_rejected_without_channel_creation(source):assert not objects+def test_local_fork_requires_scope_before_credentials_or_storage(monkeypatch):+ from scripts.releases import channel_build, r2+ monkeypatch.delenv("GITHUB_ACTIONS", raising=False)+ monkeypatch.delenv("GITHUB_REPOSITORY", raising=False)+ monkeypatch.delenv("R2_DISPOSABLE_RUN", raising=False)+ monkeypatch.setenv("CLOUDFLARE_R2_PUBLIC_URL", "https://archive.example")+ monkeypatch.setattr(r2, "credentials", lambda: pytest.fail("Unscoped fork reached credentials"))+ with pytest.raises(ValueError, match="disposable"):+ channel_build.configured_publisher("ethernet8023/hermes-agent")+ monkeypatch.setenv("R2_DISPOSABLE_RUN", "123-1")+ monkeypatch.setenv("GITHUB_REPOSITORY_ID", "456")+ monkeypatch.setattr(channel_build.commit_build, "output", lambda args: "789")+ with pytest.raises(ValueError, match="another repository"):+ channel_build.configured_publisher("ethernet8023/hermes-agent")+ monkeypatch.setattr(channel_build.commit_build, "output", lambda args: "456")+ monkeypatch.setattr(r2, "credentials", lambda: ({"access_key_id": "inert", "secret_key": "inert"}, "https://r2.example", "bucket"))+ publisher = channel_build.configured_publisher("ethernet8023/hermes-agent")+ assert publisher.store.scope.key("releases/channels/preview.json") == "ci-disposable/456/123-1/releases/channels/preview.json"+ assert publisher.reader.base_url == "https://archive.example/ci-disposable/456/123-1"++def test_release_parser_preserves_plain_oneoff_dispatch(monkeypatch):import sysfrom scripts import releasediff --git a/tests/scripts/test_release_channels.py b/tests/scripts/test_release_channels.pyindex a4208871491..a2811111e4a 100644--- a/tests/scripts/test_release_channels.py+++ b/tests/scripts/test_release_channels.py@@ -125,7 +125,7 @@ def put_build(objects, request):prefix = build_prefix(request["buildId"])data = b"fixture native artifact"objects[prefix + "darwin/package.zip"] = data- manifest = {"schema": 1, "request": request, "packages": [{"platform": "darwin", "arch": "arm64", "variant": "bundled",+ manifest = {"schema": 1, "receiverProtocol": 1, "request": request, "packages": [{"platform": "darwin", "arch": "arm64", "variant": "bundled","artifact": {"key": prefix + "darwin/package.zip", "sha256": hashlib.sha256(data).hexdigest(), "size": len(data)},"version": request["version"], "identity": request["identity"]["appId"], "teamId": "ABCDEFGHIJ","feed": {"key": prefix + "darwin/stable-mac.yml", "channel": "stable"}}]}@@ -138,9 +138,8 @@ def test_concurrent_allocations_reverse_completion_retirement_and_readback():from hermes_cli.release_channels import ChannelError, canonical_jsonfrom scripts.releases.channels import PublicVisibilityErrorwith object_server() as (url, objects, headers, requests, faults):- pub = publisher(url, verify_build=lambda request, manifest: True,- verify_retirement=lambda record, target, qualification: True)with ThreadPoolExecutor(max_workers=2) as pool:+ pub = publisher(url, verify_build=lambda request, manifest: True)created = list(pool.map(pub.create, ["race-preview"] * 2))assert created[0]["identity"] == created[1]["identity"]with ThreadPoolExecutor(max_workers=2) as pool:@@ -162,11 +161,18 @@ def test_concurrent_allocations_reverse_completion_retirement_and_readback():raw = canonical_json(stable_manifest)target.update(nextSequence=stable["sequence"] + 1, head={"buildId": stable["buildId"], "sequence": stable["sequence"], "manifestKey": "releases/channel-builds/" + stable["buildId"] + "/build.json", "sha256": hashlib.sha256(raw).hexdigest()})objects["releases/channels/destination.json"] = canonical_json(target)- key = "releases/channel-builds/" + two["buildId"] + "/retirement.json"- qualification = {"schema": 1, "source": "race-preview", "sourceHead": pub._read("race-preview")[0]["head"], "destination": "destination", "destinationHead": target["head"], "minimumVersion": "2.0.0"}- raw = canonical_json(qualification)- objects[key] = raw- retired = pub.retire("race-preview", "destination", "2.0.0", key, hashlib.sha256(raw).hexdigest())+ unsupported = dict(stable_manifest)+ del unsupported["receiverProtocol"]+ objects[target["head"]["manifestKey"]] = canonical_json(unsupported)+ old_target = {**target, "head": {**target["head"], "sha256": hashlib.sha256(canonical_json(unsupported)).hexdigest()}}+ objects["releases/channels/destination.json"] = canonical_json(old_target)+ with pytest.raises(ChannelError, match="receiver support"):+ pub.retire("race-preview", "destination", "2.0.0")+ assert pub._read("race-preview")[0]["state"] == "active"+ objects[target["head"]["manifestKey"]] = raw+ objects["releases/channels/destination.json"] = canonical_json(target)+ retired = pub.retire("race-preview", "destination", "2.0.0")+ assert retired["destinationHead"] == target["head"]assert retired["lastHead"]["buildId"] == two["buildId"]with pytest.raises(ChannelError, match="Retired"):pub.promote(two["buildId"])@@ -207,12 +213,11 @@ def test_list_bootstrap_protected_roles_and_qualification_gate():assert pub.reader.resolve("first").terminal["head"] is None-def test_retirement_race_never_reuses_stale_qualification():+def test_retirement_race_requires_a_new_explicit_attempt():from hermes_cli.release_channels import ChannelError, canonical_jsonfrom scripts.releases.channels import ChannelConflictwith object_server() as (url, objects, headers, requests, faults):- pub = publisher(url, verify_build=lambda request, manifest: True,- verify_retirement=lambda record, target, qualification: True)+ pub = publisher(url, verify_build=lambda request, manifest: True)pub.create("preview")first = pub.allocate("preview", "a" * 40, "1.0.0")second = pub.allocate("preview", "b" * 40, "1.0.0")@@ -226,11 +231,7 @@ def test_retirement_race_never_reuses_stale_qualification():manifest = put_build(objects, stable)target.update(nextSequence=2, head={"buildId": stable["buildId"], "sequence": 1, "manifestKey": "releases/channel-builds/" + stable["buildId"] + "/build.json", "sha256": hashlib.sha256(canonical_json(manifest)).hexdigest()})objects["releases/channels/stable.json"] = canonical_json(target)- before = pub._read("preview")[0]- qualification = {"schema": 1, "source": "preview", "sourceHead": before["head"], "destination": "stable", "destinationHead": target["head"], "minimumVersion": "2.0.0"}- key = "releases/channel-builds/" + first["buildId"] + "/retirement.json"- raw = canonical_json(qualification)- objects[key] = raw+def race(store, object_key):record = json.loads(store[object_key])record["revision"] += 1@@ -238,12 +239,11 @@ def test_retirement_race_never_reuses_stale_qualification():store[object_key] = canonical_json(record)faults["conflict"] = racewith pytest.raises(ChannelConflict):- pub.retire("preview", "stable", "2.0.0", key, hashlib.sha256(raw).hexdigest())+ pub.retire("preview", "stable", "2.0.0")assert pub.reader.resolve("preview").manifest["request"] == second- with pytest.raises(ChannelError, match="qualification"):- pub.retire("preview", "stable", "2.0.0", key, hashlib.sha256(raw).hexdigest())with pytest.raises(ChannelError, match="cycle"):- pub.retire("preview", "preview", "2.0.0", key, hashlib.sha256(raw).hexdigest())+ pub.retire("preview", "preview", "2.0.0")+ assert pub.retire("preview", "stable", "2.0.0")["lastHead"]["buildId"] == second["buildId"]def test_mutable_read_loss_recovery_never_clones_another_allocation():@@ -382,18 +382,23 @@ def test_accepted_release_receipts_feed_the_protected_head_without_rebuilding(tmassert channel_releases.select_channel(pub, "stable-release") == "released"native = channel_releases.read_native_receipts(tmp_path, tag, commit)request = pub.allocate_protected("released", commit, "2.0.0", release_tag=tag, version="2.0.0", windows_version="2.0.0.0", identity=identity, policy="stable-release", release_gate=lambda request: True)- manifest, feeds = channel_releases.assemble(request, native, tmp_path)+ from scripts.bundles.channel_artifacts import assemble+ manifest, feeds = assemble(request, native, tmp_path, artifact_prefix=prefix)assert {p["arch"] for p in manifest["packages"]} == {"arm64", "x64"}assert all(p["artifact"]["key"].startswith(prefix) for p in manifest["packages"])assert all(f.is_file() for f in feeds)accepted = {"packages": []}for row in manifest["packages"]:accepted["packages"].append({"platform": "macos" if row["platform"] == "darwin" else "windows", "arch": row["arch"], "identity": row["identity"], "version": row["version"], "artifact": {"url": base + "/" + row["artifact"]["key"], "sha256": row["artifact"]["sha256"]}, **{k: row[k] for k in ("teamId", "publisher") if k in row}})+ if row["platform"] == "win32":+ accepted["packages"][-1]["applicationId"] = identity["appNamePascal"]channel_releases.match_accepted_packages(manifest, accepted)wrong = deepcopy(accepted)wrong["packages"][0]["artifact"]["sha256"] = "0" * 64with pytest.raises(ChannelError, match="accepted"):channel_releases.match_accepted_packages(manifest, wrong)+ with pytest.raises(ChannelError, match="every native"):+ channel_releases.match_accepted_packages(dict(manifest, packages=manifest["packages"][:1]), accepted)# Exercise the real controller, HTTP receipt downloader, immutable feeds,# manifest and final CAS; only GitHub admission and generated product facts# are fixture inputs (no native signature acceptance is claimed here).diff --git a/tests/scripts/test_release_r2.py b/tests/scripts/test_release_r2.pyindex f6d75c2bdd3..3aef2642de3 100644--- a/tests/scripts/test_release_r2.py+++ b/tests/scripts/test_release_r2.py@@ -48,6 +48,8 @@ from scripts.releases.r2 import (stale_feed_bundle_keys,)+from scripts.releases.r2_scope import R2Scope, channel_public_base+AKID = "AKIDEXAMPLE"SECRET = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"NOW = "20150830T123600Z"@@ -61,6 +63,71 @@ def _auth(**kwargs):return auth_header(**kwargs)+def test_disposable_scope_streams_lists_and_never_touches_production(r2_server, tmp_path, monkeypatch):+ monkeypatch.setenv("R2_DISPOSABLE_RUN", "98765-1")+ monkeypatch.setenv("GITHUB_REPOSITORY_ID", "12345")+ scope = R2Scope.configured()+ root = f"http://127.0.0.1:{r2_server.server_port}/hermes-releases"+ monkeypatch.setenv("CLOUDFLARE_R2_PUBLIC_URL", root)+ key = "releases/channel-builds/" + "a" * 32 + "/payload.bin"+ r2_server.store[key] = (b"production sentinel", '"production"')+ path = tmp_path / "payload.bin"+ payload = b"x" * (5 * 1024 * 1024 + 1)+ path.write_bytes(payload)+ creds, base, bucket = r2.credentials()+ r2.put_object(creds, base, bucket, key, path, NOW, "application/octet-stream",+ {"If-None-Match": "*"}, multipart_part_size=5 * 1024 * 1024)+ # Same immutable bytes are reusable, but only inside this run's prefix.+ r2.put_object(creds, base, bucket, key, path, NOW, None, {"If-None-Match": "*"})+ assert r2.get_object(creds, base, bucket, key, NOW) == payload.decode()+ digest = hashlib.sha256(payload).hexdigest()+ r2.download_object(creds, base, bucket, key, tmp_path / "signed", NOW,+ expected_size=len(payload), expected_sha256=digest)+ r2.download_public_object(channel_public_base(), key, tmp_path / "public",+ expected_size=len(payload), expected_sha256=digest)+ assert (tmp_path / "signed").read_bytes() == (tmp_path / "public").read_bytes() == payload+ assert r2.list_objects(prefix="releases/")["keys"] == [key]+ assert r2_server.store[key][0] == b"production sentinel"+ assert r2_server.store[scope.key(key)][0] == payload+ for method, url, headers in r2_server.requests:+ parsed = urlsplit(url)+ if parsed.query and "list-type" in parsed.query:+ assert parsed.path == "/hermes-releases"+ assert parse_qs(parsed.query)["prefix"] == [scope.prefix + "releases/"]+ else:+ assert parsed.path.startswith("/hermes-releases/" + scope.prefix)+ if method != "GET" or headers.get("authorization"):+ assert headers["authorization"].startswith("AWS4-HMAC-SHA256 ")+ before = list(r2_server.requests)+ for bad in ("../escape", "/releases/x", "releases/%2e%2e/x", "releases//x"):+ with pytest.raises(ValueError):+ r2.put_object(creds, base, bucket, bad, b"x", NOW, None)+ with pytest.raises(ValueError, match="bucket"):+ r2.list_objects(creds=creds, base=base, bucket=bucket + "/ci-disposable")+ with pytest.raises(ValueError, match="escaped"):+ scope.logical_key("releases/channels/stable.json")+ for bad in (root, "https://elsewhere.example", root + "/ci-disposable/999/98765-1"):+ with pytest.raises(ValueError, match="authority"):+ channel_public_base(bad)+ monkeypatch.setenv("R2_DISPOSABLE_RUN", "../production")+ with pytest.raises(ValueError):+ r2.put_object(creds, base, bucket, key, b"x", NOW, None)+ monkeypatch.delenv("R2_DISPOSABLE_RUN")+ monkeypatch.setenv("GITHUB_ACTIONS", "true")+ monkeypatch.setenv("GITHUB_REPOSITORY", "fixture/fork")+ with pytest.raises(ValueError, match="disposable"):+ r2.put_object(creds, base, bucket, key, b"x", NOW, None)+ assert r2_server.requests == before+ monkeypatch.delenv("GITHUB_ACTIONS")+ from scripts.releases.channel_disposable import probe+ from scripts.releases.channels import ChannelPublisher, R2ChannelStore+ unscoped = ChannelPublisher(R2ChannelStore(creds, base, bucket), "fixture/fork", root,+ authorize=lambda *_: None)+ with pytest.raises(ValueError, match="disposable"):+ probe(unscoped, "a" * 40, "1.2.3", "b" * 40)+ assert r2_server.requests == before++# ── SigV4 vectors ───────────────────────────────────────────────────────────@pytest.mark.parametrize('method,path,query,payload,scope,signature', [