The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(release): dynamic R2-owned channels and preview retirement (rounds 1-2)
ethernetb37acb8389b1
diff --git a/.github/workflows/canary-release.yml b/.github/workflows/canary-release.ymlindex 916d3691132..78692dcf668 100644--- a/.github/workflows/canary-release.yml+++ b/.github/workflows/canary-release.yml@@ -17,7 +17,10 @@ name: Canary Release# does — same tag, same draft, same build, same auto-publish.## The desktop build uploads the installers to the Cloudflare R2 release-# bucket and publishes the draft when the whole matrix is green. A failed+# bucket and publishes the draft when the whole matrix is green. Its final+# protected channel_releases canary step advances the R2 head from those same+# receipts, after the published-release read-back. This scheduler must not+# advance a head: dispatch success is not native acceptance. A failed# matrix leaves a draft: inspectable, re-runnable, and unreachable by# users. The prune job deletes both the GitHub releases+tags and the R2# canary objects older than 14 days.diff --git a/.github/workflows/desktop-bundle-smoke.yml b/.github/workflows/desktop-bundle-smoke.ymlindex 36ee497d4b6..396fcb02ef9 100644--- a/.github/workflows/desktop-bundle-smoke.yml+++ b/.github/workflows/desktop-bundle-smoke.yml@@ -21,6 +21,15 @@ on:commit-build:default: falsetype: boolean+ channel-build:+ default: ''+ type: string+ channel-request-sha256:+ default: ''+ type: string+ controller-sha:+ default: ''+ type: stringpublic-base:required: truetype: string@@ -29,8 +38,24 @@ permissions:contents: readjobs:+ validate:+ name: Require a supported native smoke target+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ env:+ TARGET: ${{ inputs.platform }}/${{ inputs.arch }}/${{ inputs.format }}+ steps:+ - name: Reject empty or unsupported native smoke jobs+ shell: bash+ run: |+ case "$TARGET" in+ darwin/arm64/dmg|darwin/x64/dmg|darwin/arm64/zip|darwin/x64/zip|win32/arm64/msix|win32/x64/msix|win32/arm64/msixbundle|win32/x64/msixbundle) ;;+ *) echo '::error::unsupported native smoke target'; exit 1 ;;+ esac+macos:name: macOS install and chat+ needs: validateif: inputs.platform == 'darwin'runs-on: ${{ inputs.arch == 'x64' && 'macos-15-intel' || 'macos-15' }}timeout-minutes: 30@@ -40,6 +65,8 @@ jobs:RELEASE_COMMIT: ${{ inputs.sha }}RELEASE_TAG: ${{ inputs.tag }}COMMIT_BUILD: ${{ inputs.commit-build }}+ CHANNEL_BUILD: ${{ inputs.channel-build }}+ CHANNEL_REQUEST_SHA256: ${{ inputs.channel-request-sha256 }}PUBLIC_BASE: ${{ inputs.public-base }}PLATFORM: ${{ inputs.platform }}ARCH: ${{ inputs.arch }}@@ -51,7 +78,7 @@ jobs:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:- ref: ${{ inputs.sha }}+ ref: ${{ inputs.channel-build != '' && inputs.controller-sha || inputs.sha }}persist-credentials: false- name: Set up driver tools only@@ -74,13 +101,22 @@ jobs:run: |set -euo pipefailmkdir -p "$SMOKE_ROOT/out"+ product=HermesBundled+ if [ -n "${CHANNEL_BUILD:-}" ]; then+ test "$COMMIT_BUILD" = false+ test -z "$RELEASE_TAG"+ python -m scripts.releases.channel_publish request --build-id "$CHANNEL_BUILD" \+ --request-sha256 "$CHANNEL_REQUEST_SHA256" --public-base "$PUBLIC_BASE" \+ --out "$SMOKE_ROOT/request.json"+ product=$(python -c 'import json,sys; print(json.load(open(sys.argv[1]))["identity"]["artifactNamePascal"])' "$SMOKE_ROOT/request.json")+ ficase "$PLATFORM/$ARCH/$FORMAT" indarwin/arm64/dmg|darwin/x64/dmg|darwin/arm64/zip|darwin/x64/zip)- name="darwin-$ARCH"; pattern="HermesBundled-*-mac-$ARCH.$FORMAT" ;;+ name="darwin-$ARCH"; pattern="$product-*-mac-$ARCH.$FORMAT" ;;win32/arm64/msix|win32/x64/msix)- name="win32-$ARCH"; pattern="HermesBundled-*-win-$ARCH.msix" ;;+ name="win32-$ARCH"; pattern="$product-*-win-$ARCH.msix" ;;win32/arm64/msixbundle|win32/x64/msixbundle)- name=windows-universal; pattern='HermesBundled-*-win.msixbundle' ;;+ name=windows-universal; pattern="$product-*-win.msixbundle" ;;*) echo '::error::unsupported native smoke target'; exit 1 ;;esacargs=(--tag "$RELEASE_TAG" --commit "$RELEASE_COMMIT")@@ -88,6 +124,7 @@ jobs:test -z "$RELEASE_TAG"args=(--commit-build "$RELEASE_COMMIT")fi+ if [ -n "${CHANNEL_BUILD:-}" ]; then args=(--channel-request "$SMOKE_ROOT/request.json"); fipython -m scripts.releases.handoff fetch --public-base "$PUBLIC_BASE" "${args[@]}" \--name "$name" --root "$SMOKE_ROOT/download" --include "$pattern" 2>&1 | tee "$SMOKE_ROOT/out/fetch.log"python - "$name" "$pattern" <<'PY'@@ -106,7 +143,7 @@ jobs:raise ValueError('Downloaded artifact no longer matches its receipt')(root / 'out' / 'download.json').write_text(json.dumps({'commit': data['commit'], 'tag': data.get('tag'), 'receipt': receipt.name,- 'receiptSha256': file_sha256(receipt), 'artifact': row,+ 'receiptSha256': file_sha256(receipt), 'artifact': row, 'request': data.get('request'),}, indent=2) + '\n', encoding='utf-8')with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:output.write(f'path={artifact.resolve().as_posix()}\n')@@ -128,6 +165,7 @@ jobs:run: |args=()if [ -n "$RELEASE_TAG" ]; then args+=(--tag "$RELEASE_TAG"); fi+ if [ -n "${CHANNEL_BUILD:-}" ]; then args+=(--channel-request "$SMOKE_ROOT/request.json"); fibash tests/install/macos-bundle-smoke.sh --artifact "$ARTIFACT" --arch "$ARCH" \--commit "$RELEASE_COMMIT" "${args[@]}" --work "$SMOKE_ROOT/work" --out "$SMOKE_ROOT/out"@@ -140,6 +178,7 @@ jobs:run: |$tagArgs = @()if ($env:RELEASE_TAG) { $tagArgs = @('-Tag', $env:RELEASE_TAG) }+ if ($env:CHANNEL_BUILD) { $tagArgs = @('-ChannelRequest', "$env:SMOKE_ROOT/request.json") }powershell -NoProfile -ExecutionPolicy Bypass -File tests/install/windows-bundle-smoke.ps1 -Artifact $env:ARTIFACT -Arch $env:ARCH -Commit $env:RELEASE_COMMIT @tagArgs -Work "$env:SMOKE_ROOT/work" -Out "$env:SMOKE_ROOT/out"if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }@@ -171,6 +210,7 @@ jobs:windows:name: Windows install and chat+ needs: validateif: inputs.platform == 'win32'runs-on: ${{ inputs.arch == 'arm64' && 'windows-11-arm' || 'windows-2025' }}timeout-minutes: 30diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.ymlindex f614957d608..663a1c518aa 100644--- a/.github/workflows/desktop-bundled-release.yml+++ b/.github/workflows/desktop-bundled-release.yml@@ -41,6 +41,9 @@ name: Desktop Bundled Release# carry release files. Non-publishing tag builds leave output on the runner.# Commit builds stage under releases/commit/<sha>/ and write a run summary.# They never publish a release, updater feed, Store submission, or APT channel.+# Admitted channel requests reuse those native build/smoke legs with read-only+# dependency caches. Their receipts use releases/channel-builds/<id>/; only the+# trusted publish-channel controller may CAS the channel after all smoke passes.## Payload staging is `hermes pm bundle` on the native runner. There is# no cross-target staging. The darwin legs sign (CSC_LINK) and notarize@@ -97,6 +100,16 @@ on:required: falsetype: stringdefault: ''+ channel_build:+ description: 'Admitted immutable channel build ID (32 lowercase hex); trusted default-branch dispatch only.'+ required: false+ type: string+ default: ''+ channel_request_sha256:+ description: 'SHA256 of the admitted immutable channel request.'+ required: false+ type: string+ default: ''build_commit:description: 'Commit-only build: EXACT full 40-hex SHA already pushed to this repo (workflow_dispatch from the default branch only). Mutually exclusive with tag.'required: false@@ -130,7 +143,7 @@ permissions:id-token: writeconcurrency:- group: desktop-bundled-release-${{ inputs.tag || inputs.build_commit || 'canary' }}-${{ inputs.release-phase || 'canary' }}+ group: desktop-bundled-release-${{ inputs.channel_build || inputs.tag || inputs.build_commit || 'canary' }}-${{ inputs.release-phase || 'canary' }}cancel-in-progress: falsejobs:@@ -153,7 +166,7 @@ jobs:steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:- ref: ${{ inputs.build_commit != '' && github.sha || inputs.tag }}+ ref: ${{ (inputs.build_commit != '' || inputs.channel_build != '') && github.sha || inputs.tag }}# Full history: the admission gate below runs merge-base against# origin/main, which needs the shared ancestry, not a depth-1 tip.fetch-depth: 0@@ -162,6 +175,8 @@ jobs:sparse-checkout: |pyproject.tomlscripts/releases+ scripts/release-content-types.json+ hermes_cli/release_channels.pysparse-checkout-cone-mode: false- name: Validate tag shape, pyproject lockstep, and ancestry on origin/main@@ -169,6 +184,10 @@ jobs:env:TAG: ${{ inputs.tag }}BUILD_COMMIT: ${{ inputs.build_commit }}+ CHANNEL_BUILD: ${{ inputs.channel_build }}+ CHANNEL_REQUEST_SHA256: ${{ inputs.channel_request_sha256 }}+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}+ TERMUX_ONLY: ${{ inputs.termux_only }}BUNDLE_ENV_JSON: ${{ inputs.bundle_env }}RELEASE_PHASE: ${{ inputs.release-phase }}DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}@@ -176,6 +195,16 @@ jobs:TERMUX_UPGRADE_FROM_TAG: ${{ inputs.termux_upgrade_from_tag }}GH_TOKEN: ${{ github.token }}run: |+ if [ -n "${CHANNEL_BUILD:-}" ]; then+ if [ "$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" ]; then+ echo '::error::channel builds require the default-branch dispatch workflow'; exit 1+ fi+ python -m scripts.releases.channel_publish admit+ exit 0+ fi+ if [ -n "${CHANNEL_REQUEST_SHA256:-}" ]; then+ echo '::error::channel_request_sha256 requires channel_build'; exit 1+ fiif [ -n "$BUILD_COMMIT" ]; then# Reject mixed inputs before loading code from the checkout.if [ -n "$TAG" ] || [ -n "$RELEASE_PHASE" ] || [ -n "$TERMUX_UPGRADE_FROM_TAG" ] || [ "$UPLOAD_RELEASE" != false ]; then@@ -260,7 +289,7 @@ jobs:# Share execution via anchors, and keep the original IDs as downstream gates.build-win32-release:name: bundled ${{ matrix.target.label }}- if: inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate') && inputs.build_commit == ''+ if: 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@@ -275,6 +304,7 @@ jobs:- label: win32-arm64runner: windows-11-armenv: &win32-env+ CHANNEL_BUILD: ${{ inputs.channel_build }}HERMES_DESKTOP_VARIANT: bundledHERMES_PAYLOAD_TAG: ${{ inputs.tag }}HERMES_BUILD_COMMIT: ${{ needs.validate.outputs.sha && inputs.build_commit != '' && needs.validate.outputs.sha || '' }}@@ -314,6 +344,23 @@ jobs:ref: ${{ needs.validate.outputs.sha }}fetch-tags: true+ - name: Check out trusted channel controller+ if: inputs.channel_build != ''+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.sha }}+ path: .build/channel-controller+ persist-credentials: false++ - name: Retrieve pinned channel request+ if: inputs.channel_build != ''+ shell: bash+ working-directory: .build/channel-controller+ env:+ CHANNEL_BUILD: ${{ inputs.channel_build }}+ CHANNEL_REQUEST_SHA256: ${{ inputs.channel_request_sha256 }}+ run: python -m scripts.releases.channel_publish request --out "$RUNNER_TEMP/channel-request.json"+- name: Restore desktop dependency inputsid: build-cacheuses: ./.github/actions/desktop-build-cache@@ -332,12 +379,13 @@ jobs:run: |args=(--tag "$HERMES_PAYLOAD_TAG")if [ -n "$HERMES_BUILD_COMMIT" ]; then args=(--commit "$HERMES_BUILD_COMMIT"); fi+ if [ -n "${CHANNEL_BUILD:-}" ]; then args=(--channel-request "$RUNNER_TEMP/channel-request.json"); fipython scripts/bundles/desktop.py "${args[@]}" --variant bundled --prepare-only \--work "$RUNNER_TEMP/desktop-job" --cache "$GITHUB_WORKSPACE/.cache/desktop-inputs"python -m scripts.ci.desktop_commands "$RUNNER_TEMP/desktop-job/prepared.json"- name: Save dependency inputs before building- if: ${{ !cancelled() && steps.prepare.outcome == 'success' && inputs.build_commit == '' }}+ if: ${{ !cancelled() && steps.prepare.outcome == 'success' && inputs.build_commit == '' && inputs.channel_build == '' }}uses: ./.github/actions/desktop-build-cachewith:phase: save@@ -395,7 +443,7 @@ jobs:run: |python scripts/bundles/desktop.py --prepared "$env:RUNNER_TEMP/desktop-job/prepared.json" --variant bundledif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }- if (-not $env:HERMES_BUILD_COMMIT -and $env:HERMES_PAYLOAD_TAG -notlike "*-canary.*") {+ if (-not $env:CHANNEL_BUILD -and -not $env:HERMES_BUILD_COMMIT -and $env:HERMES_PAYLOAD_TAG -notlike "*-canary.*") {python scripts/bundles/desktop.py --prepared "$env:RUNNER_TEMP/desktop-job/prepared.json" --variant storeif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }}@@ -412,6 +460,24 @@ jobs:node apps/desktop/scripts/audit-bundle-arch.mjs \--arch="${MATRIX_LABEL##*-}" --root=apps/desktop/release+ - name: Record and stage channel windows packages+ if: inputs.channel_build != ''+ shell: bash+ working-directory: .build/channel-controller+ env:+ TARGET: ${{ matrix.target.label }}+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}+ 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 }}+ run: |+ root="$GITHUB_WORKSPACE/apps/desktop/release"+ python -m scripts.bundles.release_artifacts record --platform windows --arch "${TARGET##*-}" \+ --root "$root" --commit "$RELEASE_COMMIT" --channel-request "$RUNNER_TEMP/channel-request.json" \+ --out "$root/metadata-windows-${TARGET##*-}.json"+ python -m scripts.releases.handoff stage --channel-request "$RUNNER_TEMP/channel-request.json" \+ --name "$TARGET" --root "$root" --include '*.msix' --include 'metadata-*.json'+- name: Stage Windows packages to R2if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''shell: bash@@ -444,7 +510,7 @@ 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 != ''+ if: 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@@ -467,8 +533,8 @@ jobs:timeout-minutes: 5env:SELECTED_BUILD_SUCCEEDED: >-- ${{ (inputs.build_commit == '' && needs.build-win32-release.result == 'success' && needs.build-win32-commit.result == 'skipped')- || (inputs.build_commit != '' && needs.build-win32-commit.result == 'success' && needs.build-win32-release.result == 'skipped') }}+ ${{ (inputs.build_commit == '' && inputs.channel_build == '' && needs.build-win32-release.result == 'success' && needs.build-win32-commit.result == 'skipped')+ || ((inputs.build_commit != '' || inputs.channel_build != '') && needs.build-win32-commit.result == 'success' && needs.build-win32-release.result == 'skipped') }}steps: &native-build-result-steps- name: Require exactly the selected native build to succeedshell: bash@@ -491,7 +557,7 @@ jobs:# pointer last, whole channel green before anything publishes.build-darwin-release:name: bundled ${{ matrix.target.label }}- if: inputs.termux_only != true && (inputs.release-phase == '' || inputs.release-phase == 'candidate') && inputs.build_commit == ''+ if: 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@@ -506,6 +572,7 @@ jobs:- label: darwin-x64runner: macos-15-intelenv: &darwin-env+ CHANNEL_BUILD: ${{ inputs.channel_build }}HERMES_DESKTOP_VARIANT: bundledHERMES_PAYLOAD_TAG: ${{ inputs.tag }}HERMES_BUILD_COMMIT: ${{ needs.validate.outputs.sha && inputs.build_commit != '' && needs.validate.outputs.sha || '' }}@@ -529,6 +596,23 @@ jobs:fetch-tags: truefetch-depth: 0+ - name: Check out trusted channel controller+ if: inputs.channel_build != ''+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.sha }}+ path: .build/channel-controller+ persist-credentials: false++ - name: Retrieve pinned channel request+ if: inputs.channel_build != ''+ shell: bash+ working-directory: .build/channel-controller+ env:+ CHANNEL_BUILD: ${{ inputs.channel_build }}+ CHANNEL_REQUEST_SHA256: ${{ inputs.channel_request_sha256 }}+ run: python -m scripts.releases.channel_publish request --out "$RUNNER_TEMP/channel-request.json"+- name: Restore desktop dependency inputsid: build-cacheuses: ./.github/actions/desktop-build-cache@@ -547,12 +631,13 @@ jobs:run: |args=(--tag "$HERMES_PAYLOAD_TAG")if [ -n "$HERMES_BUILD_COMMIT" ]; then args=(--commit "$HERMES_BUILD_COMMIT"); fi+ if [ -n "${CHANNEL_BUILD:-}" ]; then args=(--channel-request "$RUNNER_TEMP/channel-request.json"); fipython3 scripts/bundles/desktop.py "${args[@]}" --variant bundled --prepare-only \--work "$RUNNER_TEMP/desktop-job" --cache "$GITHUB_WORKSPACE/.cache/desktop-inputs"python3 -m scripts.ci.desktop_commands "$RUNNER_TEMP/desktop-job/prepared.json"- name: Save dependency inputs before building- if: ${{ !cancelled() && steps.prepare.outcome == 'success' && inputs.build_commit == '' }}+ if: ${{ !cancelled() && steps.prepare.outcome == 'success' && inputs.build_commit == '' && inputs.channel_build == '' }}uses: ./.github/actions/desktop-build-cachewith:phase: save@@ -565,7 +650,7 @@ jobs:# Commit artifacts are downloadable too. Require signing for them,# candidates, and published tags before building any payload.- name: Require signing credentials when publishing- if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''+ if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '' || inputs.channel_build != ''shell: bashenv:CSC_LINK: ${{ secrets.CSC_LINK }}@@ -591,7 +676,7 @@ jobs:# notarytool takes a FILE PATH for --key; raw .p8 content in argv# dies with `Invalid option: ***`. The build step must NOT re-declare# APPLE_API_KEY in its env: step env shadows GITHUB_ENV.- if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''+ if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '' || inputs.channel_build != ''shell: bashenv:APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}@@ -632,7 +717,7 @@ jobs:# The backstop against a silent unsigned publish: assess the packed# app against the real Gatekeeper policy (requires a Developer ID# signature AND a stapled notarization ticket to pass offline).- if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''+ if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '' || inputs.channel_build != ''shell: bashrun: |shopt -s nullglob@@ -666,6 +751,24 @@ jobs:test -s "$f"mv "$f" "apps/desktop/release/${arch}-${channel}-mac.yml"+ - name: Record and stage channel macos packages+ if: inputs.channel_build != ''+ shell: bash+ working-directory: .build/channel-controller+ env:+ TARGET: ${{ matrix.target.label }}+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}+ 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 }}+ run: |+ root="$GITHUB_WORKSPACE/apps/desktop/release"+ python -m scripts.bundles.release_artifacts record --platform macos --arch "${TARGET##*-}" \+ --root "$root" --commit "$RELEASE_COMMIT" --channel-request "$RUNNER_TEMP/channel-request.json" \+ --out "$root/metadata-macos-${TARGET##*-}.json"+ python -m scripts.releases.handoff stage --channel-request "$RUNNER_TEMP/channel-request.json" \+ --name "$TARGET" --root "$root" --include '*.dmg' --include '*.zip' --include '*.blockmap' --include 'metadata-*.json'+- name: Stage macOS packages and feed inputs to R2if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''shell: bash@@ -698,7 +801,7 @@ 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 != ''+ if: 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@@ -721,8 +824,8 @@ jobs:timeout-minutes: 5env:SELECTED_BUILD_SUCCEEDED: >-- ${{ (inputs.build_commit == '' && needs.build-darwin-release.result == 'success' && needs.build-darwin-commit.result == 'skipped')- || (inputs.build_commit != '' && needs.build-darwin-commit.result == 'success' && needs.build-darwin-release.result == 'skipped') }}+ ${{ (inputs.build_commit == '' && inputs.channel_build == '' && needs.build-darwin-release.result == 'success' && needs.build-darwin-commit.result == 'skipped')+ || ((inputs.build_commit != '' || inputs.channel_build != '') && needs.build-darwin-commit.result == 'success' && needs.build-darwin-release.result == 'skipped') }}steps: *native-build-result-steps# ── Linux builders (DISABLED for now) ─────────────────────────────────────@@ -749,7 +852,7 @@ jobs:!cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''&& needs.build-darwin.result == 'success' && inputs.termux_only != true&& (inputs.release-phase == '' || inputs.release-phase == 'candidate')- && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '' || inputs.channel_build != '')permissions:contents: readstrategy:@@ -765,6 +868,9 @@ jobs:sha: ${{ needs.validate.outputs.sha }}tag: ${{ inputs.tag }}commit-build: ${{ inputs.build_commit != '' }}+ channel-build: ${{ inputs.channel_build }}+ channel-request-sha256: ${{ inputs.channel_request_sha256 }}+ controller-sha: ${{ github.sha }}public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}smoke-win32:@@ -774,7 +880,7 @@ jobs:!cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''&& needs.build-win32.result == 'success' && inputs.termux_only != true&& (inputs.release-phase == '' || inputs.release-phase == 'candidate')- && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '' || inputs.channel_build != '')permissions:contents: readstrategy:@@ -789,6 +895,9 @@ jobs:sha: ${{ needs.validate.outputs.sha }}tag: ${{ inputs.tag }}commit-build: ${{ inputs.build_commit != '' }}+ channel-build: ${{ inputs.channel_build }}+ channel-request-sha256: ${{ inputs.channel_request_sha256 }}+ controller-sha: ${{ github.sha }}public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}smoke-win32-universal:@@ -798,7 +907,7 @@ jobs:!cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''&& needs.assemble-win32-bundle.result == 'success' && inputs.termux_only != true&& (inputs.release-phase == '' || inputs.release-phase == 'candidate')- && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '' || inputs.channel_build != '')permissions:contents: readstrategy:@@ -813,6 +922,9 @@ jobs:sha: ${{ needs.validate.outputs.sha }}tag: ${{ inputs.tag }}commit-build: ${{ inputs.build_commit != '' }}+ channel-build: ${{ inputs.channel_build }}+ channel-request-sha256: ${{ inputs.channel_request_sha256 }}+ controller-sha: ${{ github.sha }}public-base: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}# Assembly never writes a feed, including for canaries.@@ -823,12 +935,14 @@ jobs:!cancelled() && needs.validate.result == 'success' && needs.validate.outputs.sha != ''&& needs.build-win32.result == 'success' && inputs.termux_only != true&& (inputs.release-phase == '' || inputs.release-phase == 'candidate')- && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')+ && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '' || inputs.channel_build != '')runs-on: windows-2025environment: release-signingcache-mode: readtimeout-minutes: 45env:+ CHANNEL_BUILD: ${{ inputs.channel_build }}+ CHANNEL_REQUEST_SHA256: ${{ inputs.channel_request_sha256 }}HERMES_PAYLOAD_TAG: ${{ inputs.tag }}HERMES_BUILD_COMMIT: ${{ needs.validate.outputs.sha && inputs.build_commit != '' && needs.validate.outputs.sha || '' }}HERMES_PAYLOAD_VERSION: ${{ needs.validate.outputs.payload-version }}@@ -847,12 +961,17 @@ jobs:# job runs it with no checkout at all today — ERR_MODULE_NOT_FOUND.- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:- # Privileged job: pin to the SHA validate admitted, not the tag.- ref: ${{ needs.validate.outputs.sha }}+ # Channel assembly/publishing code stays at the trusted controller.+ ref: ${{ inputs.channel_build != '' && github.sha || needs.validate.outputs.sha }}# stage-msixbundle derives the canary MSIX build number as# minutes-since-the-last-stable from git tags — must see them.fetch-tags: true+ - name: Retrieve pinned channel request+ if: inputs.channel_build != ''+ shell: bash+ run: python -m scripts.releases.channel_publish request --out "$RUNNER_TEMP/channel-request.json"+- name: Set up the locked build toolchainuses: ./.github/actions/setup-pmwith:@@ -907,7 +1026,10 @@ jobs:env:RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}run: |- if [ -n "$HERMES_BUILD_COMMIT" ]; then+ if [ -n "${CHANNEL_BUILD:-}" ]; then+ python -m scripts.releases.handoff fetch --channel-request "$RUNNER_TEMP/channel-request.json" \+ --name win32-x64 --name win32-arm64 --root apps/desktop/release --include '*.msix'+ elif [ -n "$HERMES_BUILD_COMMIT" ]; thenpython -m scripts.releases.handoff fetch --commit-build "$HERMES_BUILD_COMMIT" \--commit "$RELEASE_COMMIT" \--name win32-x64 --name win32-arm64 --root apps/desktop/release --include '*.msix'@@ -946,6 +1068,10 @@ jobs:run: |# All modes stop at signed bytes. The separate handoff stages them# for smoke; publication must not assemble or sign a second time.+ if [ -n "${CHANNEL_BUILD:-}" ]; then+ node scripts/stage-msixbundle.mjs --channel-request "$RUNNER_TEMP/channel-request.json" --variant bundled+ exit 0+ fiif [ -n "$HERMES_BUILD_COMMIT" ]; thennode scripts/stage-msixbundle.mjs --commit "$HERMES_BUILD_COMMIT" --version "$HERMES_PAYLOAD_VERSION" --variant bundled --no-uploadexit 0@@ -962,7 +1088,10 @@ jobs:env:RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}run: |- if [ -n "$HERMES_BUILD_COMMIT" ]; then+ if [ -n "${CHANNEL_BUILD:-}" ]; then+ python -m scripts.releases.handoff stage --channel-request "$RUNNER_TEMP/channel-request.json" \+ --name windows-universal --root apps/desktop/release --include '*.msixbundle'+ elif [ -n "$HERMES_BUILD_COMMIT" ]; thenpython -m scripts.releases.handoff stage --commit-build "$HERMES_BUILD_COMMIT" \--commit "$RELEASE_COMMIT" \--name windows-universal --root apps/desktop/release --include '*.msixbundle'@@ -971,11 +1100,50 @@ jobs:--name windows-universal --root apps/desktop/release --include '*.msixbundle'fi+ publish-channel:+ name: Publish the complete native-smoked channel build+ needs: [validate, build-darwin, build-win32, assemble-win32-bundle, smoke-darwin, smoke-win32, smoke-win32-universal]+ if: >-+ !cancelled() && inputs.channel_build != '' && needs.validate.result == 'success'+ && needs.build-darwin.result == 'success' && needs.build-win32.result == 'success'+ && needs.assemble-win32-bundle.result == 'success' && needs.smoke-darwin.result == 'success'+ && needs.smoke-win32.result == 'success' && needs.smoke-win32-universal.result == 'success'+ runs-on: ubuntu-24.04+ environment: release-signing+ cache-mode: read+ timeout-minutes: 45+ permissions:+ contents: read+ env:+ CHANNEL_BUILD: ${{ inputs.channel_build }}+ CHANNEL_REQUEST_SHA256: ${{ inputs.channel_request_sha256 }}+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}+ GH_TOKEN: ${{ github.token }}+ 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 }}+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.sha }}+ fetch-depth: 0+ fetch-tags: true+ - name: Publish immutable feeds and manifest, then CAS channel head+ shell: bash+ run: |+ 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" \+ --summary-out "$GITHUB_STEP_SUMMARY"+publish-win32-updater:name: Publish the tested Windows canary bundleneeds: [validate, assemble-win32-bundle, smoke-win32, smoke-win32-universal]if: >-- !cancelled() && inputs.build_commit == '' && inputs.upload_release == true+ !cancelled() && inputs.build_commit == '' && inputs.channel_build == '' && inputs.upload_release == true&& inputs.release-phase == '' && inputs.termux_only != true&& needs.validate.result == 'success' && needs.validate.outputs.sha != ''&& needs.assemble-win32-bundle.result == 'success'@@ -1053,7 +1221,7 @@ jobs:name: Publish the macOS updater feedneeds: [validate, build-darwin, smoke-darwin]if: >-- !cancelled() && inputs.build_commit == '' && inputs.upload_release == true+ !cancelled() && inputs.build_commit == '' && inputs.channel_build == '' && inputs.upload_release == true&& inputs.release-phase == '' && inputs.termux_only != true&& needs.validate.result == 'success' && needs.validate.outputs.sha != ''&& needs.build-darwin.result == 'success' && needs.smoke-darwin.result == 'success'@@ -1118,7 +1286,7 @@ jobs:termux-deb:name: Build + publish the termux .deb (aarch64)needs: [validate, archive-inputs]- if: inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != ''+ if: inputs.channel_build == '' && (inputs.upload_release == true || inputs.release-phase == 'candidate' || inputs.build_commit != '')runs-on: ubuntu-24.04-armenvironment: release-signingtimeout-minutes: 90@@ -1490,7 +1658,7 @@ jobs:# Failed builds still get a per-tag diagnostic page. The renderer only# advances the channel landing page when every prerequisite succeeded.if: |- always() && inputs.build_commit == '' && inputs.upload_release == true && inputs.release-phase == ''+ always() && inputs.build_commit == '' && inputs.channel_build == '' && inputs.upload_release == true && inputs.release-phase == ''&& needs.validate.result == 'success' && needs.validate.outputs.sha != ''runs-on: ubuntu-24.04environment: release-signing@@ -1750,7 +1918,7 @@ jobs: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]if: |always()- && inputs.build_commit == ''+ && inputs.build_commit == '' && inputs.channel_build == ''&& inputs.upload_release == true&& contains(inputs.tag, '-canary.')&& needs.build-win32.result == 'success'diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.ymlindex e9de1e35e15..5ae3e95c411 100644--- a/.github/workflows/stable-release.yml+++ b/.github/workflows/stable-release.yml@@ -269,12 +269,22 @@ jobs:- uses: ./.github/actions/setup-pmwith:cache-python: false+ - name: Set up the native identity reader+ uses: ./.github/actions/setup-pm+ with:+ toolchain: node+ cache-python: false- run: python -m scripts.releases.stable gate admit ci docker acceptance candidates publication promote-docker promote-bundlesenv:RELEASE_NEEDS: ${{ toJSON(needs) }}- - name: Record accepted stable packages and publish release- run: python -m scripts.releases.stable complete+ - name: Record accepted stable packages and publish release, then advance the R2 head+ # Keep the source/native head last: a failed manifest or GitHub transaction+ # must leave protocol-aware readers on the previous accepted release.+ run: |+ python -m scripts.releases.stable complete+ python -m scripts.releases.channel_releases stableenv:+ RELEASE_NEEDS: ${{ toJSON(needs) }}GH_TOKEN: ${{ github.token }}RELEASE_TAG: ${{ inputs.tag }}CANDIDATE_MANIFEST_URL: ${{ needs.candidates.outputs.manifest-url }}diff --git a/apps/desktop/electron-builder.config.cjs b/apps/desktop/electron-builder.config.cjsindex 8412c71421f..c1fcab01e78 100644--- a/apps/desktop/electron-builder.config.cjs+++ b/apps/desktop/electron-builder.config.cjs@@ -49,7 +49,8 @@ function mustStoreMsix(value) {// The out-of-store MSIX publisher (ATS cert subject) — single source, shared// with the .appinstaller generator so the manifest and the App Installer can// never drift (see scripts/msix-shared.mjs).-const { OUT_OF_STORE_PUBLISHER } = require('../../scripts/msix-shared.mjs')+const { OUT_OF_STORE_PUBLISHER, channelBuildRequest, stageChannelManifest } = require('../../scripts/msix-shared.mjs')+const channelRequest = channelBuildRequest()/** @typedef {import("app-builder-lib").Configuration} Configuration */@@ -62,10 +63,10 @@ if (!/^\d+\.\d+\.\d+$/.test(electronVersion)) {throw new Error(`invalid electron version ${electronVersion} in package.json`)}-const macFeed = feedContract.darwinFeed(channel === 'canary' || channel === 'light-canary' ? 'canary' : 'stable', light)+const macFeed = channelRequest ? null : feedContract.darwinFeed(channel === 'canary' || channel === 'light-canary' ? 'canary' : 'stable', light)const publicUrl = process.env.CLOUDFLARE_R2_PUBLIC_URL?.replace(/\/+$/, '')-/** @type {Configuration} */+/** @satisfies {Configuration} */module.exports = {electronVersion,appId,@@ -89,7 +90,7 @@ module.exports = {// var (local, or a fork without the R2 vars) keep the github provider, which// is exactly today's behavior. The store build has no feed at all (the Store// owns its distribution and updates).- publish: !channel+ publish: channelRequest ? null : !channel? null: [process.env.CLOUDFLARE_R2_PUBLIC_URL@@ -100,14 +101,18 @@ module.exports = {name: appNamePascal,// Electron bootstrap reads package.productName before main.ts. Keep the// shipped stable default, but isolate nonstable userData from first access.- ...(appNamePascal !== artifactNamePascal ? { productName: displayName } : {}),+ ...(channelRequest || appNamePascal !== artifactNamePascal ? { productName: displayName } : {}),desktopName: appId},directories: {output: 'release'},files: ['dist/**', 'assets/**', 'public/**', 'package.json'],- beforeBuild: 'scripts/before-build.mjs',+ beforeBuild: channelRequest ? async () => {+ await require(path.join(__dirname, 'scripts/before-build.mjs')).default()+ stageChannelManifest(__dirname, channelRequest)+ return false+ } : 'scripts/before-build.mjs',beforePack: 'scripts/before-pack.mjs',afterPack: 'scripts/after-pack.mjs',...(process.platform === 'darwin' ? { afterSign: 'scripts/notarize.mjs' } : {}),@@ -131,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: publicUrl && channel+ publish: 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 }]: null,category: 'public.app-category.developer-tools',@@ -213,7 +220,7 @@ module.exports = {// stable build sets no BUILD_NUMBER and stays X.Y.Z.0, a canary build sets// it via scripts/bundles/desktop.py so App Installer updates over equal// canary-over-canary versions instead of refusing them.- setBuildNumber: !store,+ setBuildNumber: !store && !channelRequest,// Store versions are baked into a build-time template. App semver and// artifact filenames stay unchanged; the Store reserves revision zero.// Floor Windows 11 22H2. Below build 18307 the manifest schema caps@@ -229,7 +236,7 @@ module.exports = {// time, so typecheck/test imports don't touch the filesystem.customExtensionsPath: 'build/msix-extensions.xml',customManifestPath: store ? 'build/store-msix-manifest.xml'- : appNamePascal !== artifactNamePascal ? 'build/msix-manifest.xml' : 'assets/msix-manifest.xml',+ : channelRequest || appNamePascal !== artifactNamePascal ? 'build/msix-manifest.xml' : 'assets/msix-manifest.xml',// Hermes state is deliberately shared with unpackaged CLI/gateway// processes. Pair the manifest's disabled virtualization properties with// the restricted capability that permits unvirtualized AppData/HKCU writes.@@ -246,6 +253,19 @@ module.exports = {}}+if (channelRequest) {+ Object.assign(module.exports, { buildVersion: channelRequest.version })+ Object.assign(module.exports.extraMetadata, {+ version: channelRequest.version,+ shortVersion: channelRequest.windowsVersion,+ shortVersionWindows: channelRequest.windowsVersion+ })+ Object.assign(module.exports.mac, {+ bundleVersion: channelRequest.version,+ bundleShortVersion: channelRequest.version+ })+}+// MSIX build-time staging (build/appx icons + build/msix-extensions.xml)// lives in scripts/before-build.mjs — an electron-builder lifecycle hook —// NOT here at require time, so importing this config for typecheck/testsdiff --git a/apps/desktop/electron/app-updater.ts b/apps/desktop/electron/app-updater.tsindex 0587b0333aa..6bb20134ed8 100644--- a/apps/desktop/electron/app-updater.ts+++ b/apps/desktop/electron/app-updater.ts@@ -18,6 +18,8 @@// The win32 helpers are pure so vitest covers them; the impure pieces// (electron shell, payload python) are injected.+import feedContract from '../update-feed.cjs'+// ─── feed hosting ───────────────────────────────────────────────────────────/**@@ -28,9 +30,10 @@* packages.*/export function win32AppInstallerFeedPath(- channel: 'stable' | 'canary',+ channel: string,light: boolean): string {+ feedContract.darwinFeed(channel, light)const variant = light ? 'light/' : ''return `win32/${variant}${channel}/`@@ -92,7 +95,7 @@ export function parseCheckOutput(code: number, stdout: string): AppInstallerChec/** Open a local descriptor. The ms-appinstaller protocol is disabled by default. */export async function triggerAppInstallerUpdate(feedBaseUrl: string,- channel: 'stable' | 'canary',+ channel: string,light: boolean,installer: { prepare: (url: string) => Promise<string>; open: (file: string) => Promise<string> },beforeInstall?: () => void | Promise<void>,diff --git a/apps/desktop/electron/app-version.test.ts b/apps/desktop/electron/app-version.test.tsindex 489772e67d7..827f65821de 100644--- a/apps/desktop/electron/app-version.test.ts+++ b/apps/desktop/electron/app-version.test.ts@@ -20,6 +20,21 @@ describe('artifact version identity', (): void => {expect((): void => assertSourceUpdateChannel(stamp)).toThrow()})+ it('reports baked channel source version independently of native sequence version', (): void => {+ const stamp: InstallStamp = {+ schemaVersion: 1, source: 'channel-build', payload: 'bundled', distribution: 'desktop-app',+ updateMechanism: 'electron-updater', tag: null, commit: 'a'.repeat(40), commitDate: null,+ branch: null, builtAt: null, dirty: false, baseVersion: '1.2.3', displayVersion: '0.0.7', distance: null,+ channelBuild: { schema: 1, buildId: 'b'.repeat(32), channel: 'new-name', sequence: 7,+ repository: 'example/hermes-agent', commit: 'a'.repeat(40), sourceVersion: '1.2.3', version: '0.0.7', windowsVersion: '0.0.7.0', publicBase: 'https://example.com', bundleEnv: {},+ identity: { token: '1234567890abcdef', displayName: 'Preview', appId: 'chat.preview', appNamePascal: 'Preview', artifactNamePascal: 'Preview', cliName: 'preview', windowsExecutableName: 'Preview.exe', msixAppIdWithOrg: 'Nous.Preview' } }+ }+ expect(appVersionInfo(stamp, '9.9.9-remote', '0.0.7')).toMatchObject({+ channel: 'new-name', baseVersion: '1.2.3', appVersion: '1.2.3 (new-name #7, aaaaaaaa)',+ sequence: 7, buildId: 'b'.repeat(32)+ })+ })+it('keeps source installs on their runtime version without a fixed package channel', (): void => {expect(appVersionInfo(null, '9.9.9-runtime', '1.2.3')).toMatchObject({ appVersion: '9.9.9-runtime' })expect((): void => assertSourceUpdateChannel(null)).not.toThrow()diff --git a/apps/desktop/electron/app-version.ts b/apps/desktop/electron/app-version.tsindex 611ecbff9cb..65fed21e4ca 100644--- a/apps/desktop/electron/app-version.ts+++ b/apps/desktop/electron/app-version.ts@@ -5,7 +5,9 @@ import { COMMIT_BUILD_UPDATE_MESSAGE } from './updater/external'export interface AppVersionInfo {appVersion: stringbaseVersion?: string- channel?: 'stable' | 'canary' | null+ channel?: string | null+ sequence?: number+ buildId?: stringdistance?: numbercommit?: string | nullbranch?: string | null@@ -16,7 +18,8 @@ export interface AppVersionInfo {}/** A release channel is an artifact identity, not a user preference. */-export function packagedReleaseChannel(stamp: Readonly<InstallStamp> | null): 'stable' | 'canary' | null {+export function packagedReleaseChannel(stamp: Readonly<InstallStamp> | null): string | null {+ if (stamp?.channelBuild) { return stamp.channelBuild.channel }if (!stamp?.tag || stamp.source === 'commit-build') { return null }return isCanaryTag(stamp.tag) ? 'canary' : 'stable'@@ -26,9 +29,13 @@ export function packagedReleaseChannel(stamp: Readonly<InstallStamp> | null): 'sexport function appVersionInfo(stamp: Readonly<InstallStamp> | null, runtimeVersion: string, packageVersion: string): AppVersionInfo {if (!stamp) { return { appVersion: runtimeVersion, baseVersion: packageVersion } }+ const build = stamp.channelBuildreturn {- appVersion: stamp.payload === 'bootstrap' ? runtimeVersion : stamp.displayVersion || packageVersion,- baseVersion: stamp.baseVersion ?? undefined,+ appVersion: build ? `${build.sourceVersion} (${build.channel} #${build.sequence}, ${build.commit.slice(0, 8)})` :+ stamp.payload === 'bootstrap' ? runtimeVersion : stamp.displayVersion || packageVersion,+ baseVersion: build?.sourceVersion ?? stamp.baseVersion ?? undefined,+ sequence: build?.sequence,+ buildId: build?.buildId,channel: packagedReleaseChannel(stamp),distance: stamp.distance ?? undefined,commit: stamp.commit,diff --git a/apps/desktop/electron/channel-build-version.test.ts b/apps/desktop/electron/channel-build-version.test.tsnew file mode 100644index 00000000000..dc456324df9--- /dev/null+++ b/apps/desktop/electron/channel-build-version.test.ts@@ -0,0 +1,207 @@+import assert from 'node:assert/strict'+import { execFileSync } from 'node:child_process'+import fs from 'node:fs'+import { createRequire } from 'node:module'+import os from 'node:os'+import path from 'node:path'++import type { Configuration } from 'app-builder-lib'+import { afterEach, test } from 'vitest'++import type { ChannelBuildRequest, InstallStamp } from './install-stamp'+import { applyDesktopIdentity, type ProductIdentity } from './product-identity'++const require: NodeJS.Require = createRequire(import.meta.url)+const desktop: string = path.resolve(import.meta.dirname, '..')+const repo: string = path.resolve(desktop, '../..')++function request(sequence: number = 65536, token: string = 'ab12cd34ef56ab78'): ChannelBuildRequest {+ return {+ schema: 1, buildId: 'a'.repeat(32), channel: 'no-registry-needed', sequence,+ repository: 'fixture/project', commit: 'b'.repeat(40), sourceVersion: '1.2.3',+ version: `0.0.${sequence}`, windowsVersion: `0.${Math.floor(sequence / 65536)}.${sequence % 65536}.0`,+ identity: {+ token, displayName: 'Hermes no-registry-needed', appId: `com.nousresearch.hermes-channel-${token}`,+ appNamePascal: `HermesChannel${token}`, artifactNamePascal: `HermesChannel${token}`,+ cliName: 'hermes-no-registry-needed', windowsExecutableName: 'hermes-no-registry-needed',+ msixAppIdWithOrg: `NousResearch.HermesChannel${token}`+ },+ bundleEnv: { HERMES_GUEST_ONBOARDING: '1' }, publicBase: 'https://builds.example.test'+ }+}++interface PackagingFacts { identity: ProductIdentity; config: Configuration }+interface StampPayload { runtime: { repoDir: string; commands: { hermes: string } } }++function load(build: ChannelBuildRequest): PackagingFacts {+ process.env.HERMES_DESKTOP_VARIANT = 'bundled'+ process.env._HERMES_CHANNEL_REQUEST_JSON = JSON.stringify(build)++ for (const file of ['../product-identity.cjs', '../electron-builder.config.cjs']) {+ delete require.cache[require.resolve(file)]+ }++ return { identity: require('../product-identity.cjs'), config: require('../electron-builder.config.cjs') }+}++afterEach((): void => {+ for (const key of ['_HERMES_CHANNEL_REQUEST_JSON', 'HERMES_DESKTOP_VARIANT', 'HERMES_BUILD_COMMIT', 'HERMES_PAYLOAD_TAG']) {delete process.env[key]}++ for (const file of ['../product-identity.cjs', '../electron-builder.config.cjs']) {delete require.cache[require.resolve(file)]}+})++test('channel packaging reuses admitted identity and rejects unsupported or unsafe identities', (): void => {+ const first: ChannelBuildRequest = request()+ const a: ReturnType<typeof load> = load(first)+ const b: ReturnType<typeof load> = load({ ...first, ...request(65537), commit: 'c'.repeat(40), sourceVersion: '0.1.0' })++ for (const field of ['displayName', 'appId', 'appNamePascal', 'cliName', 'windowsExecutableName', 'msixAppIdWithOrg'] as const) {+ assert.equal(a.identity[field], first.identity[field])+ assert.equal(a.identity[field], b.identity[field])+ }++ const other: ReturnType<typeof load> = load(request(1, '1234567890abcdef'))+ assert.notEqual(other.identity.appId, a.identity.appId)+ assert.equal(a.config.extraMetadata?.version, first.version)+ assert.equal(a.config.extraMetadata?.shortVersionWindows, first.windowsVersion)+ assert.equal(a.config.msix?.identityName, first.identity.msixAppIdWithOrg)+ const appData: string = fs.mkdtempSync(path.join(os.tmpdir(), 'channel-runtime-identity-'))+ let userData: string = appData+ let displayName: string = ''++ try {+ assert.equal(applyDesktopIdentity({+ getPath: (): string => appData,+ setPath: (_name: 'userData', value: string): void => { userData = value },+ setName: (value: string): void => { displayName = value }+ }, a.identity), first.identity.displayName)+ assert.equal(userData, path.join(appData, first.identity.appNamePascal))+ assert.equal(displayName, first.identity.displayName)+ } finally {+ fs.rmSync(appData, { recursive: true, force: true })+ }++ assert.deepEqual(a.config.mac?.publish, [{ provider: 'generic', url: `${first.publicBase}/releases/channel-builds/${first.buildId}/darwin/`, channel: 'latest' }])+ process.env.HERMES_DESKTOP_VARIANT = 'light'+ delete require.cache[require.resolve('../product-identity.cjs')]+ assert.throws((): void => { require('../product-identity.cjs') }, /bundled/)+ const invalid: ChannelBuildRequest = request()+ invalid.identity.cliName = 'con'+ assert.throws((): void => { load(invalid) }, /identity/)+ invalid.identity.cliName = first.identity.cliName+ invalid.identity.windowsExecutableName = 'trailing.'+ assert.throws((): void => { load(invalid) }, /identity/)+})++test('channel stamps verify the real checkout and retain source version and native ownership', async (): Promise<void> => {+ const { resolveStamp, buildStampPayload, writeDesktopStamp }: {+ resolveStamp: (options: { env: NodeJS.ProcessEnv; repoRoot: string }) => InstallStamp+ buildStampPayload: (stamp: InstallStamp, env: NodeJS.ProcessEnv, platform: string, payload: StampPayload) => InstallStamp+ writeDesktopStamp: (directory: string, stamp: InstallStamp) => void+ } = await import('../scripts/write-build-stamp.mjs')++ const dir: string = fs.mkdtempSync(path.join(os.tmpdir(), 'channel-stamp-'))++ try {+ execFileSync('git', ['init', '-q', dir])+ execFileSync('git', ['-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'fixture'], { cwd: dir })+ const build: ChannelBuildRequest = { ...request(), commit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim() }+ const env: NodeJS.ProcessEnv = { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled', _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(build), GITHUB_SHA: 'd'.repeat(40) }+ const provenance: InstallStamp = resolveStamp({ env, repoRoot: dir })+ const payload: StampPayload = { runtime: { repoDir: 'repo', commands: { hermes: 'bin/hermes' } } }+ const built: InstallStamp = buildStampPayload(provenance, env, 'darwin', payload)+ assert.equal(built.source, 'channel-build')+ assert.equal(built.updateMechanism, 'electron-updater')+ assert.equal(built.baseVersion, build.sourceVersion)+ assert.equal(built.tag, null)+ 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/)+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+})+++test('actual MSIX manifest writer consumes the channel quad across rollover instead of semver patch', (): void => {+ const 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 }++ try {+ for (const file of ['apps/desktop/product-identity.cjs', 'apps/desktop/electron-builder.config.cjs',+ 'apps/desktop/package.json', 'apps/desktop/update-feed.cjs', 'apps/desktop/assets/msix-manifest.xml',+ 'apps/desktop/scripts/before-build.mjs', 'apps/desktop/scripts/mac-sign.mjs',+ 'apps/desktop/scripts/payload-digests.mjs', 'apps/desktop/scripts/utils.mjs',+ 'scripts/msix-shared.mjs', 'scripts/release-content-types.json', 'scripts/build/python.mjs',+ 'scripts/bundles/desktop_prepare.py', 'scripts/releases/bundle_env.py', 'hermes_cli/release_channels.py', 'hermes_cli/__init__.py']) {+ const destination: string = path.join(root, file)+ fs.mkdirSync(path.dirname(destination), { recursive: true })+ fs.copyFileSync(path.join(repo, file), destination)+ }++ fs.symlinkSync(path.join(repo, 'node_modules'), path.join(root, 'node_modules'), 'junction')+ const assets: string = path.join(app, 'assets/appx')+ fs.mkdirSync(assets)++ for (const name of ['Square44x44Logo.png', 'Square150x150Logo.png', 'StoreLogo.png', 'Wide310x150Logo.png']) {+ fs.writeFileSync(path.join(assets, name), 'artwork is not inspected by manifest generation')+ }++ fs.mkdirSync(path.join(app, 'build/agent-payload'), { recursive: true })+ fs.writeFileSync(path.join(app, 'build/agent-payload/manifest.json'), JSON.stringify({ launchers: ['hermes-no-registry-needed', 'hermes-no-registry-needed-acp'] }))+ const facts: ManifestFacts[] = []++ for (const sequence of [65535, 65536, 65537, 0xffffffff]) {+ const build: ChannelBuildRequest = request(sequence)++ const script: string = `+ const { AppInfo } = require('./node_modules/app-builder-lib/dist/appInfo.js');+ const Msix = require('./node_modules/app-builder-lib/dist/targets/win/MsixTarget.js').default;+ const config = require('./apps/desktop/electron-builder.config.cjs');+ const pkg = require('./apps/desktop/package.json');+ const fs = require('node:fs');+ const path = require('node:path');+ const appDir = path.resolve('apps/desktop');+ (async () => {+ await config.beforeBuild();+ const metadata = { ...pkg, ...config.extraMetadata };+ const appInfo = new AppInfo({ config, metadata }, null, config.win);+ if (require('semver').valid(appInfo.version) !== appInfo.version) throw Error('Invalid packager semver');+ const packager = { appInfo, config, metadata, appDir, platformOptions: config.win,+ getResource: async (file) => path.resolve(appDir, file) };+ const target = { packager, options: config.msix,+ getCapabilities: Msix.prototype.getCapabilities, getExtensions: Msix.prototype.getExtensions };+ const output = path.resolve('manifest.xml');+ await Msix.prototype.writeManifest.call(target, output, 1, config.msix.publisher, []);+ console.log(JSON.stringify({version: appInfo.shortVersionWindows, semver: appInfo.version,+ appId: appInfo.id, xml: fs.readFileSync(output, 'utf8')}));+ })().catch(e => {console.error(e);process.exitCode=1});+ `++ const output: string = execFileSync(process.execPath, ['-e', script], {+ cwd: root, encoding: 'utf8', env: { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled', _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(build) }+ })++ const row: ManifestFacts = JSON.parse(output.trim().split('\n').at(-1)!)+ assert.equal(row.version, build.windowsVersion)+ assert.equal(row.semver, build.version)+ assert.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/)+ facts.push(row)+ }++ for (let index: number = 1; index < facts.length; index++) {+ assert.equal(facts[index].appId, facts[0].appId)+ assert.ok(facts[index - 1].version.localeCompare(facts[index].version, undefined, { numeric: true }) < 0)+ }++ assert.throws((): void => { load(request(0x100000000)) }, /sequence/)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/data-paths.ts b/apps/desktop/electron/data-paths.tsindex c5515115d0f..c4d4abf9591 100644--- a/apps/desktop/electron/data-paths.ts+++ b/apps/desktop/electron/data-paths.ts@@ -26,6 +26,7 @@ export function resolveDesktopUserData(defaultPath: string, env: NodeJS.ProcessEinterface HermesHomeOptions {home: string+ adoptedHome?: stringenv?: NodeJS.ProcessEnvplatform?: NodeJS.PlatformdirectoryExists?: (directory: string) => boolean@@ -34,6 +35,7 @@ interface HermesHomeOptions {export function resolveDesktopHermesHome({home,+ adoptedHome,env = process.env,platform = process.platform,directoryExists = (): boolean => false,@@ -50,6 +52,12 @@ export function resolveDesktopHermesHome({return paths.join(paths.resolve(env.HERMES_DESKTOP_USER_DATA_DIR), 'hermes-home')}+ if (adoptedHome) {+ if (!paths.isAbsolute(adoptedHome)) { throw new Error('Adopted Hermes home must be absolute') }++ return normalizeHermesHomeRoot(adoptedHome, { pathModule: paths })+ }+if (platform === 'win32' && env.HERMES_HOME === undefined) {// Explorer can miss setx changes. An explicit empty value opts out of that fallback.const registryHome: string | null = readWindowsHome()diff --git a/apps/desktop/electron/desktop-boot-preference.test.ts b/apps/desktop/electron/desktop-boot-preference.test.tsnew file mode 100644index 00000000000..f8b24c1bfdb--- /dev/null+++ b/apps/desktop/electron/desktop-boot-preference.test.ts@@ -0,0 +1,46 @@+import assert from 'node:assert/strict'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { test } from 'vitest'++import { resolveDesktopHermesHome } from './data-paths'+import { adoptDesktopHome, readDesktopBootPreference, writeDesktopProfile } from './desktop-boot-preference'++test('an adopted home survives profile changes and cold boot without overriding explicit launch state', (): void => {+ const directory: string = mkdtempSync(path.join(os.tmpdir(), 'hermes-boot-preference-'))+ const preference: string = path.join(directory, 'active-profile.json')+ const home: string = path.join(directory, 'preview-state')++ try {+ adoptDesktopHome(preference, { home, profile: 'work' }, null)+ writeDesktopProfile(preference, 'research')+ const stored = readDesktopBootPreference(preference)++ assert.deepEqual(stored, { home, profile: 'research' })+ assert.equal(resolveDesktopHermesHome({ home: directory, env: {}, adoptedHome: stored?.home }), home)+ assert.equal(resolveDesktopHermesHome({ home: directory, env: { HERMES_HOME: directory }, adoptedHome: home }), directory)+ assert.equal(resolveDesktopHermesHome({ home: directory, env: { HERMES_DESKTOP_USER_DATA_DIR: directory }, adoptedHome: home }), path.join(directory, 'hermes-home'))+ } finally {+ rmSync(directory, { recursive: true, force: true })+ }+})++test('adoption refuses a concurrent preference change and preserves unreadable user settings', (): void => {+ const directory: string = mkdtempSync(path.join(os.tmpdir(), 'hermes-boot-conflict-'))+ const preference: string = path.join(directory, 'active-profile.json')++ try {+ writeDesktopProfile(preference, 'original')+ const original = readDesktopBootPreference(preference)+ writeDesktopProfile(preference, 'changed')+ assert.throws(() => adoptDesktopHome(preference, { home: directory, profile: 'preview' }, original), /changed/)+ assert.equal(readDesktopBootPreference(preference)?.profile, 'changed')+ writeFileSync(preference, '{broken', 'utf8')+ assert.throws(() => writeDesktopProfile(preference, 'preview'), /preference/)+ assert.equal(readFileSync(preference, 'utf8'), '{broken')+ } finally {+ rmSync(directory, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/desktop-boot-preference.ts b/apps/desktop/electron/desktop-boot-preference.tsnew file mode 100644index 00000000000..4687b38a29c--- /dev/null+++ b/apps/desktop/electron/desktop-boot-preference.ts@@ -0,0 +1,120 @@+import { randomUUID } from 'node:crypto'+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import path from 'node:path'+import { isDeepStrictEqual } from 'node:util'++export interface DesktopBootPreference {+ profile: string | null+ home?: string+ _migrated?: boolean+}++export interface AdoptedDesktopHome {+ home: string+ profile: string | null+}++/** Ordinary startup may ignore a broken legacy profile; adoption must still fail closed. */+export function readStartupDesktopPreference(file: string, warn: (message: string) => void): DesktopBootPreference | null {+ try { 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+ }+}++function validProfile(profile: string | null): boolean {+ return profile === null || /^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)+}++/** Missing is a fresh install; unreadable state must not be treated as permission to replace it. */+export function readDesktopBootPreference(file: string): DesktopBootPreference | null {+ let text: string++ try {+ text = readFileSync(file, 'utf8')+ } catch (error: unknown) {+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { return null }+ throw error+ }++ const parsed: unknown = JSON.parse(text)++ if (!parsed || typeof parsed !== 'object' || !('profile' in parsed)) {+ throw new Error('Invalid desktop boot preference')+ }++ const profile: unknown = parsed.profile++ if (profile !== null && (typeof profile !== 'string' || !validProfile(profile))) {+ 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')+ }++ if ('_migrated' in parsed && typeof parsed._migrated !== 'boolean') {+ throw new Error('Invalid migration marker in desktop boot preference')+ }++ 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 } : {})+ }+}++function updatePreference(file: string, update: (current: DesktopBootPreference | null) => DesktopBootPreference): DesktopBootPreference {+ mkdirSync(path.dirname(file), { recursive: true })+ const temporary: string = `${file}.${randomUUID()}.tmp`++ // The destination's single-instance main process owns all preference writes.+ // Keep read, compare, and rename synchronous so its IPC handlers cannot interleave.+ try {+ let current: DesktopBootPreference | null++ try {+ current = readDesktopBootPreference(file)+ } catch (error: unknown) {+ throw new Error('Cannot update an unreadable desktop boot preference', { cause: error })+ }++ const next: DesktopBootPreference = update(current)++ writeFileSync(temporary, JSON.stringify(next, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })+ renameSync(temporary, file)++ return next+ } finally {+ rmSync(temporary, { force: true })+ }+}++export function writeDesktopProfile(file: string, profile: string | null): string | null {+ if (!validProfile(profile)) { throw new Error(`Invalid profile name: ${profile}`) }++ return updatePreference(file, (current: DesktopBootPreference | null): DesktopBootPreference => {+ const next: DesktopBootPreference = { ...current, profile }++ delete next._migrated++ return next+ }).profile+}++/** The acceptance prompt names the previous preference; a concurrent user choice invalidates it. */+export function adoptDesktopHome(file: string, target: AdoptedDesktopHome, expected: DesktopBootPreference | null): void {+ if (!path.isAbsolute(target.home) || !validProfile(target.profile)) {+ throw new Error('Invalid adopted desktop home or profile')+ }++ updatePreference(file, (current: DesktopBootPreference | null): DesktopBootPreference => {+ if (!isDeepStrictEqual(current, expected)) {+ throw new Error('Desktop boot preference changed; review the migration again')+ }++ return { ...current, home: target.home, profile: target.profile, _migrated: false }+ })+}diff --git a/apps/desktop/electron/install-stamp.ts b/apps/desktop/electron/install-stamp.tsindex 7ab7ffe7f72..5865dd467de 100644--- a/apps/desktop/electron/install-stamp.ts+++ b/apps/desktop/electron/install-stamp.ts@@ -29,6 +29,32 @@ export interface PayloadRuntime {commands: Record<string, string>}+/** Immutable admitted channel build. Native names come from R2, never the slug. */+export interface ChannelBuildRequest {+ schema: 1+ buildId: string+ channel: string+ sequence: number+ repository: string+ commit: string+ controllerCommit?: string+ sourceVersion: string+ version: string+ windowsVersion: string+ identity: {+ token: string+ displayName: string+ appId: string+ appNamePascal: string+ artifactNamePascal: string+ cliName: string+ windowsExecutableName: string+ msixAppIdWithOrg: string+ }+ bundleEnv: Record<string, string | null>+ publicBase: string+}+/** Mirrors the build stamp with the PM builder's completed launch contract. */export interface InstallStamp {schemaVersion: number@@ -38,7 +64,7 @@ export interface InstallStamp {builtAt: string | nulldirty: boolean/** Build provenance: where the stamp's facts came from. */- source: 'build' | 'commit-build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown' | null+ source: 'build' | 'commit-build' | 'channel-build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown' | null/** The steward of a sealed tree ('desktop-app' | 'docker' | 'nix'), when packaged. */distribution: string | null/** Who applies the next update. Required in every stamp. */@@ -49,15 +75,28 @@ export interface InstallStamp {payload: ArtifactKind/** Present on bundled artifacts. Validated at build time, never discovered at boot. */runtime?: PayloadRuntime- /** The pinned release tag. Always set for 'bundled' and 'light', never for 'bootstrap'. */+ /** Complete channel inputs, absent on legacy releases and one-off builds. */+ channelBuild?: Readonly<ChannelBuildRequest>+ /** Pinned release tag; null for channel builds, one-offs and bootstrap. */tag: string | null}declare const __HERMES_INSTALL_STAMP__: InstallStamp+/** The baked request is immutable as well as its containing artifact stamp. */+function freezeStamp(stamp: InstallStamp): Readonly<InstallStamp> {+ if (stamp.channelBuild) {+ Object.freeze(stamp.channelBuild.identity)+ Object.freeze(stamp.channelBuild.bundleEnv)+ Object.freeze(stamp.channelBuild)+ }++ return Object.freeze(stamp)+}+/** The baked stamp of this artifact, or null on dev bundles. */export const INSTALL_STAMP: Readonly<InstallStamp> | null =- typeof __HERMES_INSTALL_STAMP__ === 'undefined' ? null : Object.freeze(__HERMES_INSTALL_STAMP__)+ typeof __HERMES_INSTALL_STAMP__ === 'undefined' ? null : freezeStamp(__HERMES_INSTALL_STAMP__)/*** The install shape this process runs as — THE single split everydiff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex ed63ca76544..b2d3773d191 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -168,6 +168,7 @@ import type { RosterProfileMetadata } from './connection-registry'import { describeCrashReason, installCrashForensics } from './crash-forensics'import { adoptServedDashboardToken } from './dashboard-token'import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'+import { writeDesktopProfile } from './desktop-boot-preference'import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'import { formatDesktopLogLine } from './desktop-log-line'import { resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'@@ -440,7 +441,15 @@ import {import { readSourceUpdate, type SourceUpdate } from './updater/checkout-source'import { ExternalStrategy } from './updater/external'import { readUpdatesFeedBaseFromConfig } from './updater/feed-config'-import { createMacStrategy } from './updater/mac-client'+import { createMacStrategy, createChannelMacStrategy } from './updater/mac-client'+import { createChannelAppInstallerStrategy } from './updater/app-installer'+import { ChannelResolver, type ChannelTarget } from './updater/channel'+import { ChannelStrategy } from './updater/channel-strategy'+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 { readStartupDesktopPreference } from './desktop-boot-preference'import { type ConsumedRelaunch, consumePendingRelaunch, registerUpdateRelaunch, type RelaunchRegistration } from './updater/relaunch'import { startRelaunchWaiter } from './updater/relaunch-waiter'import { preflightStateDb } from './updater/state-db-preflight'@@ -739,8 +748,26 @@ if (INSTALL_STAMP) {)}+const DESKTOP_PROFILE_CONFIG_PATH: string = path.join(app.getPath('userData'), 'active-profile.json')+// Only the lock-owning destination may adopt a workspace or start a backend.+const isPrimaryInstance: boolean = app.requestSingleInstanceLock()+if (!isPrimaryInstance) { app.exit(0) }+if (INSTALL_STAMP?.channelBuild && await forwardRetiredPreview()) { app.exit(0) }+const retirementReception: RetirementReception | null = isPrimaryInstance ? await prepareRetirementStartup({+ argv: process.argv,+ userData: 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)+}).catch(async (error: Error): Promise<null> => {+ await app.whenReady()+ dialog.showErrorBox('Migration paused — preview preserved', error.message)+ app.exit(1)+ return null+}) : nullconst HERMES_HOME: string = resolveDesktopHermesHome({home: app.getPath('home'),+ adoptedHome: readStartupDesktopPreference(DESKTOP_PROFILE_CONFIG_PATH, console.warn)?.home,directoryExists,readWindowsHome: (): string | null => readWindowsUserEnvVar('HERMES_HOME')})@@ -783,7 +810,7 @@ const DESKTOP_MANAGED_SSH_RECOVERY_PATH = path.join(app.getPath('userData'), 'ma// _apply_profile_override in hermes_cli/main.py) and bypasses the sticky// ~/.hermes/active_profile file. Unset (null) preserves the legacy behavior:// no --profile flag, so the backend honors active_profile / default.-const DESKTOP_PROFILE_CONFIG_PATH = path.join(app.getPath('userData'), 'active-profile.json')+// Mirrors hermes_cli.profiles._PROFILE_ID_RE so we never hand the backend a// value its profile resolver would reject and exit on.const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/@@ -2969,7 +2996,7 @@ async function checkUpdates(opts: { force?: boolean } = {}): Promise<UpdaterStatlet strategy: UpdaterStrategy | null = nulltry {- strategy = resolvePackagedUpdateStrategy()+ strategy = await resolvePackagedUpdateStrategy()if (strategy) { return await strategy.check(opts) }} catch (error) {@@ -2998,7 +3025,7 @@ let updateInFlight = false*/let packagedUpdateStrategy: UpdaterStrategy | undefined-function resolvePackagedUpdateStrategy(): UpdaterStrategy | null {+async function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {const mechanism = resolveUpdaterMechanism({platform: process.platform,updateMechanism: INSTALL_STAMP?.updateMechanism,@@ -3009,8 +3036,33 @@ function resolvePackagedUpdateStrategy(): UpdaterStrategy | null {if (packagedUpdateStrategy) { return packagedUpdateStrategy }+ if (INSTALL_STAMP?.channelBuild && (mechanism === 'electron-updater' || mechanism === 'app-installer')) {+ const build = INSTALL_STAMP.channelBuild+ const installed = await inspectRunningChannelApp(build)+ const payload = bundledPayload(process.resourcesPath)+ 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({+ 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,+ restore: restoreBundledBackend, quit: (): void => app.quit(),+ progress: (message: string): void => emitUpdateProgress({ stage: 'prepare', message, percent: null }) })+ })+ return packagedUpdateStrategy+ }++ packagedUpdateStrategy = createNativePackagedStrategy(mechanism)+ return packagedUpdateStrategy+}++function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], target?: ChannelTarget): UpdaterStrategy {+if (mechanism === 'electron-updater') {- packagedUpdateStrategy = createMacStrategy({+ const deps: Parameters<typeof createMacStrategy>[0] = {channel: resolveUpdaterChannelFromStamp(),light: isLightVariant(),feedBaseUrl: resolveDesktopFeedBaseUrl(),@@ -3019,15 +3071,14 @@ function resolvePackagedUpdateStrategy(): UpdaterStrategy | null {emitProgress: emitUpdateProgress,beforeInstall: teardownBundledBackend,onInstallFailure: restoreBundledBackend- })-- return packagedUpdateStrategy+ }+ return target ? createChannelMacStrategy(deps, target) : createMacStrategy(deps)}if (mechanism === 'app-installer') {const payload = bundledPayload(process.resourcesPath)!- packagedUpdateStrategy = new AppInstallerStrategy({+ const deps: ConstructorParameters<typeof AppInstallerStrategy>[0] = {python: payload.storePython,// The checker ships inside the payload's repo snapshot (git archive of// the committed tree): <payload>/<repo>/apps/desktop/scripts/.@@ -3046,7 +3097,7 @@ function resolvePackagedUpdateStrategy(): UpdaterStrategy | null {teardownBundledBackend,restoreBundledBackend,emitUpdateProgress,- appVersion: app.getVersion(),+ appVersion: INSTALL_STAMP?.channelBuild?.windowsVersion ?? app.getVersion(),quit: () => app.quit(),registerPendingRelaunch: (fromVersion: string): Promise<RelaunchRegistration> =>registerUpdateRelaunch(app, fromVersion, {@@ -3072,9 +3123,8 @@ function resolvePackagedUpdateStrategy(): UpdaterStrategy | null {)})})- })-- return packagedUpdateStrategy+ }+ return target ? createChannelAppInstallerStrategy(deps, target, verifyPreparedChannelInstaller) : new AppInstallerStrategy(deps)}if (mechanism === 'microsoft-store') {@@ -3166,7 +3216,7 @@ function resolveDesktopFeedBaseUrl(): string {}/** The updater channel from the baked install stamp ('canary' vs 'stable'). */-function resolveUpdaterChannelFromStamp(): 'stable' | 'canary' {+function resolveUpdaterChannelFromStamp(): string {return packagedReleaseChannel(INSTALL_STAMP) ?? 'stable'}@@ -3754,17 +3804,19 @@ 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(): Promise<UpdaterApplyResultWire> {+async function applyUpdates(retirementConsent: boolean = false): Promise<UpdaterApplyResultWire> {if (updateInFlight) {throw new Error('An update is already in progress.')}- const strategy = resolvePackagedUpdateStrategy() ?? resolveCheckoutUpdateStrategy()+ const strategy = await resolvePackagedUpdateStrategy() ?? resolveCheckoutUpdateStrategy()updateInFlight = truelet handedOff = falsetry {- const result: UpdaterApplyResultWire = await strategy.apply()+ const result: UpdaterApplyResultWire = retirementConsent+ ? strategy instanceof ChannelStrategy ? await strategy.applyRetirement() : { ok: false, error: 'No retirement offer is selected.' }+ : await strategy.apply()handedOff = result.handedOff === truereturn result@@ -8656,17 +8708,8 @@ function readActiveDesktopProfile() {return null}-function writeActiveDesktopProfile(name) {- const value = typeof name === 'string' ? name.trim() : ''-- if (value && value !== 'default' && !PROFILE_NAME_RE.test(value)) {- throw new Error(`Invalid profile name: ${value}`)- }-- fs.mkdirSync(path.dirname(DESKTOP_PROFILE_CONFIG_PATH), { recursive: true })- writeFileAtomic(DESKTOP_PROFILE_CONFIG_PATH, JSON.stringify({ profile: value || null }, null, 2))-- return value || null+function writeActiveDesktopProfile(name: string | null): string | null {+ return writeDesktopProfile(DESKTOP_PROFILE_CONFIG_PATH, name?.trim() || null)}// True when the given pid belongs to a running process whose command line@@ -16547,6 +16590,11 @@ 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> => {+ 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 }))+})+ipcMain.handle('hermes:updates:branch:set', async (_event: Electron.IpcMainInvokeEvent, name: unknown): Promise<{ branch: string }> => {assertSourceUpdateChannel(INSTALL_STAMP)const branch: string = typeof name === 'string' && name.trim() ? name.trim() : DEFAULT_UPDATE_BRANCH@@ -17039,6 +17087,20 @@ ipcMain.handle('hermes:deep-link-ready', () => {return { ok: true }})+async function finishDesktopRetirement(reception: RetirementReception): Promise<void> {+ const result = await completeDesktopRetirement(reception, {+ home: HERMES_HOME, profile: primaryProfileKey, isLocal: (): boolean => !primaryBackendIsRemote(),+ rendererMounted: (): boolean => Boolean(_rendererReadyForDeepLink && mainWindow && !mainWindow.isDestroyed()),+ backend: async (): Promise<void> => {+ await startHermes()+ await handleHermesApiRequest({ path: '/api/status', timeoutMs: 5000 })+ }+ })+ if (result.status === 'cleanup-pending') {+ dialog.showErrorBox('Stable ready — preview cleanup pending', `${result.error}\nYour preview and all user data are preserved. Reopen the preview and choose Move to stable to retry cleanup.`)+ }+}+function registerDeepLinkProtocol() {try {if (process.defaultApp && process.argv.length >= 2) {@@ -17060,9 +17122,6 @@ function registerDeepLinkProtocol() {// Single-instance lock: deep links on a running app (Win/Linux) arrive as a// second-instance argv. Without the lock a second `hermes://` launch spawns a// whole new app instead of routing into the running one.-const _gotSingleInstanceLock = app.requestSingleInstanceLock()-const isPrimaryInstance = _gotSingleInstanceLock-if (!isPrimaryInstance) {// Hard-exit, not app.quit(): the before-quit teardown coordinator defers a// plain quit (event.preventDefault + async backend shutdown), and in that@@ -17074,6 +17133,15 @@ if (!isPrimaryInstance) {app.exit(0)} else {app.on('second-instance', (_event, argv) => {+ 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' }+ }).then(async (reception: RetirementReception | null): Promise<void> => {+ if (reception) { await finishDesktopRetirement(reception) }+ }).catch((error: Error): void => dialog.showErrorBox('Migration paused — preview preserved', error.message))+ return+ }const url = _extractDeepLink(argv)if (url) {@@ -17184,6 +17252,7 @@ app.whenReady().then(() => {// captured by the original transaction before removing the journal entry.void resumeManagedSshRecoveries()createWindow()+ if (retirementReception) { void finishDesktopRetirement(retirementReception) }// Win/Linux cold start: the launching hermes:// URL is in our own argv.const _coldStartLink = _extractDeepLink(process.argv)diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 225232b1a55..a58ad705f00 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -536,6 +536,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),getBranch: () => ipcRenderer.invoke('hermes:updates:branch:get'),setBranch: name => ipcRenderer.invoke('hermes:updates:branch:set', name),onProgress: callback => {diff --git a/apps/desktop/electron/product-identity.ts b/apps/desktop/electron/product-identity.tsindex 6bec3f1b67a..5092b90ce8d 100644--- a/apps/desktop/electron/product-identity.ts+++ b/apps/desktop/electron/product-identity.ts@@ -31,7 +31,7 @@ export function applyDesktopIdentity(app: { getPath(name: 'appData'): string; setPath(name: 'userData', value: string): void; setName(name: string): void },identity: Readonly<ProductIdentity> = PRODUCT_IDENTITY): string | null {- if (identity.appNamePascal === identity.artifactNamePascal) {return null}+ if (!identity.token && identity.appNamePascal === identity.artifactNamePascal) {return null}const userData: string = path.join(app.getPath('appData'), identity.appNamePascal)mkdirSync(userData, { recursive: true })app.setPath('userData', userData)diff --git a/apps/desktop/electron/profile-migration.ts b/apps/desktop/electron/profile-migration.tsindex 6ba0ca7c692..34b0b11e6b4 100644--- a/apps/desktop/electron/profile-migration.ts+++ b/apps/desktop/electron/profile-migration.ts@@ -270,11 +270,12 @@ export function readExistingPreference(* `--profile` instead of pinning `default`.*/export function migrateActiveProfileIfMissing(desktopProfileConfigPath: string, deps: MigrationDeps): boolean {- const existing = deps.existsSync(desktopProfileConfigPath)+ const exists: boolean = deps.existsSync(desktopProfileConfigPath)+ const existing = exists? readExistingPreference(desktopProfileConfigPath, deps.readFileSync): null- if (existing && !existing.migrated) {+ if (exists && (!existing || !existing.migrated)) {return false}diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.tsindex 0a887c66e36..a19512d09cb 100644--- a/apps/desktop/electron/updater/app-installer-strategy.test.ts+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts@@ -75,6 +75,23 @@ describe('AppInstallerStrategy.apply', () => {expect(calls).toEqual(['relaunch-marker', 'teardown', 'quit'])})+ it('uses an exact descriptor without a Python check, and rejects unverified prepared packages before teardown', async (): Promise<void> => {+ const { deps, calls } = makeDeps({+ run: async (): Promise<never> => { throw new Error('Dynamic channels do not query the registered moving feed') },+ feed: { url: 'https://updates.example/releases/channel-builds/abc/win32/update.appinstaller', version: '0.0.2.0',+ verifyPrepared: async (): Promise<void> => { calls.push('verify'); throw new Error('wrong signature') }+ },+ appVersion: '0.0.1.0', feedBaseUrl: 'https://updates.example',+ installer: { prepare: async (url: string): Promise<string> => { calls.push(url); return 'pinned.appinstaller' }, open: async (): Promise<string> => { calls.push('open'); return '' } }+ })+ const strategy = new AppInstallerStrategy(deps)+ expect(await strategy.check()).toMatchObject({ updateAvailable: true })+ await expect(strategy.apply()).rejects.toThrow('wrong signature')+ expect(calls).toContain('https://updates.example/releases/channel-builds/abc/win32/update.appinstaller')+ expect(calls).not.toContain('teardown')+ expect(calls).not.toContain('open')+ })+it('no feed URL → manual card, no teardown, no quit', async () => {const { deps, calls } = makeDeps({ feedBaseUrl: '' })const result = await new AppInstallerStrategy(deps).apply()@@ -86,11 +103,11 @@ describe('AppInstallerStrategy.apply', () => {it.each([[0, '{"available":true,"availability":"Available"}', true, undefined],[0, '{"available":false}', false, undefined],- [2, '{"available":null,"error":"winrt missing"}', false, 'winrt missing'],- [0, '', false, 'checker returned no availability'],- [1, 'boom', false, 'checker exited 1'],- [0, '{"available":"yes"}', false, 'checker returned no availability']-] as const)('checker %s %s → available=%s error=%s', async (code: number, stdout: string, available: boolean, error: string | undefined): Promise<void> => {+ [2, '{"available":null,"error":"winrt missing"}', undefined, 'winrt missing'],+ [0, '', undefined, 'checker returned no availability'],+ [1, 'boom', undefined, 'checker exited 1'],+ [0, '{"available":"yes"}', undefined, 'checker returned no availability']+] as const)('checker %s %s → available=%s error=%s', async (code: number, stdout: string, available: boolean | undefined, error: string | undefined): Promise<void> => {const { deps }: ReturnType<typeof makeDeps> = makeDeps({run: async (python: string, script: string): Promise<{ code: number; stdout: string }> => {expect([python, script]).toEqual(['python.exe', 'check.py'])diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.tsindex 21c86c0452a..2ce430cd407 100644--- a/apps/desktop/electron/updater/app-installer.ts+++ b/apps/desktop/electron/updater/app-installer.ts@@ -20,6 +20,8 @@ import {} from '../app-updater'import { applyPackagedHandoff } from './packaged-handoff'+import { channelPublicBase } from './channel-protocol'+import type { ChannelTarget } from './channel'import type { RelaunchRegistration } from './relaunch'import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'@@ -31,7 +33,9 @@ export interface AppInstallerStrategyDeps {script: stringrun: PayloadPythonRunner['run']/** Channel + variant from the baked install stamp. */- channel: 'stable' | 'canary'+ channel: string+ /** Verification must bind descriptor, artifact digest, native identity and signer. */+ feed?: { url: string; version: string; verifyPrepared: (file: string) => Promise<void> }light: boolean/** The App Installer feed base URL; empty when nothing configured it. */feedBaseUrl: string@@ -63,19 +67,36 @@ export function appInstallerCheckToStatus(check: AppInstallerCheck, appVersion:supported: true,mechanism: 'app-installer',currentVersion: appVersion,- updateAvailable: check.available === true,+ updateAvailable: check.available ?? undefined,// null = unknown (checker unavailable) — surface honestly, never "no update".error: check.available === null ? check.error || 'update check unavailable' : undefined,fetchedAt: Date.now()}}+export function createChannelAppInstallerStrategy(+ deps: AppInstallerStrategyDeps,+ target: ChannelTarget,+ verifyPrepared: (file: string, target: ChannelTarget) => Promise<void>+): AppInstallerStrategy {+ if (target.package.platform !== 'win32') { throw new Error('Expected Windows channel target') }+ return new AppInstallerStrategy({+ ...deps, channel: target.channel.name, feedBaseUrl: target.manifest.request.publicBase,+ feed: { url: target.feedUrl, version: target.package.version,+ verifyPrepared: (file: string): Promise<void> => verifyPrepared(file, target) }+ })+}+export class AppInstallerStrategy {readonly mechanism = 'app-installer' as constconstructor(private readonly deps: AppInstallerStrategyDeps) {}async check(): Promise<UpdaterStatusWire> {+ if (this.deps.feed) {+ return { supported: true, mechanism: this.mechanism, currentVersion: this.deps.appVersion,+ updateAvailable: newerWindowsVersion(this.deps.feed.version, this.deps.appVersion), fetchedAt: Date.now() }+ }const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)const check = parseCheckOutput(code, stdout)@@ -84,9 +105,15 @@ export class AppInstallerStrategy {async apply(): Promise<UpdaterApplyResultWire> {const feedBaseUrl = this.deps.feedBaseUrl- let sourceUri: string | undefined+ let sourceUri: string | undefined = this.deps.feed?.url+ if (sourceUri) {+ channelPublicBase(sourceUri)+ const base = channelPublicBase(feedBaseUrl)+ if (!sourceUri.startsWith(`${base}/`) || new URL(sourceUri).origin !== new URL(base).origin) { throw new Error('Native feed authority mismatch') }+ if (!newerWindowsVersion(this.deps.feed!.version, this.deps.appVersion)) { return { ok: true, mechanism: this.mechanism } }+ }- if (!feedBaseUrl) {+ if (!feedBaseUrl && !sourceUri) {const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)sourceUri = parseCheckOutput(code, stdout).sourceUri}@@ -127,7 +154,14 @@ export class AppInstallerStrategy {feedBaseUrl,this.deps.channel,this.deps.light,- this.deps.installer,+ {+ prepare: async (url: string): Promise<string> => {+ const file = await this.deps.installer.prepare(url)+ await this.deps.feed?.verifyPrepared(file)+ return file+ },+ open: this.deps.installer.open+ },stop,sourceUri)@@ -139,6 +173,21 @@ export class AppInstallerStrategy {}}+function newerWindowsVersion(target: string, current: string): boolean {+ const parse = (version: string): number[] => {+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(version)) { throw new Error('Windows channel updates require native numeric versions') }+ const parts = version.split('.').map(Number)+ if (parts.some((part: number): boolean => part > 65535)) { throw new Error('Invalid Windows native version') }+ return parts+ }+ const left = parse(target)+ const right = parse(current)+ for (let index = 0; index < 4; index += 1) {+ if (left[index] !== right[index]) { return left[index] > right[index] }+ }+ return false+}+export { parseCheckOutput }export { win32AppInstallerFeedPath }diff --git a/apps/desktop/electron/updater/artifact.ts b/apps/desktop/electron/updater/artifact.tsnew file mode 100644index 00000000000..f6fade1985c--- /dev/null+++ b/apps/desktop/electron/updater/artifact.ts@@ -0,0 +1,52 @@+import { createHash } from 'node:crypto'+import { createReadStream } from 'node:fs'+import { lstat, open, rename, unlink } from 'node:fs/promises'+import type { FileHandle } from 'node:fs/promises'+import path from 'node:path'++export interface PinnedArtifact {+ url: string+ sha256: string+ size: number+ format: 'zip' | 'msix' | 'msixbundle'+}++export async function verifyPinnedArtifact(file: string, artifact: PinnedArtifact): Promise<void> {+ const info = await lstat(file)+ if (!info.isFile() || info.isSymbolicLink() || info.size !== artifact.size) {+ throw new Error('Pinned artifact size or type mismatch')+ }+ const hash = createHash('sha256')+ for await (const chunk of createReadStream(file)) { hash.update(chunk) }+ if (hash.digest('hex') !== artifact.sha256) { throw new Error('Pinned artifact digest mismatch') }+}++/** Caller owns private storage and its lifetime. Redirects cannot change authority. */+export async function downloadPinnedArtifact(directory: string, artifact: PinnedArtifact): Promise<string> {+ const file: string = path.join(directory, `destination.${artifact.format}`)+ try {+ await verifyPinnedArtifact(file, 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(artifact.url, { redirect: 'error', signal: AbortSignal.timeout(600_000) })+ if (!response.ok || !response.body) { throw new Error(`Pinned artifact 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 > artifact.size) { throw new Error('Pinned artifact download exceeds pinned size') }+ await handle.writeFile(chunk)+ }+ await handle.sync()+ } finally { await handle.close() }+ await verifyPinnedArtifact(temporary, artifact)+ await rename(temporary, file)+ return file+}\ No newline at end of filediff --git a/apps/desktop/electron/updater/channel-native.test.ts b/apps/desktop/electron/updater/channel-native.test.tsnew file mode 100644index 00000000000..1e2b8a0945e--- /dev/null+++ b/apps/desktop/electron/updater/channel-native.test.ts@@ -0,0 +1,20 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { createHash } from 'node:crypto'+import os from 'node:os'+import path from 'node:path'+import { expect, test } from 'vitest'+import { verifyChannelDownload } from './channel-native'++test('download verification binds native bytes to the manifest size and digest before signature preparation', async (): Promise<void> => {+ const directory = await mkdtemp(path.join(os.tmpdir(), 'channel-artifact-'))+ const file = path.join(directory, 'update.zip')+ try {+ const content = Buffer.from('real local archive fixture bytes')+ await writeFile(file, content)+ const artifact = { key: 'releases/fixture.zip', size: content.length, sha256: createHash('sha256').update(content).digest('hex') }+ await verifyChannelDownload([file], artifact)+ await writeFile(file, Buffer.alloc(content.length))+ await expect(verifyChannelDownload([file], artifact)).rejects.toThrow('digest')+ await expect(verifyChannelDownload([], artifact)).rejects.toThrow('one')+ } finally { await rm(directory, { recursive: true, force: true }) }+})diff --git a/apps/desktop/electron/updater/channel-native.ts b/apps/desktop/electron/updater/channel-native.tsnew file mode 100644index 00000000000..f536c443124--- /dev/null+++ b/apps/desktop/electron/updater/channel-native.ts@@ -0,0 +1,17 @@+import { createHash } from 'node:crypto'+import { open } from 'node:fs/promises'++import type { ChannelPackage } from './channel-protocol'++/** Native feeds carry their own hashes; also require the admitted build's hash. */+export async function verifyChannelDownload(files: string[], artifact: ChannelPackage['artifact']): Promise<void> {+ if (files.length !== 1) { throw new Error('Expected exactly one channel artifact') }+ const file = await open(files[0], 'r')+ try {+ const stat = await file.stat()+ if (!stat.isFile() || stat.size !== artifact.size) { throw new Error('Channel artifact size mismatch') }+ const digest = createHash('sha256')+ for await (const chunk of file.createReadStream({ autoClose: false })) { digest.update(chunk) }+ if (digest.digest('hex') !== artifact.sha256) { throw new Error('Channel artifact digest mismatch') }+ } finally { await file.close() }+}diff --git a/apps/desktop/electron/updater/channel-protocol.ts b/apps/desktop/electron/updater/channel-protocol.tsnew file mode 100644index 00000000000..e4bc14b11fd--- /dev/null+++ b/apps/desktop/electron/updater/channel-protocol.ts@@ -0,0 +1,321 @@+/* The protocol decoder is the sole untrusted-JSON boundary. Unknown inputs and+ * primitive checks belong here; only validated domain objects leave this file. */+/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-runtime-typeof, anti-slop/no-reflect-get */+import feedContract from '../../update-feed.cjs'++export interface ChannelIdentity {+ token: string+ displayName: string+ appId: string+ appNamePascal: string+ artifactNamePascal: string+ cliName: string+ windowsExecutableName: string+ msixAppIdWithOrg: string+}++/** Build-stamp facts, independent of the Python payload or stamp module. */+export interface ChannelBuild {+ buildId: string+ channel: string+ sequence: number+ repository: string+ commit: string+ sourceVersion: string+ version: string+ windowsVersion: string+ identity: ChannelIdentity+ bundleEnv: { [name: string]: string | null }+ publicBase: string+}++export interface ChannelRequest extends ChannelBuild {+ schema: 1+ controllerCommit?: string+ releaseTag?: string+}+export interface ChannelHead { buildId: string; sequence: number; manifestKey: string; sha256: string }+interface ChannelRecordBase {+ schema: 1+ name: string+ repository: string+ policy: 'preview' | 'stable-release' | 'canary-release'+ revision: number+ nextSequence: number+ identity: ChannelIdentity+ head: ChannelHead | null+}+export interface ActiveChannel extends ChannelRecordBase { state: 'active' }+export interface RetiredChannel extends ChannelRecordBase {+ state: 'retired'+ destination: string+ minimumVersion: string+ compatibilityKey: string+ compatibilitySha256: string+ lastHead: ChannelHead | null+}+export type ChannelRecord = ActiveChannel | RetiredChannel+export interface ChannelPackage {+ platform: 'darwin' | 'win32'+ arch: 'x64' | 'arm64'+ variant: 'bundled'+ version: string+ identity: string+ artifact: { key: string; sha256: string; size: number }+ publisher?: string+ teamId?: string+ feed: { 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[]+}++const SHA256 = /^[a-f0-9]{64}$/+const COMMIT = /^[a-f0-9]{40}$/+const BUILD_ID = /^[a-f0-9]{32}$/+const VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/++function parseChannelJson(body: string): unknown {+ const parsed: unknown = JSON.parse(body)+ // JSON.parse discards duplicate members; scan validated JSON tokens to keep+ // the same reject-duplicates contract as the publisher's object_pairs_hook.+ const objects: Set<string>[] = []+ const tokens = /"(?:[^"\\]|\\[\s\S])*"\s*:|"(?:[^"\\]|\\[\s\S])*"|[{}]/g+ for (const match of body.matchAll(tokens)) {+ const token = match[0]+ if (token === '{') { objects.push(new Set<string>()); continue }+ if (token === '}') { objects.pop(); continue }+ if (!token.endsWith(':')) { continue }+ const key: string = JSON.parse(token.slice(0, -1))+ const keys = objects[objects.length - 1]+ if (keys.has(key)) { throw new Error('Duplicate channel JSON member') }+ keys.add(key)+ }+ return parsed+}++/** Untrusted JSON is confined to these network decoders. */+class Fields {+ private readonly input: object+ constructor(input: unknown) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) { throw new Error('Expected channel object') }+ this.input = input+ }+ get(key: string): unknown { return Reflect.get(this.input, key) }+ keys(): string[] { return Object.keys(this.input) }+ text(key: string, pattern: RegExp = /^[\s\S]{1,2048}$/): string {+ const value: unknown = this.get(key)+ if (typeof value !== 'string' || [...value].some((character: string): boolean => character.charCodeAt(0) < 32) || !pattern.test(value)) { throw new Error(`Invalid channel ${key}`) }+ return value+ }+ integer(key: string, maximum: number = Number.MAX_SAFE_INTEGER): number {+ const value: unknown = this.get(key)+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > maximum) {+ throw new Error(`Invalid channel ${key}`)+ }+ return value+ }+ object(key: string): Fields { return new Fields(this.get(key)) }+ optional(key: string, pattern?: RegExp): string | undefined {+ return this.get(key) === undefined ? undefined : this.text(key, pattern)+ }+ schema(): void { if (this.get('schema') !== 1) { throw new Error('Unsupported channel schema') } }+}++export function validateChannelName(name: string): string {+ // This validates syntax, not whether R2 has registered the name.+ feedContract.darwinFeed(name)+ return name+}++export function channelPublicBase(value: string): string {+ const url = new URL(value)+ const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||+ url.username || url.password || url.search || url.hash || /[%\\;\s]/.test(value) ||+ value.split('/').some((part: string): boolean => part === '.' || part === '..')) {+ throw new Error('Channel archive must use HTTPS or loopback HTTP without credentials or traversal')+ }+ return value.replace(/\/+$/, '')+}++export function channelKey(value: string): string {+ if (!/^releases\/[A-Za-z0-9_./+-]+$/.test(value) ||+ value.split('/').some((part: string): boolean => !part || part === '.' || part === '..' || part.endsWith('.') || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) {+ throw new Error('Invalid channel object key')+ }+ return value+}++export function buildPrefix(buildId: string): string {+ if (!BUILD_ID.test(buildId)) { throw new Error('Invalid channel buildId') }+ return `releases/channel-builds/${buildId}/`+}++function identity(fields: Fields): ChannelIdentity {+ return {+ token: fields.text('token', /^[a-f0-9]{16}$/),+ displayName: fields.text('displayName', /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,79}$/),+ appId: fields.text('appId', /^[a-z][a-z0-9.-]{2,127}$/),+ appNamePascal: fields.text('appNamePascal', /^[A-Za-z][A-Za-z0-9]{0,63}$/),+ artifactNamePascal: fields.text('artifactNamePascal', /^[A-Za-z][A-Za-z0-9]{0,63}$/),+ cliName: fields.text('cliName', /^[a-z][a-z0-9-]{0,63}$/),+ windowsExecutableName: fields.text('windowsExecutableName', /^[A-Za-z][A-Za-z0-9 ._-]{0,79}$/),+ msixAppIdWithOrg: fields.text('msixAppIdWithOrg', /^[A-Za-z][A-Za-z0-9.-]{2,49}$/)+ }+}++export function sameChannelIdentity(left: ChannelIdentity, right: ChannelIdentity): boolean {+ return left.token === right.token && left.displayName === right.displayName && left.appId === right.appId &&+ left.appNamePascal === right.appNamePascal && left.artifactNamePascal === right.artifactNamePascal &&+ left.cliName === right.cliName && left.windowsExecutableName === right.windowsExecutableName &&+ left.msixAppIdWithOrg === right.msixAppIdWithOrg+}++function head(value: unknown): ChannelHead | null {+ if (value === null) { return null }+ const fields = new Fields(value)+ const buildId = fields.text('buildId', BUILD_ID)+ const manifestKey = fields.text('manifestKey')+ if (manifestKey !== `${buildPrefix(buildId)}build.json`) { throw new Error('Invalid channel manifestKey') }+ return { buildId, manifestKey, sequence: fields.integer('sequence', 0xffffffff), sha256: fields.text('sha256', SHA256) }+}++function requiredHead(value: unknown): ChannelHead {+ const result = head(value)+ if (!result) { throw new Error('Missing qualification destination head') }+ return result+}++export function decodeChannelRecord(body: string): ChannelRecord {+ const fields = new Fields(parseChannelJson(body))+ fields.schema()+ const policy = fields.text('policy')+ if (policy !== 'preview' && policy !== 'stable-release' && policy !== 'canary-release') {+ throw new Error('Channel has no supported desktop delivery')+ }+ const common: ChannelRecordBase = {+ schema: 1, name: validateChannelName(fields.text('name')),+ repository: fields.text('repository', /^[A-Za-z0-9][A-Za-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/),+ policy, identity: identity(fields.object('identity')), revision: fields.integer('revision'),+ nextSequence: fields.integer('nextSequence', 0x100000000), head: head(fields.get('head'))+ }+ if (common.head && common.head.sequence >= common.nextSequence) { throw new Error('Channel head exceeds allocation') }+ const state = fields.text('state')+ if (state === 'active') { return { ...common, state } }+ 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') }+ return {+ ...common, state, lastHead, destination: validateChannelName(fields.text('destination')),+ minimumVersion: fields.text('minimumVersion', VERSION),+ compatibilityKey: channelKey(fields.text('compatibilityKey')),+ compatibilitySha256: fields.text('compatibilitySha256', SHA256)+ }+}++function request(fields: Fields): ChannelRequest {+ fields.schema()+ const environment = fields.object('bundleEnv')+ const bundleEnv: ChannelBuild['bundleEnv'] = {}+ for (const key of environment.keys()) {+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) { throw new Error('Invalid bundle environment name') }+ const value: unknown = environment.get(key)+ if (value !== null && (typeof value !== 'string' || value.includes('\0'))) { throw new Error('Invalid bundle environment value') }+ Object.defineProperty(bundleEnv, key, { value, enumerable: true })+ }+ const publicBase = fields.text('publicBase')+ if (channelPublicBase(publicBase) !== publicBase) { throw new Error('Noncanonical request publicBase') }+ const windowsVersion = fields.text('windowsVersion', /^\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')),+ sequence: fields.integer('sequence', 0xffffffff), repository: fields.text('repository', /^[A-Za-z0-9][A-Za-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/),+ 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+)?$/)+ }+}++function packageEntry(value: unknown): ChannelPackage {+ const fields = new Fields(value)+ const platform = fields.text('platform')+ const arch = fields.text('arch')+ if ((platform !== 'darwin' && platform !== 'win32') || (arch !== 'x64' && arch !== 'arm64') || fields.get('variant') !== 'bundled') {+ throw new Error('Unsupported channel package')+ }+ 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'),+ 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))+ fields.schema()+ const entries: unknown = fields.get('packages')+ if (!Array.isArray(entries) || !entries.length || entries.length > 4) { throw new Error('Invalid channel packages') }+ 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 }+}diff --git a/apps/desktop/electron/updater/channel-strategy.ts b/apps/desktop/electron/updater/channel-strategy.tsnew file mode 100644index 00000000000..ec51b07035f--- /dev/null+++ b/apps/desktop/electron/updater/channel-strategy.ts@@ -0,0 +1,100 @@+import type { ChannelBuild } from './channel-protocol'+import type { ChannelResolver, ChannelRetirement, ChannelTarget } from './channel'+import type { UpdaterApplyResultWire, UpdaterStatusWire, UpdaterStrategy } from './index'++export interface ChannelRetirementStatus {+ state: 'available' | 'waiting' | 'incompatible' | 'conflict' | 'migrating' | 'cleanup-pending' | 'complete'+ destination: string+ version: string+ message?: string+}+export interface ChannelRetirementCallbacks {+ check: (retirement: ChannelRetirement) => Promise<Pick<ChannelRetirementStatus, 'state' | 'message'>>+ apply: (retirement: ChannelRetirement) => Promise<UpdaterApplyResultWire>+}+export interface ChannelStrategyDeps {+ resolver: Pick<ChannelResolver, 'resolve'>+ build: ChannelBuild+ mechanism: 'electron-updater' | 'app-installer'+ nativeFactory: (target: ChannelTarget) => UpdaterStrategy+ retirement?: ChannelRetirementCallbacks+}+interface NativeSelection { kind: 'native'; strategy: UpdaterStrategy; available: boolean }+interface RetirementSelection { kind: 'retirement'; value: ChannelRetirement; state: ChannelRetirementStatus['state'] }+type Selection = NativeSelection | RetirementSelection | { kind: 'empty' }++/** One selection owns a check/apply operation; background checks cannot retarget it. */+export class ChannelStrategy implements UpdaterStrategy {+ readonly mechanism: ChannelStrategyDeps['mechanism']+ private selection: Selection | null = null+ private busy = false++ constructor(private readonly deps: ChannelStrategyDeps) { this.mechanism = deps.mechanism }++ private enter(): void {+ if (this.busy) { throw new Error('An update operation is already in progress.') }+ this.busy = true+ }++ async check(): Promise<UpdaterStatusWire> {+ this.enter()+ try { return await this.select() } finally { this.busy = false }+ }++ private async select(): Promise<UpdaterStatusWire> {+ // Failed reads invalidate prior availability, never leave a stale install action.+ this.selection = null+ const 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> {+ 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)+ } finally { this.busy = false }+ }+}diff --git a/apps/desktop/electron/updater/channel-windows-host.ts b/apps/desktop/electron/updater/channel-windows-host.tsnew file mode 100644index 00000000000..b9f1afe5e89--- /dev/null+++ b/apps/desktop/electron/updater/channel-windows-host.ts@@ -0,0 +1,51 @@+import path from 'node:path'++import type { ChannelTarget } from './channel'+import { runRetirementPowerShell } from './retirement-discovery'+import { downloadRetirementArtifact } from './retirement-native'+import { newRetirementCorrelation, RetirementJournal, defaultRetirementRoot } from './retirement-state'++/** Verify downloaded bytes and native metadata before App Installer can stop the backend. */+export async function verifyPreparedChannelInstaller(file: string, target: ChannelTarget): Promise<void> {+ const pkg = target.package+ if (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,+ format: pkg.artifact.key.endsWith('.msixbundle') ? 'msixbundle' : 'msix' }+ })+ await runRetirementPowerShell(String.raw`+$ErrorActionPreference='Stop'+$p=[Console]::In.ReadToEnd() | ConvertFrom-Json+function Read-SafeXml($stream) {+ $settings=[Xml.XmlReaderSettings]::new(); $settings.DtdProcessing=[Xml.DtdProcessing]::Prohibit; $settings.XmlResolver=$null+ $reader=[Xml.XmlReader]::Create($stream,$settings)+ try { $xml=[Xml.XmlDocument]::new(); $xml.XmlResolver=$null; $xml.Load($reader); return ,$xml } finally { $reader.Dispose() }+}+$stream=[IO.File]::OpenRead($p.file)+try { $xml=Read-SafeXml $stream } finally { $stream.Dispose() }+$root=$xml.DocumentElement+if ($root.LocalName -cne 'AppInstaller' -or $root.GetAttribute('Uri') -cne $p.feedUrl -or $root.GetAttribute('Version') -cne $p.version) { throw 'Channel descriptor binding mismatch' }+$main=@($root.ChildNodes | Where-Object { $_.LocalName -in @('MainPackage','MainBundle') })+if ($main.Count -ne 1 -or $main[0].GetAttribute('Name') -cne $p.identity -or $main[0].GetAttribute('Publisher') -cne $p.publisher -or $main[0].GetAttribute('Version') -cne $p.version -or $main[0].GetAttribute('Uri') -cne $p.artifactUrl) { throw 'Descriptor does not reference the pinned native package' }+if (@($root.ChildNodes | Where-Object { $_.LocalName -notin @('MainPackage','MainBundle') }).Count) { throw 'Pinned channel descriptor must not add dependencies, optional packages or background update policies' }+$signature=Get-AuthenticodeSignature -LiteralPath $p.artifact+if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -cne $p.publisher) { throw 'Native artifact signature/publisher mismatch' }+Add-Type -AssemblyName System.IO.Compression.FileSystem+$zip=[IO.Compression.ZipFile]::OpenRead($p.artifact)+try {+ $name=if ($p.artifact.EndsWith('.msixbundle')) { 'AppxMetadata/AppxBundleManifest.xml' } else { 'AppxManifest.xml' }+ $entry=$zip.GetEntry($name)+ if (-not $entry) { throw 'Native manifest missing' }+ $stream=$entry.Open()+ try { $native=Read-SafeXml $stream } finally { $stream.Dispose() }+ if ($name -ceq 'AppxManifest.xml') { $identity=$native.Package.Identity; if ($identity.ProcessorArchitecture -cne $p.arch) { throw 'Package architecture mismatch' } }+ else { $identity=$native.Bundle.Identity; $slices=@($native.Bundle.Packages.Package | Where-Object { $_.Type -ceq 'application' -and $_.Architecture -ceq $p.arch -and $_.Version -ceq $p.version }); if ($slices.Count -ne 1) { throw 'Bundle architecture/version mismatch' } }+ if ($identity.Name -cne $p.identity -or $identity.Publisher -cne $p.publisher -or $identity.Version -cne $p.version) { throw 'Native manifest binding mismatch' }+} 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 }))+}diff --git a/apps/desktop/electron/updater/channel.test.ts b/apps/desktop/electron/updater/channel.test.tsnew file mode 100644index 00000000000..57cd2d8b581--- /dev/null+++ b/apps/desktop/electron/updater/channel.test.ts@@ -0,0 +1,287 @@+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 type { ChannelBuild, ChannelManifest, ChannelRecord, RetiredChannel } from './channel-protocol'++const servers: Server[] = []+afterEach(async (): Promise<void> => {+ await Promise.all(servers.splice(0).map((server: Server): Promise<void> => new Promise((resolve): void => {+ server.closeAllConnections()+ server.close((): void => resolve())+ })))+})++async function fixture(): Promise<{+ build: ChannelBuild; record: ChannelRecord; manifest: ChannelManifest;+ objects: Map<string, string>; requests: string[]; publish: () => void;+}> {+ 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',+ version: '0.0.1', windowsVersion: '0.0.1.0', publicBase: `http://127.0.0.1:${address.port}`,+ bundleEnv: {}, identity: {+ token: '1234567890abcdef', displayName: 'Hermes fresh-preview-29',+ appId: 'chat.nous.hermes.h1234567890abcdef', appNamePascal: 'HermesH1234567890abcdef',+ artifactNamePascal: 'HermesH1234567890abcdef', cliName: 'hermes-fresh-preview-29',+ 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,+ identity: build.identity.appId, teamId: 'ABCDE12345',+ artifact: { key: `${prefix}darwin/Hermes.zip`, sha256: 'd'.repeat(64), size: 100 },+ 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)+ }+ 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.appId+ f.manifest.packages[0].version = '1.2.3'+ f.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)+ 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()+ 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 }])+})++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 } },+ 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()+ await entered+ f.objects.clear()+ await expect(strategy.check()).rejects.toThrow('in progress')+ await expect(strategy.apply()).rejects.toThrow('in progress')+ releaseResolve()+ expect((await pending).ok).toBe(true)+ expect(calls).toEqual(['check', 'c'.repeat(32)])+ expect(f.requests).toHaveLength(2)+})++test('retirement has a separate consented path and never invokes the ordinary native updater', async (): Promise<void> => {+ const f = await retiredFixture()+ 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: (): never => { throw new Error('Not a same-identity update') },+ retirement: {+ check: async () => ({ state: 'available' }),+ apply: async () => { 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 })+ expect(applied).toBe(true)+})++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> => {+ const f = await retiredFixture()+ if (fault === 'unprotected') {+ f.record.policy = 'preview'+ f.manifest.request.version = '0.0.2'+ f.manifest.request.windowsVersion = '0.0.2.0'+ f.manifest.packages[0].version = '0.0.2'+ f.publish()+ }+ if (fault === 'floor') { f.retired.minimumVersion = '2.0.0' }+ 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}`) }+ f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify(f.retired))+ await expect(new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()).rejects.toThrow()+})++test('missing and oversized metadata remain errors while unpublished channels are explicitly empty', async (): Promise<void> => {+ const f = await fixture()+ const resolver = new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' })+ f.objects.clear()+ await expect(resolver.resolve()).rejects.toThrow('404')+ f.objects.set(`/releases/channels/${f.build.channel}.json`, ' '.repeat(4 * 1024 * 1024 + 1))+ await expect(resolver.resolve()).rejects.toThrow('size limit')+ f.record.head = null+ f.objects.set(`/releases/channels/${f.build.channel}.json`, JSON.stringify(f.record))+ expect((await resolver.resolve()).kind).toBe('empty')+})++test.each(['UPPER', 'a--b', '../a', 'a%2fb', 'con', 'a\n', 'a'.repeat(33)])('refuses invalid channel slug %j without normalization', (name: string): void => {+ expect((): void => { feedContract.darwinFeed(name) }).toThrow()+})++test('refuses public HTTP archive origins before network access', async (): Promise<void> => {+ const f = await fixture()+ f.build.publicBase = 'http://example.com'+ expect((): void => { new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }) }).toThrow('HTTPS')+})++test('Windows resolves its numeric native version, publisher and immutable descriptor without Python', async (): Promise<void> => {+ const f = await fixture()+ f.manifest.packages = [{+ platform: 'win32', arch: 'x64', variant: 'bundled', version: '0.0.2.0',+ 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.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')+})++test('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 } }+ })+ })+ await strategy.check()+ f.objects.clear()+ await expect(strategy.check()).rejects.toThrow('404')+ await expect(strategy.apply()).rejects.toThrow('404')+ expect(applied).toBe(false)+})++test('long-offline previews retain the qualified migration target after stable advances', async (): Promise<void> => {+ const f = await retiredFixture()+ const qualifiedBuild = f.manifest.request.buildId+ f.manifest.request = { ...f.manifest.request, buildId: 'e'.repeat(32), sequence: 3, version: '1.3.0', windowsVersion: '1.3.0.0', sourceVersion: '1.3.0', releaseTag: 'v1.3.0' }+ f.record.head = { buildId: f.manifest.request.buildId, sequence: 3, manifestKey: `releases/channel-builds/${f.manifest.request.buildId}/build.json`, sha256: '' }+ f.record.nextSequence = 4+ f.manifest.packages[0] = { ...f.manifest.packages[0], version: '1.3.0',+ artifact: { ...f.manifest.packages[0].artifact, key: `releases/channel-builds/${f.manifest.request.buildId}/darwin/Hermes.zip` },+ feed: { key: `releases/channel-builds/${f.manifest.request.buildId}/darwin/stable-mac.yml`, channel: 'stable' }+ }+ f.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')+})++test('rejects duplicate JSON members rather than disagreeing with the publisher decoder', async (): Promise<void> => {+ const f = await fixture()+ const body = f.objects.get(`/releases/channels/${f.build.channel}.json`)!+ f.objects.set(`/releases/channels/${f.build.channel}.json`, body.replace('"schema":1', '"schema":2,"schema":1'))+ await expect(new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()).rejects.toThrow('Duplicate')+})++test('resolves an arbitrary R2 name through a real HTTP channel and digest-bound immutable build', async (): Promise<void> => {+ const { 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`)+ expect(requests).toEqual([`/releases/channels/${build.channel}.json`, `/releases/channel-builds/${'c'.repeat(32)}/build.json`])+})diff --git a/apps/desktop/electron/updater/channel.ts b/apps/desktop/electron/updater/channel.tsnew file mode 100644index 00000000000..94fe27a8e9e--- /dev/null+++ b/apps/desktop/electron/updater/channel.ts@@ -0,0 +1,187 @@+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+} from './channel-protocol'++export interface ChannelTarget {+ channel: ActiveChannel+ manifest: ChannelManifest+ package: ChannelPackage+ manifestSha256: string+ artifactUrl: string+ feedUrl: string+}+export interface ChannelRetirement {+ source: ChannelBuild+ target: ChannelTarget+ constraints: RetiredChannel[]+ qualifications: ChannelQualification[]+}+export type ChannelResolution =+ | { kind: 'active'; target: ChannelTarget }+ | { kind: 'empty'; channel: ActiveChannel }+ | { kind: 'retirement'; retirement: ChannelRetirement }++export interface ChannelResolverDeps {+ build: ChannelBuild+ platform: ChannelPackage['platform']+ arch: ChannelPackage['arch']+ /** Locally trusted signing identity, not a value supplied by the feed. */+ signer: string+ fetch?: typeof fetch+}++function assertVersionFloor(version: string, floor: string): void {+ // Retirement floors are release versions, never preview sequence quads.+ if (!/^\d+\.\d+\.\d+$/.test(version) || !/^\d+\.\d+\.\d+$/.test(floor)) {+ throw new Error('Retirement version floor is not comparable')+ }+ const current = version.split('.').map(BigInt)+ const minimum = floor.split('.').map(BigInt)+ for (let index = 0; index < 3; index += 1) {+ if (current[index] > minimum[index]) { return }+ if (current[index] < minimum[index]) { throw new Error('Destination is below retirement minimum version') }+ }+}++/** Metadata reads never download an application or follow redirects. */+export class ChannelResolver {+ private readonly base: string+ private readonly fetcher: typeof fetch++ constructor(private readonly deps: ChannelResolverDeps) {+ this.base = channelPublicBase(deps.build.publicBase)+ this.fetcher = deps.fetch ?? fetch+ validateChannelName(deps.build.channel)+ }++ async read(key: string, digest?: string): Promise<string> {+ const url = `${this.base}/${channelKey(key)}`+ const response = await this.fetcher(url, {+ redirect: 'error', signal: AbortSignal.timeout(30_000), cache: 'no-store',+ headers: { 'Cache-Control': 'no-cache' }+ })+ if (!response.ok || response.url !== url) { throw new Error(`Channel read unavailable: HTTP ${response.status}`) }+ const maximum = 4 * 1024 * 1024+ const reader = response.body?.getReader()+ if (!reader) { throw new Error('Channel metadata has no body') }+ const chunks: Uint8Array[] = []+ let size = 0+ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) { break }+ size += value.byteLength+ if (size > maximum) { throw new Error('Channel metadata exceeds size limit') }+ chunks.push(value)+ }+ } finally {+ await reader.cancel()+ }+ const body = Buffer.concat(chunks)+ if (digest && createHash('sha256').update(body).digest('hex') !== digest) { throw new Error('Channel metadata SHA256 mismatch') }+ return new TextDecoder('utf-8', { fatal: true }).decode(body)+ }++ async resolve(): Promise<ChannelResolution> {+ 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.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)+ }+ 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')+ }+ }++ private assertRecord(record: ActiveChannel | RetiredChannel, name: string): void {+ if (record.name !== name) { throw new Error('Channel name does not match object key') }+ if (record.repository.toLowerCase() !== this.deps.build.repository.toLowerCase()) { throw new Error('Channel repository authority mismatch') }+ }++ private async target(channel: ActiveChannel): Promise<ChannelTarget> {+ if (!channel.head) { throw new Error('No destination build published') }+ const manifest = decodeChannelManifest(await this.read(channel.head.manifestKey, channel.head.sha256))+ const request = manifest.request+ if (request.buildId !== channel.head.buildId || request.sequence !== channel.head.sequence || request.channel !== channel.name ||+ request.repository.toLowerCase() !== channel.repository.toLowerCase() || request.publicBase !== this.base ||+ !sameChannelIdentity(request.identity, channel.identity)) { throw new Error('Channel manifest request binding mismatch') }+ if (channel.policy === 'preview' && (request.version !== `0.0.${request.sequence}` ||+ request.windowsVersion !== `0.${Math.floor(request.sequence / 65536)}.${request.sequence % 65536}.0`)) {+ throw new Error('Channel package version does not match sequence')+ }+ this.assertPackages(channel, manifest)+ const entry = manifest.packages.find((item: ChannelPackage): boolean => item.platform === this.deps.platform && item.arch === this.deps.arch)+ if (!entry) { throw new Error('Channel has no package for this platform and architecture') }+ const signer = entry.platform === 'darwin' ? entry.teamId : entry.publisher+ if (!this.deps.signer || signer !== this.deps.signer) { throw new Error('Channel package signing identity mismatch') }+ return {+ channel, manifest, package: entry, manifestSha256: channel.head.sha256,+ artifactUrl: `${this.base}/${entry.artifact.key}`, feedUrl: `${this.base}/${entry.feed.key}`+ }+ }++ private assertPackages(channel: ActiveChannel, manifest: ChannelManifest): void {+ const request = manifest.request+ const prefixes = [buildPrefix(request.buildId)]+ if (channel.policy !== 'preview') {+ if (!request.releaseTag || request.version !== request.releaseTag.slice(1)) { throw new Error('Protected release version mismatch') }+ prefixes.push(`releases/tag/${request.releaseTag}/`)+ }+ for (const entry of manifest.packages) {+ const expectedIdentity = entry.platform === 'darwin' ? request.identity.appId : request.identity.msixAppIdWithOrg+ const expectedVersion = entry.platform === 'darwin' ? request.version : request.windowsVersion+ if (entry.identity !== expectedIdentity || entry.version !== expectedVersion || entry.feed.channel !== 'stable' ||+ !prefixes.some((prefix: string): boolean => entry.artifact.key.startsWith(prefix)) ||+ !prefixes.some((prefix: string): boolean => entry.feed.key.startsWith(prefix))) {+ throw new Error('Channel package identity, version or immutable prefix mismatch')+ }+ if (entry.platform === 'darwin' && !entry.feed.key.endsWith(`/${entry.feed.channel}-mac.yml`)) {+ throw new Error('Invalid native macOS feed descriptor')+ }+ if (entry.platform === 'win32' && !entry.feed.key.endsWith('.appinstaller')) { throw new Error('Invalid native Windows feed descriptor') }+ }+ }+}diff --git a/apps/desktop/electron/updater/index.ts b/apps/desktop/electron/updater/index.tsindex 443969623a9..fbc591353da 100644--- a/apps/desktop/electron/updater/index.ts+++ b/apps/desktop/electron/updater/index.ts@@ -16,6 +16,7 @@// or Store inference; the strategy reports its mechanism to the renderer.import type { InstallStamp } from '../install-stamp'+import type { ChannelRetirementStatus } from './channel-strategy'export type UpdaterMechanism =| 'app-installer'@@ -61,7 +62,8 @@ export interface UpdaterStatusWire {behind?: number | nullcurrentSha?: stringcurrentVersion?: string- channel?: 'stable' | 'canary'+ channel?: string+ retirement?: ChannelRetirementStatuslatestTag?: string | nulltargetSha?: stringcommits?: { sha: string; summary: string; author: string; at: number }[]diff --git a/apps/desktop/electron/updater/mac-client.test.ts b/apps/desktop/electron/updater/mac-client.test.tsindex a15ee3644ac..7d4cf9dc223 100644--- a/apps/desktop/electron/updater/mac-client.test.ts+++ b/apps/desktop/electron/updater/mac-client.test.ts@@ -32,6 +32,16 @@ describe('macOS client wiring', () => {expect(client.allowPrerelease).toBe(false)})+ it('pins a neutral immutable descriptor instead of interpolating the dynamic name', (): void => {+ createMacStrategy({ ...deps('https://updates.example'), channel: 'unknown-preview',+ feed: { url: 'https://updates.example/releases/channel-builds/abc/darwin/latest-mac.yml', channel: 'latest' }+ })+ expect(client.setFeedURL).toHaveBeenCalledWith({ provider: 'generic', url: 'https://updates.example/releases/channel-builds/abc/darwin/', channel: 'latest' })+ expect(client.allowDowngrade).toBe(false)+ expect(client.autoDownload).toBe(false)+ expect((): void => { createMacStrategy({ ...deps('https://updates.example'), feed: { url: 'https://other.example/latest-mac.yml', channel: 'latest' } }) }).toThrow('authority')+ })+it('overrides the provider with the same variant/channel path as the publisher', () => {createMacStrategy(deps('https://updates.example/', true, 'canary'))expect(client.setFeedURL).toHaveBeenCalledWith({ provider: 'generic', url: 'https://updates.example/releases/darwin/light/canary/', channel: 'canary' })diff --git a/apps/desktop/electron/updater/mac-client.ts b/apps/desktop/electron/updater/mac-client.tsindex 15da592ee4e..b9460676e32 100644--- a/apps/desktop/electron/updater/mac-client.ts+++ b/apps/desktop/electron/updater/mac-client.ts@@ -2,35 +2,52 @@ import { autoUpdater as nativeUpdater } from 'electron'import electronUpdater from 'electron-updater'import feedContract from '../../update-feed.cjs'+import { channelPublicBase } from './channel-protocol'+import type { ChannelTarget } from './channel'+import { verifyChannelDownload } from './channel-native'import { MacStrategy, type MacStrategyDeps, prepareMacInstall } from './mac'export interface MacClientDeps extends Omit<MacStrategyDeps, 'updater' | 'prepareInstall'> {light: booleanfeedBaseUrl: string+ /** Exact per-build metadata, not a moving channel directory. */+ feed?: { url: string; channel: string }log: (message: string) => void}+export function createChannelMacStrategy(deps: MacClientDeps, target: ChannelTarget): MacStrategy {+ if (target.package.platform !== 'darwin') { throw new Error('Expected macOS channel target') }+ return createMacStrategy({+ ...deps, channel: target.channel.name, feedBaseUrl: target.manifest.request.publicBase,+ feed: { url: target.feedUrl, channel: target.package.feed.channel },+ expectedVersion: target.package.version,+ verifyDownload: (files: string[]): Promise<void> => verifyChannelDownload(files, target.package.artifact)+ })+}+export function createMacStrategy(deps: MacClientDeps): MacStrategy {- const feed = feedContract.darwinFeed(deps.channel, deps.light)+ const legacy = feedContract.darwinFeed(deps.channel, deps.light)+ const channel = deps.feed?.channel ?? legacy.channelconst updater = new electronUpdater.MacUpdater()updater.autoDownload = falseupdater.autoInstallOnAppQuit = falseupdater.autoRunAppAfterInstall = true- updater.channel = feed.channel- updater.allowPrerelease = feed.allowPrerelease+ updater.channel = channel+ updater.allowPrerelease = deps.feed ? Boolean(deps.expectedVersion?.includes('-')) : legacy.allowPrerelease// Setting channel enables downgrades in electron-updater. This app never does.updater.allowDowngrade = falseupdater.on('error', error => deps.log(`macOS updater: ${error.message}`))- if (deps.feedBaseUrl) {- const base = new URL(deps.feedBaseUrl)-- if (base.protocol !== 'https:' && !(base.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname))) {- throw new Error('The update feed must use HTTPS or a loopback HTTP address.')- }-- updater.setFeedURL({ provider: 'generic', url: `${base.href.replace(/\/+$/, '')}/${feed.directory}/`, channel: feed.channel })+ if (deps.feed) {+ const base = channelPublicBase(deps.feedBaseUrl)+ const url = new URL(channelPublicBase(deps.feed.url))+ if (!deps.feed.url.startsWith(`${base}/`) || url.origin !== new URL(base).origin) { throw new Error('Native feed authority mismatch') }+ if (!/^[a-z][a-z0-9-]*$/.test(channel) || !url.pathname.endsWith(`/${channel}-mac.yml`)) { throw new Error('Invalid macOS feed descriptor') }+ updater.setFeedURL({ provider: 'generic', url: new URL('./', url).href, channel })+ } else if (deps.feedBaseUrl) {+ const base = channelPublicBase(deps.feedBaseUrl)+ updater.setFeedURL({ provider: 'generic', url: `${base}/${legacy.directory}/`, channel })}return new MacStrategy({ ...deps, updater, prepareInstall: () => prepareMacInstall(nativeUpdater) })diff --git a/apps/desktop/electron/updater/mac.test.ts b/apps/desktop/electron/updater/mac.test.tsindex c105d042524..6b55cb9f014 100644--- a/apps/desktop/electron/updater/mac.test.ts+++ b/apps/desktop/electron/updater/mac.test.ts@@ -80,6 +80,18 @@ describe('macOS strategy', () => {expect(deps.updater.downloadUpdate).not.toHaveBeenCalled()})+ it('refuses a substituted pinned version or artifact before native signature preparation', async (): Promise<void> => {+ const { deps, events } = fixture()+ deps.expectedVersion = '0.30.0'+ await expect(new MacStrategy(deps).apply()).rejects.toThrow('pinned channel version')+ expect(events).toEqual(['check'])+ deps.expectedVersion = '0.29.0'+ deps.verifyDownload = async (): Promise<void> => { throw new Error('artifact digest mismatch') }+ await expect(new MacStrategy(deps).apply()).rejects.toThrow('artifact digest')+ expect(events).not.toContain('verify')+ expect(events).not.toContain('stop')+ })+it('restores the backend if install handoff throws', async () => {const { deps, strategy, events } = fixture()vi.mocked(deps.updater.quitAndInstall).mockImplementation(() => {diff --git a/apps/desktop/electron/updater/mac.ts b/apps/desktop/electron/updater/mac.tsindex 03a4df8f7bb..683d037d94f 100644--- a/apps/desktop/electron/updater/mac.ts+++ b/apps/desktop/electron/updater/mac.ts@@ -6,7 +6,9 @@ import type { UpdaterApplyResultWire, UpdaterStatusWire, UpdaterStrategy } fromexport interface MacStrategyDeps {updater: Pick<AppUpdater, 'checkForUpdates' | 'downloadUpdate' | 'quitAndInstall' | 'on' | 'removeListener'>- channel: 'stable' | 'canary'+ channel: string+ expectedVersion?: string+ verifyDownload?: (files: string[]) => Promise<void>appVersion: string/** Squirrel verifies the signed app before any backend is stopped. */prepareInstall: () => Promise<void>@@ -36,6 +38,10 @@ export class MacStrategy implements UpdaterStrategy {throw new Error('The macOS updater is not active for this app.')}+ if (this.deps.expectedVersion && result.updateInfo.version !== this.deps.expectedVersion) {+ throw new Error('Native macOS feed does not match the pinned channel version')+ }+return {supported: true,mechanism: this.mechanism,@@ -74,7 +80,8 @@ export class MacStrategy implements UpdaterStrategy {return { ok: true, mechanism: this.mechanism }}- await this.deps.updater.downloadUpdate()+ const files = await this.deps.updater.downloadUpdate()+ await this.deps.verifyDownload?.(files)this.deps.emitProgress({ stage: 'prepare', message: 'Verifying the signed macOS update.', percent: null })await this.deps.prepareInstall()await stop()diff --git a/apps/desktop/electron/updater/operation.test.ts b/apps/desktop/electron/updater/operation.test.tsnew file mode 100644index 00000000000..b73d74d9073--- /dev/null+++ b/apps/desktop/electron/updater/operation.test.ts@@ -0,0 +1,82 @@+import { expect, test } from 'vitest'++import { UpdateOperation } from './operation'++import type { UpdaterApplyResultWire, UpdaterStrategy } from './index'++interface Deferred<T> {+ promise: Promise<T>+ resolve: (value: T) => void+ reject: (error: Error) => void+}++function deferred<T = void>(): Deferred<T> {+ let resolve!: (value: T) => void+ let reject!: (error: Error) => void++ const promise: Promise<T> = new Promise<T>((done, fail): void => {+ resolve = done+ reject = fail+ })++ return { promise, resolve, reject }+}++function strategy(): UpdaterStrategy {+ return {+ mechanism: 'external',+ check: async () => ({ supported: false }),+ apply: async () => ({ ok: true })+ }+}++test('check and apply share one pending strategy, and a failed initialization can retry', async (): Promise<void> => {+ const pending = deferred<UpdaterStrategy | null>()+ const installed: UpdaterStrategy = strategy()+ let attempts: number = 0++ const operation = new UpdateOperation((): Promise<UpdaterStrategy | null> => {+ attempts += 1++ return attempts === 1 ? pending.promise : Promise.resolve(installed)+ })++ const first: Promise<UpdaterStrategy | null> = operation.resolve()+ const second: Promise<UpdaterStrategy | null> = operation.resolve()+ expect(attempts).toBe(1)+ const failures = Promise.allSettled([first, second])+ pending.reject(new Error('native inspection failed'))+ expect((await failures).map((result): string => result.status)).toEqual(['rejected', 'rejected'])+ expect(await operation.resolve()).toBe(installed)+ expect(await operation.resolve()).toBe(installed)+ expect(attempts).toBe(2)+})++test('apply ownership precedes async resolution, survives restoration, and retains a successful handoff', async (): Promise<void> => {+ const pending = deferred<UpdaterStrategy | null>()+ const operation = new UpdateOperation((): Promise<UpdaterStrategy | null> => pending.promise)+ const restoration = deferred()+ const restoring = deferred()+ let applications: number = 0++ const first: Promise<UpdaterApplyResultWire> = operation.apply(async (): Promise<UpdaterApplyResultWire> => {+ applications += 1+ await operation.resolve()+ restoring.resolve()+ await restoration.promise+ throw new Error('install failed')+ })++ const competing: Promise<UpdaterApplyResultWire> = operation.apply(async () => ({ ok: true }))+ const rejected = expect(competing).rejects.toThrow('already in progress')+ pending.resolve(strategy())+ await rejected+ await restoring.promise+ await expect(operation.apply(async () => ({ ok: true }))).rejects.toThrow('already in progress')+ restoration.resolve()+ await expect(first).rejects.toThrow('install failed')+ expect(applications).toBe(1)+ await expect(operation.apply(async () => ({ ok: false }))).resolves.toEqual({ ok: false })+ await expect(operation.apply(async () => ({ ok: true, handedOff: true }))).resolves.toEqual({ ok: true, handedOff: true })+ await expect(operation.apply(async () => ({ ok: true }))).rejects.toThrow('already in progress')+})diff --git a/apps/desktop/electron/updater/operation.ts b/apps/desktop/electron/updater/operation.tsnew file mode 100644index 00000000000..def83bbea05--- /dev/null+++ b/apps/desktop/electron/updater/operation.ts@@ -0,0 +1,33 @@+import type { UpdaterApplyResultWire, UpdaterStrategy } from './index'++/** Preserve one native selection across check/apply and one owner through handoff. */+export class UpdateOperation {+ private strategy: Promise<UpdaterStrategy | null> | undefined+ private applying: boolean = false++ constructor(private readonly initialize: () => Promise<UpdaterStrategy | null>) {}++ resolve(): Promise<UpdaterStrategy | null> {+ this.strategy ??= this.initialize().catch((error: Error): never => {+ this.strategy = undefined+ throw error+ })++ return this.strategy+ }++ async apply(run: () => Promise<UpdaterApplyResultWire>): Promise<UpdaterApplyResultWire> {+ if (this.applying) { throw new Error('An update is already in progress.') }+ this.applying = true+ let handedOff: boolean = false++ try {+ const result: UpdaterApplyResultWire = await run()+ handedOff = result.handedOff === true++ return result+ } finally {+ if (!handedOff) { this.applying = false }+ }+ }+}diff --git a/apps/desktop/electron/updater/retirement-compatibility.ts b/apps/desktop/electron/updater/retirement-compatibility.tsnew file mode 100644index 00000000000..157607fec07--- /dev/null+++ b/apps/desktop/electron/updater/retirement-compatibility.ts@@ -0,0 +1,44 @@+import path from 'node:path'++import type { PayloadInfo } from '../payload-backend'+import { runRetirementCommand } from './retirement-native'+import type { RetirementRecord } from './retirement-state'++const compatibilityProbe: string = `import os, pathlib, sys+repo, site, root, profile = sys.argv[1:]+sys.path[:0] = [repo, site]+home = pathlib.Path(root)+if profile != 'default': home = home / 'profiles' / profile+os.environ['HERMES_HOME'] = str(home)+os.environ['HERMES_SHARED_AUTH_DIR'] = str(pathlib.Path(root) / 'shared')+import yaml+from hermes_cli.config import validate_config_structure+config_file = home / 'config.yaml'+config = yaml.safe_load(config_file.read_text()) 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')+from hermes_state import SessionDB+from hermes_state_schema import schema_read_probe_statements+file = home / 'state.db'+if file.exists():+ # Only the disposable snapshot receives the destination migrations. Never+ # initialize the live database as a compatibility probe.+ db = SessionDB(db_path=file)+ try:+ for sql in schema_read_probe_statements(): db._conn.execute(sql)+ for row in db._conn.execute('SELECT id FROM sessions').fetchall():+ db.get_session(row[0])+ db.get_messages(row[0])+ finally: db.close()+`++/** Exact cohort admission is checked separately; this catches damaged local state. */+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)+}++export function retirementSnapshotTools(payload: PayloadInfo): { python: string; backupScript: string } {+ return { python: payload.storePython, backupScript: path.join(payload.repoDir, 'hermes_cli/backup_sqlite.py') }+}diff --git a/apps/desktop/electron/updater/retirement-connections.test.ts b/apps/desktop/electron/updater/retirement-connections.test.tsnew file mode 100644index 00000000000..6b116ebea4b--- /dev/null+++ b/apps/desktop/electron/updater/retirement-connections.test.ts@@ -0,0 +1,79 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++import { expect, test } from 'vitest'++import { prepareRetirementConnection, retirementConnection } from './retirement-connections'++interface RemoteEntry {+ id: string+ kind: 'remote'+ label: string+ url: string+ authMode: 'token'+}++const research: Omit<RemoteEntry, 'id'> = {+ kind: 'remote',+ label: 'Research',+ url: 'https://gateway.example',+ authMode: 'token'+}++async function stableRegistry(entries: RemoteEntry[]): Promise<string> {+ const userData: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-connections-'))+ const primary: string = entries[0]?.id ?? 'local'+ await writeFile(+ path.join(userData, 'connections.json'),+ JSON.stringify({ primary, launchMode: 'primary', lastUsed: primary, connections: entries })+ )+ return userData+}++test('retired connections reject URL credentials before journal serialization', () => {+ expect(() => retirementConnection({+ id: 'remote',+ kind: 'remote',+ label: 'Demo',+ url: 'https://alice:[email protected]',+ authMode: 'token'+ })).toThrowError(/remove url credentials/i)+})++test('prepare resolves an identical stable endpoint under its existing id', async () => {+ const userData = await stableRegistry([{ id: 'stable-remote', ...research }])+ try {+ const resolved = prepareRetirementConnection(userData, 'retired-remote', research)+ expect(resolved.id).toBe('stable-remote')+ expect(resolved.settings).toEqual(research)+ } finally {+ await rm(userData, { recursive: true, force: true })+ }+})++test('prepare rejects an ambiguous endpoint registered twice in stable', async () => {+ const userData = await stableRegistry([+ { id: 'stable-remote', ...research },+ { id: 'duplicate-remote', ...research }+ ])+ try {+ expect(() => prepareRetirementConnection(userData, 'retired-remote', research))+ .toThrowError(/multiple stable connections/i)+ } finally {+ await rm(userData, { recursive: true, force: true })+ }+})++test('prepare still applies registry validation for genuinely new endpoints', async () => {+ const userData = await stableRegistry([{ id: 'stable-remote', ...research }])+ try {+ // Same label, different endpoint: the ordinary registry rules decide.+ expect(() => prepareRetirementConnection(userData, 'retired-remote', { ...research, url: 'https://other.example' }))+ .toThrowError()+ const fresh = prepareRetirementConnection(userData, 'retired-remote', { ...research, label: 'Other', url: 'https://other.example' })+ expect(fresh.id).toBe('retired-remote')+ } finally {+ await rm(userData, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/updater/retirement-connections.ts b/apps/desktop/electron/updater/retirement-connections.tsnew file mode 100644index 00000000000..1467b44b84e--- /dev/null+++ b/apps/desktop/electron/updater/retirement-connections.ts@@ -0,0 +1,137 @@+import { closeSync, fsyncSync, openSync, readFileSync } from 'node:fs'+import path from 'node:path'++import {+ type ConnectionRegistry, migrateV1ToRegistry, normalizeConnectionInput, normalizeRegistry, type RegistryConnection,+ setPrimaryConnection, upsertConnection+} from '../connection-registry'+import { resolveDesktopRemoteRoute } from '../desktop-remote-route'+import { writeSecretFileAtomic } from '../hardening'++/** Explicit allowlist: credentials, proxy headers and opaque keychain envelopes never transfer. */+export interface RetirementConnection {+ kind: RegistryConnection['kind']+ label: string+ url?: string+ authMode?: 'oauth' | 'token'+ host?: string+ user?: string+ port?: number+ keyPath?: string+ remoteHermesPath?: string+ remoteProfile?: string+ org?: string+ name?: string+}++export interface RetirementConnectionSelection {+ id: string+ settings?: RetirementConnection+}++function retirementEndpointKey(connection: Pick<RetirementConnection, 'host' | 'kind' | 'port' | 'remoteProfile' | 'url' | 'user'>): string {+ if (connection.kind === 'ssh') {+ return `ssh:${(connection.user || '').toLowerCase()}@${(connection.host || '').toLowerCase()}:${connection.port ?? 22}::${(connection.remoteProfile || '').trim()}`+ }+ return `url:${String(connection.url || '').trim().replace(/\/+$/, '').toLowerCase()}`+}++export function retirementConnection(entry: RegistryConnection): RetirementConnection {+ if (entry.url) {+ const url: URL = new URL(entry.url)+ if (url.username || url.password) { throw new Error('Remove URL credentials and use saved authentication before migration') }+ }+ return { kind: entry.kind, label: entry.label, url: entry.url, authMode: entry.authMode,+ host: entry.host, user: entry.user, port: entry.port, keyPath: entry.keyPath,+ remoteHermesPath: entry.remoteHermesPath, remoteProfile: entry.remoteProfile, org: entry.org, name: entry.name }+}++interface StoredConnectionConfig {+ mode?: string+ profiles?: { [profile: string]: { mode?: string } }+}++function readConfig(file: string): StoredConnectionConfig | null {+ try { return JSON.parse(readFileSync(file, 'utf8')) }+ catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { return null }+ throw error+ }+}++interface StoredConnections {+ registry: ConnectionRegistry+ config: StoredConnectionConfig+}++function readConnections(userData: string): StoredConnections {+ const config: StoredConnectionConfig = readConfig(path.join(userData, 'connection.json')) ?? {}+ const stored: StoredConnectionConfig | null = readConfig(path.join(userData, 'connections.json'))+ const registry: ConnectionRegistry = stored ? normalizeRegistry(stored) : migrateV1ToRegistry(config)+ if (registry.quarantined?.length) { throw new Error('Repair the saved connections before migration; original settings were preserved') }+ return { registry, config }+}++export function retirementSelectedConnection(userData: string, profile: string): string {+ const { registry, config } = readConnections(userData)+ const route = resolveDesktopRemoteRoute({ registry, config, profile })+ const id: string = route ? route.connectionId ?? '' : 'local'+ if (!id || (registry.launchMode === 'last-used' && registry.lastUsed !== id)) {+ throw new Error('Select a primary saved connection before migration; the launch route is ambiguous')+ }+ return id+}++export function assertRetirementConnection(userData: string, id: string, connection: RetirementConnection): void {+ const existing: RegistryConnection | undefined = readConnections(userData).registry.connections.find(entry => entry.id === id)+ if (!existing || JSON.stringify(retirementConnection(existing)) !== JSON.stringify(connection)) {+ throw new Error('Stable connection changed during migration; review the selection again')+ }+}++/** Resolve collisions before the receiver crosses its forward-only boundary. */+export function prepareRetirementConnection(userData: string, id: string, connection: RetirementConnection): RetirementConnectionSelection {+ // Reuse the allowlist guard so an embedded-credential URL can never start adoption.+ retirementConnection({ id, ...connection })+ if (connection.kind === 'local') { return { id: 'local' } }+ const { registry } = readConnections(userData)+ const key = retirementEndpointKey(connection)+ const same: RegistryConnection[] = registry.connections.filter((entry: RegistryConnection): boolean =>+ entry.kind !== 'local' && retirementEndpointKey(entry) === key)+ if (same.length > 1) { throw new Error('Multiple stable connections already point at the preview endpoint; select one in stable before migration') }+ if (same.length === 1) { return { id: same[0].id, settings: retirementConnection(same[0]) } }+ // The ordinary registry validator owns label and endpoint collision rules.+ normalizeConnectionInput({ ...connection, id }, registry)+ return { id, settings: connection }+}++/** Stable's existing credentials win when an identical endpoint is already registered. */+export function adoptRetirementConnection(userData: string, id: string, profile: string, connection?: RetirementConnection): void {+ const { registry, config } = readConnections(userData)+ const current: string = retirementSelectedConnection(userData, profile)++ if (current !== id && ((config.mode && config.mode !== 'local') ||+ (config.profiles?.[profile]?.mode && config.profiles[profile].mode !== 'local'))) {+ throw new Error('Stable has a legacy connection override. Keep its workspace, or select Local in stable and retry; saved connections remain intact')+ }+ let next: ConnectionRegistry = registry+ if (connection) {+ const existing: RegistryConnection | undefined = registry.connections.find(entry => entry.id === id)+ if (existing) {+ assertRetirementConnection(userData, id, connection)+ } else {+ next = upsertConnection(registry, normalizeConnectionInput({ ...connection, id }, registry))+ }+ }+ if (current === id) { return }+ next = { ...setPrimaryConnection(next, id), lastUsed: id, launchMode: 'primary' }+ const file: string = path.join(userData, 'connections.json')+ writeSecretFileAtomic(file, JSON.stringify(next, null, 2))+ const handle: number = openSync(file, 'r+')+ try { fsyncSync(handle) } finally { closeSync(handle) }+ if (process.platform !== 'win32') {+ const directory: number = openSync(userData, 'r')+ try { fsyncSync(directory) } finally { closeSync(directory) }+ }+ if (retirementSelectedConnection(userData, profile) !== id) { throw new Error('Connection adoption did not persist') }+}\ No newline at end of filediff --git a/apps/desktop/electron/updater/retirement-dialog.ts b/apps/desktop/electron/updater/retirement-dialog.tsnew file mode 100644index 00000000000..378006c1ee6--- /dev/null+++ b/apps/desktop/electron/updater/retirement-dialog.ts@@ -0,0 +1,44 @@+import type { Dialog, MessageBoxOptions, MessageBoxReturnValue } from 'electron'++import type { RetirementWorkspaceConflict } from './retirement-receiver'+import type { RetirementWorkspaceChoice } from './retirement-state'++export interface RetirementDialogHost {+ ready: () => Promise<void>+ showMessageBox: Dialog['showMessageBox']+}++/** The destination confirms its current workspace, not a stale source-side guess. */+export async function confirmRetirementWorkspace(+ conflict: RetirementWorkspaceConflict,+ host: RetirementDialogHost+): Promise<RetirementWorkspaceChoice | null> {+ const choices: (RetirementWorkspaceChoice | null)[] = [null, 'keep-stable']+ const buttons: string[] = ['Cancel migration', 'Keep stable workspace']++ if (conflict.canOpenPreview) {+ choices.push('open-preview')+ buttons.push('Open preview workspace')+ }++ const options: MessageBoxOptions = {+ type: 'question',+ title: 'Choose the workspace for stable',+ message: 'Stable and the preview have different workspaces.',+ detail: [+ `Stable: ${conflict.current.home}\nProfile: ${conflict.current.profile}\nConnection: ${conflict.current.connectionId}`,+ `Preview: ${conflict.requested.home}\nProfile: ${conflict.requested.profile}\nConnection: ${conflict.requested.connectionId}`,+ 'Both workspaces will be preserved. This does not merge or copy their data.',+ conflict.canOpenPreview ? '' : 'To open the preview workspace, close stable and remove any explicit home override, then retry.'+ ].filter(Boolean).join('\n\n'),+ buttons,+ defaultId: 0,+ cancelId: 0,+ noLink: true+ }+ await host.ready()++ const result: MessageBoxReturnValue = await host.showMessageBox(options)++ return choices[result.response] ?? null+}diff --git a/apps/desktop/electron/updater/retirement-discovery.test.ts b/apps/desktop/electron/updater/retirement-discovery.test.tsnew file mode 100644index 00000000000..10d10b1634f--- /dev/null+++ b/apps/desktop/electron/updater/retirement-discovery.test.ts@@ -0,0 +1,96 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++import { expect, test } from 'vitest'++import type { ChannelTarget } from './channel'+import type { ChannelIdentity, ChannelPackage, ChannelRequest } from './channel-protocol'+import { discoverRetirementDestination, runRetirementPowerShell } from './retirement-discovery'+import type { RetirementSource } from './retirement-state'++function retirementTarget(platform: ChannelPackage['platform']): ChannelTarget {+ const identity: ChannelIdentity = { token: 'a'.repeat(16), displayName: 'Hermes Agent', appId: 'com.nousresearch.hermes-bundled',+ appNamePascal: 'HermesBundled', artifactNamePascal: 'HermesBundled', cliName: 'hermes', windowsExecutableName: 'Hermes Agent', msixAppIdWithOrg: 'NousResearch.HermesBundled' }+ const request: ChannelRequest = { schema: 1, buildId: 'b'.repeat(32), channel: 'stable', sequence: 2,+ repository: 'NousResearch/hermes-agent', commit: 'c'.repeat(40), sourceVersion: '1.2.3', version: '1.2.3', windowsVersion: '1.2.3.0',+ publicBase: 'https://example.com', identity, bundleEnv: {} }+ const pkg: ChannelPackage = { platform, arch: 'x64', variant: 'bundled', version: platform === 'darwin' ? request.version : request.windowsVersion,+ identity: platform === 'darwin' ? identity.appId : identity.msixAppIdWithOrg,+ artifact: { key: 'releases/fixture/stable.msixbundle', sha256: 'd'.repeat(64), size: 1 }, feed: { key: 'releases/fixture/stable.appinstaller', channel: 'stable' } }+ return { channel: { schema: 1, state: 'active', name: 'stable', policy: 'stable-release', repository: request.repository,+ identity, revision: 2, nextSequence: 3, head: null }, manifest: { schema: 1, request, packages: [pkg] }, package: pkg,+ manifestSha256: 'e'.repeat(64), artifactUrl: 'https://example.com/releases/fixture/stable.msixbundle', feedUrl: 'https://example.com/releases/fixture/stable.appinstaller' }+}++function retirementSource(directory: string, platform: ChannelPackage['platform']): RetirementSource {+ return { platform, architecture: 'x64', identity: 'NousResearch.Preview', signer: 'TESTTEAM12', nativeVersion: '1.0.0.0',+ appPath: path.join(directory, 'Preview.app'), executable: path.join(directory, 'Preview.app/preview'), applicationId: 'PreviewApplication',+ packageFullName: 'NousResearch.Preview_1.0.0.0_x64__abcdefghijklm', home: path.join(directory, 'home'), userData: path.join(directory, 'desktop'),+ profile: 'default', connectionId: 'local', removalRoots: [path.join(directory, 'Preview.app')] }+}++test('Mac discovery reuses the uniquely owned bundle by identity and names a new install from product metadata', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-mac-discovery-'))+ const target: ChannelTarget = retirementTarget('darwin')+ const source: RetirementSource = retirementSource(directory, 'darwin')+ const renamed: string = path.join(directory, 'My stable application.app')+ const inspectMac = async (app: string): Promise<{ identity: string }> => JSON.parse(await readFile(path.join(app, 'identity.json'), 'utf8'))+ const discovery = { mac: { roots: [directory], registered: async (): Promise<string[]> => [], inspect: inspectMac } }+ try {+ expect((await discoverRetirementDestination(target, source, discovery)).appPath).toBe(path.join(directory, `${target.manifest.request.identity.displayName}.app`))+ await mkdir(path.join(renamed, 'Contents'), { recursive: true, mode: 0o700 })+ await writeFile(path.join(renamed, 'Contents/Info.plist'), '')+ await writeFile(path.join(renamed, 'identity.json'), JSON.stringify({ identity: target.package.identity }))+ expect((await discoverRetirementDestination(target, source, discovery)).appPath).toBe(renamed)+ const duplicate: string = path.join(directory, 'Other stable.app')+ await mkdir(path.join(duplicate, 'Contents'), { recursive: true, mode: 0o700 })+ await writeFile(path.join(duplicate, 'Contents/Info.plist'), '')+ await writeFile(path.join(duplicate, 'identity.json'), JSON.stringify({ identity: target.package.identity }))+ await expect(discoverRetirementDestination(target, source, discovery)).rejects.toThrow('Multiple')+ await rm(duplicate, { recursive: true })+ await expect(discoverRetirementDestination(target, source, { mac: {+ ...discovery.mac, inspect: async (): Promise<{ identity: string }> => { throw new Error('different installation steward') }+ } })).rejects.toThrow('steward')+ } finally { await rm(directory, { recursive: true, force: true }) }+})++// Native Windows lane: queries the actual AppX default volume; never installs a package.+test.runIf(process.platform === 'win32')('Windows discovery uses the OS package store, not the preview volume', async (): Promise<void> => {+ const target: ChannelTarget = retirementTarget('win32')+ target.package.identity = `NousResearch.RetirementProbe${Date.now()}`+ const source: RetirementSource = retirementSource(os.tmpdir(), 'win32')+ const result = await discoverRetirementDestination(target, source)+ const volume = await runRetirementPowerShell('(Get-AppxDefaultVolume).PackageStorePath | ConvertTo-Json -Compress')+ expect(path.dirname(result.appPath).toLowerCase()).toBe(String(JSON.parse(volume.stdout)).toLowerCase())+ expect(result.applicationId).toBe(target.manifest.request.identity.appNamePascal)+})++// Native macOS lane: parses a real plist and rejects an unsigned matching bundle.+test.runIf(process.platform === 'darwin')('Mac discovery refuses a matching bundle without native signing ownership', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-mac-native-'))+ try {+ const target: ChannelTarget = retirementTarget('darwin')+ const renamed: string = path.join(directory, 'Renamed stable.app')+ await mkdir(path.join(renamed, 'Contents'), { recursive: true, mode: 0o700 })+ await writeFile(path.join(renamed, 'Contents/Info.plist'), `<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${target.package.identity}</string><key>CFBundleShortVersionString</key><string>1.2.3</string><key>CFBundleExecutable</key><string>Hermes</string></dict></plist>`)+ await expect(discoverRetirementDestination(target, retirementSource(directory, 'darwin'), {+ mac: { roots: [directory], registered: async (): Promise<string[]> => [] }+ })).rejects.toThrow('Native retirement operation failed')+ } finally { await rm(directory, { recursive: true, force: true }) }+})++test('destination binds the target application ID and the native install location, not preview naming', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-discovery-'))+ try {+ const target: ChannelTarget = retirementTarget('win32')+ const source: RetirementSource = retirementSource(directory, 'win32')+ const installedPath: string = path.join(directory, 'different-package-volume', 'native-target')+ const result = await discoverRetirementDestination(target, source, {+ windows: async (): Promise<string> => installedPath+ })+ expect(result.applicationId).toBe(target.manifest.request.identity.appNamePascal)+ expect(result.applicationId).not.toBe(source.applicationId)+ expect(result.appPath).toBe(installedPath)+ } finally { await rm(directory, { recursive: true, force: true }) }+})diff --git a/apps/desktop/electron/updater/retirement-discovery.ts b/apps/desktop/electron/updater/retirement-discovery.tsnew file mode 100644index 00000000000..e8152fb3408--- /dev/null+++ b/apps/desktop/electron/updater/retirement-discovery.ts@@ -0,0 +1,103 @@+import path from 'node:path'++import type { ChannelBuild } from './channel-protocol'+import type { ChannelTarget } from './channel'+import { runRetirementCommand, type NativeCommandResult } from './retirement-native'+import { canonicalRetirementPath, insideRetirementRoot, type RetirementDestination, type RetirementSource } from './retirement-state'++interface InstalledApp {+ identity: string+ signer: string+ appPath: string+ nativeVersion: string+ executable: string+ applicationId: string | null+ packageFullName: string | null+ packageFamilyName: string | null+ removalRoots: string[]+}++export async function runRetirementPowerShell(script: string, input: string = ''): Promise<NativeCommandResult> {+ if (process.platform !== 'win32') { throw new Error('This operation requires Windows') }+ return 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, input+ )+}++/** Derive trust from the signed running application, never from an R2 document. */+export async function inspectRunningChannelApp(build: ChannelBuild): Promise<InstalledApp> {+ const executable: string = await canonicalRetirementPath(process.execPath)+ if (process.platform === 'darwin') {+ const appPath: string = path.resolve(executable, '../../..')+ await runRetirementCommand('/usr/bin/codesign', ['--verify', '--deep', '--strict', appPath])+ const signature: NativeCommandResult = await runRetirementCommand('/usr/bin/codesign', ['-dv', '--verbose=4', appPath])+ const signer: string = /^TeamIdentifier=(.+)$/m.exec(signature.stderr)?.[1] || ''+ const identity: string = /^Identifier=(.+)$/m.exec(signature.stderr)?.[1] || ''+ if (!/^[A-Z0-9]{10}$/.test(signer) || identity !== build.identity.appId) {+ throw new Error('Running channel application signature does not match its baked identity')+ }+ return { identity, signer, appPath, executable, nativeVersion: build.version,+ applicationId: null, packageFullName: null, packageFamilyName: null, removalRoots: [appPath] }+ }+ 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 -ne 1) { throw 'Running channel package is not uniquely registered' }+$pkg=$packages[0]+if ($pkg.Status.ToString() -cne 'Ok' -or $pkg.SignatureKind.ToString() -cne 'Developer' -or $pkg.IsDevelopmentMode -or $pkg.NonRemovable) { throw 'Channel package is not a trusted current-user sideload' }+if (-not $p.executable.StartsWith($pkg.InstallLocation.TrimEnd('\')+'\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Running executable is outside registered package' }+$manifest=Get-AppxPackageManifest -Package $pkg.PackageFullName+$apps=@($manifest.Package.Applications.Application | Where-Object { [IO.Path]::GetFullPath((Join-Path $pkg.InstallLocation $_.Executable)) -ieq $p.executable })+if ($apps.Count -ne 1) { throw 'Running executable is not the registered application' }+@{ identity=$pkg.Name; signer=$pkg.Publisher; appPath=$pkg.InstallLocation; nativeVersion=$pkg.Version.ToString(); executable=$p.executable; applicationId=$apps[0].Id; packageFullName=$pkg.PackageFullName; packageFamilyName=$pkg.PackageFamilyName; removalRoots=@($pkg.InstallLocation,(Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) ('Packages\'+$pkg.PackageFamilyName))) } | ConvertTo-Json -Compress+`, JSON.stringify({ identity: build.identity.msixAppIdWithOrg, executable }))+ const installed: InstalledApp = JSON.parse(result.stdout)+ if (installed.nativeVersion !== build.windowsVersion || installed.identity !== build.identity.msixAppIdWithOrg || !installed.signer) {+ throw new Error('Running package does not match its baked channel version')+ }+ return installed+}++export async function discoverRetirementSource(build: ChannelBuild, home: string, userData: string, profile: string): Promise<RetirementSource> {+ if ((process.platform !== 'darwin' && process.platform !== 'win32') || (process.arch !== 'x64' && process.arch !== 'arm64')) {+ throw new Error('Native retirement is supported only on bundled macOS and Windows')+ }+ const installed: InstalledApp = await inspectRunningChannelApp(build)+ return { ...installed, platform: process.platform, architecture: process.arch, home: await canonicalRetirementPath(home),+ userData: await canonicalRetirementPath(userData), profile, connectionId: 'local' }+}++export async function discoverRetirementDestination(target: ChannelTarget, source: RetirementSource): Promise<RetirementDestination> {+ const pkg = target.package+ const artifact: RetirementDestination['artifact'] = {+ url: target.artifactUrl, sha256: pkg.artifact.sha256, size: pkg.artifact.size,+ format: pkg.platform === 'darwin' ? 'zip' : pkg.artifact.key.endsWith('.msixbundle') ? 'msixbundle' : 'msix'+ }+ const 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 }+ }+ 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 || ''+ if (!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.tsnew file mode 100644index 00000000000..d36a02b7692--- /dev/null+++ b/apps/desktop/electron/updater/retirement-host.test.ts@@ -0,0 +1,75 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++import { expect, test } from 'vitest'++import { readDesktopBootPreference, readStartupDesktopPreference } from '../desktop-boot-preference'+import { resolveDesktopHermesHome } from '../data-paths'+import type { PayloadInfo } from '../payload-backend'+import { prepareRetirementStartup, type RetirementStartupOptions } from './retirement-host'+import { MacRetirementAdapter } from './retirement-macos'+import { retirementArgument } from './retirement-receiver'+import { RetirementJournal, retirementDigest, type RetirementRequest } from './retirement-state'++class TestDestination extends MacRetirementAdapter {+ 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 }> {+ 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' } },+ 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 } }+ 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> => {} } }+}++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'))+ await prepareRetirementStartup(options)+ expect((await journal.read()).receiverApplied).toBe(true)+ expect(await readFile(path.join(directory, 'preview-home/witness'), 'utf8')).toBe('untouched')+ const changed: string = JSON.stringify({ profile: 'work', home: path.join(directory, 'other-home') })+ await 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('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(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 }) }+})diff --git a/apps/desktop/electron/updater/retirement-host.ts b/apps/desktop/electron/updater/retirement-host.tsnew file mode 100644index 00000000000..78836727f35--- /dev/null+++ b/apps/desktop/electron/updater/retirement-host.ts@@ -0,0 +1,246 @@+import { open, readFile, readdir, unlink } from 'node:fs/promises'+import type { FileHandle } from 'node:fs/promises'+import path from 'node:path'++import { adoptDesktopHome, readDesktopBootPreference, type DesktopBootPreference } from '../desktop-boot-preference'+import type { PayloadInfo } from '../payload-backend'+import { ChannelResolver, type ChannelRetirement } from './channel'+import type { ChannelRetirementCallbacks, ChannelRetirementStatus } from './channel-strategy'+import { probeRetirementSnapshot, retirementSnapshotTools } from './retirement-compatibility'+import { assertPersistentRetirementHome, 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 { 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')+}++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')+ }+}++/** 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 interface RetirementStartupOptions {+ argv: readonly string[]+ userData: string+ defaultHome: string+ operatorOverride: boolean+ payload: PayloadInfo | null+ /** A live stable process cannot silently retarget already-open databases. */+ runningSelection?: { home: string; profile: string; connectionId: string }+ journalRoot?: string+ adapter?: RetirementAdapter+ assertQualified?: (request: RetirementRequest) => Promise<void>+ probeSnapshot?: (record: RetirementRecord, payload: PayloadInfo) => Promise<void>+}+export interface RetirementReception {+ journal: RetirementJournal+ token: string+ dependencies: RetirementReceiverDependencies+}++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 } }+ }+ 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 file: string = path.join(options.userData, 'active-profile.json')+ let expected: DesktopBootPreference | null = readDesktopBootPreference(file)+ const dependencies: RetirementReceiverDependencies = {+ verifyRunningDestination: async (request: RetirementRequest): Promise<string> => {+ const executable: string = await adapter.verifyRunningDestination(request)+ await (options.assertQualified ?? assertRetirementQualified)(request)+ return executable+ },+ assertCompatibleSnapshot: async (record: RetirementRecord): Promise<void> => {+ await (options.probeSnapshot ?? probeRetirementSnapshot)(record, options.payload!)+ },+ 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 }+ },+ 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.') }+ 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') }+ }+ 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)+ }+ 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 }+ for (const id of await readdir(root)) {+ 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 }+ }+ 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 record = await pending.read()+ await assertRetirementQualified(record.request)+ await nativeRetirementAdapter().activate(record.request, pending)+ return true+}++export interface RetirementHostOptions {+ home: string+ userData: string+ payload: PayloadInfo+ profile: () => string+ isLocal: () => boolean+ stop: () => Promise<void>+ restore: () => Promise<void>+ quit: () => void+ progress: (message: string) => void+}++export class RetirementHost implements ChannelRetirementCallbacks {+ private journal: RetirementJournal | null = null+ constructor(private readonly options: RetirementHostOptions) {}++ 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)+ 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.')+ }+ 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 } }+ }++ async apply(retirement: ChannelRetirement): Promise<UpdaterApplyResultWire> {+ let stopped: boolean = false+ try {+ const request: RetirementRequest = this.journal ? (await this.journal.read()).request : await this.request(retirement)+ 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+ })+ }+ 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 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 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.tsnew file mode 100644index 00000000000..ea7873cd59e--- /dev/null+++ b/apps/desktop/electron/updater/retirement-macos.ts@@ -0,0 +1,305 @@+import { constants } from 'node:fs'+import { access, lstat, mkdir, mkdtemp, readdir, readFile, rename } from 'node:fs/promises'+import path from 'node:path'++import type * as Electron from 'electron'++import { assertNativeRetirementRemoval, type RetirementNativeAdapter } from './retirement'+import {+ assertRetirementStamp,+ assertRunningRetirementStamp,+ downloadRetirementArtifact,+ type NativeCommandResult,+ retirementPathExists,+ runRetirementCommand+} from './retirement-native'+import { retirementArgument } from './retirement-receiver'+import {+ canonicalRetirementPath,+ insideRetirementRoot,+ type RetirementDestination,+ type RetirementJournal,+ type RetirementNativeIdentity,+ type RetirementRequest+} from './retirement-state'++interface MacInfoPlist {+ CFBundleIdentifier: string+ CFBundleShortVersionString: string+ CFBundleExecutable: string+}+interface MacSourceStamp {+ commit: string+ distribution: string+ payload: string+ updateMechanism: string+}++function requireMac(): void {+ if (process.platform !== 'darwin') {+ throw new Error('Native macOS retirement requires macOS')+ }+}++async function assertOwnedBundle(app: string): Promise<void> {+ if (!app.endsWith('.app') || (await canonicalRetirementPath(app)) !== app) {+ throw new Error('Bundle must be a canonical .app path')+ }++ const info: Awaited<ReturnType<typeof lstat>> = await lstat(app)++ if (!info.isDirectory() || !process.getuid || info.uid !== process.getuid() || (info.mode & 0o022) !== 0) {+ throw new Error('App is not privately owned by this user; use its administrator or steward')+ }++ if (await retirementPathExists(path.join(app, 'Contents/_MASReceipt/receipt'))) {+ throw new Error('App Store owns this application')+ }++ await access(path.dirname(app), constants.W_OK)+}++async function verifyMacBundle(identity: RetirementNativeIdentity, app: string = identity.appPath): Promise<string> {+ requireMac()+ await runRetirementCommand('/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=2', app])+ const signature: NativeCommandResult = await runRetirementCommand('/usr/bin/codesign', ['-dv', '--verbose=4', app])++ if (+ /^TeamIdentifier=(.+)$/m.exec(signature.stderr)?.[1] !== identity.signer ||+ /^Identifier=(.+)$/m.exec(signature.stderr)?.[1] !== identity.identity+ ) {+ throw new Error('macOS signing team or identifier mismatch')+ }++ const plistResult: NativeCommandResult = await runRetirementCommand('/usr/bin/plutil', [+ '-convert',+ 'json',+ '-o',+ '-',+ path.join(app, 'Contents/Info.plist')+ ])++ const plist: MacInfoPlist = JSON.parse(plistResult.stdout)++ if (+ plist.CFBundleIdentifier !== identity.identity ||+ plist.CFBundleShortVersionString !== identity.nativeVersion ||+ !plist.CFBundleExecutable ||+ /[/\\]/.test(plist.CFBundleExecutable)+ ) {+ throw new Error('macOS bundle identity or native version mismatch')+ }++ const executable: string = await canonicalRetirementPath(path.join(app, 'Contents/MacOS', plist.CFBundleExecutable))++ if (!insideRetirementRoot(await canonicalRetirementPath(app), executable)) {+ throw new Error('Bundle executable escapes the application')+ }++ const archs: NativeCommandResult = await runRetirementCommand('/usr/bin/lipo', ['-archs', executable])++ if (archs.stdout.trim() !== (identity.architecture === 'arm64' ? 'arm64' : 'x86_64')) {+ throw new Error('macOS native architecture mismatch')+ }++ await runRetirementCommand('/usr/sbin/spctl', ['-a', '-vv', '-t', 'exec', app])++ return executable+}++async function assertNoBundleProcesses(app: string): Promise<void> {+ const result: NativeCommandResult = await runRetirementCommand('/bin/ps', ['-axo', 'comm='])++ if (result.stdout.split('\n').some((command: string): boolean => command.trim().startsWith(`${app}/`))) {+ throw new Error('Application has live processes; stop through its lifecycle owner first')+ }+}++async function stageMacBundle(request: RetirementRequest, journal: RetirementJournal): Promise<string> {+ const artifact: string = await downloadRetirementArtifact(journal, request.destination)++ if (request.destination.artifact.format !== 'zip') {+ throw new Error('macOS retirement requires the signed update ZIP')+ }++ const entries: NativeCommandResult = await runRetirementCommand('/usr/bin/unzip', ['-Z1', artifact])++ for (const name of entries.stdout.split('\n').filter(Boolean)) {+ if (name.startsWith('/') || name.includes('\\') || name.split('/').includes('..')) {+ throw new Error('Unsafe retirement ZIP path')+ }+ }++ const stage: string = await mkdtemp(path.join(journal.directory, 'extract-'))+ await runRetirementCommand('/usr/bin/ditto', ['-x', '-k', artifact, stage], 600_000)+ const apps: string[] = (await readdir(stage)).filter((name: string): boolean => name.endsWith('.app'))++ if (apps.length !== 1) {+ throw new Error('Expected one application in the pinned ZIP')+ }++ const app: string = path.join(stage, apps[0])+ await verifyMacBundle(request.destination, app)+ await assertRetirementStamp(path.join(app, 'Contents/Resources/install-stamp.json'), request.destination)++ return app+}++export class MacRetirementAdapter implements RetirementNativeAdapter {+ async verifyDestination(request: RetirementRequest): Promise<void> {+ await verifyMacBundle(request.destination)+ await assertRetirementStamp(+ path.join(request.destination.appPath, 'Contents/Resources/install-stamp.json'),+ request.destination+ )+ }++ async verifyRunningDestination(request: RetirementRequest): Promise<string> {+ assertRunningRetirementStamp(request.destination)+ await this.verifyDestination(request)+ const executable: string = await verifyMacBundle(request.destination)++ if ((await canonicalRetirementPath(process.execPath)) !== executable) {+ throw new Error('Receiver is not the exact installed stable executable')+ }++ return executable+ }++ async install(request: RetirementRequest, journal: RetirementJournal): Promise<void> {+ requireMac()+ const target: RetirementDestination = request.destination+ const parent: string = path.dirname(target.appPath)++ if ((await canonicalRetirementPath(parent)) !== parent) {+ throw new Error('Destination parent must be canonical')+ }++ await access(parent, constants.W_OK)++ if (await retirementPathExists(target.appPath)) {+ try {+ await this.verifyDestination(request)++ return+ } catch (error) {+ if (!request.consent.replaceExistingStable) {+ throw new Error('Existing stable differs from the exact target; replacement consent required', {+ cause: error+ })+ }+ }++ await assertOwnedBundle(target.appPath)++ const plistOutput: NativeCommandResult = await runRetirementCommand('/usr/bin/plutil', [+ '-convert',+ 'json',+ '-o',+ '-',+ path.join(target.appPath, 'Contents/Info.plist')+ ])++ const previous: MacInfoPlist = JSON.parse(plistOutput.stdout)+ const oldParts: number[] = previous.CFBundleShortVersionString.split('.').map(Number)+ const targetParts: number[] = target.nativeVersion.split('.').map(Number)++ if (+ !/^\d+\.\d+\.\d+$/.test(previous.CFBundleShortVersionString) ||+ !/^\d+\.\d+\.\d+$/.test(target.nativeVersion)+ ) {+ throw new Error('Stable native versions must be numeric release versions')+ }++ const firstDifference: number = oldParts.findIndex(+ (part: number, index: number): boolean => part !== targetParts[index]+ )++ if (firstDifference < 0 || oldParts[firstDifference] > targetParts[firstDifference]) {+ throw new Error('Refusing stable downgrade or same-version replacement')+ }++ await verifyMacBundle({ ...target, nativeVersion: previous.CFBundleShortVersionString })++ const previousStamp: MacSourceStamp = JSON.parse(+ await readFile(path.join(target.appPath, 'Contents/Resources/install-stamp.json'), 'utf8')+ )++ if (+ previousStamp.distribution !== 'desktop-app' ||+ previousStamp.payload !== 'bundled' ||+ previousStamp.updateMechanism !== 'electron-updater'+ ) {+ throw new Error('Existing application has a different steward')+ }++ await assertNoBundleProcesses(target.appPath)+ }++ const extracted: string = await stageMacBundle(request, journal)+ const stagingDirectory: string = await mkdtemp(path.join(parent, `.hermes-retirement-${request.id}-`))+ const staged: string = path.join(stagingDirectory, 'Hermes.app')+ const backup: string = path.join(parent, `.hermes-retirement-${request.id}-previous.app`)++ await mkdir(staged, { mode: 0o700 })+ await runRetirementCommand('/usr/bin/ditto', [extracted, staged], 600_000)++ await verifyMacBundle(target, staged)+ await assertRetirementStamp(path.join(staged, 'Contents/Resources/install-stamp.json'), target)++ if (await retirementPathExists(target.appPath)) {+ if (await retirementPathExists(backup)) {+ throw new Error('Prior stable backup already exists; refusing overwrite')+ }++ await assertNoBundleProcesses(target.appPath)+ await rename(target.appPath, backup)+ }++ await rename(staged, target.appPath)+ await this.verifyDestination(request)+ }++ async activate(request: RetirementRequest, journal: RetirementJournal): Promise<void> {+ await this.verifyDestination(request)+ // -n starts the exact bundle even if another stable instance owns the lock.+ // Electron forwards the argument to that instance; the receiver verifies its own stamp.+ await runRetirementCommand('/usr/bin/open', [+ '-n',+ '-a',+ request.destination.appPath,+ '--args',+ retirementArgument(journal.id, request.token)+ ])+ }++ async removePreview(request: RetirementRequest, journal: RetirementJournal): Promise<void> {+ await assertNativeRetirementRemoval(journal, request)+ await this.verifyRunningDestination(request)+ const source: string = request.source.appPath+ await assertOwnedBundle(source)+ await verifyMacBundle(request.source)++ const stamp: MacSourceStamp = JSON.parse(+ await readFile(path.join(source, 'Contents/Resources/install-stamp.json'), 'utf8')+ )++ if (+ stamp.commit !== request.qualification.sourceCommit ||+ stamp.distribution !== 'desktop-app' ||+ stamp.payload !== 'bundled'+ ) {+ throw new Error('Preview source stamp changed before removal')+ }++ await assertNoBundleProcesses(source)+ const { shell }: typeof Electron = await import('electron')+ await shell.trashItem(source)+ }++ async isPreviewRemoved(request: RetirementRequest): Promise<boolean> {+ requireMac()++ return !(await retirementPathExists(request.source.appPath))+ }+}diff --git a/apps/desktop/electron/updater/retirement-native.test.ts b/apps/desktop/electron/updater/retirement-native.test.tsnew file mode 100644index 00000000000..cec93a44aa0--- /dev/null+++ b/apps/desktop/electron/updater/retirement-native.test.ts@@ -0,0 +1,103 @@+import { createHash } from 'node:crypto'+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+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 { snapshotRetirementHome } from './retirement-preservation'+import type { RetirementDestination } from './retirement-state'++const directories: string[] = []+afterEach(async (): Promise<void> => {+ for (const directory of directories.splice(0)) {+ await rm(directory, { recursive: true, force: true })+ }+})++test('snapshot includes WAL-backed state and private config without copying Electron envelopes', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-retirement-snapshot-'))+ directories.push(directory)+ const home: string = path.join(directory, 'home')+ await mkdir(home)+ await writeFile(path.join(home, 'config.yaml'), 'model: test-model\n')+ const database: DatabaseSync = new DatabaseSync(path.join(home, 'state.db'))+ database.exec(+ "PRAGMA journal_mode=WAL; CREATE TABLE witness(value TEXT); INSERT INTO witness VALUES ('survives-wal')"+ )++ try {+ const snapshot: string = await snapshotRetirementHome(home, path.join(directory, 'snapshot'), {+ python: 'python3',+ backupScript: path.resolve('../../hermes_cli/backup_sqlite.py')+ })++ const copied: DatabaseSync = new DatabaseSync(path.join(snapshot, 'state.db'), { readOnly: true })++ try {+ expect(copied.prepare('SELECT value FROM witness').get()?.value).toBe('survives-wal')+ } finally {+ copied.close()+ }++ expect(await readFile(path.join(snapshot, 'config.yaml'), 'utf8')).toBe('model: test-model\n')+ } finally {+ database.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)+ const artifact: string = path.join(directory, 'stable.zip')+ const bytes: Buffer = Buffer.from('signed bytes are checked by the native host')+ await writeFile(artifact, bytes)++ const target: RetirementDestination = {+ platform: 'darwin',+ appPath: path.join(directory, 'Hermes.app'),+ identity: 'chat.nous.hermes',+ nativeVersion: '1.0.0',+ signer: 'ABCDE12345',+ architecture: 'arm64',+ applicationId: null,+ packageFamilyName: null,+ commit: 'a'.repeat(40),+ artifact: {+ url: 'https://example.com/a.zip',+ sha256: createHash('sha256').update(bytes).digest('hex'),+ size: bytes.length,+ format: 'zip'+ }+ }++ expect((): void => assertRunningRetirementStamp(target)).toThrow('baked stamp')+ await expect(verifyRetirementArtifact(artifact, target.artifact)).resolves.toBeUndefined()+ await writeFile(artifact, Buffer.alloc(bytes.length))+ await expect(verifyRetirementArtifact(artifact, target.artifact)).rejects.toThrow('digest')+ const stamp: string = path.join(directory, 'install-stamp.json')+ await writeFile(+ stamp,+ JSON.stringify({+ commit: target.commit,+ payload: 'bundled',+ distribution: 'desktop-app',+ dirty: false,+ updateMechanism: 'electron-updater'+ })+ )+ await expect(assertRetirementStamp(stamp, target)).resolves.toBeUndefined()+ await writeFile(+ stamp,+ JSON.stringify({+ commit: 'b'.repeat(40),+ payload: 'bundled',+ distribution: 'desktop-app',+ dirty: false,+ updateMechanism: 'external'+ })+ )+ await expect(assertRetirementStamp(stamp, target)).rejects.toThrow('stamp')+})diff --git a/apps/desktop/electron/updater/retirement-native.ts b/apps/desktop/electron/updater/retirement-native.tsnew file mode 100644index 00000000000..be70edeb451--- /dev/null+++ b/apps/desktop/electron/updater/retirement-native.ts@@ -0,0 +1,169 @@+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 { INSTALL_STAMP } from '../install-stamp'++import type { RetirementDestination, RetirementJournal } from './retirement-state'++export interface NativeCommandResult {+ stdout: string+ stderr: string+}++export function runRetirementCommand(+ file: string,+ args: readonly string[],+ timeout: number = 120_000,+ input: string = ''+): Promise<NativeCommandResult> {+ return new Promise<NativeCommandResult>((resolve, reject): void => {+ const child: ReturnType<typeof execFile> = execFile(+ file,+ [...args],+ { encoding: 'utf8', windowsHide: true, timeout, maxBuffer: 4 * 1024 * 1024 },+ (error: Error | null, stdout: string, stderr: string): void => {+ if (error) {+ reject(new Error(`Native retirement operation failed: ${file}: ${stderr}`, { cause: error }))++ return+ }++ resolve({ stdout, stderr })+ }+ )++ child.stdin?.end(input)+ })+}++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+}++interface NativeInstallStamp {+ commit: string+ payload: string+ distribution: string+ dirty: boolean+ updateMechanism: string+}++export function assertRunningRetirementStamp(target: RetirementDestination): void {+ if (+ !INSTALL_STAMP ||+ INSTALL_STAMP.commit !== target.commit ||+ INSTALL_STAMP.payload !== 'bundled' ||+ INSTALL_STAMP.distribution !== 'desktop-app' ||+ INSTALL_STAMP.dirty ||+ INSTALL_STAMP.updateMechanism !== (target.platform === 'darwin' ? 'electron-updater' : 'app-installer')+ ) {+ throw new Error('Running destination baked stamp is not the pinned official stable release')+ }+}++export async function assertRetirementStamp(file: string, target: RetirementDestination): Promise<void> {+ const stamp: NativeInstallStamp = JSON.parse(await readFile(file, 'utf8'))++ if (+ stamp.commit !== target.commit ||+ stamp.payload !== 'bundled' ||+ stamp.distribution !== 'desktop-app' ||+ stamp.dirty !== false ||+ stamp.updateMechanism !== (target.platform === 'darwin' ? 'electron-updater' : 'app-installer')+ ) {+ throw new Error('Destination stamp does not identify the pinned stable bundled release')+ }+}++export async function retirementPathExists(file: string): Promise<boolean> {+ try {+ await lstat(file)++ return true+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {+ return false+ }++ throw error+ }+}diff --git a/apps/desktop/electron/updater/retirement-preservation.test.ts b/apps/desktop/electron/updater/retirement-preservation.test.tsnew file mode 100644index 00000000000..abfc2ec7f98--- /dev/null+++ b/apps/desktop/electron/updater/retirement-preservation.test.ts@@ -0,0 +1,93 @@+import { spawn } from 'node:child_process'+import { once } from 'node:events'+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++import { build } from 'esbuild'+import { expect, test } from 'vitest'++import { snapshotRetirementHome } from './retirement-preservation'+import { RetirementJournal } from './retirement-state'++const tools = { python: process.env.PYTHON || 'python3', repo: path.resolve('../..'), sitePackages: '' }++test('a killed journal owner and interrupted snapshot can be retried without touching live state', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-recovery-'))++ try {+ const home: string = path.join(directory, 'home')+ await mkdir(home)+ await writeFile(path.join(home, 'witness'), 'preserve me')+ const root: string = path.join(directory, 'transactions')+ const id: string = 'a'.repeat(32)+ const journal: RetirementJournal = await RetirementJournal.open(root, id)+ const target: string = path.join(journal.directory, 'snapshot')+ const childFile: string = path.join(directory, 'owner.mjs')+ await build({+ stdin: {+ contents: `+ import { RetirementJournal } from './retirement-state'+ import { mkdir, writeFile } from 'node:fs/promises'+ const journal = await RetirementJournal.open(${JSON.stringify(root)}, ${JSON.stringify(id)})+ await journal.exclusive(async () => {+ await mkdir(${JSON.stringify(target + '.partial')}, {mode: 0o700})+ await writeFile(${JSON.stringify(target + '.partial/stale')}, 'interrupted')+ process.send('locked')+ await new Promise(() => {})+ })+ `,+ resolveDir: path.resolve('electron/updater')+ },+ outfile: childFile,+ bundle: true,+ platform: 'node',+ format: 'esm'+ })+ const child = spawn(process.execPath, [childFile], { stdio: ['ignore', 'pipe', 'pipe', 'ipc'] })++ try {+ await once(child, 'message')+ await expect(journal.exclusive(async (): Promise<void> => {})).rejects.toThrow('busy')+ } finally {+ const exited = once(child, 'exit')+ child.kill('SIGKILL')+ await exited+ }++ const reopened: RetirementJournal = await RetirementJournal.open(root, id)+ await reopened.exclusive(async (): Promise<void> => {+ expect(await snapshotRetirementHome(home, target, tools)).toBe(target)+ })+ expect(await readFile(path.join(target, 'witness'), 'utf8')).toBe('preserve me')+ expect(await readFile(path.join(home, 'witness'), 'utf8')).toBe('preserve me')+ await expect(readFile(path.join(target, 'stale'))).rejects.toMatchObject({ code: 'ENOENT' })+ // A crash after snapshot rename but before journal publication also retries.+ await writeFile(path.join(home, 'witness'), 'latest quiesced state')+ await reopened.exclusive(async (): Promise<void> => {+ await snapshotRetirementHome(home, target, tools)+ })+ expect(await readFile(path.join(target, 'witness'), 'utf8')).toBe('latest quiesced state')+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+})++test.skipIf(process.platform === 'win32')(+ 'snapshot retry refuses a symlink staging root without deleting its target',+ async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-snapshot-link-'))++ try {+ const home: string = path.join(directory, 'home')+ const target: string = path.join(directory, 'snapshot')+ await mkdir(home)+ await writeFile(path.join(home, 'witness'), 'preserve me')+ await symlink(home, `${target}.partial`)+ await expect(snapshotRetirementHome(home, target, tools)).rejects.toThrow('private owned directory')+ expect(await readFile(path.join(home, 'witness'), 'utf8')).toBe('preserve me')+ } finally {+ await rm(directory, { recursive: true, force: true })+ }+ }+)diff --git a/apps/desktop/electron/updater/retirement-preservation.ts b/apps/desktop/electron/updater/retirement-preservation.tsnew file mode 100644index 00000000000..564e4476403--- /dev/null+++ b/apps/desktop/electron/updater/retirement-preservation.ts@@ -0,0 +1,99 @@+import { chmod, copyFile, lstat, mkdir, open, readdir, rename } from 'node:fs/promises'+import type { FileHandle } from 'node:fs/promises'+import path from 'node:path'++import { runRetirementCommand } from './retirement-native'+import { canonicalRetirementPath, insideRetirementRoot } from './retirement-state'++export interface RetirementSnapshotTools {+ python: string+ backupScript: 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')+`++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)++ return header.toString('utf8') === 'SQLite format 3\0'+ } finally {+ await handle.close()+ }+}++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)+ }++ await chmod(output, info.mode & 0o700)+ }+}++/** Caller holds the lifecycle lock. This is private preservation, not a profile export. */+export async function snapshotRetirementHome(+ home: string,+ destination: string,+ tools: RetirementSnapshotTools+): Promise<string> {+ const source: string = await canonicalRetirementPath(home)+ const target: string = await canonicalRetirementPath(destination)++ if (insideRetirementRoot(source, target) || insideRetirementRoot(target, source)) {+ throw new Error('Snapshot and live state roots overlap')+ }++ const partial: string = `${target}.partial`+ await copyStateTree(source, partial, tools)+ await rename(partial, target)++ return target+}diff --git a/apps/desktop/electron/updater/retirement-readiness.ts b/apps/desktop/electron/updater/retirement-readiness.tsnew file mode 100644index 00000000000..c45dfd5ae4f--- /dev/null+++ b/apps/desktop/electron/updater/retirement-readiness.ts@@ -0,0 +1,40 @@+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.tsnew file mode 100644index 00000000000..8f5cc4bbb7a--- /dev/null+++ b/apps/desktop/electron/updater/retirement-receiver.ts@@ -0,0 +1,175 @@+import { randomBytes, timingSafeEqual } from 'node:crypto'++import { recordRetirementReady } from './retirement'+import {+ canonicalRetirementPath,+ type RetirementCorrelation,+ type RetirementJournal,+ type RetirementReady,+ type RetirementRecord,+ type RetirementRequest,+ type RetirementSelection,+ signRetirementReady+} from './retirement-state'++export interface RetirementExistingSelection {+ home: string+ profile: string+ connectionId: string+ operatorOverride: boolean+}++export interface RetirementReceiverDependencies {+ /** 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>+ readSelection(): 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>+ /** Real renderer and selected local/remote backend; finish reauthentication before resolving. */+ assertReady(record: RetirementRecord): Promise<void>+}++const receiverInstance: string = randomBytes(32).toString('hex')++export function retirementArgument(id: string, token: string): string {+ if (!/^[a-f0-9]{32}$/.test(id) || !/^[a-f0-9]{64}$/.test(token)) {+ throw new Error('Invalid retirement correlation')+ }++ return `--hermes-retirement=${id}.${token}`+}++/** Parse only our argument. The journal root is local policy, never a launch argument. */+export function parseRetirementArgument(argv: readonly string[]): RetirementCorrelation | null {+ const values: string[] = argv.filter((arg: string): boolean => arg.startsWith('--hermes-retirement='))++ if (!values.length) {+ return null+ }++ const match: RegExpExecArray | null = /^--hermes-retirement=([a-f0-9]{32})\.([a-f0-9]{64})$/.exec(values[0])++ if (values.length !== 1 || !match) {+ throw new Error('Invalid retirement activation argument')+ }++ return { id: match[1], token: match[2] }+}++function assertToken(record: RetirementRecord, token: string): void {+ if (+ !/^[a-f0-9]{64}$/.test(token) ||+ !timingSafeEqual(Buffer.from(token, 'hex'), Buffer.from(record.request.token, 'hex'))+ ) {+ throw new Error('Retirement correlation mismatch')+ }+}++function sameSelection(current: RetirementExistingSelection, selection: RetirementSelection): boolean {+ return (+ current.home === selection.home &&+ current.profile === selection.profile &&+ current.connectionId === selection.connectionId+ )+}++/** Invoke before normal home selection, and on the existing stable second-instance path. */+export async function receiveRetirement(+ journal: RetirementJournal,+ token: string,+ deps: RetirementReceiverDependencies+): Promise<RetirementSelection> {+ return journal.exclusive(async (): Promise<RetirementSelection> => {+ const record: RetirementRecord = await journal.read()+ assertToken(record, token)++ if (record.stage !== 'destination-installed' && record.stage !== 'destination-ready') {+ throw new Error('Retirement is not awaiting this destination')+ }++ await journal.assertPaths(record.request)+ await deps.verifyRunningDestination(record.request)++ if (record.request.selection.connectionId !== 'local' && !record.request.selection.reauthenticate) {+ throw new Error(+ 'Reauthentication required: encrypted connection credentials cannot transfer between applications'+ )+ }++ if (record.receiverApplied) {+ const active: RetirementExistingSelection | null = await deps.readSelection()++ if (active && !sameSelection(active, record.request.selection)) {+ throw new Error('Stable workspace changed after retirement adoption; explicit forward recovery is required')+ }++ return record.request.selection+ }++ 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.previousSelection = current+ record.receiverStarted = true+ await journal.write(record)+ }++ await deps.adoptSelection(record, record.previousSelection)+ record.receiverApplied = true+ await journal.write(record)++ return record.request.selection+ })+}++/** Readiness is authored only by the verified destination, never by the installer. */+export async function completeRetirementReception(+ journal: RetirementJournal,+ token: string,+ deps: RetirementReceiverDependencies+): Promise<RetirementReady> {+ const record: RetirementRecord = await journal.read()+ assertToken(record, token)++ if (!record.receiverApplied || record.stage !== 'destination-installed') {+ throw new Error('Retirement state has not been adopted')+ }++ const executable: string = await deps.verifyRunningDestination(record.request)+ await deps.assertReady(record)++ const ready: RetirementReady = signRetirementReady(record.request, {+ requestDigest: record.requestDigest,+ id: record.request.id,+ home: record.state.selectedHome,+ profile: record.request.selection.profile,+ connectionId: record.request.selection.connectionId,+ executable,+ commit: record.request.destination.commit,+ pid: process.pid,+ instance: receiverInstance+ })++ await recordRetirementReady(journal, ready)++ return ready+}diff --git a/apps/desktop/electron/updater/retirement-state.ts b/apps/desktop/electron/updater/retirement-state.tsnew file mode 100644index 00000000000..637ce257fa5--- /dev/null+++ b/apps/desktop/electron/updater/retirement-state.ts@@ -0,0 +1,424 @@+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'+import { constants } from 'node:fs'+import { lstat, mkdir, open, readFile, realpath, rename, unlink } from 'node:fs/promises'+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'++export type RetirementStage =+ 'prepared' | 'destination-installed' | 'destination-ready' | 'preview-removed' | 'complete'+export type RetirementPlatform = 'darwin' | 'win32'++export interface RetirementNativeIdentity {+ platform: RetirementPlatform+ appPath: string+ identity: string+ nativeVersion: string+ signer: string+ architecture: 'arm64' | 'x64'+ applicationId: string | null+}++export interface RetirementSource extends RetirementNativeIdentity {+ executable: string+ packageFullName: string | null+ home: string+ userData: string+ profile: string+ connectionId: string+ /** Include the AppX LocalState/LocalCache roots, not only InstallLocation. */+ removalRoots: string[]+}++export interface RetirementDestination extends RetirementNativeIdentity {+ packageFamilyName: string | null+ artifact: { url: string; sha256: string; size: number; format: 'zip' | 'msix' | 'msixbundle' }+ commit: string+}++export interface RetirementSelection {+ home: string+ profile: string+ connectionId: string+ choice: 'open-preview' | 'keep-stable'+ reauthenticate: boolean+ conflictConsent?: { home: string; profile: string; connectionId: string; operatorOverride: boolean }+}++export interface RetirementRequest {+ protocol: 1+ id: string+ token: string+ source: RetirementSource+ destination: RetirementDestination+ selection: RetirementSelection+ qualification: { sha256: string; sourceCommit: string; destinationCommit: string; receiverProtocol: 1; sourceBuild?: ChannelBuild }+ consent: { install: boolean; removePreview: boolean; replaceExistingStable: boolean }+}++export interface RetirementStateSnapshot {+ snapshotHome: string+ selectedHome: string+}++export interface RetirementReady {+ requestDigest: string+ id: string+ home: string+ profile: string+ connectionId: string+ executable: string+ commit: string+ pid: number+ instance: string+ mac: string+}++export interface RetirementRecord {+ request: RetirementRequest+ requestDigest: string+ stage: RetirementStage+ state: RetirementStateSnapshot+ receiverStarted: boolean+ receiverApplied: boolean+ previousSelection: { home: string; profile: string; connectionId: string; operatorOverride: boolean } | null+ ready: RetirementReady | null+}++export interface RetirementCorrelation {+ id: string+ token: string+}++export function newRetirementCorrelation(): RetirementCorrelation {+ return { id: randomBytes(16).toString('hex'), token: randomBytes(32).toString('hex') }+}++export function defaultRetirementRoot(): string {+ return path.join(os.homedir(), '.hermes-desktop-retirement')+}++async function protectWindowsDirectory(directory: string): Promise<void> {+ const encoded: string = Buffer.from(directory, 'utf8').toString('base64')+ const script: string = `$ErrorActionPreference='Stop'; $p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}')); $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User; $acl=[Security.AccessControl.DirectorySecurity]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true,$false); $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')); Set-Acl -LiteralPath $p -AclObject $acl; $read=Get-Acl -LiteralPath $p; if ($read.GetOwner([Security.Principal.SecurityIdentifier]).Value -cne $sid.Value -or -not $read.AreAccessRulesProtected) { throw 'Private journal ACL did not apply' }; foreach ($rule in $read.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) { if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -cne $sid.Value) { throw 'Journal ACL grants another identity access' } }`+ await runRetirementCommand(+ path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),+ ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]+ )+}++export function retirementDigest(request: RetirementRequest): string {+ return createHash('sha256').update(JSON.stringify(request)).digest('hex')+}++export function insideRetirementRoot(root: string, candidate: string): boolean {+ const relative: string = path.relative(root, candidate)++ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))+}++export async function canonicalRetirementPath(candidate: string): Promise<string> {+ if (!path.isAbsolute(candidate) || candidate.includes('\0')) {+ throw new Error('Retirement requires absolute local paths')+ }++ try {+ return await realpath(candidate)+ } catch (error) {+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') {+ throw error+ }++ const parent: string = path.dirname(candidate)++ if (parent === candidate) {+ throw error+ }++ return path.join(await canonicalRetirementPath(parent), path.basename(candidate))+ }+}++export function validateRetirementRequest(request: RetirementRequest): void {+ if (request.protocol !== 1 || !/^[a-f0-9]{32}$/.test(request.id) || !/^[a-f0-9]{64}$/.test(request.token)) {+ throw new Error('Invalid retirement correlation')+ }++ if (!request.consent.install || !request.consent.removePreview) {+ throw new Error('Retirement consent required')+ }++ const destination: RetirementDestination = request.destination+ validateRetirementTarget(request)++ if (request.source.platform !== destination.platform || request.source.identity === destination.identity) {+ throw new Error('Retirement must cross native identities on one platform')+ }++ for (const identity of [request.source, destination]) {+ if (+ !identity.identity ||+ !identity.signer ||+ !identity.nativeVersion ||+ !['arm64', 'x64'].includes(identity.architecture)+ ) {+ throw new Error('Incomplete native retirement identity')+ }+ }++ for (const profile of [request.source.profile, request.selection.profile]) {+ if (!/^[a-zA-Z0-9_-]+$/.test(profile)) {+ throw new Error('Invalid retirement profile')+ }+ }++ if (!request.selection.connectionId || !request.source.removalRoots.length) {+ throw new Error('Incomplete retirement state inventory')+ }+}++function validateRetirementTarget(request: RetirementRequest): void {+ const destination: RetirementDestination = request.destination++ if (+ !/^[a-f0-9]{40}$/.test(destination.commit) ||+ !/^[a-f0-9]{64}$/.test(destination.artifact.sha256) ||+ !Number.isSafeInteger(destination.artifact.size) ||+ destination.artifact.size <= 0+ ) {+ throw new Error('Invalid pinned retirement artifact')+ }++ const url: URL = new URL(destination.artifact.url)++ if (url.protocol !== 'https:' || url.username || url.password || url.hash) {+ throw new Error('Retirement requires public HTTPS artifact URL')+ }++ 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)+ ) {+ throw new Error('Missing exact retirement qualification')+ }+}++function receiptMac(request: RetirementRequest, ready: Omit<RetirementReady, 'mac'>): string {+ return createHmac('sha256', Buffer.from(request.token, 'hex')).update(JSON.stringify(ready)).digest('hex')+}++export function signRetirementReady(request: RetirementRequest, ready: Omit<RetirementReady, 'mac'>): RetirementReady {+ return { ...ready, mac: receiptMac(request, ready) }+}++export function assertRetirementReady(record: RetirementRecord, ready: RetirementReady): void {+ const { mac, ...body }: RetirementReady = ready+ const expected: string = receiptMac(record.request, body)++ if (+ !/^[a-f0-9]{64}$/.test(mac) ||+ !timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(mac, 'hex')) ||+ ready.id !== record.request.id ||+ ready.requestDigest !== record.requestDigest ||+ ready.home !== record.state.selectedHome ||+ ready.profile !== record.request.selection.profile ||+ ready.connectionId !== record.request.selection.connectionId ||+ ready.commit !== record.request.destination.commit ||+ !insideRetirementRoot(record.request.destination.appPath, ready.executable) ||+ !Number.isSafeInteger(ready.pid) ||+ ready.pid <= 0 ||+ !/^[a-f0-9]{64}$/.test(ready.instance)+ ) {+ throw new Error('Stale or mismatched retirement readiness receipt')+ }+}++/** Root must be private physical storage, outside AppX virtualization and removal roots. */+export class RetirementJournal {+ readonly directory: string+ private constructor(+ readonly root: string,+ readonly id: string+ ) {+ this.directory = path.join(root, id)+ }++ static async open(root: string, id: string): Promise<RetirementJournal> {+ if (!/^[a-f0-9]{32}$/.test(id)) {+ throw new Error('Invalid retirement transaction ID')+ }++ if ((await canonicalRetirementPath(root)) !== path.resolve(root)) {+ throw new Error('Journal root must not be a symlink')+ }++ await mkdir(root, { recursive: true, mode: 0o700 })++ const rootInfo: Awaited<ReturnType<typeof lstat>> = await lstat(root)++ if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink()) {+ throw new Error('Journal root must be an owned directory')+ }++ if (process.platform === 'win32') {+ await protectWindowsDirectory(root)+ }++ await mkdir(path.join(root, id), { mode: 0o700 }).catch((error: NodeJS.ErrnoException): void => {+ if (error.code !== 'EEXIST') {+ throw error+ }+ })++ for (const directory of [root, path.join(root, id)]) {+ const info: Awaited<ReturnType<typeof lstat>> = await lstat(directory)++ if (+ !info.isDirectory() ||+ info.isSymbolicLink() ||+ (process.platform !== 'win32' &&+ ((info.mode & 0o077) !== 0 || !process.getuid || info.uid !== process.getuid()))+ ) {+ throw new Error('Retirement journal is not private and owned by this user')+ }+ }++ if (process.platform === 'win32') {+ await protectWindowsDirectory(path.join(root, id))+ }++ return new RetirementJournal(root, id)+ }++ async assertPaths(request: RetirementRequest): Promise<void> {+ const roots: string[] = await Promise.all(+ [request.source.appPath, ...request.source.removalRoots].map(canonicalRetirementPath)+ )++ for (const candidate of [this.directory, request.selection.home, request.source.home, request.source.userData]) {+ const canonical: string = await canonicalRetirementPath(candidate)++ if (roots.some((root: string): boolean => insideRetirementRoot(root, canonical))) {+ throw new Error('State or journal is inside the preview removal footprint; preserve it before retirement')+ }+ }++ const sourceApp: string = await canonicalRetirementPath(request.source.appPath)+ const destinationApp: string = await canonicalRetirementPath(request.destination.appPath)++ if (insideRetirementRoot(sourceApp, destinationApp) || insideRetirementRoot(destinationApp, sourceApp)) {+ throw new Error('Source and destination application paths overlap')+ }+ }++ async read(): Promise<RetirementRecord> {+ const handle: FileHandle = await open(+ path.join(this.directory, 'journal.json'),+ constants.O_RDONLY | constants.O_NOFOLLOW+ )++ try {+ const record: RetirementRecord = JSON.parse(await handle.readFile('utf8'))+ validateRetirementRequest(record.request)++ if (+ record.request.id !== this.id ||+ record.requestDigest !== retirementDigest(record.request) ||+ !['prepared', 'destination-installed', 'destination-ready', 'preview-removed', 'complete'].includes(+ record.stage+ )+ ) {+ throw new Error('Retirement journal binding mismatch')+ }++ if (record.ready) {+ assertRetirementReady(record, record.ready)+ }++ return record+ } finally {+ await handle.close()+ }+ }++ async write(record: RetirementRecord): Promise<void> {+ const temporary: string = path.join(this.directory, `${randomBytes(16).toString('hex')}.partial`)+ const handle: FileHandle = await open(temporary, 'wx', 0o600)++ try {+ await handle.writeFile(JSON.stringify(record))+ await handle.sync()+ } finally {+ await handle.close()+ }++ await rename(temporary, path.join(this.directory, 'journal.json'))++ if (process.platform !== 'win32') {+ const directory: FileHandle = await open(this.directory, 'r')++ try {+ await directory.sync()+ } finally {+ await directory.close()+ }+ }+ }++ async exclusive<T>(operation: () => Promise<T>): Promise<T> {+ const lock: string = path.join(this.directory, 'writer.lock')+ let handle: FileHandle++ try {+ handle = await open(lock, 'wx', 0o600)+ } catch (error) {+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') {+ throw error+ }++ const pid: number = Number(await readFile(lock, 'utf8'))++ if (!Number.isSafeInteger(pid) || pid <= 0) {+ throw new Error('Retirement journal lock needs manual recovery')+ }++ try {+ process.kill(pid, 0)+ } catch (probe) {+ if (probe instanceof Error && 'code' in probe && probe.code === 'ESRCH') {+ const reaper: FileHandle = await open(`${lock}.reclaim`, 'wx', 0o600)++ try {+ if (Number(await readFile(lock, 'utf8')) === pid) {+ await unlink(lock)+ }+ } finally {+ await reaper.close()+ await unlink(`${lock}.reclaim`)+ }++ return this.exclusive(operation)+ }++ throw probe+ }++ throw new Error('Retirement transaction is busy')+ }++ try {+ await handle.writeFile(String(process.pid))+ await handle.sync()++ return await operation()+ } finally {+ await handle.close()+ await unlink(lock)+ }+ }+}diff --git a/apps/desktop/electron/updater/retirement-windows.test.ts b/apps/desktop/electron/updater/retirement-windows.test.tsnew file mode 100644index 00000000000..d569d24e753--- /dev/null+++ b/apps/desktop/electron/updater/retirement-windows.test.ts@@ -0,0 +1,90 @@+import { createHash } from 'node:crypto'+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++import { expect, test } from 'vitest'++import { WindowsRetirementAdapter } from './retirement-windows'+import type { NativeCommandResult } from './retirement-native'+import { RetirementJournal, type RetirementRequest } from './retirement-state'+import { runRetirementPowerShell } from './retirement-discovery'++function windowsRequest(): RetirementRequest {+ const native = { platform: 'win32' as const, architecture: 'x64' as const, signer: 'CN=Fixture', nativeVersion: '1.2.3.0', applicationId: 'HermesBundled' }+ return { protocol: 1, id: 'a'.repeat(32), token: 'b'.repeat(64),+ source: { ...native, identity: 'NousResearch.Preview', appPath: 'C:\\Apps\\Preview', executable: 'C:\\Apps\\Preview\\preview.exe',+ packageFullName: 'NousResearch.Preview_1.0.0.0_x64__abcdefghijklm', home: 'C:\\home', userData: 'C:\\desktop', profile: 'default', connectionId: 'local', removalRoots: ['C:\\Apps\\Preview'] },+ destination: { ...native, identity: 'NousResearch.HermesBundled', appPath: 'C:\\Apps\\Stable', packageFamilyName: 'NousResearch.HermesBundled_abcdefghijklm', commit: 'c'.repeat(40),+ artifact: { url: 'https://example.com/releases/tag/v1.2.3/stable.msixbundle', sha256: 'd'.repeat(64), size: 1, format: 'msixbundle' } },+ 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: 'com.nousresearch.preview', appNamePascal: 'Preview', artifactNamePascal: 'Preview', cliName: 'preview', windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' } },+ selection: { home: 'C:\\home', profile: 'default', connectionId: 'local', choice: 'open-preview', reauthenticate: false },+ consent: { install: true, removePreview: true, replaceExistingStable: false } }+}++test('pinned installation precedes metadata-only updater registration and exact read-back', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-windows-install-'))+ try {+ const request: RetirementRequest = windowsRequest()+ const journal: RetirementJournal = await RetirementJournal.open(directory, request.id)+ const bytes: Buffer = Buffer.from('native signature verification belongs to the command boundary')+ request.destination.artifact.size = bytes.length+ request.destination.artifact.sha256 = createHash('sha256').update(bytes).digest('hex')+ const artifact: string = path.join(journal.directory, 'destination.msixbundle')+ await writeFile(artifact, bytes)+ const operations: string[] = []+ const command = async (_script: string, input: string): Promise<NativeCommandResult> => {+ const payload: { operation: string; artifact: string | null } = JSON.parse(input)+ operations.push(payload.operation)+ expect(payload.artifact).toBe(payload.operation === 'install' ? artifact : null)+ return { stdout: '{}', stderr: '' }+ }+ await new WindowsRetirementAdapter(command).install(request, journal)+ expect(operations).toEqual(['install', 'register-updater', 'verify'])+ operations.length = 0+ const unavailable = async (script: string, input: string): Promise<NativeCommandResult> => {+ const payload: { operation: string } = JSON.parse(input)+ if (payload.operation === 'register-updater') { throw new Error('native registration failed') }+ return command(script, input)+ }+ await expect(new WindowsRetirementAdapter(unavailable).install(request, journal)).rejects.toThrow('registration failed')+ expect(operations).toEqual(['install'])+ operations.length = 0+ await writeFile(artifact, Buffer.alloc(bytes.length))+ await expect(new WindowsRetirementAdapter(command).install(request, journal)).rejects.toThrow('digest')+ expect(operations).toEqual([])+ } finally { await rm(directory, { recursive: true, force: true }) }+})++// Native Windows lane: require the real source-registration API; no package writes.+test.runIf(process.platform === 'win32')('Windows exposes metadata-only update registration and current-user WinRT queries', async (): Promise<void> => {+ const result: NativeCommandResult = await runRetirementPowerShell(String.raw`+$ErrorActionPreference='Stop'+Get-Command Set-AppxPackageAutoUpdateSettings -ErrorAction Stop | Out-Null+$manager=[Windows.Management.Deployment.PackageManager,Windows.Management.Deployment,ContentType=WindowsRuntime]::new()+$packages=@(Get-AppxPackage | Where-Object { $_.Status.ToString() -eq 'Ok' })+if (-not $packages.Count) { throw 'Native runner has no current-user packages to query' }+$native=$manager.FindPackageForUser('', $packages[0].PackageFullName)+$source=$native.GetAppInstallerInfo()+@{ found=($native.Id.FullName -ceq $packages[0].PackageFullName) } | ConvertTo-Json -Compress+`)+ expect(JSON.parse(result.stdout)).toEqual({ found: true })+ const request: RetirementRequest = windowsRequest()+ request.destination.identity = `NousResearch.RetirementProbe${Date.now()}`+ await expect(new WindowsRetirementAdapter().verifyDestination(request)).rejects.toThrow('Expected exactly one current-user package')+})++test('native verification binds the subsequent stable updater to the same archive authority', async (): Promise<void> => {+ const request: RetirementRequest = windowsRequest()+ let payload: { appInstallerUri: string } | undefined+ const command = async (_script: string, input: string): Promise<NativeCommandResult> => {+ payload = JSON.parse(input)+ return { stdout: '{}', stderr: '' }+ }+ await new WindowsRetirementAdapter(command).verifyDestination(request)+ expect(payload?.appInstallerUri).toBe('https://example.com/releases/win32/stable/stable.appinstaller')+ request.destination.artifact.url = 'https://other.example/releases/tag/v1.2.3/stable.msixbundle'+ await expect(new WindowsRetirementAdapter(command).verifyDestination(request)).rejects.toThrow('authority')+})diff --git a/apps/desktop/electron/updater/retirement-windows.ts b/apps/desktop/electron/updater/retirement-windows.tsnew file mode 100644index 00000000000..5dc58faa3f6--- /dev/null+++ b/apps/desktop/electron/updater/retirement-windows.ts@@ -0,0 +1,240 @@+import path from 'node:path'++import { assertNativeRetirementRemoval, type RetirementNativeAdapter } from './retirement'+import {+ assertRunningRetirementStamp,+ downloadRetirementArtifact,+ type NativeCommandResult,+ runRetirementCommand+} from './retirement-native'+import { retirementArgument } from './retirement-receiver'+import { canonicalRetirementPath, type RetirementJournal, type RetirementRequest } from './retirement-state'++interface WindowsInstalled {+ executable: string+ packageFullName: string+ appPath: string+}+type WindowsOperation = 'install' | '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.+const windowsNativeScript: string = String.raw`+$ErrorActionPreference = 'Stop'+Set-StrictMode -Version Latest+[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)+Add-Type -AssemblyName System.IO.Compression.FileSystem+function Read-ZipXml($zip, [string]$name) {+ $entries = @($zip.Entries | Where-Object { $_.FullName -ceq $name })+ if ($entries.Count -ne 1) { throw 'Ambiguous package manifest' }+ $settings = [Xml.XmlReaderSettings]::new()+ $settings.DtdProcessing = [Xml.DtdProcessing]::Prohibit+ $settings.XmlResolver = $null+ $stream = $entries[0].Open()+ $reader = [Xml.XmlReader]::Create($stream, $settings)+ try {+ $xml = [Xml.XmlDocument]::new(); $xml.XmlResolver = $null; $xml.Load($reader)+ return ,$xml+ } finally { $reader.Dispose(); $stream.Dispose() }+}+function Assert-Artifact {+ if ((Get-FileHash -Algorithm SHA256 -LiteralPath $p.artifact).Hash.ToLowerInvariant() -cne $p.request.destination.artifact.sha256) { throw 'Artifact digest mismatch' }+ $signature = Get-AuthenticodeSignature -LiteralPath $p.artifact+ if ($signature.Status -ne 'Valid' -or -not $signature.SignerCertificate -or $signature.SignerCertificate.Subject -cne $d.signer) { throw 'Artifact signature/publisher mismatch' }+ $zip = [IO.Compression.ZipFile]::OpenRead($p.artifact)+ try {+ if ($d.artifact.format -ceq 'msixbundle') {+ $xml = Read-ZipXml $zip 'AppxMetadata/AppxBundleManifest.xml'+ $identity = $xml.Bundle.Identity+ $slices = @($xml.Bundle.Packages.Package | Where-Object { $_.Type -ceq 'application' -and $_.Architecture -ceq $d.architecture })+ if ($slices.Count -ne 1 -or $slices[0].Version -cne $d.nativeVersion) { throw 'Native slice mismatch' }+ } elseif ($d.artifact.format -ceq 'msix') {+ $xml = Read-ZipXml $zip 'AppxManifest.xml'+ $identity = $xml.Package.Identity+ if ($identity.ProcessorArchitecture -cne $d.architecture) { throw 'Native architecture mismatch' }+ } else { throw 'Expected MSIX or MSIXBUNDLE' }+ if ($identity.Name -cne $d.identity -or $identity.Publisher -cne $d.signer -or $identity.Version -cne $d.nativeVersion) { throw 'Artifact native identity mismatch' }+ } finally { $zip.Dispose() }+}+function Get-ExactPackage($identity, [bool]$required) {+ $packages = @(Get-AppxPackage -Name $identity.identity | Where-Object { $_.Name -ceq $identity.identity })+ if (-not $packages.Count -and -not $required) { return $null }+ if ($packages.Count -ne 1) { throw 'Expected exactly one current-user package' }+ $pkg = $packages[0]+ if ($pkg.Publisher -cne $identity.signer -or $pkg.Architecture.ToString() -ine $identity.architecture -or $pkg.Status.ToString() -cne 'Ok' -or $pkg.IsDevelopmentMode) { throw 'Native identity/status mismatch' }+ return $pkg+}+function Assert-Sideload($pkg) {+ if ($pkg.SignatureKind.ToString() -cne 'Developer' -or $pkg.NonRemovable -or $pkg.IsPartiallyStaged) { throw 'Package is Store/system/managed; its steward must update or remove it' }+}+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 {+ $pkg = Get-ExactPackage $d $true+ 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 })+ if ($apps.Count -ne 1) { throw 'Registered destination application missing' }+ $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' }+ return @{ executable=$exe; packageFullName=$pkg.PackageFullName; appPath=$pkg.InstallLocation }+}+$d = $p.request.destination+switch ($p.operation) {+ 'install' {+ $existing = Get-ExactPackage $d $false+ if ($existing -and $existing.Version.ToString() -ceq $d.nativeVersion) {+ Assert-Destination | ConvertTo-Json -Compress+ break+ }+ if ($existing) {+ Assert-Sideload $existing+ if (-not $p.request.consent.replaceExistingStable -or [version]$existing.Version -ge [version]$d.nativeVersion) { throw 'Existing stable requires steward update or explicit upgrade consent' }+ Assert-NoProcesses $existing+ }+ Assert-Artifact+ Add-AppxPackage -Path $p.artifact -ErrorAction Stop+ Assert-Destination | ConvertTo-Json -Compress+ }+ 'verify' { Assert-Destination | ConvertTo-Json -Compress }+ 'activate' {+ $installed = Assert-Destination+ Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;+[ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]+interface IRetirementActivation {+ [PreserveSig] int ActivateApplication([MarshalAs(UnmanagedType.LPWStr)] string id, [MarshalAs(UnmanagedType.LPWStr)] string args, uint options, out uint pid);+ [PreserveSig] int ActivateForFile([MarshalAs(UnmanagedType.LPWStr)] string id, IntPtr items, [MarshalAs(UnmanagedType.LPWStr)] string verb, out uint pid);+ [PreserveSig] int ActivateForProtocol([MarshalAs(UnmanagedType.LPWStr)] string id, IntPtr items, out uint pid);+}+public static class RetirementActivation {+ public static uint Launch(string id, string args) {+ object manager = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C")));+ try { uint pid; Marshal.ThrowExceptionForHR(((IRetirementActivation)manager).ActivateApplication(id, args, 0, out pid)); return pid; }+ finally { Marshal.FinalReleaseComObject(manager); }+ }+}+'@+ $pidValue = [RetirementActivation]::Launch(($d.packageFamilyName + '!' + $d.applicationId), $p.argument)+ @{ pid=$pidValue } | ConvertTo-Json -Compress+ }+ 'remove' {+ $installed = Assert-Destination+ if ($installed.executable -ine $p.receiverExecutable) { throw 'Cleanup must run from the destination executable' }+ $source = Get-ExactPackage $p.request.source $false+ if (-not $source) { break }+ if ($source.PackageFullName -cne $p.request.source.packageFullName -or $source.InstallLocation -ine $p.request.source.appPath -or $source.Version.ToString() -cne $p.request.source.nativeVersion) { throw 'Preview package changed before removal' }+ Assert-Sideload $source+ Assert-NoProcesses $source+ $packageData = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) ('Packages\' + $source.PackageFamilyName)+ if (Test-Path -LiteralPath $packageData) {+ # Remove-AppxPackage -PreserveApplicationData only supports development+ # registrations. Archive signed sideload data outside the package instead;+ # encrypted envelopes are retained for recovery, never imported into stable.+ $archive=Join-Path $p.journalDirectory 'preview-package-data'+ $entries=@(Get-ChildItem -LiteralPath $packageData -Recurse -Force -ErrorAction Stop)+ if (@($entries | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint }).Count) { throw 'Package data contains a reparse point; preserve its target manually before removal' }+ New-Item -ItemType Directory -Path $archive -Force | Out-Null+ & "$env:SystemRoot\System32\robocopy.exe" $packageData $archive /E /COPY:DAT /DCOPY:DAT /XJ /R:0 /W:0 /NFL /NDL /NJH /NJS | Out-Null+ if ($LASTEXITCODE -gt 7) { throw 'Package-private data archive failed; preview preserved' }+ foreach ($entry in @($entries | Where-Object { -not $_.PSIsContainer })) {+ $relative=$entry.FullName.Substring($packageData.Length).TrimStart('\')+ $copy=Join-Path $archive $relative+ if (-not (Test-Path -LiteralPath $copy -PathType Leaf) -or (Get-FileHash -LiteralPath $copy -Algorithm SHA256).Hash -cne (Get-FileHash -LiteralPath $entry.FullName -Algorithm SHA256).Hash) { throw 'Package-private data archive verification failed; preview preserved' }+ }+ }+ $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' }+ Assert-NoProcesses $source+ Remove-AppxPackage -Package $source.PackageFullName -ErrorAction Stop+ if (Get-ExactPackage $p.request.source $false) { throw 'Preview package remains registered' }+ }+ 'removed' {+ $source = Get-ExactPackage $p.request.source $false+ @{ removed=($null -eq $source) } | ConvertTo-Json -Compress+ }+}+`++export class WindowsRetirementAdapter implements RetirementNativeAdapter {+ 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') {+ throw new Error('Native Windows retirement requires Windows')+ }++ if (+ !request.destination.packageFamilyName ||+ !request.destination.applicationId ||+ !request.source.packageFullName+ ) {+ throw new Error('Exact AppX family/application/full-name bindings are required')+ }++ const payload: string = JSON.stringify({+ operation,+ request,+ artifact,+ journalDirectory,+ 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+ )++ return result.stdout.trim()+ }++ async install(request: RetirementRequest, journal: RetirementJournal): Promise<void> {+ const artifact: string = await downloadRetirementArtifact(journal, request.destination)+ await this.run('install', request, artifact)+ }++ async verifyDestination(request: RetirementRequest): Promise<void> {+ await this.run('verify', request)+ }++ async verifyRunningDestination(request: RetirementRequest): Promise<string> {+ assertRunningRetirementStamp(request.destination)+ const installed: WindowsInstalled = JSON.parse(await this.run('verify', request))+ const running: string = await canonicalRetirementPath(process.execPath)++ if (running.toLowerCase() !== (await canonicalRetirementPath(installed.executable)).toLowerCase()) {+ throw new Error('Receiver is not the exact registered stable executable')+ }++ return installed.executable+ }++ async activate(request: RetirementRequest, _journal: RetirementJournal): Promise<void> {+ await this.run('activate', request)+ }++ async removePreview(request: RetirementRequest, journal: RetirementJournal): Promise<void> {+ await assertNativeRetirementRemoval(journal, request)+ await this.verifyRunningDestination(request)+ await this.run('remove', request, null, journal.directory)+ }++ async isPreviewRemoved(request: RetirementRequest): Promise<boolean> {+ const result: { removed: boolean } = JSON.parse(await this.run('removed', request))++ return result.removed === true+ }+}diff --git a/apps/desktop/electron/updater/retirement.test.ts b/apps/desktop/electron/updater/retirement.test.tsnew file mode 100644index 00000000000..dde592abd1d--- /dev/null+++ b/apps/desktop/electron/updater/retirement.test.ts@@ -0,0 +1,293 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++import { afterEach, expect, test } from 'vitest'++import { prepareRetirement, resumeRetirement, type RetirementDependencies } from './retirement'+import { MacRetirementAdapter } from './retirement-macos'+import {+ completeRetirementReception,+ receiveRetirement,+ type RetirementReceiverDependencies+} from './retirement-receiver'+import {+ RetirementJournal,+ type RetirementReady,+ type RetirementRecord,+ type RetirementRequest+} from './retirement-state'+import { WindowsRetirementAdapter } from './retirement-windows'++const temporary: string[] = []++afterEach(async (): Promise<void> => {+ for (const directory of temporary.splice(0)) {+ await rm(directory, { recursive: true, force: true })+ }+})++async function fixture(): Promise<{+ store: RetirementJournal+ request: RetirementRequest+ calls: string[]+ deps: RetirementDependencies+}> {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-retirement-'))+ temporary.push(directory)+ const home: string = path.join(directory, 'home')+ const userData: string = path.join(directory, 'preview-user-data')+ const sourceApp: string = path.join(directory, 'Preview.app')+ await Promise.all([mkdir(home), mkdir(userData), mkdir(sourceApp)])+ await writeFile(path.join(home, 'witness'), 'preserve me')+ const snapshot: string = path.join(directory, 'snapshot')+ await mkdir(snapshot)+ await writeFile(path.join(snapshot, 'witness'), 'preserve me')++ const request: RetirementRequest = {+ protocol: 1,+ id: 'a'.repeat(32),+ token: 'b'.repeat(64),+ source: {+ platform: 'darwin',+ appPath: sourceApp,+ executable: path.join(sourceApp, 'Contents/MacOS/Preview'),+ identity: 'chat.nous.preview',+ nativeVersion: '0.0.2',+ signer: 'ABCDE12345',+ architecture: 'arm64',+ packageFullName: null,+ applicationId: null,+ home,+ userData,+ profile: 'default',+ connectionId: 'local',+ removalRoots: [sourceApp]+ },+ destination: {+ platform: 'darwin',+ appPath: path.join(directory, 'Hermes.app'),+ identity: 'chat.nous.hermes',+ nativeVersion: '1.0.0',+ signer: 'ABCDE12345',+ architecture: 'arm64',+ applicationId: null,+ packageFamilyName: null,+ artifact: { url: 'https://example.com/stable.zip', sha256: 'c'.repeat(64), size: 123, format: 'zip' },+ 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+ },+ consent: { install: true, removePreview: true, replaceExistingStable: false }+ }++ const calls: string[] = []+ const store: RetirementJournal = await RetirementJournal.open(path.join(directory, 'transactions'), request.id)++ const deps: RetirementDependencies = {+ assertQualified: async (): Promise<void> => {+ calls.push('qualified')+ },+ prepareState: async (): Promise<{ snapshotHome: string; selectedHome: string }> => {+ calls.push('snapshot')++ return { snapshotHome: snapshot, selectedHome: home }+ },+ acquireLifecycle: async (): Promise<() => Promise<void>> => async (): Promise<void> => {},+ assertSourceQuiescent: async (): Promise<void> => {+ calls.push('quiescent')+ },+ assertDestinationReady: async (): Promise<void> => {+ calls.push('ready-now')+ },+ native: {+ install: async (): Promise<void> => {+ calls.push('install')+ },+ verifyDestination: async (): Promise<void> => {+ calls.push('verify')+ },+ activate: async (): Promise<void> => {+ calls.push('activate')+ },+ removePreview: async (): Promise<void> => {+ calls.push('remove')+ },+ isPreviewRemoved: async (): Promise<boolean> => calls.includes('remove')+ }+ }++ return { store, request, calls, deps }+}++function receiverDeps(request: RetirementRequest, calls: string[]): RetirementReceiverDependencies {+ return {+ verifyRunningDestination: async (): Promise<string> =>+ path.join(request.destination.appPath, 'Contents/MacOS/Hermes'),+ assertCompatibleSnapshot: async (): Promise<void> => {+ calls.push('compatible')+ },+ readSelection: async (): Promise<null> => null,+ adoptSelection: async (): Promise<void> => {+ calls.push('adopt')+ },+ assertReady: async (): Promise<void> => {+ calls.push('ready')+ }+ }+}++test('receiver checks compatibility before adopting state and cleanup failure resumes forward without duplicate adoption', async (): Promise<void> => {+ const { store, request, calls, deps } = await fixture()+ await prepareRetirement(store, request, deps)+ await resumeRetirement(store, deps, 'source')+ const receiver: RetirementReceiverDependencies = receiverDeps(request, calls)++ receiver.assertCompatibleSnapshot = async (): Promise<void> => {+ throw new Error('incompatible snapshot')+ }++ await expect(receiveRetirement(store, request.token, receiver)).rejects.toThrow('incompatible snapshot')+ expect(calls).not.toContain('adopt')+ expect((await store.read()).receiverStarted).toBe(false)++ receiver.assertCompatibleSnapshot = async (): Promise<void> => {+ calls.push('compatible')+ }++ await receiveRetirement(store, request.token, receiver)+ await receiveRetirement(store, request.token, receiver)+ expect(calls.filter((call: string): boolean => call === 'adopt')).toHaveLength(1)+ await completeRetirementReception(store, request.token, receiver)+ const originalRemove: RetirementDependencies['native']['removePreview'] = deps.native.removePreview++ deps.native.removePreview = async (): Promise<void> => {+ throw new Error('native package busy')+ }++ expect((await resumeRetirement(store, deps, 'destination')).status).toBe('cleanup-pending')+ expect((await store.read()).stage).toBe('destination-ready')+ deps.native.removePreview = originalRemove+ expect((await resumeRetirement(store, deps, 'destination')).status).toBe('complete')+ expect((await resumeRetirement(store, deps, 'destination')).status).toBe('complete')+ expect(calls.filter((call: string): boolean => call === 'remove')).toHaveLength(1)+ expect(await readFile(path.join(request.source.home, 'witness'), 'utf8')).toBe('preserve me')+})++test('configured stable conflicts, operator overrides and stale correlation fail without adoption', async (): Promise<void> => {+ const { store, request, calls, deps } = await fixture()+ await prepareRetirement(store, request, deps)+ await resumeRetirement(store, deps, 'source')+ const receiver: RetirementReceiverDependencies = receiverDeps(request, calls)+ receiver.readSelection = async (): Promise<{+ home: string+ profile: string+ connectionId: string+ operatorOverride: boolean+ }> => ({ home: '/different', profile: 'work', connectionId: 'local', operatorOverride: true })+ await expect(receiveRetirement(store, request.token, receiver)).rejects.toThrow('conflict')+ await expect(receiveRetirement(store, '0'.repeat(64), receiver)).rejects.toThrow('correlation')+ expect(calls).not.toContain('adopt')+ expect(calls).not.toContain('remove')+})++test('remote selection requires explicit reauthentication rather than copying encrypted credentials', async (): Promise<void> => {+ const { store, request, calls, deps } = await fixture()+ request.selection.connectionId = 'remote-account'+ await prepareRetirement(store, request, deps)+ await resumeRetirement(store, deps, 'source')+ await expect(receiveRetirement(store, request.token, receiverDeps(request, calls))).rejects.toThrow(+ 'Reauthentication'+ )+ expect(calls).not.toContain('adopt')+})++test('stale receipts and a destination that stopped being ready never authorize removal', async (): Promise<void> => {+ const { store, request, calls, deps } = await fixture()+ await prepareRetirement(store, request, deps)+ await resumeRetirement(store, deps, 'source')+ const receiver: RetirementReceiverDependencies = receiverDeps(request, calls)+ await receiveRetirement(store, request.token, receiver)+ const ready: RetirementReady = await completeRetirementReception(store, request.token, receiver)+ const record: RetirementRecord = await store.read()+ await store.write({ ...record, ready: { ...ready, requestDigest: '0'.repeat(64) } })+ await expect(resumeRetirement(store, deps, 'destination')).rejects.toThrow('receipt')+ await store.write(record)++ deps.assertDestinationReady = async (): Promise<void> => {+ throw new Error('target backend disconnected')+ }++ expect((await resumeRetirement(store, deps, 'destination')).status).toBe('cleanup-pending')+ expect(calls).not.toContain('remove')+})++test('cancel, backup failure and removal-scoped state do not reach native installation', async (): Promise<void> => {+ const { store, request, calls, deps } = await fixture()+ await expect(+ prepareRetirement(store, { ...request, consent: { ...request.consent, install: false } }, deps)+ ).rejects.toThrow('consent')++ deps.prepareState = async (): Promise<never> => {+ throw new Error('backup unavailable')+ }++ await expect(prepareRetirement(store, request, deps)).rejects.toThrow('backup unavailable')+ request.source.removalRoots.push(request.source.home)+ deps.prepareState = async (): Promise<{ snapshotHome: string; selectedHome: string }> => ({+ snapshotHome: path.join(path.dirname(request.source.home), 'snapshot'),+ selectedHome: request.source.home+ })+ await expect(prepareRetirement(store, request, deps)).rejects.toThrow('removal footprint')+ expect(calls).not.toContain('install')+ expect(calls).not.toContain('remove')+ expect(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)++ 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)++ store.write = async (record: RetirementRecord): Promise<void> => {+ if (record.stage === 'preview-removed') {+ throw new Error('power loss before journal rename')+ }++ await write(record)+ }++ 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()+ await prepareRetirement(store, request, deps)+ expect((await resumeRetirement(store, deps, 'source')).status).toBe('awaiting-destination')+ const reopened: RetirementJournal = await RetirementJournal.open(store.root, request.id)+ expect((await resumeRetirement(reopened, deps, 'source')).status).toBe('awaiting-destination')+ expect(calls.filter((call: string): boolean => call === 'install')).toHaveLength(1)+ expect(calls).not.toContain('remove')+ expect((await reopened.read()).stage).toBe('destination-installed')+ await expect(new MacRetirementAdapter().removePreview(request, reopened)).rejects.toThrow('destination-ready')+ await expect(new WindowsRetirementAdapter().removePreview(request, reopened)).rejects.toThrow('destination-ready')+ expect(await readFile(path.join(request.source.home, 'witness'), 'utf8')).toBe('preserve me')+})diff --git a/apps/desktop/electron/updater/retirement.ts b/apps/desktop/electron/updater/retirement.tsnew file mode 100644index 00000000000..7581ea064dc--- /dev/null+++ b/apps/desktop/electron/updater/retirement.ts@@ -0,0 +1,231 @@+import {+ assertRetirementReady,+ canonicalRetirementPath,+ insideRetirementRoot,+ retirementDigest,+ type RetirementJournal,+ type RetirementReady,+ type RetirementRecord,+ type RetirementRequest,+ type RetirementStateSnapshot,+ validateRetirementRequest+} from './retirement-state'++export interface RetirementNativeAdapter {+ install(request: RetirementRequest, journal: RetirementJournal): Promise<void>+ verifyDestination(request: RetirementRequest): Promise<void>+ activate(request: RetirementRequest, journal: RetirementJournal): Promise<void>+ removePreview(request: RetirementRequest, journal: RetirementJournal): Promise<void>+ isPreviewRemoved(request: RetirementRequest): Promise<boolean>+}++export interface RetirementDependencies {+ native: RetirementNativeAdapter+ /** Verify the authority's exact cohort coverage, not only a version floor. */+ assertQualified(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. */+ assertDestinationReady(record: RetirementRecord): Promise<void>+}++export type RetirementOutcome =+ | { status: 'awaiting-destination'; forwardOnly: boolean }+ | { status: 'cleanup-pending'; error: string; forwardOnly: true }+ | { status: 'complete'; forwardOnly: true }++export async function prepareRetirement(+ journal: RetirementJournal,+ request: RetirementRequest,+ deps: RetirementDependencies+): Promise<RetirementRecord> {+ validateRetirementRequest(request)++ if (request.id !== journal.id) {+ throw new Error('Retirement transaction ID mismatch')+ }++ await deps.assertQualified(request)++ return journal.exclusive(async (): Promise<RetirementRecord> => {+ try {+ const existing: RetirementRecord = await journal.read()++ if (existing.requestDigest !== retirementDigest(request)) {+ throw new Error('Transaction already binds another request')+ }++ 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)++ 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)++ 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')+ }++ await journal.assertPaths(request)++ const record: RetirementRecord = {+ request,+ requestDigest: retirementDigest(request),+ stage: 'prepared',+ state,+ receiverStarted: false,+ receiverApplied: false,+ previousSelection: null,+ ready: null+ }++ await journal.write(record)++ return record+ } finally {+ await release()+ }+ })+}++/** Source stops after activation. Stable owns cleanup, outside the source package. */+export async function resumeRetirement(+ journal: RetirementJournal,+ deps: RetirementDependencies,+ caller: 'source' | 'destination'+): Promise<RetirementOutcome> {+ const outcome: RetirementOutcome = await journal.exclusive(async (): Promise<RetirementOutcome> => {+ const record: RetirementRecord = await journal.read()++ if (record.stage === 'complete') {+ return { status: 'complete', forwardOnly: true }+ }++ await journal.assertPaths(record.request)+ await deps.assertQualified(record.request)++ if (record.stage === 'prepared') {+ if (caller !== 'source') {+ throw new Error('Destination cannot install itself during retirement')+ }++ await deps.native.install(record.request, journal)+ await deps.native.verifyDestination(record.request)+ record.stage = 'destination-installed'+ await journal.write(record)+ }++ if (record.stage === 'destination-installed') {+ await deps.native.verifyDestination(record.request)++ return { status: 'awaiting-destination', forwardOnly: record.receiverStarted }+ }++ if (caller !== 'destination') {+ return { status: 'awaiting-destination', forwardOnly: true }+ }++ try {+ if (!record.ready) {+ throw new Error('Destination readiness is required before cleanup')+ }++ 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)++ 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')+ }++ record.stage = 'preview-removed'+ await journal.write(record)+ }++ record.stage = 'complete'+ await journal.write(record)+ } finally {+ await release()+ }++ return { status: 'complete', forwardOnly: true }+ } catch (error) {+ return {+ status: 'cleanup-pending',+ error: error instanceof Error ? error.message : String(error),+ forwardOnly: true+ }+ }+ })++ if (caller === 'source' && outcome.status === 'awaiting-destination') {+ const record: RetirementRecord = await journal.read()++ if (record.stage === 'destination-installed') {+ await deps.native.activate(record.request, journal)+ }+ }++ return outcome+}++export async function assertNativeRetirementRemoval(+ journal: RetirementJournal,+ request: RetirementRequest+): Promise<void> {+ const record: RetirementRecord = await journal.read()++ if (record.stage !== 'destination-ready' || record.requestDigest !== retirementDigest(request) || !record.ready) {+ throw new Error('Native removal requires the correlated destination-ready transaction')+ }++ 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/product-identity.cjs b/apps/desktop/product-identity.cjsindex 69841c90929..cdd3dd709ec 100644--- a/apps/desktop/product-identity.cjs+++ b/apps/desktop/product-identity.cjs@@ -87,4 +87,8 @@ const identity = {: {})}-module.exports = identity+const { channelBuildRequest } = require('../../scripts/msix-shared.mjs')+const request = channelBuildRequest()+module.exports = request+ ? Object.freeze({ ...request.identity, store: false, light: false, channel: request.channel })+ : identitydiff --git a/apps/desktop/product-identity.d.cts b/apps/desktop/product-identity.d.ctsindex 2051375993f..1517f028e5a 100644--- a/apps/desktop/product-identity.d.cts+++ b/apps/desktop/product-identity.d.cts@@ -17,7 +17,9 @@ interface ProductIdentity {cliName: string/** OS-level app identity w/ org prefix. e.g. "NousResearch.HermesLight" */msixAppIdWithOrg: string- /** electron-updater feed channel this build publishes to. Stable tags:+ /** R2 identity token on channel builds; absent on legacy products. */+ readonly token?: string+ /** Channel subscription for channel builds; legacy electron-updater label otherwise. Stable tags:* "latest" | "light"; canary tags: "canary" | "light-canary". Null* for Store and commit builds (no release feed). */readonly channel: string | nulldiff --git a/apps/desktop/scripts/side-by-side.windows.test.mjs b/apps/desktop/scripts/side-by-side.windows.test.mjsindex 33c557ebd51..96cad8b74e7 100644--- a/apps/desktop/scripts/side-by-side.windows.test.mjs+++ b/apps/desktop/scripts/side-by-side.windows.test.mjs@@ -46,11 +46,12 @@ async function nativeProof() {const desktop = path.join(work, 'apps/desktop')const copied = ['apps/desktop/product-identity.cjs', 'apps/desktop/electron-builder.config.cjs',- 'apps/desktop/package.json', 'apps/desktop/update-feed.cjs', 'apps/desktop/update-feed.json',+ 'apps/desktop/package.json', 'apps/desktop/update-feed.cjs','apps/desktop/assets/msix-manifest.xml',...['before-build', 'gen-msix-manifest', 'mac-sign', 'payload-digests', 'write-build-stamp', 'utils'].map(name => `apps/desktop/scripts/${name}.mjs`),'scripts/msix-shared.mjs', 'scripts/release-content-types.json', 'scripts/build/python.mjs',+ 'scripts/bundles/desktop_prepare.py', 'scripts/releases/bundle_env.py', 'hermes_cli/release_channels.py', 'hermes_cli/__init__.py',]for (const file of copied) {fs.mkdirSync(path.dirname(path.join(work, file)), { recursive: true })@@ -73,7 +74,7 @@ foreach ($asset in @(@('Square44x44Logo.png',44,44), @('Square150x150Logo.png',1checked('powershell.exe', ['-NoProfile', '-NonInteractive', '-File', iconsScript, '-Dir', path.join(desktop, 'assets/appx')])fs.symlinkSync(path.join(repo, 'node_modules'), path.join(work, 'node_modules'), 'junction')const env = { ...process.env, HERMES_HOME: path.join(root, 'home'), HERMES_RUNTIME_DIR: path.join(root, 'runtime') }- for (const key of ['HERMES_BUILD_COMMIT', 'HERMES_PAYLOAD_TAG', 'HERMES_PAYLOAD_VERSION', 'HERMES_DESKTOP_VARIANT', 'BUILD_NUMBER']) delete env[key]+ for (const key of ['_HERMES_CHANNEL_REQUEST_JSON', 'HERMES_BUILD_COMMIT', 'HERMES_PAYLOAD_TAG', 'HERMES_PAYLOAD_VERSION', 'HERMES_DESKTOP_VARIANT', 'BUILD_NUMBER']) delete env[key]const gitEnv = { ...env, GIT_AUTHOR_NAME: 'Native fixture', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Native fixture', GIT_COMMITTER_EMAIL: '[email protected]', GIT_AUTHOR_DATE: '2026-09-01T00:00:00Z', GIT_COMMITTER_DATE: '2026-09-01T00:00:00Z' }const git = (...args) => checked('git', args, { cwd: work, env: gitEnv })git('init', '-q')@@ -83,12 +84,23 @@ foreach ($asset in @(@('Square44x44Logo.png',44,44), @('Square150x150Logo.png',1git('-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'Second commit fixture')const commitB = git('rev-parse', 'HEAD')assert.notEqual(commitA, commitB)+ const channelRequest = sequence => ({+ schema: 1, buildId: 'a'.repeat(32), channel: 'sdk-preview', sequence,+ repository: 'fixture/project', commit: commitB, sourceVersion: '1.2.4', version: `0.0.${sequence}`,+ windowsVersion: `0.${Math.floor(sequence / 65536)}.${sequence % 65536}.0`,+ identity: { token: 'ab12cd34ef56ab78', displayName: 'Hermes sdk-preview',+ appId: 'ai.hermes.channel.hab12cd34ef56ab78', appNamePascal: 'HermesChannelab12cd34ef56ab78',+ artifactNamePascal: 'HermesChannelab12cd34ef56ab78', cliName: 'hermes-sdk-preview',+ windowsExecutableName: 'HermesChannelab12cd34ef56ab78', msixAppIdWithOrg: 'NousResearch.HermesChannelab12cd34ef56ab78' },+ bundleEnv: {}, publicBase: 'https://example.invalid'+ })const cases = [['stable', { HERMES_PAYLOAD_TAG: 'v1.2.3' }],['canary', { HERMES_PAYLOAD_TAG: 'v1.2.4-canary.20260902000000' }],['canary-update', { HERMES_PAYLOAD_TAG: 'v1.2.4-canary.20260903000000' }],['commit-a', { HERMES_BUILD_COMMIT: commitA, HERMES_PAYLOAD_VERSION: '1.2.4' }],['commit-b', { HERMES_BUILD_COMMIT: commitB, HERMES_PAYLOAD_VERSION: '1.2.4' }],+ ...[65535, 65536, 0xffffffff].map(sequence => [`channel-${sequence}`, { _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(channelRequest(sequence)) }]),]const rows = []const failures = []@@ -121,7 +133,8 @@ foreach ($asset in @(@('Square44x44Logo.png',44,44), @('Square150x150Logo.png',1const metadata = { ...JSON.parse(fs.readFileSync(${JSON.stringify(path.join(desktop, 'package.json'))}, 'utf8')), ...config.extraMetadata };const executable = new AppInfo({ config, metadata }, null, config.win).productFilename + '.exe';const payload = stageDesktopLaunchers(${JSON.stringify(manifestDir)});- await beforeBuild();+ if (typeof config.beforeBuild === "function") await config.beforeBuild();+ else await beforeBuild();console.log(JSON.stringify({identity, config, payload, executable, app: appIdentity(${JSON.stringify(desktop)})}));`, path.join(root, 'native-probe.mjs')]))const xml = node([path.join(desktop, 'scripts/gen-msix-manifest.mjs'), 'bundled', process.arch])@@ -159,7 +172,7 @@ foreach ($asset in @(@('Square44x44Logo.png',44,44), @('Square150x150Logo.png',1}}const descriptor = path.join(root, `${label}.appinstaller`)- if (facts.identity.channel) {+ if (facts.identity.channel && !flavorEnv._HERMES_CHANNEL_REQUEST_JSON) {const publisher = attribute(roundtrip, 'Identity', 'Publisher')const selfUri = `https://example.invalid/fixture/${facts.identity.channel}.appinstaller`const artifactUri = `https://example.invalid/fixture/${facts.app.name}-${version}-win.msixbundle`@@ -187,6 +200,11 @@ foreach ($asset in @(@('Square44x44Logo.png',44,44), @('Square150x150Logo.png',1check(new Set([stable, canary, a, b].flatMap(row => row.aliases)).size === 8, 'Flavor execution aliases collide')check(canary.name === update.name && canary.name !== stable.name, 'Canary upgrade does not stay in its own family')check(canary.version.localeCompare(update.version, undefined, { numeric: true }) < 0, 'Canary version does not increase')+ const channelRows = rows.filter(row => row.label.startsWith('channel-'))+ check(channelRows.every(row => row.name === channelRows[0].name && row.name !== stable.name), 'Channel update identity changed or collides with stable')+ for (let index = 1; index < channelRows.length; index++) {+ check(channelRows[index - 1].version.localeCompare(channelRows[index].version, undefined, { numeric: true }) < 0, 'Channel version did not increase across rollover')+ }fs.writeFileSync(path.join(root, 'rows.json'), JSON.stringify(rows, null, 2))fs.writeFileSync(path.join(root, 'contracts.json'), JSON.stringify({ failures }, null, 2))assert.deepEqual(failures, [], 'Generated packaging contract failures')diff --git a/apps/desktop/scripts/write-build-stamp.mjs b/apps/desktop/scripts/write-build-stamp.mjsindex ed92cf7a60d..cf0758a96da 100644--- a/apps/desktop/scripts/write-build-stamp.mjs+++ b/apps/desktop/scripts/write-build-stamp.mjs@@ -9,6 +9,7 @@import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs"import { resolve, join, relative, posix } from "path"import productIdentity from "../product-identity.cjs"+import { channelBuildRequest } from "../../../scripts/msix-shared.mjs"import { execFileSync } from "child_process"import { isMain } from "./utils.mjs"@@ -88,6 +89,12 @@ export function resolveStamp({execFn = tryExec,fallbackBranch = FALLBACK_BRANCH} = {}) {+ const channelBuild = channelBuildRequest(env)+ if (channelBuild) {+ const local = fromLocalGit(repoRoot, execFn)+ if (!local || local.commit !== channelBuild.commit || local.dirty) throw new Error('Channel build identity does not match clean checkout HEAD')+ return { ...local, branch: null, source: 'channel-build', baseVersion: channelBuild.sourceVersion, channelBuild }+ }if (env.HERMES_BUILD_COMMIT) {if (!/^[a-f0-9]{40}$/.test(env.HERMES_BUILD_COMMIT) || env.HERMES_PAYLOAD_TAG) {throw new Error('Commit builds require an exact full SHA without a release tag')@@ -198,6 +205,8 @@ function main() {*/export function buildStampPayload(stamp, env = process.env, platform = process.platform, payload = null) {const variant = (env.HERMES_DESKTOP_VARIANT || "").trim()+ const channelBuild = channelBuildRequest(env)+ if (channelBuild && (stamp.commit !== channelBuild.commit || stamp.dirty)) throw new Error('Channel build identity does not match stamp')const commitBuild = env.HERMES_BUILD_COMMIT || nullif (commitBuild && (!/^[a-f0-9]{40}$/.test(commitBuild) || commitBuild !== stamp.commit)) {throw new Error('Commit build identity does not match the stamp commit')@@ -209,16 +218,20 @@ export function buildStampPayload(stamp, env = process.env, platform = process.pconst base = {schemaVersion: STAMP_SCHEMA_VERSION,commit: stamp.commit,- branch: commitBuild ? null : stamp.branch,+ branch: commitBuild || channelBuild ? null : stamp.branch,builtAt: new Date().toISOString(),dirty: stamp.dirty,- source: commitBuild ? 'commit-build' : stamp.source,+ source: channelBuild ? 'channel-build' : commitBuild ? 'commit-build' : stamp.source,commitDate: stamp.commitDate ?? null,- baseVersion: stamp.baseVersion ?? version?.split('-')[0] ?? null,- displayVersion: stamp.displayVersion ?? version,+ baseVersion: channelBuild?.sourceVersion ?? stamp.baseVersion ?? version?.split('-')[0] ?? null,+ displayVersion: channelBuild+ ? `${channelBuild.sourceVersion} (${channelBuild.channel} #${channelBuild.sequence}, ${channelBuild.commit.slice(0, 7)})`+ : stamp.displayVersion ?? version,distance: stamp.distance ?? null}+ if (channelBuild) base.channelBuild = channelBuild+const updateMechanism = {'': 'self',bootstrap: 'self',@@ -227,6 +240,7 @@ export function buildStampPayload(stamp, env = process.env, platform = process.plight: platform === 'darwin' ? 'electron-updater' : 'external'}[variant]if (!updateMechanism) throw new Error(`Unknown desktop variant: ${variant}`)+ if (channelBuild && updateMechanism === 'external') throw new Error('Channel builds require a supported native update owner')const bundled = variant === 'bundled' || variant === 'store'if (bundled && !payload?.runtime?.commands?.hermes) {throw new Error('PM payload has no completed launch contract; stage the bundle before packaging')diff --git a/apps/desktop/src/app/retirement-view.test.tsx b/apps/desktop/src/app/retirement-view.test.tsxnew file mode 100644index 00000000000..85a2be90db1--- /dev/null+++ b/apps/desktop/src/app/retirement-view.test.tsx@@ -0,0 +1,54 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, expect, test, vi } from 'vitest'++import { Dialog, DialogContent } from '@/components/ui/dialog'+import type { DesktopUpdateStatus } from '@/global'+import { I18nProvider } from '@/i18n'+import { en } from '@/i18n/en'+import { $updateStatus, resetUpdateApplyState } from '@/store/updates'++import { RetirementView } from './retirement-view'++afterEach((): void => {+ cleanup()+ resetUpdateApplyState()+ $updateStatus.set(null)+ Reflect.deleteProperty(window, 'hermesDesktop')+})++test.each(['keep-stable', 'open-preview'] as const)(+ 'migration requires a workspace choice and forwards %s through the real store',+ async (choice): Promise<void> => {+ const retire = vi.fn().mockResolvedValue({ ok: true, handedOff: true })+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { updates: { retire } } })++ const retirement: NonNullable<DesktopUpdateStatus['retirement']> = {+ state: 'available',+ destination: 'stable',+ version: '1.0.0'+ }++ $updateStatus.set({ supported: true, retirement })+ render(+ <I18nProvider configClient={null} initialLocale="en">+ <Dialog open>+ <DialogContent>+ <RetirementView onLater={(): void => {}} onRetry={(): void => {}} retirement={retirement} />+ </DialogContent>+ </Dialog>+ </I18nProvider>+ )+ const action: HTMLElement = screen.getByRole('button', { name: en.updates.retirementAction })+ fireEvent.click(screen.getByRole('checkbox'))+ expect(action.hasAttribute('disabled')).toBe(true)+ fireEvent.click(+ screen.getByRole('radio', {+ name: choice === 'keep-stable' ? 'Keep stable’s existing workspace' : 'Open this preview workspace in stable'+ })+ )+ fireEvent.click(action)+ await waitFor((): void => {+ expect(retire).toHaveBeenCalledWith({ installStable: true, removePreview: true, workspaceChoice: choice })+ })+ }+)diff --git a/apps/desktop/src/app/retirement-view.tsx b/apps/desktop/src/app/retirement-view.tsxnew file mode 100644index 00000000000..9af9447e90d--- /dev/null+++ b/apps/desktop/src/app/retirement-view.tsx@@ -0,0 +1,37 @@+import { useState, type ReactElement } from 'react'++import { Button } from '@/components/ui/button'+import { DialogDescription, DialogTitle } from '@/components/ui/dialog'+import type { DesktopUpdateStatus } from '@/global'+import { useI18n } from '@/i18n'+import { applyRetirement } from '@/store/updates'++export function RetirementView({ retirement, onLater, onRetry }: {+ retirement: NonNullable<DesktopUpdateStatus['retirement']>+ onLater: () => void+ onRetry: () => void+}): ReactElement {+ const { t } = useI18n()+ const [consented, setConsented] = useState<boolean>(false)+ 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>}+ {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="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>}+ </div>+ </div>+ )+}diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsxindex 334bd52002d..af12546b2b2 100644--- a/apps/desktop/src/app/updates-overlay.tsx+++ b/apps/desktop/src/app/updates-overlay.tsx@@ -17,6 +17,7 @@ import { Loader } from '@/components/ui/loader'import { Progress } from '@/components/ui/progress'import { UpdateStatusCard, VersionHero } from '@/components/update-status'import { VersionDetails } from '@/components/version-details'+import { RetirementView } from './retirement-view'import type {DesktopUpdateCommit,@@ -137,7 +138,10 @@ export function UpdatesOverlay() {<ErrorView message={apply.message} onDismiss={() => handleClose(false)} onRetry={handleInstall} />) : null}- {phase === 'idle' && (+ {phase === 'idle' && !isBackend && status?.retirement && (+ <RetirementView retirement={status.retirement} onLater={() => handleClose(false)} onRetry={() => void check()} />+ )}+ {phase === 'idle' && (isBackend || !status?.retirement) && (<IdleViewbehind={behind}checking={checking}diff --git a/apps/desktop/src/components/update-status.test.tsx b/apps/desktop/src/components/update-status.test.tsxindex b6afc83dbb3..48fbae31d40 100644--- a/apps/desktop/src/components/update-status.test.tsx+++ b/apps/desktop/src/components/update-status.test.tsx@@ -138,6 +138,12 @@ describe('VersionHero bundle banners', () => {return relaunchApp}+ it('shows an R2 channel name that is not a built-in translated label', (): void => {+ render(<VersionHero version={version({ channel: 'pm-preview' })} />)++ expect(screen.getByText(`${en.updates.version('0.19.0')} · pm-preview`)).toBeTruthy()+ })+it.each(Object.entries(TRANSLATIONS) as [Locale, Translations][])('localizes version channels in %s',(locale: Locale, copy: Translations): void => {diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsxindex 3a2aefe09f2..c19cb1e8878 100644--- a/apps/desktop/src/components/update-status.tsx+++ b/apps/desktop/src/components/update-status.tsx@@ -61,6 +61,14 @@ 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 }}@@ -152,7 +160,7 @@ export function VersionHero({)}<p className="mt-1 text-xs text-muted-foreground">{version?.appVersion ? u.version(version.appVersion) : u.versionUnavailable}- {version?.channel ? ` · ${u.channels[version.channel]}` : ''}+ {version?.channel ? ` · ${Object.entries(u.channels).find(([name]: [string, string]): boolean => name === version.channel)?.[1] ?? version.channel}` : ''}</p></div>{(version?.bundleSwapPending || version?.bundleOutOfSync) && (@@ -267,6 +275,9 @@ 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">diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex f96f868952a..0f399d86770 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -558,6 +558,7 @@ declare global {updates: {check: (opts?: { force?: boolean }) => Promise<DesktopUpdateStatus>apply: (opts?: DesktopUpdateApplyOptions) => Promise<DesktopUpdateApplyResult>+ retire: (consent: { installStable: true; removePreview: true }) => Promise<DesktopUpdateApplyResult>getBranch: () => Promise<{ branch: string }>setBranch: (name: string) => Promise<{ branch: string }>onProgress: (callback: (payload: DesktopUpdateProgress) => void) => () => void@@ -657,7 +658,7 @@ export interface DesktopVersionInfo {/** Packaged client version, or the runtime version for source installs. */appVersion: string/** Fixed release identity. Commit builds have no update channel. */- channel?: 'stable' | 'canary' | null+ channel?: string | nullelectronVersion: stringnodeVersion: stringplatform: string@@ -756,6 +757,12 @@ export type UpdaterMechanismClient =export interface DesktopUpdateStatus {supported: boolean+ retirement?: {+ state: 'available' | 'waiting' | 'incompatible' | 'conflict' | 'migrating' | 'cleanup-pending' | 'complete'+ destination: string+ version: string+ message?: string+ }/** Which mechanism owns updates for this install (see electron/updater). */mechanism?: UpdaterMechanismClientupdateAvailable?: boolean@@ -771,9 +778,8 @@ export interface DesktopUpdateStatus {currentSha?: string/** Backend only: the version string the backend reports for itself. */currentVersion?: string- /** Release feed the check read from ('stable'/'canary'); when set, the- * update is a release and `latestTag` names it instead of a commit count. */- channel?: 'stable' | 'canary'+ /** The R2 channel name; independent of source branch and package version. */+ channel?: string/** The latest release tag on a release-feed channel, e.g. `v0.18.0`. */latestTag?: string | nulltargetSha?: stringdiff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex bce9b3b51b3..0785d40d8cd 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3082,6 +3082,13 @@ 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.',+ retirementAction: 'Move to stable',+ retirementConsent: 'Install or update stable and remove this preview only after stable is ready.',+ retirementBlocked: 'Migration paused — preview preserved',+ retirementMoving: 'Moving to stable…',+ retirementComplete: 'Stable is ready',channels: { stable: 'Stable', canary: 'Canary' },bundleSwapPending: 'Restart to finish the update',bundleSwapPendingDesc: 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex ea693e54e2f..150880e0bcc 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2657,6 +2657,13 @@ export interface Translations {}updates: {+ retirementTitle: string+ retirementBody: string+ retirementAction: string+ retirementConsent: string+ retirementBlocked: string+ retirementMoving: string+ retirementComplete: stringchannels: { stable: string; canary: string }bundleSwapPending: stringbundleSwapPendingDesc: stringdiff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.tsindex 845952aa26b..d84c387b296 100644--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@ -468,6 +468,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) {@@ -572,6 +576,29 @@ 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> {+ const bridge = window.hermesDesktop?.updates+ const 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 })+ 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 }+ }+}+const BACKEND_ACTION_POLL_MS = 1500const BACKEND_ACTION_MAX_MS = 6 * 60 * 1000const BACKEND_RETURN_MAX_MS = 4 * 60 * 1000diff --git a/apps/desktop/update-feed.cjs b/apps/desktop/update-feed.cjsindex be1e0b160c9..ff829905858 100644--- a/apps/desktop/update-feed.cjs+++ b/apps/desktop/update-feed.cjs@@ -1,28 +1,18 @@'use strict'-// Read the feed facts shared by the desktop runtime and Python publisher.-// update-feed.json owns the paths; neither consumer derives a second copy.-//-// darwinFeed('stable') → { directory: 'releases/darwin/stable',-// channel: 'stable',-// fileName: 'stable-mac.yml',-// allowPrerelease: false }-// darwinFeed('canary', true) → { directory: 'releases/darwin/light/canary',-// channel: 'canary',-// fileName: 'canary-mac.yml',-// allowPrerelease: true }-//-// A client composes its feed URL as PUBLIC_URL + '/' + feed.directory +-// '/' + feed.fileName; the producer publishes the manifest at exactly that-// key. There is no placeholder default URL — the caller supplies the base.--const feeds = require('./update-feed.json')-+// Historical native URLs are a compatibility layout, not a channel registry.+/** @param {string} channel @param {boolean} light */function darwinFeed(channel, light = false) {- if (!Object.hasOwn(feeds, channel)) {- throw new TypeError(`darwinFeed: unknown channel ${JSON.stringify(channel)} (expected stable|canary)`)+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(channel) || channel.length > 32 ||+ /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(channel)) {+ throw new TypeError('Invalid channel name')+ }+ return {+ directory: `releases/darwin/${light ? 'light/' : ''}${channel}`,+ channel,+ fileName: `${channel}-mac.yml`,+ allowPrerelease: channel !== 'stable'}- return { ...feeds[channel][light ? 'light' : 'bundled'] }}module.exports = { darwinFeed }diff --git a/apps/desktop/update-feed.d.cts b/apps/desktop/update-feed.d.ctsindex a995cfd9292..678b362da64 100644--- a/apps/desktop/update-feed.d.cts+++ b/apps/desktop/update-feed.d.cts@@ -2,11 +2,11 @@ interface DarwinFeed {/** Feed directory key under the public bucket, no trailing slash.* e.g. "releases/darwin/stable" | "releases/darwin/light/canary" */directory: string- /** Normalized channel. "stable" | "canary" */- channel: 'stable' | 'canary'+ /** Validated slug; existence is resolved through R2. */+ channel: string/** electron-updater manifest filename. e.g. "stable-mac.yml" */fileName: string- /** True only for the canary channel. */+ /** Legacy nonstable feeds admit prereleases. */allowPrerelease: boolean}@@ -15,6 +15,7 @@ interface DarwinFeed {* pipeline. `light` selects the Light-variant feed directory.* The generic-provider feed URL is PUBLIC_URL + '/' + directory + '/' + fileName.*/-declare function darwinFeed(channel: 'stable' | 'canary', light?: boolean): DarwinFeed+declare function darwinFeed(channel: string, light?: boolean): DarwinFeed-export = { darwinFeed }+declare const contract: { darwinFeed: typeof darwinFeed }+export = contractdiff --git a/apps/desktop/update-feed.json b/apps/desktop/update-feed.jsondeleted file mode 100644index 4e6bf53eb81..00000000000--- a/apps/desktop/update-feed.json+++ /dev/null@@ -1,10 +0,0 @@-{- "stable": {- "bundled": {"directory": "releases/darwin/stable", "channel": "stable", "fileName": "stable-mac.yml", "allowPrerelease": false},- "light": {"directory": "releases/darwin/light/stable", "channel": "stable", "fileName": "stable-mac.yml", "allowPrerelease": false}- },- "canary": {- "bundled": {"directory": "releases/darwin/canary", "channel": "canary", "fileName": "canary-mac.yml", "allowPrerelease": true},- "light": {"directory": "releases/darwin/light/canary", "channel": "canary", "fileName": "canary-mac.yml", "allowPrerelease": true}- }-}diff --git a/docs/macos-bundle-updates.md b/docs/macos-bundle-updates.mdindex 3e23ea7422f..73e3a4081c8 100644--- a/docs/macos-bundle-updates.md+++ b/docs/macos-bundle-updates.md@@ -13,15 +13,29 @@ backend the desktop connects to.## Feed contract-`apps/desktop/update-feed.json` defines each channel directory and filename.-The desktop CJS adapter and Python publisher read these same facts.-The builder writes that URL into `app-update.yml`. The client uses this file-unless `updates.desktop_feed_base_url` supplies an explicit bucket-base URL.+Channel registration lives in R2 at `releases/channels/NAME.json`, not in a+checked-in channel map. Channel bundles resolve that record and its digest-bound+build manifest before selecting an immutable native feed. The admitted request+keeps the application identity stable across builds and records the source commit+separately from the increasing native package version.++Existing tagged clients retain their native feed URLs. The generic+`apps/desktop/update-feed.cjs` adapter computes these legacy paths; it does not+register channels. The builder writes the legacy URL into `app-update.yml`;+`updates.desktop_feed_base_url` can supply an explicit bucket-base URL.- Stable: `releases/darwin/stable/stable-mac.yml`- Canary: `releases/darwin/canary/canary-mac.yml`- Light: the same paths with `light/` between `darwin/` and the channel.- Artifacts: `releases/tag/TAG/FILENAME`, shared by download links and feeds.+- Channel-build artifacts and native metadata: `releases/channel-builds/BUILD_ID/`.++Retirement is a different operation from a native update: the old channel points+to a qualified official destination, not to a differently named package in its+own native feed. The explicit migration action must preserve user state and+verify destination readiness before removing the preview application. Keeping+the qualified receiver manifest immutable lets an offline preview migrate after+the destination channel has advanced; the destination subsequently owns updates.The current workflow builds the bundled variant, on ARM64 and Intel runners.Light has separate client/feed routing but no release matrix leg in this change.diff --git a/docs/stable-releases.md b/docs/stable-releases.mdindex a364d94e38b..8d992e03737 100644--- a/docs/stable-releases.md+++ b/docs/stable-releases.md@@ -115,6 +115,50 @@ or pass the release-success gate.Store submission retains its fixed official stable identity. Nonstablepackages must not be submitted under that identity.+## Dynamic channels in R2++Channel names are R2 objects, not a repository registry. A preview channel owns+one native application identity across exact-commit builds. The immutable build+request records its source commit, bundle defaults, channel sequence and package+versions separately. The existing native build and smoke jobs must all pass+before the channel head advances.++Preview a custom build, then explicitly dispatch it:++```sh+python scripts/release.py --channel pm-preview --build-commit my-branch --remote fork+python scripts/release.py --channel pm-preview --build-commit my-branch --remote fork --publish+python scripts/release.py --channels --remote fork+```++The first publishing invocation creates the channel. Later invocations retain+its identity. Requests and artifacts live under+`releases/channel-builds/BUILD_ID/`; the mutable pointer is+`releases/channels/NAME.json`. A failed build leaves its previous head intact.+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:++```text+python scripts/release.py --retire-channel pm-preview --to stable --minimum-version VERSION --compatibility-key KEY --compatibility-sha256 SHA256 --remote fork+```++Add `--publish` only after reviewing the dry run and the exact native acceptance+evidence. This does not rebuild stable under the preview identity or silently+uninstall clients. Protocol-aware clients offer a consented cross-application+handoff; the destination must confirm readiness before preview removal. Keep+the retirement object and qualified artifacts available for offline clients.+Existing one-off builds have no retirement reader and require replacement.++Before shipping R2-only source readers, seed the existing `main` source-branch+record and published stable/canary records through the explicit protected+bootstrap operation. Review actual accepted manifests; do not invent a native+manifest for `main`. Production seeding, CDN cache/CAS verification and native+signed-package qualification are release operations, not implied by a passing+local helper suite. Never store the bootstrap output as a repo channel list.+## Signed-package baselineThe last successful stable release recordsdiff --git a/hermes_cli/backup_migration.py b/hermes_cli/backup_migration.pynew file mode 100644index 00000000000..2618bc79049--- /dev/null+++ b/hermes_cli/backup_migration.py@@ -0,0 +1,114 @@+"""Strict, disposable full-home snapshots using the normal backup inventory.++The caller quiesces writers and owns a private staging directory. Unlike quick+snapshots, this includes skills, profiles and transcripts; unlike automatic ZIP+backups, any unreadable required entry aborts publication. Regenerable exclusions+still follow the full-backup policy. It is not a byte-for-byte package archive.+"""++import hashlib+import json+import os+import shutil+import sqlite3+import stat+from pathlib import Path++from hermes_cli.backup import _backup_operation_lock, _iter_backup_files+from hermes_cli.backup_sqlite import _safe_copy_db+++LINK_INVENTORY = '.hermes-retained-links.json'+++def retained_link(entry: Path, relative: Path, removal_roots: tuple[Path, ...]) -> dict:+ parts = relative.parts[2:] if relative.parts[:1] == ('profiles',) else relative.parts+ if not parts or parts[0] not in {'plugins', 'skills'}:+ raise ValueError(f'Compatibility reader input cannot be a link: {relative}')+ resolved = entry.resolve(strict=True)+ if any(resolved == root or root in resolved.parents for root in removal_roots):+ raise ValueError(f'Retained link points into the removal footprint: {relative}')+ return {'path': str(relative), 'target': os.readlink(entry), 'resolved': str(resolved)}+++def verify_retained_links(source: Path, snapshot: Path, removal_roots: tuple[Path, ...]) -> None:+ file = snapshot / LINK_INVENTORY+ if file.exists():+ roots = tuple(root.resolve() for root in removal_roots)+ for row in json.loads(file.read_text(encoding='utf-8')):+ relative = Path(row['path'])+ if retained_link(source / relative, relative, roots) != row:+ raise ValueError(f'Retained link changed during migration: {relative}')+++def snapshot_migration_home(source: Path, target: Path, *, retained_removal_roots: tuple[Path, ...] | None = None) -> None:+ """Fill a new private tree; never publish a partial snapshot or follow links."""+ source = source.resolve(strict=True)+ resolved_target = target.resolve()+ if source == resolved_target or source in resolved_target.parents or resolved_target in source.parents:+ raise ValueError('Migration snapshot and source overlap')+ if target.exists() or target.is_symlink():+ raise FileExistsError(target)+ if (source / LINK_INVENTORY).exists():+ raise ValueError('Reserved migration inventory exists in source home')+ target.mkdir(mode=0o700)+ links = []+ roots = tuple(root.resolve() for root in (retained_removal_roots or ()))+ with _backup_operation_lock(source):+ for entry, relative in _iter_backup_files(source, target, strict=True):+ output = target / relative+ output.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ info = entry.lstat()+ is_link = stat.S_ISLNK(info.st_mode) or bool(getattr(info, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT)+ if is_link:+ if retained_removal_roots is None:+ raise ValueError(f'Relocating links requires explicit external preservation: {relative}')+ links.append(retained_link(entry, relative, roots))+ # Keep probes detached: the live link is retained and rechecked,+ # never followed by destination readers on this snapshot.+ continue+ if stat.S_ISDIR(info.st_mode):+ output.mkdir(exist_ok=True, mode=0o700)+ continue+ if not stat.S_ISREG(info.st_mode):+ raise ValueError(f'Backup entry is a special file: {relative}')+ with entry.open("rb") as stream:+ sqlite = stream.read(16) == b"SQLite format 3\0"+ if sqlite or entry.suffix == ".db":+ if not _safe_copy_db(entry, output):+ raise RuntimeError(f"WAL-safe migration snapshot failed: {relative}")+ connection = sqlite3.connect(output)+ try:+ if connection.execute("PRAGMA quick_check").fetchall() != [("ok",)]:+ raise RuntimeError(f"Migration snapshot integrity failed: {relative}")+ finally:+ connection.close()+ else:+ # Unknown SQLite sidecars cannot be paired with a fresh image.+ if entry.name.endswith(("-wal", "-shm", "-journal")):+ database = entry.with_name(entry.name.rsplit("-", 1)[0])+ with database.open("rb") as stream:+ if stream.read(16) != b"SQLite format 3\0":+ raise ValueError(f"Unrecognized SQLite sidecar: {relative}")+ continue+ shutil.copyfile(entry, output)+ with entry.open('rb') as original, output.open('rb') as copied:+ if hashlib.file_digest(original, 'sha256').digest() != hashlib.file_digest(copied, 'sha256').digest():+ raise OSError(f'Migration copy verification failed: {relative}')+ with output.open("rb+") as stream:+ os.fsync(stream.fileno())+ output.chmod(entry.stat().st_mode & 0o700)+ if retained_removal_roots is not None:+ with (target / LINK_INVENTORY).open('x', encoding='utf-8') as stream:+ json.dump(links, stream)+ stream.flush()+ os.fsync(stream.fileno())+ verify_retained_links(source, target, roots)+ if os.name != 'nt':+ # Persist directory entries bottom-up before the caller's rename.+ for directory, _, _ in os.walk(target, topdown=False):+ descriptor = os.open(directory, os.O_RDONLY)+ try:+ os.fsync(descriptor)+ finally:+ os.close(descriptor)\ No newline at end of filediff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex 365a0fbd9dc..f5290054fc4 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -221,7 +221,7 @@ def format_banner_version_label() -> str:from hermes_cli.update_channel import resolve_update_channelchannel = resolve_update_channel(_quiet(load_config), get_project_root())- if channel in {"stable", "canary"}:+ if channel != "main":head = source_check._git_stdout(["rev-parse", "HEAD"], cwd=get_project_root())return f"{base} · {channel}" + (f" · local {head[:12]}" if head else "")state = get_git_banner_state()diff --git a/hermes_cli/release_channels.py b/hermes_cli/release_channels.pynew file mode 100644index 00000000000..c34e32e727c--- /dev/null+++ b/hermes_cli/release_channels.py@@ -0,0 +1,361 @@+"""R2 channel wire protocol. Names are data; no local channel registry exists."""+from __future__ import annotations++from dataclasses import dataclass+import hashlib+import json+import re+from urllib.error import HTTPError, URLError+from urllib.parse import urlsplit+from urllib.request import HTTPRedirectHandler, Request, build_opener++MAX_SEQUENCE = 2**32 - 1+MAX_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))}+++class ChannelError(ValueError):+ """Invalid, unavailable, or untrusted channel metadata (never a fallback)."""+++class ChannelNotFound(ChannelError):+ pass+++def _match(pattern: str, value: object, label: str) -> str:+ if not isinstance(value, str) or re.fullmatch(pattern, value, re.ASCII) is None:+ raise ChannelError(f"Invalid {label}")+ return value+++def validate_name(value: object) -> str:+ name = _match(r"[a-z0-9]+(?:-[a-z0-9]+)*", value, "channel name")+ if len(name) > 32 or name in _RESERVED:+ raise ChannelError("Invalid channel name")+ return name+++def validate_repository(value: object) -> str:+ return _match(r"[A-Za-z0-9][A-Za-z0-9_-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", value, "repository")+++def require_sha256(value: object) -> str:+ return _match(r"[a-f0-9]{64}", value, "SHA256")+++def require_commit(value: object) -> str:+ return _match(r"[a-f0-9]{40}", value, "commit")+++def build_prefix(build_id: object) -> str:+ return "releases/channel-builds/" + _match(r"[a-f0-9]{32}", build_id, "build ID") + "/"+++def channel_key(name: object) -> str:+ return f"releases/channels/{validate_name(name)}.json"+++def canonical_json(value: object) -> bytes:+ return (json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False) + "\n").encode()+++def decode_json(body: bytes) -> dict:+ def pairs(items):+ result = {}+ for key, value in items:+ if key in result:+ raise ChannelError("Duplicate JSON key")+ result[key] = value+ return result+ try:+ value = json.loads(body, object_pairs_hook=pairs)+ except (ValueError, UnicodeError) as exc:+ raise ChannelError("Invalid channel JSON") from exc+ if not isinstance(value, dict):+ raise ChannelError("Channel metadata must be an object")+ return value+++def public_base(value: str) -> str:+ parsed = urlsplit(value)+ if (not parsed.hostname or parsed.username is not None or parsed.password is not None+ or parsed.query or parsed.fragment or any(c in value for c in "%\\;")+ or any(ord(c) <= 32 for c in value)+ or any(p in (".", "..") for p in parsed.path.split("/"))+ or not (parsed.scheme == "https" or (parsed.scheme == "http"+ and parsed.hostname in ("127.0.0.1", "localhost", "::1")))):+ raise ChannelError("Invalid channel archive authority")+ return value.rstrip("/")+++def artifact_key(value: object) -> str:+ key = _match(r"[A-Za-z0-9_./+-]+", value, "artifact key")+ if not key.startswith("releases/") or any(p in ("", ".", "..") for p in key.split("/")):+ raise ChannelError("Invalid artifact key")+ if any(p.split(".")[0].lower() in _RESERVED or p.endswith(".") for p in key.split("/")):+ raise ChannelError("Invalid artifact key")+ return key+++def package_versions(sequence: int) -> tuple[str, str]:+ _integer(sequence, "sequence", 1, MAX_SEQUENCE)+ return f"0.0.{sequence}", f"0.{sequence // 65536}.{sequence % 65536}.0"+++def _integer(value: object, label: str, minimum: int = 1, maximum: int = MAX_SEQUENCE + 1) -> int:+ if type(value) is not int or not minimum <= value <= maximum:+ raise ChannelError(f"Invalid {label}")+ return value+++def _schema(value: object) -> dict:+ if not isinstance(value, dict) or type(value.get("schema")) is not int or value["schema"] != 1:+ raise ChannelError("Unsupported channel schema")+ return value+++def validate_identity(value: object) -> dict:+ if not isinstance(value, dict):+ raise ChannelError("Invalid channel identity")+ _match(r"[a-f0-9]{16}", value.get("token"), "identity token")+ _match(r"[A-Za-z0-9][A-Za-z0-9 ._-]{0,79}", value.get("displayName"), "identity display name")+ for field in ("appNamePascal", "artifactNamePascal"):+ _match(r"[A-Za-z][A-Za-z0-9]{0,63}", value.get(field), field)+ _match(r"[a-z][a-z0-9.-]{2,127}", value.get("appId"), "app ID")+ _match(r"[A-Za-z][A-Za-z0-9.-]{2,49}", value.get("msixAppIdWithOrg"), "MSIX identity")+ _match(r"[a-z][a-z0-9-]{0,63}", value.get("cliName"), "CLI name")+ _match(r"[A-Za-z][A-Za-z0-9 ._-]{0,79}", value.get("windowsExecutableName"), "Windows executable")+ return value+++def validate_request(value: object, *, repository: str | None = None,+ base_url: str | None = None, policy: str = "preview") -> dict:+ request = _schema(value)+ build_prefix(request.get("buildId"))+ validate_name(request.get("channel"))+ actual_repo = validate_repository(request.get("repository"))+ if repository is not None and actual_repo.casefold() != repository.casefold():+ raise ChannelError("Channel repository authority mismatch")+ require_commit(request.get("commit"))+ if "controllerCommit" in request:+ require_commit(request["controllerCommit"])+ _match(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", request.get("sourceVersion"), "source version")+ versions = package_versions(request.get("sequence"))+ if policy == "preview":+ if (request.get("version"), request.get("windowsVersion")) != versions:+ raise ChannelError("Channel package version does not match sequence")+ else:+ _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")+ if any(int(part) > 65535 for part in quad.split(".")):+ raise ChannelError("Invalid Windows version")+ validate_identity(request.get("identity"))+ values = request.get("bundleEnv")+ if not isinstance(values, dict):+ raise ChannelError("Invalid bundle environment")+ for key, item in values.items():+ _match(r"[A-Za-z_][A-Za-z0-9_]*", key, "bundle environment name")+ if item is not None and (not isinstance(item, str) or "\0" in item):+ raise ChannelError("Invalid bundle environment value")+ base = request.get("publicBase")+ if not isinstance(base, str) or public_base(base) != base:+ raise ChannelError("Invalid request archive authority")+ if base_url is not None and base != public_base(base_url):+ raise ChannelError("Request archive authority mismatch")+ return request+++def _head(value: object) -> dict | None:+ if value is None:+ return None+ if not isinstance(value, dict):+ raise ChannelError("Invalid channel head")+ prefix = build_prefix(value.get("buildId"))+ _integer(value.get("sequence"), "head sequence", maximum=MAX_SEQUENCE)+ if value.get("manifestKey") != prefix + "build.json":+ raise ChannelError("Invalid channel manifest key")+ require_sha256(value.get("sha256"))+ return value+++def validate_record(value: object, *, name: str | None = None, repository: str | None = None) -> dict:+ record = _schema(value)+ if not {"name", "repository", "policy", "state", "revision", "nextSequence", "identity", "head"} <= record.keys():+ raise ChannelError("Missing channel record fields")+ validate_name(record.get("name"))+ if name is not None and record["name"] != name:+ raise ChannelError("Channel name does not match object key")+ actual_repo = validate_repository(record.get("repository"))+ if repository is not None and actual_repo.casefold() != repository.casefold():+ raise ChannelError("Channel repository authority mismatch")+ if record.get("policy") not in _POLICIES or record.get("state") not in ("active", "retired"):+ raise ChannelError("Invalid channel policy or state")+ _integer(record.get("revision"), "channel revision", maximum=2**53 - 1)+ _integer(record.get("nextSequence"), "next sequence")+ head = _head(record.get("head"))+ if head is not None and head["sequence"] >= record["nextSequence"]:+ raise ChannelError("Channel head exceeds allocation high-water")+ if record["policy"] == "source-branch":+ delivery = record.get("delivery")+ if record.get("identity") is not None or head is not None or not isinstance(delivery, dict) or delivery.get("kind") != "source-branch":+ raise ChannelError("Source branch cannot carry native artifacts")+ branch = _match(r"[A-Za-z0-9][A-Za-z0-9_./-]*", delivery.get("branch"), "source branch")+ if ".." in branch or "//" in branch or branch.endswith(("/", ".", ".lock")):+ raise ChannelError("Invalid source branch")+ else:+ validate_identity(record.get("identity"))+ 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("lastHead")) != head:+ raise ChannelError("Retirement last head mismatch")+ return record+++@dataclass(frozen=True)+class ChannelResolution:+ requested: dict+ terminal: dict+ manifest: dict | None+ constraints: tuple[dict, ...] = ()+++class _NoRedirect(HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ raise ChannelError("Channel archive redirects are not permitted")+++class ChannelReader:+ def __init__(self, base_url: str, repository: str | None = None, opener=None):+ self.base_url = public_base(base_url)+ self.repository = validate_repository(repository) if repository is not None else None+ self.opener = opener or build_opener(_NoRedirect()).open++ def read_bytes(self, key: str, sha256: str | None = None) -> bytes:+ url = self.base_url + "/" + artifact_key(key)+ if sha256 is not None:+ require_sha256(sha256)+ try:+ with self.opener(Request(url, headers={"Cache-Control": "no-cache"}), timeout=30) as response:+ if response.geturl() != url:+ raise ChannelError("Channel archive redirects are not permitted")+ body = response.read(MAX_METADATA + 1)+ except HTTPError as exc:+ if exc.code == 404:+ raise ChannelNotFound(f"Channel object not found: {key}") from exc+ raise ChannelError(f"Channel read unavailable: HTTP {exc.code}") from exc+ except (OSError, URLError) as exc:+ raise ChannelError("Channel read unavailable") from exc+ if len(body) > MAX_METADATA:+ raise ChannelError("Channel metadata exceeds size limit")+ if sha256 is not None and hashlib.sha256(body).hexdigest() != sha256:+ raise ChannelError("Channel metadata SHA256 mismatch")+ return body++ def read_record(self, name: str) -> dict:+ return validate_record(decode_json(self.read_bytes(channel_key(name))), name=name, repository=self.repository)++ 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"]:+ 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)+ 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 head is None or record["head"] is None or head["sequence"] > record["head"]["sequence"]:+ raise ChannelError("Invalid qualified 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")+ actual = tuple(map(int, manifest["request"]["sourceVersion"].split(".")))+ floor = tuple(map(int, item["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)+++def validate_manifest(value: object, record: dict, base_url: str) -> dict:+ manifest = _schema(value)+ request = validate_request(manifest.get("request"), repository=record["repository"],+ base_url=base_url, policy=record["policy"])+ if request["identity"] != record["identity"]:+ raise ChannelError("Manifest channel identity mismatch")+ if request["channel"] != record["name"]:+ raise ChannelError("Manifest channel mismatch")+ head = record.get("head")+ if head is not None and any(request[field] != head[field] for field in ("buildId", "sequence")):+ raise ChannelError("Manifest does not match channel head")+ packages = manifest.get("packages")+ if not isinstance(packages, list) or not packages:+ raise ChannelError("Build manifest has no packages")+ prefixes = [build_prefix(request["buildId"])]+ if record["policy"] in {"stable-release", "canary-release"}:+ prefixes.append(f"releases/tag/{request['releaseTag']}/")+ seen = set()+ for package in packages:+ if not isinstance(package, dict):+ raise ChannelError("Invalid native package")+ target = tuple(package.get(field) for field in ("platform", "arch", "variant"))+ if target[0] not in ("darwin", "win32") or target[1] not in ("arm64", "x64") or target[2] != "bundled":+ raise ChannelError("Unsupported channel package target")+ if target in seen:+ raise ChannelError("Duplicate package target")+ seen.add(target)+ artifact = package.get("artifact")+ if not isinstance(artifact, dict):+ raise ChannelError("Invalid package artifact")+ key = artifact_key(artifact.get("key"))+ if not any(key.startswith(prefix) for prefix in prefixes):+ raise ChannelError("Artifact outside admitted build namespace")+ require_sha256(artifact.get("sha256"))+ _integer(artifact.get("size"), "artifact size", maximum=2**53 - 1)+ identity_field, version_field, signing_field = (+ ("appId", "version", "teamId") if target[0] == "darwin"+ else ("msixAppIdWithOrg", "windowsVersion", "publisher"))+ if package.get("identity") != request["identity"][identity_field] or package.get("version") != request[version_field]:+ raise ChannelError("Native package identity or version mismatch")+ signing = package.get(signing_field)+ if not isinstance(signing, str) or not signing or any(ord(c) < 32 for c in signing):+ raise ChannelError("Missing native signing identity")+ if target[0] == "darwin":+ _match(r"[A-Z0-9]{10}", signing, "Apple team ID")+ feed = package.get("feed")+ if not isinstance(feed, dict) or feed.get("channel") != "stable":+ raise ChannelError("Channel native metadata requires a neutral stable feed")+ feed_key = artifact_key(feed.get("key"))+ if not any(feed_key.startswith(prefix) for prefix in prefixes):+ raise ChannelError("Native metadata outside admitted build namespace")+ return manifestdiff --git a/hermes_cli/source_check.py b/hermes_cli/source_check.pyindex ed8f39758f2..238d1b999a1 100644--- a/hermes_cli/source_check.py+++ b/hermes_cli/source_check.py@@ -15,7 +15,7 @@ from urllib.parse import quoteimport urllib.requestfrom hermes_constants import get_hermes_home-from hermes_cli.source_releases import OFFICIAL_REPOSITORY, _GITHUB_ORIGIN, resolve_source_release+from hermes_cli.source_releases import OFFICIAL_REPOSITORY, _GITHUB_ORIGIN, resolve_source_targetlogger = logging.getLogger(__name__)UPDATE_AVAILABLE_NO_COUNT = -1@@ -152,6 +152,7 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = Nfrom hermes_cli.config import detect_install_method, get_project_root, require_readable_config_before_writefrom hermes_cli.steward import read_install_stampfrom hermes_cli.update_channel import install_id, resolve_update_channel+ from hermes_cli.release_channels import validate_namefrom hermes_cli.update_contract import COMMIT_BUILD_UPDATE_MESSAGEembedded = (os.environ.get("HERMES_REVISION") or None) if install_root is None else None@@ -172,9 +173,7 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = Nconfig = require_readable_config_before_write(home / "config.yaml")if passive and (config.get("updates") or {}).get("check") is False:return {**result, "reason": "disabled"}- channel = channel or resolve_update_channel(config, root)- if channel not in {"main", "stable", "canary"}:- raise ValueError(f"Invalid update channel: {channel}")+ channel = resolve_update_channel(config, root) if channel is None else validate_name(channel)head = embedded or _git_stdout(["rev-parse", "HEAD"], cwd=root, git=git)current_branch = None if embedded else _git_stdout(["rev-parse", "--abbrev-ref", "HEAD"], cwd=root, git=git)desktop_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8-sig"))) if branch_config_path else None@@ -194,7 +193,7 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = Nelse:result["branch"] = selected_branchidentity = {"root": str(root), "home": str(home), "head": head, "origin": origin, "branch": selected_branch,- "channel": channel, "embedded": embedded}+ "channel": channel, "embedded": embedded, "branchOverride": branch is not None, "channelProtocol": 1}cache_file = Path(cache_path) if cache_path is not None else home / "source-checks" / f"{install_id(root)}.json"cached = _quiet(lambda: json.loads(cache_file.read_text(encoding="utf-8-sig")))now = time.time()@@ -206,17 +205,30 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = Nif isinstance(ts, (float, int)) and 0 <= now - ts < ttl:return {**status, "dirty": dirty, "currentBranch": current_branch}result["fetchedAt"] = int(now * 1000)+ source_target = Noneif not _is_full_sha(head):result.update(error="head-unavailable", message="Could not read the installed revision.")- elif channel in {"stable", "canary"}:- tag, target = resolve_source_release(channel, [git] if not embedded else None, root,- repository=repository or OFFICIAL_REPOSITORY)- if not tag or not target:- result.update(error="release-unavailable", message=f"Could not resolve the {channel} release commit.")+ elif branch is None:+ try:+ source_target = resolve_source_target(channel, [git] if not embedded else None, root,+ repository=repository or OFFICIAL_REPOSITORY)+ except (OSError, ValueError, subprocess.SubprocessError) as exc:+ result.update(error="release-unavailable", message=f"Could not resolve the {channel} source channel: {exc}")else:- result.update(latestTag=tag, targetSha=target, updateAvailable=head != target,- behind=0 if head == target else UPDATE_AVAILABLE_NO_COUNT)- else:+ if source_target.commit:+ target = source_target.commit+ result.pop("branch", None)+ result.update(channel=channel, targetSha=target, updateAvailable=head != target,+ behind=0 if head == target else UPDATE_AVAILABLE_NO_COUNT,+ sourceVersion=source_target.version, buildId=source_target.build_id)+ if source_target.retired:+ result["retirement"] = {"destination": source_target.channel, "sourceOnly": True}+ else:+ # The record supplies a default, not permission to leave the user's branch.+ selected_branch = configured_branch or (+ current_branch if current_branch and current_branch != "HEAD" else source_target.branch)+ if "error" not in result and (source_target is None or source_target.branch is not None):+ result["branch"] = selected_branchofficial_ssh = (repository and repository.lower() == OFFICIAL_REPOSITORY.lower()and origin.lower().startswith(("git@", "ssh://")))# The public official repo does not require the user's SSH credentials.@@ -265,7 +277,8 @@ def main() -> None:parser.add_argument("--home", type=Path, required=True)parser.add_argument("--git", default="git")parser.add_argument("--branch")- parser.add_argument("--channel", choices=("main", "stable", "canary"))+ from hermes_cli.release_channels import validate_name+ parser.add_argument("--channel", type=validate_name)parser.add_argument("--cache-path", type=Path)parser.add_argument("--branch-config-path", type=Path)parser.add_argument("--force", action="store_true")diff --git a/hermes_cli/source_releases.py b/hermes_cli/source_releases.pyindex ccb889ea5ec..7970463632b 100644--- a/hermes_cli/source_releases.py+++ b/hermes_cli/source_releases.py@@ -1,6 +1,7 @@"""Resolve promoted source releases, never infer publication from a Git tag."""from __future__ import annotations+from dataclasses import dataclassfrom html.parser import HTMLParserimport jsonimport logging@@ -38,6 +39,132 @@ def source_repository(git_cmd=None, cwd=None) -> str:return OFFICIAL_REPOSITORY+@dataclass(frozen=True)+class SourceTarget:+ """A pinned source build or an explicitly declared source-branch delivery."""++ requested_channel: str+ channel: str+ repository: str+ commit: str | None = None+ branch: str | None = None+ version: str | None = None+ build_id: str | None = None++ @property+ def retired(self) -> bool:+ return self.requested_channel != self.channel++ @property+ def label(self) -> str:+ return f"{self.channel} v{self.version} ({self.commit[:12]})" if self.commit else self.channel+++def _resolve_channel(name: str, repository: str):+ """The only adapter to the validated requested/terminal records and manifest.++ ChannelReader owns HTTPS, authority and digests. The source adapter below+ admits its retirement constraints before any checkout operation. No legacy+ GitHub fallback is allowed when a record is unavailable.+ """+ from hermes_cli.release_channels import ChannelReader++ return ChannelReader(_PUBLIC_BASE, repository=repository).resolve(name)+++def resolve_source_target(channel: str, git_cmd=None, cwd=None, *, repository=None) -> SourceTarget:+ """Resolve every subscription, including default labels, through R2."""+ from hermes_cli.release_channels import validate_name++ validate_name(channel)+ repository = repository or source_repository(git_cmd, cwd)+ resolved = _resolve_channel(channel, repository)+ terminal = resolved.terminal+ if terminal["repository"].lower() != repository.lower():+ raise ValueError("Channel repository does not match this source installation")+ destination = validate_name(terminal["name"])+ if terminal["policy"] == "source-branch":+ if resolved.requested["state"] == "retired":+ raise ValueError("Source retirement requires a published destination commit")+ delivery = terminal["delivery"]+ if delivery["kind"] != "source-branch":+ raise ValueError("Channel has no source-branch delivery")+ return SourceTarget(channel, destination, repository, branch=delivery["branch"])+ if 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")+ if resolved.requested["state"] == "retired":+ _refuse_retirement_downgrade(request, terminal, git_cmd, cwd)+ return SourceTarget(channel, destination, repository, commit=commit,+ version=request["sourceVersion"], build_id=request["buildId"])+++def _refuse_retirement_downgrade(request: dict, terminal: dict, git_cmd, cwd) -> None:+ """Qualification of preview data is not permission to roll back newer source."""+ from pathlib import Path+ import tomllib++ if cwd is None:+ return+ version_file = Path(cwd) / "pyproject.toml"+ if version_file.exists():+ with version_file.open("rb") as file:+ project = tomllib.load(file).get("project")+ installed_version = project.get("version") if isinstance(project, dict) else None+ if not isinstance(installed_version, str) or not re.fullmatch(r"\d+\.\d+\.\d+", installed_version, re.ASCII):+ raise ValueError("Source retirement cannot verify the installed source version")+ if tuple(map(int, installed_version.split("."))) > tuple(map(int, request["sourceVersion"].split("."))):+ raise ValueError("Source retirement would downgrade a newer source version; select the destination channel explicitly")+ if git_cmd is not None:+ from hermes_cli.source_check import source_git_env++ result = subprocess.run(+ [*git_cmd, "rev-list", "--ancestry-path", f"{request['commit']}..HEAD"], cwd=cwd,+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,+ stdin=subprocess.DEVNULL, env=source_git_env(),+ )+ # The target need not exist locally before the updater's fetch. When it+ # does, any descendants prove that this pinned build would roll us back.+ if result.returncode == 0 and result.stdout.strip():+ raise ValueError("Source retirement would downgrade a newer source commit; select the destination channel explicitly")+ if terminal["head"]["sequence"] > request["sequence"]:+ # Shallow checkouts may lack the qualified commit, even when HEAD is+ # today's stable build. Read it with the protocol's full digest checks.+ current_manifest = _resolve_channel(terminal["name"], request["repository"]).manifest+ if current_manifest is None:+ raise ValueError("Source retirement cannot verify the current destination build")+ current = current_manifest["request"]+ installed = subprocess.run(+ [*git_cmd, "rev-parse", "HEAD"], cwd=cwd, check=True,+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,+ stdin=subprocess.DEVNULL, env=source_git_env(),+ ).stdout.strip()+ if installed == current["commit"] and installed != request["commit"]:+ raise ValueError("Source retirement would downgrade the newer destination build; select the destination channel explicitly")++def _read(url: str, *, missing_ok: bool = False) -> str | None:request = urllib.request.Request(url, headers={"User-Agent": "hermes-update", "Cache-Control": "no-cache",@@ -125,8 +252,9 @@ def _release_pointer(channel: str) -> tuple[str | None, str | None]:def resolve_source_release(channel: str, git_cmd=None, cwd=None, *, repository=None) -> tuple[str | None, str | None]:- """Return the published channel's tag and exact commit, or no target on failure.+ """Read historical stable/canary release metadata (not channel discovery).+ Runtime check/apply use ``resolve_source_target`` and never fall back here.Channel pointers outrank GitHub's release listing. A malformed pointer,draft, or tag/commit mismatch is not permission to select a different build.``git_cmd`` resolves the selected tag on origin; ZIP callers omit it anddiff --git a/hermes_cli/subcommands/update.py b/hermes_cli/subcommands/update.pyindex ae1b431cdc5..fb686edf0d7 100644--- a/hermes_cli/subcommands/update.py+++ b/hermes_cli/subcommands/update.py@@ -7,6 +7,7 @@ from typing import Callabledef build_update_parser(subparsers, *, cmd_update: Callable) -> None:"""Attach the ``update`` subcommand to ``subparsers``."""+ from hermes_cli.release_channels import validate_nameupdate_parser = subparsers.add_parser("update", help="Update Hermes Agent to the latest version",description="Pull the latest changes from git and reinstall dependencies")@@ -69,15 +70,14 @@ def build_update_parser(subparsers, *, cmd_update: Callable) -> None:update_parser.add_argument("--set-channel",default=None,- choices=("main", "stable", "canary"),+ type=validate_name,metavar="CHANNEL",help=("Persist the update channel for THIS install (recorded per "- "install in config.yaml under update.installs). 'stable' tracks "- "published stable releases, 'main' the git main branch, and "- "'canary' published canary prereleases. Source installs check out "- "the selected release's exact commit. Package channels are baked "- "into their separate stable/canary identities and cannot be changed."+ "install in config.yaml under update.installs). Names are resolved "+ "from the release archive, not a built-in list. Source installs "+ "check out the published build's exact commit; main follows the "+ "source branch. Package channels are baked into their identities."),)update_parser.add_argument(@@ -92,7 +92,7 @@ def build_update_parser(subparsers, *, cmd_update: Callable) -> None:update_parser.add_argument("--channel",default=None,- choices=("stable", "main", "canary"),+ type=validate_name,metavar="CHANNEL",help=("Track CHANNEL for this run only (transient override; "diff --git a/hermes_cli/update_channel.py b/hermes_cli/update_channel.pyindex 9c50c03e82b..b614e650282 100644--- a/hermes_cli/update_channel.py+++ b/hermes_cli/update_channel.py@@ -21,8 +21,8 @@ same path, and the channel opt-in must survive that.* Written by ``hermes update --set-channel <x>`` from inside an install(it knows its own id — the user never types a sha).* Shown by ``hermes update --install-id`` and the desktop About page.-* Source installs select main or a published stable/canary release. Bundles- derive their channel from the baked tag, never from these records.+* Source installs select an R2 channel name, or use an explicit branch override.+ Bundles derive their channel from their baked identity, never these records.``external`` installs have no configurable channel; the steward owns updates.Pure-stdlib leaf module (plus hermes-internal imports done lazily): the@@ -32,6 +32,8 @@ installers and boot paths read it before the full config machinery loads.from __future__ import annotationsfrom hermes_cli.runtime_paths import install_key, installs_root+from hermes_cli.release_channels import validate_name+from contextlib import contextmanagerimport loggingimport osimport re@@ -43,7 +45,7 @@ logger = logging.getLogger(__name__)CHANNEL_MAIN = "main"CHANNEL_STABLE = "stable"CHANNEL_CANARY = "canary"-VALID_CHANNELS = (CHANNEL_MAIN, CHANNEL_STABLE, CHANNEL_CANARY)+# A canary release tag: v<major>.<minor>.<patch>-canary.<YYYYMMDDHHMMSS>,# or the legacy date-only shape. THIS is the single authority for the@@ -141,6 +143,11 @@ def default_channel(project_root: Optional[Path] = None) -> str:stamp = _read_stamp(root)if not _package_channel(stamp):return CHANNEL_MAIN+ if stamp.get("source") == "channel-build":+ request = stamp.get("channelBuild")+ if not isinstance(request, dict):+ raise ValueError("Channel bundle has no baked subscription")+ return validate_name(request.get("channel"))return CHANNEL_CANARY if is_canary_tag(stamp.get("tag")) else CHANNEL_STABLE@@ -153,8 +160,8 @@ def resolve_update_channel(if _package_channel(_read_stamp(root)):return default_channel(root)configured: Any = channel_record(config, root).get("channel")- if isinstance(configured, str) and configured.strip().lower() in VALID_CHANNELS:- return configured.strip().lower()+ if configured is not None:+ return validate_name(configured)return default_channel(root)@@ -173,11 +180,7 @@ def set_install_channel(root = Path(project_root) if project_root is not None else _default_root()if is_commit_build(root):raise ValueError(COMMIT_BUILD_UPDATE_MESSAGE)- channel = (channel or "").strip().lower()- if channel not in VALID_CHANNELS:- raise ValueError(- f"unknown channel {channel!r} (one of {', '.join(VALID_CHANNELS)})"- )+ channel = validate_name(channel)stamp = _read_stamp(root)if _package_channel(stamp) or stamp.get("updateMechanism") == "external":@@ -212,7 +215,54 @@ def handle_metadata_args(args, project_root: Path) -> bool:return True-def _write_channel_record(sha16: str, path: str, channel: str) -> None:+@contextmanager+def _channel_write_lock(config_path: Path):+ """Serialize channel selection and retirement across CLI processes."""+ from hermes_cli.config import _CONFIG_LOCK++ config_path.parent.mkdir(parents=True, exist_ok=True)+ with _CONFIG_LOCK, config_path.with_suffix(".channels.lock").open("a+b") as lock:+ if os.name == "nt":+ import msvcrt+ lock.write(b"\0")+ lock.flush()+ lock.seek(0)+ msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)+ else:+ import fcntl+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)+ try:+ yield+ finally:+ if os.name == "nt":+ lock.seek(0)+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)+++def adopt_retired_channel(request: dict) -> bool:+ """After verified completion, adopt only an unchanged persistent subscription."""+ retirement = request.get("channel_retirement")+ if retirement is None:+ return False+ return _write_channel_record(+ install_id(Path(request["source"])), request["source"],+ validate_name(retirement["destination"]),+ expected=retirement["original"], config_path=Path(request["home"]) / "config.yaml")+++def _write_channel_record(sha16: str, path: str, channel: str, *,+ expected: dict | None = None, config_path: Path | None = None) -> bool:+ from hermes_cli.config import get_config_path++ config_path = config_path if config_path is not None else get_config_path()+ with _channel_write_lock(config_path):+ return _write_channel_record_locked(sha16, path, channel, expected, config_path)+++def _write_channel_record_locked(sha16: str, path: str, channel: str,+ expected: dict | None, config_path: Path) -> bool:"""Write ``update.installs.<sha16>`` into config.yaml, preserving the rest.Persists through the shared comment-preserving atomic writer@@ -225,12 +275,7 @@ def _write_channel_record(sha16: str, path: str, channel: str) -> None:"""from utils import atomic_roundtrip_yaml_update- from hermes_cli.config import (- get_config_path,- require_readable_config_before_write,- )-- config_path = get_config_path()+ from hermes_cli.config import require_readable_config_before_writeexisting = require_readable_config_before_write(config_path)update_cfg = existing.get("update")if update_cfg is not None and not isinstance(update_cfg, dict):@@ -239,10 +284,13 @@ def _write_channel_record(sha16: str, path: str, channel: str) -> None:if installs is not None and not isinstance(installs, dict):raise ValueError("config key 'update.installs' is not a mapping")record = installs.get(sha16) if isinstance(installs, dict) else None+ if expected is not None and (record or {}) != expected:+ return Falsenew_record = dict(record) if isinstance(record, dict) else {}new_record["path"] = path # DATA, for humans + doctor GCnew_record["channel"] = channelatomic_roundtrip_yaml_update(config_path, f"update.installs.{sha16}", new_record)+ return Truedef stale_channel_records(config: Optional[dict]) -> list[tuple[str, dict, str]]:diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 26cb0e4080f..c38a35fd1a1 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -22,6 +22,7 @@ from hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patchfrom hermes_cli.update_cmd_common import _best_effort# Captured BEFORE a checkout swap: parent transport/lifecycle never imports new code.from hermes_cli.update_completion import run_completion+from hermes_cli.update_channel import adopt_retired_channelfrom pm.receipt import accept_worker_receipt as _accept_completion_pm_receiptfrom hermes_cli import update_receipt as _completion_receipt, update_cmd_config as _completion_configfrom hermes_cli._old_updater import stop_for_relaunch@@ -524,17 +525,15 @@ def _source_update_channel(args=None, *, channel=None, branch_explicit=False) ->"""Explicit branches win; otherwise transient channel, then this install's record."""if branch_explicit or getattr(args, "branch", None):return "main"- transient = channel or getattr(args, "channel", None)- if transient:- return transient- from hermes_cli.config import load_config+ transient = channel if channel is not None else getattr(args, "channel", None)+ if transient is not None:+ from hermes_cli.release_channels import validate_name+ return validate_name(transient)from hermes_cli.update_channel import resolve_update_channel- config = None- try:- config = load_config()- except Exception as exc:- logger.debug("Could not load config for channel resolution: %s", exc)+ from hermes_cli.config import get_config_path, require_readable_config_before_write++ config = require_readable_config_before_write(get_config_path())return resolve_update_channel(config, _m().PROJECT_ROOT)@@ -588,23 +587,26 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False, chif swept:print(f" (removed {len(swept)} aborted-fetch pack temp file(s))")- from hermes_cli.update_channel import CHANNEL_STABLE-selected_channel = _source_update_channel(channel=channel, branch_explicit=branch_explicit)- if selected_channel in (CHANNEL_STABLE, "canary"):- from hermes_cli.source_releases import resolve_source_release+ if not branch_explicit:+ from hermes_cli.source_releases import resolve_source_target- print(f"→ Update channel: {selected_channel} (published releases)")- tag, tag_sha = resolve_source_release(selected_channel, git_cmd, _m().PROJECT_ROOT)- if tag is None:- print(f"✗ Could not resolve the {selected_channel} release commit.")+ print(f"→ Update channel: {selected_channel}")+ try:+ target = resolve_source_target(selected_channel, git_cmd, _m().PROJECT_ROOT)+ except (OSError, ValueError, subprocess.SubprocessError) as exc:+ print(f"✗ Could not resolve the {selected_channel} source channel: {exc}")sys.exit(1)- if _capture_head_sha(git_cmd, _m().PROJECT_ROOT) == tag_sha:- print(f"✓ Up to date with the latest release ({tag}).")- else:- print(f"→ Selected release available: {tag}")- print(" Run `hermes update` to install it.")- return+ if target.commit:+ if target.retired:+ print(f"→ {selected_channel} retired; source destination: {target.channel}")+ if _capture_head_sha(git_cmd, _m().PROJECT_ROOT) == target.commit:+ print(f"✓ Up to date with the latest release ({target.label}).")+ else:+ print(f"→ Selected release available: {target.label}")+ print(" Run `hermes update` to install it.")+ return+ branch = target.branch# Fetch only the branch we compare against; prefer upstream as the canonical# reference. A bare `git fetch <remote>` pulls every ref, and this repo has@@ -830,6 +832,8 @@ def _complete_source_update(request: dict | None) -> None:_completion_receipt._current.reset(current.current_token)if result["exit_code"]:raise SystemExit(result["exit_code"])+ if adopt_retired_channel(request):+ print(f"→ Source subscription moved to {request['channel_retirement']['destination']}")def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_ref=None) -> None:@@ -1346,7 +1350,13 @@ def _apply_pulled_update(_windows_gateway_resume=_windows_gateway_resume)if completion_request is not None:- completion_request["expected_sha"] = _capture_head_sha(git_cmd, _m().PROJECT_ROOT) or post_pull_sha+ observed = _capture_head_sha(git_cmd, _m().PROJECT_ROOT) or post_pull_sha+ pinned = completion_request.get("expected_sha")+ if pinned is not None and observed != pinned:+ print("✗ Checkout no longer matches the selected channel commit. No completion was applied.")+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)+ sys.exit(1)+ completion_request["expected_sha"] = pinned or observed_complete_source_update(completion_request)@@ -1387,31 +1397,42 @@ def _cmd_update_impl(args, gateway_mode: bool):branch = _m()._resolve_update_branch(args)completion_request["branch"] = branchtarget_ref = f"origin/{branch}"- release_tag, release_sha = None, None+ release_sha = Nonetarget_repository = None- from hermes_cli.update_channel import CHANNEL_STABLE-selected_channel = _source_update_channel(args)- if selected_channel in (CHANNEL_STABLE, "canary"):- from hermes_cli.source_releases import resolve_source_release, source_repository+ if not getattr(args, "branch", None):+ from hermes_cli.source_releases import resolve_source_target- print(f"→ Update channel: {selected_channel} (published releases)")+ from copy import deepcopy+ from hermes_cli.config import require_readable_config_before_write+ from hermes_cli.update_channel import channel_record++ original_record = deepcopy(channel_record(require_readable_config_before_write(+ Path(completion_request["home"]) / "config.yaml"), _m().PROJECT_ROOT))+ print(f"→ Update channel: {selected_channel}")try:- target_repository = source_repository(None if use_zip_update else git_cmd, _m().PROJECT_ROOT)- except (OSError, subprocess.SubprocessError) as exc:- print(f"✗ Could not identify the release repository: {exc}")- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(1)- release_tag, release_sha = resolve_source_release(- selected_channel, None if use_zip_update else git_cmd, _m().PROJECT_ROOT,- repository=target_repository)- if release_tag is None or not re.fullmatch(r"[0-9a-f]{40}", release_sha or ""):- print(f"✗ Could not resolve the {selected_channel} release commit. No update was applied.")- print(" Retry, or switch channels with: hermes update --set-channel main")+ target = resolve_source_target(+ selected_channel, None if use_zip_update else git_cmd, _m().PROJECT_ROOT)+ except (OSError, ValueError, subprocess.SubprocessError) as exc:+ print(f"✗ Could not resolve the {selected_channel} source channel: {exc}. No update was applied.")_m()._resume_windows_gateways_after_update(_windows_gateway_resume)sys.exit(1)- print(f"→ Latest release: {release_tag}")- target_ref = release_sha+ if target.retired:+ print(f"→ {selected_channel} retired; source destination: {target.channel}")+ if (not getattr(args, "channel", None)+ and original_record.get("channel", "main") == selected_channel):+ completion_request["channel_retirement"] = {+ "original": original_record, "destination": target.channel}+ target_repository = target.repository+ release_sha = target.commit+ if release_sha:+ print(f"→ Latest release: {target.label}")+ target_ref = release_sha+ completion_request["expected_sha"] = release_sha+ else:+ branch = target.branch+ completion_request["branch"] = branch+ target_ref = f"origin/{branch}"if use_zip_update:try:@@ -1450,18 +1471,8 @@ def _cmd_update_impl(args, gateway_mode: bool):_m()._warn_orphaned_update_autostashes(git_cmd, _m().PROJECT_ROOT)print("→ Fetching updates...")- if release_tag:+ if release_sha:fetch_result = _git_run(git_cmd, ["fetch", "--no-tags", "origin", target_ref], network=True)- if fetch_result.returncode != 0:- # Older servers require a named ref. Do not change local tags.- fetch_result = _git_run(- git_cmd, ["fetch", "--no-tags", "origin", f"refs/tags/{release_tag}"], network=True)- if fetch_result.returncode == 0:- fetched = _git_run(git_cmd, ["rev-parse", "--verify", "FETCH_HEAD^{commit}"])- if fetched.returncode != 0 or fetched.stdout.strip() != target_ref:- print("✗ The release tag changed during this update. Retry to select its new commit.")- _m()._resume_windows_gateways_after_update(_windows_gateway_resume)- sys.exit(1)else:fetch_result = _git_run(git_cmd, ["fetch", "origin", branch], network=True)if fetch_result.returncode != 0:@@ -1482,8 +1493,8 @@ def _cmd_update_impl(args, gateway_mode: bool):completion_request=completion_request)return- if release_tag:- print(f"→ Switching to release {release_tag} ({release_sha[:10]})")+ if release_sha:+ print(f"→ Switching to source commit {release_sha[:10]}")elif commit_count > 0:print(f"→ Found {commit_count} new commit(s)")else:@@ -1495,7 +1506,7 @@ def _cmd_update_impl(args, gateway_mode: bool):git_cmd, branch, _plan.auto_stash_ref, prompt_for_restore=_plan.prompt_for_restore,gw_input_fn=gw_input_fn, discard_local_changes=opts.discard_local_changes,keep_stash=opts.keep_stash, target_ref=target_ref, pre_sync_sha=_plan.pre_sync_sha,- sync_upstream=is_fork and branch == "main" and not release_tag, assume_yes=assume_yes,+ sync_upstream=is_fork and branch == "main" and not release_sha, assume_yes=assume_yes,in_place_update=_plan.in_place_update, _windows_gateway_resume=_windows_gateway_resume)_apply_pulled_update(git_cmd, branch, pre_pull_sha, _plan,diff --git a/scripts/bundles/channel_artifacts.py b/scripts/bundles/channel_artifacts.pynew file mode 100644index 00000000000..f7a982c3d25--- /dev/null+++ b/scripts/bundles/channel_artifacts.py@@ -0,0 +1,63 @@+"""One native manifest/feed writer for admitted previews and protected releases."""+from __future__ import annotations++import base64+import hashlib+from pathlib import Path+++from hermes_cli.release_channels import ChannelError, build_prefix, canonical_json, validate_manifest+from scripts.bundles.release_artifacts import single, validate_windows_bundle, write_appinstaller+++def assemble(request: dict, native: dict, root: Path, *, artifact_prefix: str) -> tuple[dict, list[Path]]:+ files = native["files"]+ rows = native["packages"]+ if sorted((row["platform"], row["arch"]) for row in rows) != [+ (platform, arch) for platform in ("macos", "windows") for arch in ("arm64", "x64")]:+ raise ChannelError("Native metadata must cover both platforms and architectures")+ prefix = build_prefix(request["buildId"])+ base = request["publicBase"]+ windows = [row for row in rows if row["platform"] == "windows"]+ 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-"))+ validate_windows_bundle(root / bundle_name, windows)+ packages, mac_files = [], []+ for row in rows:+ 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": artifact_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}/{artifact_prefix}{name}", "sha512": digest, "size": files[name]["size"]})+ manifest = {"schema": 1, "request": request, "packages": packages}+ if all(row.get("receiverProtocol") == 1 for row in rows):+ manifest["receiverProtocol"] = 1+ tag = request.get("releaseTag", "")+ record = {"name": request["channel"], "repository": request["repository"], "identity": request["identity"],+ "policy": ("canary-release" if "-canary." in tag else "stable-release") if tag else "preview", "head": None}+ validate_manifest(manifest, record, base)+ 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}/{artifact_prefix}{bundle_name}", update_policy="pinned")+ 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"))+ # A neutral feed name avoids interpreting custom channel names as prereleases.+ feed.write_bytes(canonical_json({"version": request["version"], "files": mac_files,+ "path": first["url"], "sha512": first["sha512"]}))+ return manifest, [feed, descriptor]diff --git a/scripts/bundles/desktop.py b/scripts/bundles/desktop.pyindex 81eec9b1361..27be104dae1 100644--- a/scripts/bundles/desktop.py+++ b/scripts/bundles/desktop.py@@ -59,10 +59,13 @@ def build_prepared(path: Path, builder_args: list[str], variant: str | None = Nodef _build_prepared(prepared, builder_args: list[str], variant: str | None) -> None:prepared.validate()- from scripts.bundles.desktop_inputs import build_environment, packaging_environment, select_variant+ from scripts.bundles.desktop_inputs import build_environment, packaging_environment, select_variant, validate_builder_identityfrom scripts.bundles.native import finish_nativerequest = prepared.request+ validate_builder_identity(request, builder_args)+ if request.channel_request is not None and not request.target.startswith(("darwin-", "win32-")):+ raise ValueError("channel builds require a supported native macOS or Windows target")variant = select_variant(prepared, variant)repo, node = request.source, str(prepared.node)env = build_environment(prepared, variant, os.environ)@@ -97,7 +100,9 @@ def _build_prepared(prepared, builder_args: list[str], variant: str | None) -> N# Windows file-version and MSIX build-number policy remains with its packager.version_args = []if sys.platform == "win32":- if request.tag is None:+ if request.channel_request is not None:+ metadata = {"file": request.channel_request["windowsVersion"], "build": None}+ elif request.tag is None:# The plain version needs no canary build-number override.metadata = {"file": None, "build": None}else:@@ -116,10 +121,11 @@ def _build_prepared(prepared, builder_args: list[str], variant: str | None) -> Ndef main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--tag", required=False,- help="Release tag (vX.Y.Z / canary). Required unless --commit is given")+ help="Release tag (vX.Y.Z / canary), exclusive with --commit/--channel-request")parser.add_argument("--commit", dest="commit_build", default=None,help="Commit-only build: exact full 40-char SHA the checkout is at; ""version comes from the target pyproject, no tag is referenced")+ parser.add_argument("--channel-request", type=Path, help="Immutable admitted channel request JSON")parser.add_argument("--variant", choices=["bundled", "store", "light"])parser.add_argument("--repo", type=Path, default=ROOT)parser.add_argument("--work", type=Path)@@ -131,7 +137,7 @@ def main() -> None:builder_args = [v for v in args.builder_args if v != "--"]try:if args.prepared:- if args.tag or args.commit_build or args.prepare_only or args.work or args.cache:+ if args.tag or args.commit_build or args.channel_request or args.prepare_only or args.work or args.cache:parser.error("--prepared supplies the complete build request")build_prepared(args.prepared, builder_args, args.variant)else:@@ -141,7 +147,9 @@ def main() -> None:variant=args.variant or "bundled",work=args.work or args.repo / ".build/desktop-job",cache=args.cache or args.repo / ".cache/desktop-inputs",- bundle_env=decode(os.environ.get("HERMES_BUNDLE_ENV_JSON", "")))+ bundle_env=decode(os.environ.get("HERMES_BUNDLE_ENV_JSON", "")),+ channel_request=json.loads(args.channel_request.read_text(encoding="utf-8-sig"))+ if args.channel_request else None)if args.prepare_only and builder_args:parser.error("builder arguments belong to the build phase")result = prepare(request)diff --git a/scripts/bundles/desktop_inputs.py b/scripts/bundles/desktop_inputs.pyindex 10d090ae4d2..62f0e9a8c8c 100644--- a/scripts/bundles/desktop_inputs.py+++ b/scripts/bundles/desktop_inputs.py@@ -4,11 +4,12 @@ from __future__ import annotationsfrom collections.abc import Mappingfrom contextlib import contextmanagerimport json+import refrom pathlib import Pathfrom typing import TYPE_CHECKINGif TYPE_CHECKING:- from scripts.bundles.desktop_prepare import PreparedDesktop+ from scripts.bundles.desktop_prepare import BuildRequest, PreparedDesktop@contextmanager@@ -37,13 +38,29 @@ def build_environment(prepared: PreparedDesktop, variant: str, inherited: Mappinif prepared.python != selection.entries["python"].binary or prepared.node != selection.entries["node"].binary:raise ValueError("prepared Python/Node paths do not match selected tools; prepare again")env = selection.environment(env)+ env["HERMES_PYTHON"] = str(prepared.python)+ return identity_environment(request, variant, env)+++def identity_environment(request: BuildRequest, variant: str, inherited: Mapping[str, str]) -> dict[str, str]:+ """One build-only bridge shared by dependency workers, stamp and packagers."""+ request.validate_channel()+ if request.channel_request is not None and variant != "bundled":+ raise ValueError("channel builds currently support only the bundled variant")+ env = dict(inherited)env.update(CI="true", PYTHONUTF8="1", GITHUB_SHA=request.commit,- HERMES_DESKTOP_VARIANT=variant, HERMES_PYTHON=str(prepared.python),+ HERMES_DESKTOP_VARIANT=variant,HERMES_PAYLOAD_VERSION=request.version,HERMES_BUNDLE_ENV_JSON=json.dumps(request.bundle_env, sort_keys=True))env.pop("BUILD_NUMBER", None)env.pop("GITHUB_HEAD_REF", None)- if request.tag is None:+ env.pop("_HERMES_CHANNEL_REQUEST_JSON", None)+ if request.channel_request is not None:+ env["_HERMES_CHANNEL_REQUEST_JSON"] = json.dumps(request.channel_request, sort_keys=True)+ env["GITHUB_REPOSITORY"] = request.channel_request["repository"]+ for key in ("HERMES_BUILD_COMMIT", "HERMES_PAYLOAD_TAG", "GITHUB_REF_NAME"):+ env.pop(key, None)+ elif request.tag is None:env["HERMES_BUILD_COMMIT"] = request.commitenv.pop("HERMES_PAYLOAD_TAG", None)env.pop("GITHUB_REF_NAME", None)@@ -54,6 +71,14 @@ def build_environment(prepared: PreparedDesktop, variant: str, inherited: Mappinreturn env+def validate_builder_identity(request: BuildRequest, args: list[str]) -> None:+ if request.channel_request is not None and any(+ re.match(r"(?:-c|--config)\.extraMetadata\.(?:version|shortVersion|shortVersionWindows)=", arg)+ for arg in args+ ):+ raise ValueError("channel package versions come only from the admitted request")++def packaging_environment(build: Mapping[str, str], inherited: Mapping[str, str],target: str) -> dict[str, str]:env = dict(build)diff --git a/scripts/bundles/desktop_prepare.py b/scripts/bundles/desktop_prepare.pyindex c6492fd59cd..d5dca72140c 100644--- a/scripts/bundles/desktop_prepare.py+++ b/scripts/bundles/desktop_prepare.py@@ -5,6 +5,8 @@ import argparsefrom dataclasses import asdict, dataclassimport hashlibimport json+import re+from copy import deepcopyimport osfrom pathlib import Pathimport shutil@@ -63,6 +65,24 @@ def selected_tool_inputs(request: BuildRequest) -> list[Path]:return [entry.path for entry in selection.entries.values()]+def validate_channel_request(value: dict) -> dict:+ """Add native packaging constraints to the shared release protocol."""+ from hermes_cli.release_channels import validate_request+ from scripts.releases.bundle_env import validate++ validate_request(value)+ validate(value["bundleEnv"])+ identity = value["identity"]+ for field in ("cliName", "windowsExecutableName", "appNamePascal", "artifactNamePascal"):+ if re.fullmatch(r"(?i:con|prn|aux|nul|com[0-9]|lpt[0-9])", identity[field].split(".")[0]):+ raise ValueError(f"reserved channel native identity {field}")+ if identity["windowsExecutableName"].endswith((".", " ")):+ raise ValueError("invalid channel native identity windowsExecutableName")+ if not value["publicBase"].startswith("https://"):+ raise ValueError("channel publicBase must be HTTPS for packaged clients")+ return deepcopy(value)++@dataclass(frozen=True)class BuildRequest:source: Path@@ -74,16 +94,28 @@ class BuildRequest:variant: strtarget: strbundle_env: dict[str, str | None]+ channel_request: dict | None = None@classmethoddef create(cls, source: Path, *, tag: str | None, commit: str | None, variant: str,- work: Path, cache: Path, bundle_env: dict[str, str | None]) -> BuildRequest:+ work: Path, cache: Path, bundle_env: dict[str, str | None],+ channel_request: dict | None = None) -> BuildRequest:from pm.store import current_targetfrom scripts.bundles.desktop import release_versionfrom scripts.releases.bundle_env import validatefrom scripts.releases.commit_build import require_commit, version_atfrom scripts.termux.deb_version import channel_for_tag+ if channel_request is not None:+ channel_request = validate_channel_request(channel_request)+ if variant != "bundled":+ raise ValueError("channel builds currently support only the bundled variant")+ if tag or commit not in (None, channel_request["commit"]):+ raise ValueError("channel request conflicts with tag or commit selection")+ if bundle_env and bundle_env != channel_request["bundleEnv"]:+ raise ValueError("bundle defaults conflict with channel request")+ commit = channel_request["commit"]+ bundle_env = channel_request["bundleEnv"]if variant == "store" and (commit or not tag or channel_for_tag(tag) != "stable"):raise ValueError("Store packaging requires a stable release tag")if variant not in {"bundled", "store", "light"}:@@ -109,14 +141,31 @@ class BuildRequest:version = release_version(source, tag)commit = git(source, "rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}")require_source(source, commit)- return cls(source, work, cache, commit, tag, version, variant, current_target(), bundle_env)+ if channel_request is not None:+ if version != channel_request["sourceVersion"]:+ raise ValueError("channel sourceVersion differs from checkout project version")+ version = channel_request["version"]+ return cls(source, work, cache, commit, tag, version, variant, current_target(), bundle_env, channel_request)def data(self) -> dict:return {**asdict(self), "source": str(self.source), "work": str(self.work), "cache": str(self.cache)}@classmethoddef from_data(cls, data: dict) -> BuildRequest:- return cls(**{**data, **{name: Path(data[name]) for name in ("source", "work", "cache")}})+ request = cls(**{**deepcopy(data), **{name: Path(data[name]) for name in ("source", "work", "cache")}})+ request.validate_channel()+ return request++ def validate_channel(self) -> None:+ if self.channel_request is None:+ return+ channel = validate_channel_request(self.channel_request)+ if (self.variant != "bundled" or self.tag is not None or self.commit != channel["commit"]+ or self.version != channel["version"] or self.bundle_env != channel["bundleEnv"]):+ raise ValueError("prepared build differs from admitted channel request")++ def identity_digest(self) -> str:+ return hashlib.sha256(json.dumps(self.data(), sort_keys=True, separators=(",", ":")).encode()).hexdigest()def workspaces(self) -> list[str]:return ["apps/desktop"] + ([] if self.variant == "light" else ["ui-tui", "web"])@@ -133,6 +182,7 @@ class PreparedDesktop:payload: Path | Nonedigests: dict[str, str]native_toolchain: str+ request_digest: str | None = None@classmethoddef record(cls, request: BuildRequest, *, python: Path, node: Path, icon_python: Path,@@ -143,7 +193,7 @@ class PreparedDesktop:require_owned(request, files)files.extend(selected_tool_inputs(request))return cls(request, python, node, icon_python, native, packager, payload,- {str(path): fingerprint(path) for path in files}, native_toolchain)+ {str(path): fingerprint(path) for path in files}, native_toolchain, request.identity_digest())def write(self, path: Path) -> None:from pm.lock import _write@@ -151,7 +201,8 @@ class PreparedDesktop:**{name: str(value) if value is not None else None for name, value in (("python", self.python), ("node", self.node), ("icon_python", self.icon_python),("native", self.native), ("packager", self.packager), ("payload", self.payload))},- "digests": self.digests, "native_toolchain": self.native_toolchain})+ "digests": self.digests, "native_toolchain": self.native_toolchain,+ "request_digest": self.request_digest})@classmethoddef load(cls, path: Path) -> PreparedDesktop:@@ -169,6 +220,9 @@ class PreparedDesktop:def validate(self) -> None:from pm.store import current_target+ self.request.validate_channel()+ if (self.request_digest is not None or self.request.channel_request is not None) and self.request_digest != self.request.identity_digest():+ raise ValueError("preparation request identity changed; prepare again")require_source(self.request.source, self.request.commit)if self.request.target != current_target():raise ValueError("preparation target differs from this host")@@ -187,6 +241,9 @@ class PreparedDesktop:def prepare(request: BuildRequest) -> Path:from scripts.bundles.desktop_inputs import build_lock+ request.validate_channel()+ if request.channel_request is not None and not request.target.startswith(("darwin-", "win32-")):+ raise ValueError("channel builds require a supported native macOS or Windows target")require_source(request.source, request.commit)with build_lock(request.source):return _prepare(request)@@ -227,7 +284,10 @@ def prepare_in_worker(request: BuildRequest) -> Path:from scripts.bundles.native import prepare_nativerequire_source(request.source, request.commit)+ from scripts.bundles.desktop_inputs import identity_environment+ request.validate_channel()python, node, env = prepare_tools(request.source, request.work, request.cache, os.environ)+ env = identity_environment(request, request.variant, env)native_toolchain = Path(env["UV_CACHE_DIR"]).namerun([str(node), "scripts/build/node-deps.mjs", "--source", str(request.source), "--reuse","--native-toolchain", native_toolchain,diff --git a/scripts/bundles/release_artifacts.py b/scripts/bundles/release_artifacts.pyindex 79e55efea60..e5ee2ac2248 100644--- a/scripts/bundles/release_artifacts.py+++ b/scripts/bundles/release_artifacts.py@@ -22,7 +22,12 @@ def sha256_file(file: Path) -> str:return hashlib.file_digest(handle, "sha256").hexdigest()-def stamp_matches(stamp: dict, tag: str, commit: str) -> None:+def stamp_matches(stamp: dict, tag: str, commit: str, *, channel_request: dict | None = None) -> None:+ if channel_request is not None:+ if (stamp.get("source") != "channel-build" or stamp.get("channelBuild") != channel_request+ or stamp.get("commit") != channel_request["commit"] or stamp.get("tag")):+ raise ValueError("Built package provenance does not match the channel request")+ returnif stamp.get("commit") != commit or stamp.get("tag") != tag:raise ValueError("Built package provenance does not match the release")@@ -34,9 +39,10 @@ def single(items):return items[0]-def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Path) -> None:+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."""- row = {"platform": platform, "arch": arch, "tag": tag, "commit": commit}+ row: dict = {"platform": platform, "arch": arch, "tag": tag, "commit": commit}if platform == "windows":package = single(p for p in root.glob(f"*-win-{arch}.msix") if not p.name.startswith("Store-"))with zipfile.ZipFile(package) as archive:@@ -44,7 +50,7 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Patidentity = manifest.find("{*}Identity")application = single(manifest.findall("{*}Applications/{*}Application"))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)+ stamp_matches(json.loads(archive.read(stamp_name)), 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"],@@ -60,9 +66,9 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Patwith zipfile.ZipFile(package) as archive:info = 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)+ stamp_matches(stamp, tag, commit, channel_request=channel_request)row.update(identity=info["CFBundleIdentifier"], teamId=team.group(1), version=info["CFBundleShortVersionString"], filename=package.name)- if row["version"] != tag[1:]:+ if row["version"] != (channel_request["version"] if channel_request else tag[1:]):raise ValueError("App version differs from release tag")elif platform == "termux":package = single((root / "deb").glob("*.deb"))@@ -78,6 +84,12 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Patraise ValueError("Termux package has no matching provenance")else:raise ValueError("Unknown platform")+ if channel_request is not None:+ expected = channel_request["identity"]["msixAppIdWithOrg" if platform == "windows" else "appId"]+ version = channel_request["windowsVersion" if platform == "windows" else "version"]+ if row["identity"] != expected or row["version"] != version:+ raise ValueError("Native package identity/version differs from channel request")+ row["request"] = channel_requestout.parent.mkdir(parents=True, exist_ok=True)out.write_text(json.dumps(row, sort_keys=True, indent=2) + "\n", encoding="utf-8")@@ -185,7 +197,7 @@ def publish(manifest: dict, root: Path, public_base: str) -> None:def write_appinstaller(out: Path, *, identity: str, publisher: str, version: str,- self_uri: str, artifact_uri: str) -> None:+ self_uri: str, artifact_uri: str, update_policy: str = "automatic") -> None:"""Serialize verified package facts; callers own channel/acceptance policy."""if not all((identity, publisher, version, self_uri, artifact_uri)):raise ValueError("Explicit identity, publisher, version, self URI and artifact URI are required")@@ -195,8 +207,11 @@ def write_appinstaller(out: Path, *, identity: str, publisher: str, version: strET.SubElement(descriptor, f"{{{ns}}}MainBundle", {"Name": identity, "Publisher": publisher, "Version": version, "Uri": artifact_uri,})- settings = ET.SubElement(descriptor, f"{{{ns}}}UpdateSettings")- ET.SubElement(settings, f"{{{ns}}}OnLaunch", {"HoursBetweenUpdateChecks": "12"})+ if update_policy not in ("automatic", "pinned"):+ raise ValueError("Unknown App Installer update policy")+ if update_policy == "automatic":+ settings = ET.SubElement(descriptor, f"{{{ns}}}UpdateSettings")+ ET.SubElement(settings, f"{{{ns}}}OnLaunch", {"HoursBetweenUpdateChecks": "12"})out.parent.mkdir(parents=True, exist_ok=True)ET.ElementTree(descriptor).write(out, encoding="utf-8", xml_declaration=True)@@ -263,6 +278,8 @@ def main(argv: list[str] | None = None) -> None:parser.add_argument("command", choices=["record", "assemble", "publish", "promote", "materialize", "appinstaller", "publish-appinstaller"])parser.add_argument("--platform", choices=["windows", "macos", "termux"])parser.add_argument("--arch")+ parser.add_argument("--channel-request", type=Path)+ parser.add_argument("--update-policy", choices=["automatic", "pinned"], default="automatic")parser.add_argument("--root", type=Path, required=True)parser.add_argument("--out", type=Path)parser.add_argument("--tag", default=os.environ.get("RELEASE_TAG"))@@ -285,10 +302,12 @@ def main(argv: list[str] | None = None) -> None:if not args.out:parser.error("appinstaller requires --out")write_appinstaller(args.out, identity=args.identity, publisher=args.publisher,- version=args.version, self_uri=args.self_uri, artifact_uri=args.artifact_uri)+ version=args.version, self_uri=args.self_uri, artifact_uri=args.artifact_uri,+ update_policy=args.update_policy)returnif args.command == "record":- record(args.platform, args.arch, args.root, args.tag, args.commit, args.out)+ request = json.loads(args.channel_request.read_text(encoding="utf-8-sig")) if args.channel_request else None+ record(args.platform, args.arch, args.root, args.tag, args.commit, args.out, channel_request=request)elif args.command == "assemble":assemble(args.root, args.tag, args.commit, args.public_base, args.out,smoke_results=json.loads(os.environ.get("RELEASE_NEEDS", "{}")))diff --git a/scripts/msix-shared.mjs b/scripts/msix-shared.mjsindex bf3baf23e46..35b7d12c6e0 100644--- a/scripts/msix-shared.mjs+++ b/scripts/msix-shared.mjs@@ -8,6 +8,34 @@ import { createRequire } from 'node:module'const require = createRequire(import.meta.url)+/** Build-only structured bridge; never read by the installed runtime.+ * @param {NodeJS.ProcessEnv} [env]+ * @returns {import('../apps/desktop/electron/install-stamp.js').ChannelBuildRequest | null}+ */+export function channelBuildRequest(env = process.env) {+ if (!env._HERMES_CHANNEL_REQUEST_JSON) return null+ const value = JSON.parse(env._HERMES_CHANNEL_REQUEST_JSON)+ if (env.HERMES_DESKTOP_VARIANT !== 'bundled') throw new Error('Channel builds support only bundled packaging')+ if (env.HERMES_BUILD_COMMIT || env.HERMES_PAYLOAD_TAG) throw new Error('Channel request conflicts with commit or tag identity')+ // The bundled toolchain already supplies Python. Reuse the authoritative+ // validator rather than maintaining a third protocol decoder for packaging.+ const validator = [+ 'import sys',+ 'sys.path.insert(0, sys.argv[1])',+ 'from hermes_cli.release_channels import decode_json',+ 'from scripts.bundles.desktop_prepare import validate_channel_request',+ 'validate_channel_request(decode_json(sys.stdin.buffer.read()))'+ ].join('; ')+ execFileSync(env.HERMES_PYTHON || 'python', ['-I', '-S', '-c', validator, path.resolve(import.meta.dirname, '..')], {+ env, input: env._HERMES_CHANNEL_REQUEST_JSON, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 30_000+ })+ if (env.HERMES_PAYLOAD_VERSION && env.HERMES_PAYLOAD_VERSION !== value.version) throw new Error('Channel package version conflicts with prepared request')+ Object.freeze(value.identity)+ Object.freeze(value.bundleEnv)+ return Object.freeze(value)+}++// The out-of-store MSIX publisher — the ATS signing cert subject, which is// what Windows compares against the package manifest publisher at install.// Mirrored from electron-builder.config.cjs so the .appinstaller and the@@ -174,6 +202,27 @@ export function storeManifestTemplate(template, version) {return template.replace('${version}', version)}+/** MsixTarget derives its quad from app semver even when shortVersion is set.+ * Bake the admitted quad into the already staged nonstable template instead.+ * @param {string} desktopDir+ * @param {import('../apps/desktop/electron/install-stamp.js').ChannelBuildRequest} request+ */+export function stageChannelManifest(desktopDir, request) {+ const file = path.join(desktopDir, 'build/msix-manifest.xml')+ const template = fs.readFileSync(path.join(desktopDir, 'assets/msix-manifest.xml'), 'utf8')+ const payload = JSON.parse(fs.readFileSync(path.join(desktopDir, 'build/agent-payload/manifest.json'), 'utf8'))+ const { appExecutionAliasApplications } = require(path.join(desktopDir, 'scripts/before-build.mjs'))+ const applications = appExecutionAliasApplications(payload.launchers, request.identity)+ if (template.split('${version}').length !== 2) throw new Error('Channel MSIX template must have one version macro')+ fs.writeFileSync(file, template.replace('${version}', request.windowsVersion)+ .replace('</Applications>', `${applications}\n </Applications>`), 'utf8')+ // The legacy hook emits one multi-alias extension when artifact/app names agree.+ // Channels always use separate applications for distinct CLI entrypoints.+ const extensions = path.join(desktopDir, 'build/msix-extensions.xml')+ const xml = fs.readFileSync(extensions, 'utf8')+ fs.writeFileSync(extensions, xml.replace(/<uap5:Extension\b[^>]*Category="windows\.appExecutionAlias"[^>]*>[\s\S]*?<\/uap5:Extension>/g, ''), 'utf8')+}+/*** Resolve the app identity for a desktop build from the app dir: the product* identity + package version. Pure-ish (reads product-identity.cjs and@@ -188,6 +237,11 @@ export function appIdentity(desktopDir, tag = process.env.HERMES_PAYLOAD_TAG ||const identity = require(path.join(desktopDir, 'product-identity.cjs'))const pkg = JSON.parse(fs.readFileSync(path.join(desktopDir, 'package.json'), 'utf8'))const repoRoot = path.resolve(desktopDir, '..', '..')+ const request = channelBuildRequest()+ if (request) {+ if (tag) throw new Error('Channel builds must not select a release tag')+ return { identity, version: request.windowsVersion, fileVersion: request.version, name: identity.artifactNamePascal }+ }// Commit artifacts retain app semver but do not advance an update channel.if (process.env.HERMES_BUILD_COMMIT) {if (tag) throw new Error('Commit-only builds must not set HERMES_PAYLOAD_TAG')diff --git a/scripts/release.py b/scripts/release.pyindex 493382f7b01..4ba9ae15769 100755--- a/scripts/release.py+++ b/scripts/release.py@@ -2963,8 +2963,14 @@ def main():help="Write changelog to file instead of stdout")parser.add_argument("--no-changelog", action="store_true",help="Skip changelog")+ from scripts.releases.channel_build import add_arguments, validate_arguments, cmd_channel++ add_arguments(parser)args = parser.parse_args()+ if validate_arguments(parser, args):+ cmd_channel(args)+ returnif (args.bundle_env or args.bundle_unset) and args.build_commit is None:parser.error("--bundle-env and --bundle-unset require --build-commit")if args.canary and args.bump:diff --git a/scripts/releases/channel_build.py b/scripts/releases/channel_build.pynew file mode 100644index 00000000000..8ba05d5743d--- /dev/null+++ b/scripts/releases/channel_build.py@@ -0,0 +1,184 @@+"""Exact-commit channel requests and release-tool dispatch (one-offs stay separate)."""+from __future__ import annotations++import hashlib+import json+from pathlib import Path+import subprocess++from hermes_cli.release_channels import (+ ChannelError, canonical_json,+ require_commit, require_sha256, validate_name, validate_repository,+ validate_request,+)+from scripts.releases import commit_build, r2+from scripts.releases.bundle_env import parse_assignments, validate+from scripts.releases.channels import ChannelPublisher, R2ChannelStore+++def dispatch_command(request: dict, repository: str, branch: 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,+ "-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="]+++def prepare_build(*, name: str, revision: str, remote: str, repo: Path, repository: str,+ default_branch: str, publisher: ChannelPublisher, dispatch,+ bundle_env: dict | None = None, controller_commit: str | None = None,+ publish: bool = False) -> dict:+ validate_name(name)+ validate_repository(repository)+ if publisher.repository.casefold() != repository.casefold():+ raise ChannelError("Publisher repository authority mismatch")+ bundle_env = validate({} if bundle_env is None else bundle_env)+ commit = commit_build.resolve_revision(revision, remote, repo)+ version = commit_build.version_at(repo, commit)+ if not default_branch or default_branch.startswith("-"):+ raise ChannelError("Missing repository default branch")+ if controller_commit is None:+ advertised = commit_build.output(["git", "ls-remote", remote, f"refs/heads/{default_branch}"], repo).split()+ if len(advertised) != 2 or advertised[1] != f"refs/heads/{default_branch}":+ raise ChannelError("Could not resolve repository default branch")+ controller_commit = require_commit(advertised[0])+ require_commit(controller_commit)+ current = publisher._read(name)+ if current is not None:+ publisher._preview("allocate", current[0])+ result = {"channel": name, "repository": repository, "commit": commit,+ "sourceVersion": version, "controllerCommit": controller_commit, "created": current is None}+ if not publish:+ return result+ publisher.create(name)+ request = publisher.allocate(name, commit, version, bundle_env, controller_commit)+ command = dispatch_command(request, repository, default_branch)+ print(f"Admitted build {request['buildId']}; request SHA256 {hashlib.sha256(canonical_json(request)).hexdigest()}")+ dispatch(command)+ return {**result, "request": request, "command": command}+++def resume_build(build_id: str, digest: str, *, publisher: ChannelPublisher,+ default_branch: str, dispatch, publish: bool = True) -> dict:+ request = publisher.request(build_id, digest)+ current = publisher._read(request["channel"])+ if current is None:+ raise ChannelError("Request channel no longer exists")+ 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)+ if publish:+ dispatch(command)+ return {"request": request, "command": command}+++def maintainer_authorizer(repository: str):+ validate_repository(repository)+ def authorize(action: str, record: dict) -> None:+ actor = commit_build.output(["gh", "api", "user", "--jq", ".login"])+ permission = commit_build.output(["gh", "api", f"repos/{repository}/collaborators/{actor}/permission", "--jq", ".permission"])+ if permission not in {"write", "maintain", "admin"}:+ raise ChannelError("Channel administration requires a repository maintainer")+ if action == "bootstrap" and permission not in {"maintain", "admin"}:+ raise ChannelError("Protected bootstrap requires maintain or admin permission")+ return authorize+++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.+ 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)++ return ChannelPublisher(store, repository, base, authorize=maintainer_authorizer(repository),+ verify_build=verify_build, verify_retirement=verify_retirement)+++def cmd_channel(args) -> None:+ from scripts import release+ try:+ remote = release.resolve_push_remote(args.remote)+ repository = release.remote_github_repo(remote)+ if not repository:+ raise ChannelError("Channel commands require an explicit GitHub remote")+ publisher = configured_publisher(repository)+ operations = {+ "channels": lambda: publisher.list(),+ "resume_channel_build": lambda: resume_build(+ args.resume_channel_build, args.request_sha256, publisher=publisher,+ default_branch=release._default_branch(repository), publish=args.publish,+ 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,+ repository=repository, default_branch=release._default_branch(repository), publisher=publisher,+ dispatch=lambda command: subprocess.run(command, cwd=release.REPO_ROOT, check=True, timeout=60),+ bundle_env=parse_assignments(args.bundle_env, args.bundle_unset), publish=args.publish),+ }+ selected = next(key for key in operations if getattr(args, key, None))+ result = operations[selected]()+ print(json.dumps(result, sort_keys=True, indent=2))+ if not args.publish and selected != "channels":+ print("Dry run: no R2 object or workflow was written. Add --publish to execute.")+ except (OSError, ValueError, subprocess.SubprocessError, r2.R2RequestError) as exc:+ raise SystemExit(f"release: channel operation refused: {exc}") from exc+++def _bootstrap_file(publisher: ChannelPublisher, path: Path, publish: bool) -> list[dict]:+ value = json.loads(path.read_text(encoding="utf-8-sig"))+ if not isinstance(value, list):+ raise ChannelError("Bootstrap input must be a list of {record, manifest} accepted release facts")+ # Validate every row before the first write; multi-object publication is not atomic.+ for row in value:+ publisher.bootstrap(row["record"], row.get("manifest"), publish=False)+ return [publisher.bootstrap(row["record"], row.get("manifest"), publish=publish) for row in value]+++def add_arguments(parser) -> None:+ parser.add_argument("--resume-channel-build", metavar="BUILD_ID", help="Retry an immutable admitted request without allocating")+ parser.add_argument("--request-sha256", type=require_sha256, metavar="SHA256", help="Pinned request digest for --resume-channel-build")+ parser.add_argument("--channel", type=validate_name, metavar="NAME", help="R2 channel for --build-commit")+ 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("--bootstrap-channels", metavar="JSON", help="Preview protected channel bootstrap from accepted release facts")+++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)+ if any(retirement) and not args.retire_channel:+ parser.error("Retirement options require --retire-channel")+ if len(selected) > 1:+ parser.error("Channel administration operations are mutually exclusive")+ if not selected:+ return False+ if (args.bundle_env or args.bundle_unset) and not args.channel:+ parser.error("--bundle-env and --bundle-unset require --build-commit")+ 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")+ 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")+ return Truediff --git a/scripts/releases/channel_disposable.py b/scripts/releases/channel_disposable.pynew file mode 100644index 00000000000..6bcd1d77b5f--- /dev/null+++ b/scripts/releases/channel_disposable.py@@ -0,0 +1,138 @@+"""Privileged allocation only: print a separate maintainer build dispatch."""+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import shlex++from hermes_cli.release_channels import canonical_json, channel_key, validate_name+from scripts.releases import commit_build, r2+from scripts.releases.channel_build import dispatch_command+from scripts.releases.channels import ChannelConflict, ChannelPublisher, R2ChannelStore+from scripts.releases.r2_scope import R2Scope, channel_public_base, require_run+++def probe(publisher: ChannelPublisher, commit: str, version: str, controller: str) -> None:+ """Exercise real create, CAS, stale-writer refusal, list and CDN readback."""+ scope = publisher.store.scope+ if not scope.prefix or publisher.public_base != channel_public_base():+ raise ValueError("CAS/CDN probes require the configured disposable namespace")+ name = "ci-cas-probe"+ publisher.create(name)+ current = publisher._read(name)+ if current is None:+ raise ValueError("Probe channel disappeared")+ old, etag = current+ first = publisher.allocate(name, commit, version, controller_commit=controller)+ second = publisher.allocate(name, commit, version, controller_commit=controller)+ try:+ publisher.store.put(channel_key(name), canonical_json(old), etag)+ except ChannelConflict:+ pass+ else:+ raise ValueError("R2 accepted a stale conditional channel write")+ if (second["sequence"] <= first["sequence"]+ or publisher.request(second["buildId"]) != second+ or name not in {record["name"] for record in publisher.list()}):+ raise ValueError("Disposable channel CAS/list probe failed")+ visible = publisher.reader.resolve(name).terminal+ if visible["nextSequence"] != second["sequence"] + 1 or visible["head"] is not None:+ raise ValueError("Disposable channel public readback differs from allocation")+++def require_receiver_scope(publisher) -> None:+ scope = getattr(publisher.store, "scope", None)+ if not isinstance(scope, R2Scope) or not scope.prefix or not publisher.public_base.endswith("/" + scope.prefix.rstrip("/")):+ raise ValueError("Receiver candidates require physically disposable storage")+++def allocate_receivers(publisher, commit: str, source_version: str, controller: str) -> dict:+ """Reserve official-identity test packages, not accepted or published releases."""+ from hermes_cli.release_channels import build_prefix, validate_request+ from scripts.releases.channel_releases import product_identity++ require_receiver_scope(publisher)+ if publisher._read("stable") is not None:+ raise ValueError("Receiver allocation requires a fresh disposable stable record")+ identity = product_identity("v0.0.1")+ requests = {}+ for sequence, slot in enumerate(("S", "T"), 1):+ request = {"schema": 1, "channel": "stable", "repository": publisher.repository,+ "sequence": sequence, "commit": commit, "sourceVersion": source_version,+ "controllerCommit": controller, "version": f"0.0.{sequence}",+ "windowsVersion": f"0.0.{sequence}.0", "releaseTag": f"v0.0.{sequence}",+ "receiverCandidate": True, "identity": identity, "bundleEnv": {},+ "publicBase": publisher.public_base}+ request["buildId"] = hashlib.sha256(canonical_json(request)).hexdigest()[:32]+ validate_request(request, policy="stable-release")+ requests[slot] = request+ record = {"schema": 1, "name": "stable", "repository": publisher.repository, "policy": "stable-release",+ "testOnly": True, "state": "active", "revision": 1, "nextSequence": 3, "head": None,+ "identity": identity}+ publisher._write(channel_key("stable"), record)+ for request in requests.values():+ publisher._write(build_prefix(request["buildId"]) + "request.json", request)+ return requests+++def allocate(env: dict[str, str]) -> dict:+ name = validate_name(env.get("DISPOSABLE_CHANNEL", ""))+ if name in {"ci-cas-probe", "stable", "canary", "main"}:+ raise ValueError("Use a non-protected disposable preview name")+ if env.get("CHANNEL_BUILD") or env.get("CHANNEL_REQUEST_SHA256") or env.get("R2_DISPOSABLE_RUN"):+ raise ValueError("Allocation cannot reuse a build request or select a storage scope")+ if env.get("TERMUX_ONLY") == "true":+ raise ValueError("Disposable allocation cannot select Termux")+ # A fresh attempt gets a fresh prefix, including controller reruns. Never+ # accept a caller-supplied path, public URL, or allocation namespace.+ run = require_run(env.get("GITHUB_RUN_ID", "") + "-" + env.get("GITHUB_RUN_ATTEMPT", ""))+ admitted = commit_build.admit(env)+ controller = commit_build.require_commit(env.get("GITHUB_SHA", ""))+ os.environ["R2_DISPOSABLE_RUN"] = run+ scope = R2Scope.configured()+ base = channel_public_base()+ repository = env["GITHUB_REPOSITORY"]++ def authorize(action: str, record: dict) -> None:+ if action not in {"create", "allocate"} or record["policy"] != "preview":+ raise ValueError("Disposable controller only creates and allocates previews")+ commit_build.admit(env)++ publisher = ChannelPublisher(R2ChannelStore(*r2.credentials(), scope=scope), repository,+ base, authorize=authorize)+ probe(publisher, admitted["sha"], admitted["payload-version"], controller)+ publisher.create(name)+ from scripts.releases.bundle_env import decode+ request = publisher.allocate(name, admitted["sha"], admitted["payload-version"],+ decode(env.get("BUNDLE_ENV_JSON", "")), controller)+ requests = {"A": request}+ if env.get("DISPOSABLE_RECEIVERS") == "true":+ requests["B"] = publisher.allocate(name, admitted["sha"], admitted["payload-version"],+ decode(env.get("BUNDLE_ENV_JSON", "")), controller)+ requests.update(allocate_receivers(publisher, admitted["sha"], admitted["payload-version"], controller))+ digest = hashlib.sha256(canonical_json(request)).hexdigest()+ command = dispatch_command(request, repository, env["DEFAULT_BRANCH"], disposable_run=run)+ return {"request": request, "requestSha256": digest, "disposableRun": run,+ "storagePrefix": scope.prefix, "command": command, "requests": requests,+ "commands": {slot: dispatch_command(value, repository, env["DEFAULT_BRANCH"], disposable_run=run)+ for slot, value in requests.items()}}+++def main() -> None:+ result = allocate(dict(os.environ))+ summary = ("## Disposable channel allocation\n\n"+ "CAS, stale-writer rejection, listing and public readback passed. "+ "No native build or production record was published.\n\n"+ f"Storage prefix: `{result['storagePrefix']}`\n\n"+ "Run this separately using your maintainer login; the controller token "+ "does not dispatch a publication run:\n\n" + "\n\n".join(+ f"### {slot}\n```sh\n{shlex.join(cmd)}\n```" for slot, cmd in result["commands"].items()) + "\n")+ with Path(os.environ["GITHUB_STEP_SUMMARY"]).open("a", encoding="utf-8") as stream:+ stream.write(summary)+ print(json.dumps(result, sort_keys=True))+++if __name__ == "__main__":+ main()diff --git a/scripts/releases/channel_publish.py b/scripts/releases/channel_publish.pynew file mode 100644index 00000000000..1b7abee4330--- /dev/null+++ b/scripts/releases/channel_publish.py@@ -0,0 +1,228 @@+"""Admit channel requests and publish only complete, native-smoked build manifests."""+from __future__ import annotations++import argparse+import base64+import hashlib+import json+import os+from pathlib import Path+import tempfile+import xml.etree.ElementTree as ET+import zipfile++from hermes_cli.release_channels import ChannelReader, build_prefix, canonical_json, decode_json, require_sha256, validate_request+from scripts.releases import commit_build, handoff, r2++NATIVE_LEGS = ("darwin-arm64", "darwin-x64", "win32-arm64", "win32-x64", "windows-universal")+REQUIRED_JOBS = ("validate", "build-darwin", "build-win32", "assemble-win32-bundle",+ "smoke-darwin", "smoke-win32", "smoke-win32-universal")+++def read_request(build_id: str, digest: str, public_base: str, repository: str) -> dict:+ require_sha256(digest)+ reader = ChannelReader(public_base, repository=repository)+ body = reader.read_bytes(build_prefix(build_id) + "request.json", digest)+ request = validate_request(decode_json(body), repository=repository, base_url=public_base)+ if request["buildId"] != build_id:+ raise ValueError("Channel request build ID differs from its key")+ return request+++def require_success(needs: dict) -> None:+ """Skipped, absent and empty native matrices cannot qualify publication."""+ if not isinstance(needs, dict):+ raise ValueError("Missing workflow results")+ failed = [name for name in REQUIRED_JOBS+ if not isinstance(needs.get(name), dict) or needs[name].get("result") != "success"]+ if failed:+ raise ValueError("Channel publication requires successful jobs: " + ", ".join(failed))+++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")+ 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"]}+++def _metadata(root: Path, request: dict, platform: str, arch: str) -> dict:+ native_platform = {"darwin": "macos", "win32": "windows"}[platform]+ row = json.loads((root / f"metadata-{native_platform}-{arch}.json").read_text(encoding="utf-8-sig"))+ identity_key, version_key = (("appId", "version") if platform == "darwin"+ else ("msixAppIdWithOrg", "windowsVersion"))+ if (row.get("request") != request or row.get("commit") != request["commit"]+ or row.get("arch") != arch or row.get("platform") != native_platform+ or row.get("identity") != request["identity"][identity_key]+ or row.get("version") != request[version_key]):+ raise ValueError("Native metadata differs from the admitted channel request")+ if platform == "win32" and row.get("applicationId") != request["identity"]["appNamePascal"]:+ raise ValueError("Windows application ID differs from channel identity")+ return row+++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++ require_success(needs)+ validate_request(request)+ prefix = build_prefix(request["buildId"])+ files: dict[str, dict] = {}+ for name in NATIVE_LEGS:+ receipt = json.loads((root / handoff.receipt_name(name)).read_text(encoding="utf-8-sig"))+ listed = handoff.validate_channel_receipt(receipt, request, name)+ product = request["identity"]["artifactNamePascal"]+ if name == "windows-universal":+ expected = {f"{product}-{request['windowsVersion']}-win.msixbundle"}+ else:+ platform, arch = name.split("-")+ native = "macos" if platform == "darwin" else "windows"+ expected = {f"metadata-{native}-{arch}.json"}+ if platform == "darwin":+ expected.update(f"{product}-{request['version']}-mac-{arch}.{suffix}"+ for suffix in ("zip", "dmg", "zip.blockmap", "dmg.blockmap"))+ else:+ expected.add(f"{product}-{request['version']}-win-{arch}.msix")+ if not expected.issubset({row["path"] for row in listed}):+ raise ValueError(f"Channel handoff {name} omits required native files")+ for row in listed:+ if row["path"] in files and files[row["path"]] != row:+ raise ValueError("Channel handoffs disagree on artifact receipts")+ file = root / row["path"]+ if 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]+++def publish(request: dict, root: Path, *, needs: dict, publisher) -> dict:+ require_success(needs)+ # The protocol publisher rechecks policy/identity/retirement at CAS time.+ if publisher.request(request["buildId"]) != request:+ raise ValueError("Publisher request differs from pinned admission")+ current = publisher._read(request["channel"])+ if current is None:+ raise ValueError("Publication channel not found")+ publisher._preview("promote", current[0])+ 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"])+ 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)+ r2.download_public_object(request["publicBase"], key, root / "verified" / file.name,+ expected_size=file.stat().st_size, expected_sha256=r2.file_sha256(file))+ publisher.store.put(prefix + "build.json", canonical_json(manifest))+ return publisher.promote(request["buildId"])+++def main(argv: list[str] | None = None) -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("command", choices=["request", "admit", "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("--repository", default=os.environ.get("GITHUB_REPOSITORY", ""))+ parser.add_argument("--out", type=Path)+ parser.add_argument("--root", type=Path)+ args = parser.parse_args(argv)+ request = read_request(args.build_id, args.request_sha256, args.public_base, args.repository)+ if args.command == "admit":+ values = admit(request, dict(os.environ))+ with 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":+ from scripts.releases.channels import ChannelPublisher, R2ChannelStore+ needs = json.loads(os.environ.get("RELEASE_NEEDS", "{}"))+ require_success(needs)+ # Repeat maintainer/default-controller admission on promotion, including reruns.+ admit(request, dict(os.environ))+ def authorize(action: str, record: dict) -> None:+ if action != "promote" or record["policy"] != "preview":+ raise ValueError("This workflow only promotes preview channel builds")+ admit(request, dict(os.environ))++ def qualified(pinned: dict, manifest: dict) -> bool:+ # Re-evaluate exact downloaded receipt bytes on every CAS attempt.+ expected, _feeds = assemble(pinned, root, needs=needs)+ return pinned == request and manifest == expected++ publisher = ChannelPublisher(R2ChannelStore(*r2.credentials()), args.repository, args.public_base,+ authorize=authorize, verify_build=qualified)+ if args.root:+ root = args.root+ result = publish(request, args.root, needs=needs, publisher=publisher)+ else:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ result = publish(request, root, needs=needs, publisher=publisher)+ print(json.dumps(result, sort_keys=True))+ if args.out:+ args.out.parent.mkdir(parents=True, exist_ok=True)+ args.out.write_text(json.dumps(request, sort_keys=True) + "\n", encoding="utf-8")+++if __name__ == "__main__":+ main()diff --git a/scripts/releases/channel_qualification.py b/scripts/releases/channel_qualification.pynew file mode 100644index 00000000000..9775e8c9cca--- /dev/null+++ b/scripts/releases/channel_qualification.py@@ -0,0 +1,280 @@+"""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.pynew file mode 100644index 00000000000..6f8da53278c--- /dev/null+++ b/scripts/releases/channel_releases.py@@ -0,0 +1,272 @@+"""Advance protected R2 heads from the release transaction's accepted native bytes."""+from __future__ import annotations++import argparse+import base64+import hashlib+import json+import os+from pathlib import Path+import subprocess+import tempfile+import xml.etree.ElementTree as ET+import zipfile++from hermes_cli.release_channels import (+ ChannelError, build_prefix, canonical_json, validate_identity, validate_manifest,+)+from scripts.releases import handoff, r2, stable+from scripts.releases.channels import ChannelPublisher, R2ChannelStore++NATIVE_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",+ "smoke-darwin", "smoke-win32", "smoke-win32-universal", "publish-win32-updater", "publish-darwin-updater")+++def select_channel(publisher: ChannelPublisher, policy: str) -> str:+ """R2 records select the name; historical labels are first-rollout defaults only."""+ matches = [record for record in publisher.list() if record["policy"] == policy]+ if len(matches) > 1:+ raise ChannelError("Ambiguous protected policy in R2; select one authority before publishing")+ if matches:+ if matches[0]["state"] != "active":+ raise ChannelError("Protected channel is retired")+ return matches[0]["name"]+ return {"stable-release": "stable", "canary-release": "canary"}[policy]+++def product_identity(tag: str, run=subprocess.check_output) -> dict:+ """Consume the packager's identity, not a Python copy of its naming rules."""+ env = dict(os.environ, HERMES_DESKTOP_VARIANT="bundled", HERMES_PAYLOAD_TAG=tag)+ for key in ("HERMES_BUILD_COMMIT", "_HERMES_CHANNEL_REQUEST_JSON"):+ env.pop(key, None)+ raw = run(["node", "-e", "console.log(JSON.stringify(require('./apps/desktop/product-identity.cjs')))"],+ env=env, text=True, encoding="utf-8", timeout=30)+ identity = json.loads(raw)+ # This token reserves existing native identity; it does not create a new app.+ identity = {key: value for key, value in identity.items() if key not in {"store", "light", "channel"}}+ identity["token"] = hashlib.sha256(canonical_json(identity)).hexdigest()[:16]+ return validate_identity(identity)+++def read_native_receipts(root: Path, tag: str, commit: str) -> dict:+ files = {}+ for name in NATIVE_LEGS:+ receipt = json.loads((root / handoff.receipt_name(name)).read_text(encoding="utf-8-sig"))+ for row in handoff.validate_receipt(receipt, tag, commit, name):+ if row["path"] in files and files[row["path"]] != row:+ raise ChannelError("Native release receipts disagree")+ file = root / row["path"]+ # Only native metadata, distributables and blockmaps are downloaded.+ if file.is_file() and (file.stat().st_size != row["size"] or r2.file_sha256(file) != row["sha256"]):+ raise ChannelError("Native artifact differs from its receipt")+ files[row["path"]] = row+ rows = []+ for platform in ("macos", "windows"):+ for arch in ("arm64", "x64"):+ name = f"metadata-{platform}-{arch}.json"+ if name not in files or not (root / name).is_file():+ raise ChannelError(f"Missing receipt-bound native metadata: {name}")+ row = json.loads((root / name).read_text(encoding="utf-8-sig"))+ if any(row.get(k) != v for k, v in {"platform": platform, "arch": arch, "tag": tag, "commit": commit}.items()):+ raise ChannelError("Native metadata release identity mismatch")+ rows.append(row)+ 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"]}+ for package in manifest["packages"]:+ platform = "macos" if package["platform"] == "darwin" else "windows"+ row = by_target.get((platform, package["arch"]), {})+ signing = "teamId" if platform == "macos" else "publisher"+ if (any(row.get(key) != package.get(key) for key in ("identity", "version", signing))+ or row.get("artifact") != {"url": manifest["request"]["publicBase"] + "/" + package["artifact"]["key"],+ "sha256": package["artifact"]["sha256"]}):+ raise ChannelError("Protected package differs from the accepted release")+++def admit_transaction(policy: str, env: dict, *, run=stable.output) -> tuple[str, str]:+ """A callable CLI is not permission to bypass the existing workflow gate."""+ from scripts.releases.semver import is_valid_version+ from hermes_cli.release_channels import require_commit, validate_repository++ repository = validate_repository(env.get("GITHUB_REPOSITORY"))+ tag = env.get("RELEASE_TAG", "")+ if not tag.startswith("v") or not is_valid_version(tag[1:]):+ raise ChannelError("Invalid protected release tag")+ if (policy == "canary-release") != ("-canary." in tag):+ raise ChannelError("Protected release policy/tag mismatch")+ if env.get("GITHUB_ACTIONS") != "true" or env.get("GITHUB_EVENT_NAME") != "workflow_dispatch":+ raise ChannelError("Protected heads require the accepted release workflow")+ default = ""+ if policy == "stable-release":+ expected = f"{repository}/.github/workflows/stable-release.yml@refs/tags/{tag}"+ required = STABLE_NEEDS+ elif policy == "canary-release":+ default = run(["gh", "api", f"repos/{repository}", "--jq", ".default_branch"])+ expected = f"{repository}/.github/workflows/desktop-bundled-release.yml@refs/heads/{default}"+ required = CANARY_NEEDS+ else:+ raise ChannelError("Invalid protected release policy")+ if env.get("GITHUB_WORKFLOW_REF") != expected:+ raise ChannelError("Protected publication requires its existing release workflow")+ stable.require_success(json.loads(env.get("RELEASE_NEEDS", "{}")), list(required))+ if policy == "stable-release":+ tag, commit = stable.check_tag(env, run=run)+ else:+ commit = require_commit(env.get("RELEASE_COMMIT"))+ actual = run(["git", "rev-parse", f"refs/tags/{tag}^{{commit}}"])+ remote = dict(line.split()[::-1] for line in run(+ ["git", "ls-remote", "origin", f"refs/tags/{tag}", f"refs/tags/{tag}^{{}}"] ).splitlines())+ if actual != commit or remote.get(f"refs/tags/{tag}^{{}}", remote.get(f"refs/tags/{tag}")) != commit:+ raise ChannelError("Canary release tag moved")+ run(["git", "merge-base", "--is-ancestor", commit, f"origin/{default}"])+ release = json.loads(run(["gh", "release", "view", tag, "--repo", repository,+ "--json", "tagName,isDraft,isPrerelease"]))+ if (release.get("tagName") != tag or release.get("isDraft") is not False+ or release.get("isPrerelease") is not (policy == "canary-release")):+ raise ChannelError("Protected head requires the published GitHub release transaction")+ return tag, commit+++def accepted_stable(publisher: ChannelPublisher, env: dict, tag: str, commit: str) -> dict:+ from hermes_cli.release_channels import decode_json, require_sha256++ digest = require_sha256(env.get("CANDIDATE_MANIFEST_SHA256"))+ key = f"releases/tag/{tag}/release-candidates.json"+ if env.get("CANDIDATE_MANIFEST_URL") != publisher.public_base + "/" + key:+ raise ChannelError("Accepted candidate URL differs from release archive")+ candidate = decode_json(publisher.reader.read_bytes(key, digest))+ stable.validate_candidates(candidate, tag, commit, publisher.public_base)+ accepted = publisher.store.get("releases/stable/release-candidates.json")+ if accepted is None or decode_json(accepted[0]) != candidate:+ raise ChannelError("Stable accepted manifest transaction has not completed")+ if decode_json(publisher.reader.read_bytes("releases/stable/release-candidates.json")) != candidate:+ raise ChannelError("Stable accepted manifest is not publicly visible")+ return candidate+++def publish_release(policy: str, env: dict, root: Path) -> dict:+ from scripts.releases.commit_build import version_at++ tag, commit = admit_transaction(policy, env)+ 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)+ identity = product_identity(tag)+ current = publisher._read(name)+ if current:+ # Explicit bootstrap may have reserved another opaque token for the same app.+ identity["token"] = current[0]["identity"]["token"]+ if identity != current[0]["identity"]:+ raise ChannelError("Protected R2 identity differs from the existing product")+ accepted = accepted_stable(publisher, env, tag, commit) if policy == "stable-release" else None+ handoff.fetch(tag, commit, list(NATIVE_LEGS), root,+ ["metadata-*.json", "*.zip", "*.dmg", "*.blockmap", "*.msixbundle"], public_base=publisher.public_base)+ native = read_native_receipts(root, tag, commit)+ windows = next(row for row in native["packages"] if row["platform"] == "windows")++ def release_gate(request: dict) -> bool:+ if admit_transaction(policy, env) != (tag, commit):+ return False+ if policy == "stable-release":+ return accepted_stable(publisher, env, tag, commit) == accepted+ return True++ 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)+ if accepted is not None:+ match_accepted_packages(manifest, accepted)+ prefix = build_prefix(request["buildId"])+ for file in feeds:+ key = prefix + file.relative_to(root).as_posix()+ r2.put(tag=tag, key=key, file=str(file), key_is_full=True, immutable=True)+ if publisher.reader.read_bytes(key) != file.read_bytes():+ raise ChannelError("Immutable protected feed public read-back differs")+ publisher._write(prefix + "build.json", manifest)++ 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)+ if accepted is not None:+ match_accepted_packages(expected, accepted)+ return pinned == request and actual == expected++ publisher.verify_build = qualified+ return publisher.promote_protected(request["buildId"], policy=policy, release_gate=release_gate)+++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")+ args = parser.parse_args(argv)+ with tempfile.TemporaryDirectory() as directory:+ result = publish_release(args.role + "-release", dict(os.environ), Path(directory))+ print(json.dumps(result, sort_keys=True))+++if __name__ == "__main__":+ main()diff --git a/scripts/releases/channels.py b/scripts/releases/channels.pynew file mode 100644index 00000000000..fcdb4d5afb6--- /dev/null+++ b/scripts/releases/channels.py@@ -0,0 +1,415 @@+"""Authenticated channel administration; mutable records use ETag CAS, never CDN state."""+from __future__ import annotations++from copy import deepcopy+import hashlib+import http.client+import secrets+import uuid++from hermes_cli.release_channels import (+ ChannelError, ChannelNotFound, ChannelReader, artifact_key, build_prefix,+ canonical_json, channel_key, decode_json, package_versions, public_base as validate_public_base,+ validate_name, validate_record, validate_repository, validate_request, validate_manifest, require_sha256,+)+from scripts.releases import r2+++class ChannelConflict(ChannelError):+ pass+++class PublicVisibilityError(ChannelError):+ """The authenticated write committed; do not roll it back on a stale CDN read."""+++class R2ChannelStore:+ def __init__(self, creds: dict, base: str, bucket: str):+ self.creds, self.base, self.bucket = creds, base.rstrip("/"), bucket++ def get(self, key: str) -> tuple[bytes, str] | None:+ url = f"{self.base}/{self.bucket}/{r2.encode_key_path(artifact_key(key))}"+ try:+ response = r2.signed_request("GET", url, creds=self.creds, now=r2.amz_timestamp())+ except r2.R2RequestError as exc:+ if exc.status == 404:+ return None+ raise+ etag = response.header("etag")+ if not etag:+ raise ChannelError("Authenticated channel read missing ETag")+ body = response._body+ if len(body) > 4 * 1024 * 1024:+ raise ChannelError("Channel metadata exceeds size limit")+ return body, etag++ def put(self, key: str, body: bytes, etag: str | None = None) -> None:+ url = f"{self.base}/{self.bucket}/{r2.encode_key_path(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:+ r2.signed_request("PUT", url, body=body, body_hash=hashlib.sha256(body).hexdigest(),+ content_length=len(body), content_type="application/json",+ creds=self.creds, now=r2.amz_timestamp(), extra_headers=condition, tries=1)+ except (r2.R2RequestError, OSError, http.client.HTTPException) as exc:+ # Lost success responses and conditional retries are settled by exact bytes.+ current = self.get(key)+ if current is not None and current[0] == body:+ return+ if isinstance(exc, r2.R2RequestError) and exc.status == 412:+ raise ChannelConflict(f"Channel write conflict: {key}") from exc+ raise ChannelError(f"Channel write outcome uncertain: {key}; inspect before retry") from exc+ current = self.get(key)+ if current is None or current[0] != body:+ raise ChannelConflict(f"Channel changed before authenticated readback: {key}")++ def keys(self, prefix: str) -> list[str]:+ keys, seen = [], set()+ token = None+ while 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)}"+ response = r2.signed_request("GET", url, creds=self.creds, now=r2.amz_timestamp())+ page = r2.parse_list_xml(response.text())+ keys.extend(page["keys"])+ if not page["truncated"]:+ return keys+ token = page["nextToken"]+ if not token or token in seen:+ raise ChannelError("Incomplete or repeated channel pagination token")+ seen.add(token)+++def preview_identity(name: str, token: str) -> dict:+ validate_name(name)+ pascal = f"HermesChannel{token}"+ return {"token": token, "displayName": f"Hermes {name}",+ "appId": f"ai.hermes.channel.h{token}", "appNamePascal": pascal,+ "artifactNamePascal": pascal, "cliName": f"hermes-{name}",+ "windowsExecutableName": pascal, "msixAppIdWithOrg": f"NousResearch.{pascal}"}+++class ChannelPublisher:+ def __init__(self, store: R2ChannelStore, repository: str, public_base: str,+ authorize, verify_build=None, verify_retirement=None):+ self.store = store+ self.repository = validate_repository(repository)+ self.public_base = validate_public_base(public_base)+ self.reader = ChannelReader(self.public_base, self.repository)+ self.authorize = authorize+ self.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))+ if value is None:+ return None+ body, etag = value+ return validate_record(decode_json(body), name=name, repository=self.repository), etag++ def _write(self, key: str, value: dict, etag: str | None = None) -> None:+ body = canonical_json(value)+ self.store.put(key, body, etag)+ try:+ visible = self.reader.read_bytes(key)+ except ChannelError as exc:+ raise PublicVisibilityError(f"Committed {key}; public visibility verification failed") from exc+ if visible != body:+ current = self.store.get(key)+ if current is not None and current[0] != body:+ # A real subsequent CAS is not a stale CDN response. Allocation may+ # retry (leaving a gap); retirement must re-qualify the changed head.+ raise ChannelConflict(f"Committed {key}; superseded before public readback")+ raise PublicVisibilityError(f"Committed {key}; public visibility verification failed")++ def _preview(self, action: str, record: dict) -> None:+ if record["policy"] != "preview":+ raise ChannelError("Protected release policy requires its existing release gate")+ if record["state"] != "active":+ raise ChannelError("Retired channel is permanently closed to publication")+ self.authorize(action, record)++ def create(self, name: str) -> dict:+ validate_name(name)+ existing = self._read(name)+ if existing:+ self._preview("create", existing[0])+ return existing[0]+ record = {"schema": 1, "name": name, "repository": self.repository,+ "policy": "preview", "state": "active", "revision": 1,+ "nextSequence": 1, "head": None}+ self.authorize("create", record)+ for _ in range(16):+ token = secrets.token_hex(8)+ try:+ self.store.put(f"releases/channel-identities/{token}.json",+ canonical_json({"schema": 1, "repository": self.repository, "channel": name}))+ record["identity"] = preview_identity(name, token)+ break+ except ChannelConflict:+ continue+ else:+ raise ChannelConflict("Could not reserve a channel identity")+ validate_record(record)+ try:+ self._write(channel_key(name), record)+ except ChannelConflict:+ winner = self._read(name)+ if winner is None:+ raise+ self._preview("create", winner[0])+ return winner[0]+ return record++ def allocate(self, name: str, commit: str, source_version: str,+ bundle_env: dict | None = None, controller_commit: str | None = None) -> dict:+ from scripts.releases.bundle_env import validate+ bundle_env = validate({} if bundle_env is None else bundle_env)+ for _ in range(16):+ current = self._read(name)+ if current is None:+ raise ChannelNotFound(f"Channel not found: {name}")+ record, etag = current+ self._preview("allocate", record)+ sequence = record["nextSequence"]+ version, windows_version = package_versions(sequence)+ request = {"schema": 1, "buildId": uuid.uuid4().hex, "channel": name,+ "sequence": sequence, "repository": self.repository, "commit": commit,+ "sourceVersion": source_version, "version": version, "windowsVersion": windows_version,+ "identity": deepcopy(record["identity"]), "bundleEnv": bundle_env,+ "publicBase": self.public_base}+ if controller_commit is not None:+ request["controllerCommit"] = controller_commit+ validate_request(request, repository=self.repository, base_url=self.public_base)+ # Distinguish competing allocations with otherwise identical CAS bodies.+ updated = {**record, "revision": record["revision"] + 1, "nextSequence": sequence + 1,+ "lastAllocation": {"buildId": request["buildId"], "sequence": sequence}}+ try:+ self._write(channel_key(name), updated, etag)+ except ChannelConflict:+ continue+ self._write(build_prefix(request["buildId"]) + "request.json", request)+ return request+ raise ChannelConflict("Channel allocation remained contended")++ def _protected(self, action: str, record: dict, request: dict, policy: str, release_gate) -> None:+ if policy not in {"stable-release", "canary-release"} or record["policy"] != policy:+ raise ChannelError("Protected release policy mismatch")+ if record["state"] != "active":+ raise ChannelError("Retired channel is permanently closed to publication")+ from scripts.releases.semver import is_valid_version+ version = request["version"]+ if not is_valid_version(version) or ("-canary." in version) != (policy == "canary-release"):+ raise ChannelError("Release version does not match protected policy")+ self.authorize(action, record)+ if release_gate(request) is not True:+ raise ChannelError("Protected publication requires the successful release gate")++ def allocate_protected(self, name: str, commit: str, source_version: str, *,+ release_tag: str, version: str, windows_version: str,+ identity: dict, policy: str, release_gate) -> dict:+ """Reserve accepted legacy bytes, never authorize a custom build as stable."""+ facts = {"schema": 1, "channel": name, "repository": self.repository, "commit": commit,+ "sourceVersion": source_version, "version": version, "windowsVersion": windows_version,+ "releaseTag": release_tag, "identity": deepcopy(identity), "bundleEnv": {},+ "publicBase": self.public_base}+ build_id = hashlib.sha256(canonical_json(facts)).hexdigest()[:32]+ key = build_prefix(build_id) + "request.json"+ for _ in range(16):+ current = self._read(name)+ record, etag = current if current else ({+ "schema": 1, "name": name, "repository": self.repository, "policy": policy,+ "state": "active", "revision": 1, "nextSequence": 1, "head": None,+ "identity": deepcopy(identity)}, None)+ validate_record(record, repository=self.repository)+ request = {**facts, "buildId": build_id, "sequence": record["nextSequence"]}+ validate_request(request, repository=self.repository, base_url=self.public_base, policy=policy)+ self._protected("allocate-protected", record, request, policy, release_gate)+ if record["identity"] != identity:+ raise ChannelError("Protected release identity mismatch")+ existing = self.store.get(key)+ if existing is not None:+ pinned = self.request(build_id)+ if {k: v for k, v in pinned.items() if k != "sequence"} != {k: v for k, v in request.items() if k != "sequence"}:+ raise ChannelError("Protected immutable request differs from accepted release")+ return pinned+ # Retain the request in the CAS reservation so a lost request PUT can+ # resume with its original sequence, including after process restart.+ last = record.get("lastAllocation", {})+ if last.get("buildId") == build_id and last.get("request"):+ request = last["request"]+ else:+ if last.get("request"):+ # Flush a prior interrupted reservation before replacing its+ # recovery slot. Otherwise retries would allocate new inputs.+ prior_key = build_prefix(last["buildId"]) + "request.json"+ self._write(prior_key, last["request"])+ updated = {**record, "revision": record["revision"] + 1,+ "nextSequence": request["sequence"] + 1,+ "lastAllocation": {"buildId": build_id, "sequence": request["sequence"],+ "request": request}}+ try:+ self._write(channel_key(name), updated, etag)+ except ChannelConflict:+ continue+ try:+ self._write(key, request)+ except ChannelConflict:+ # Identical concurrent releases adopt the first immutable request;+ # their other reservation is only an unused sequence gap.+ continue+ return request+ raise ChannelConflict("Protected release allocation remained contended")++ def request(self, build_id: str, sha256: str | None = None) -> dict:+ if sha256 is not None:+ require_sha256(sha256)+ key = build_prefix(build_id) + "request.json"+ found = self.store.get(key)+ if found is None:+ raise ChannelNotFound(f"Request not found: {build_id}")+ body = found[0]+ if sha256 is not None and hashlib.sha256(body).hexdigest() != sha256:+ raise ChannelError("Request SHA256 mismatch")+ decoded = decode_json(body)+ current = self._read(validate_name(decoded.get("channel")))+ if current is None:+ raise ChannelNotFound("Request channel not found")+ request = validate_request(decoded, repository=self.repository, base_url=self.public_base,+ policy=current[0]["policy"])+ if request["buildId"] != build_id:+ raise ChannelError("Request build ID mismatch")+ return request++ def list(self) -> list[dict]:+ result = []+ for key in self.store.keys("releases/channels/"):+ name = key.removeprefix("releases/channels/").removesuffix(".json")+ if channel_key(name) != key:+ raise ChannelError("Invalid object in channel namespace")+ current = self._read(name)+ if current is None:+ raise ChannelError("Listed channel disappeared")+ result.append(current[0])+ return result++ def bootstrap(self, record: dict, manifest: dict | None = None, *, publish: bool = False) -> dict:+ record = deepcopy(validate_record(record, repository=self.repository))+ if record["policy"] not in {"stable-release", "canary-release", "source-branch"} or record["state"] != "active":+ raise ChannelError("Bootstrap requires an active protected release policy")+ self.authorize("bootstrap", record)+ if record["policy"] == "source-branch":+ if manifest is not None:+ raise ChannelError("Source branch bootstrap has no artifact manifest")+ else:+ if record["head"] is None or manifest is None:+ raise ChannelError("Bootstrap requires actual accepted release metadata")+ validate_manifest(manifest, record, self.public_base)+ if hashlib.sha256(canonical_json(manifest)).hexdigest() != record["head"]["sha256"]:+ raise ChannelError("Bootstrap manifest SHA256 mismatch")+ if self.verify_build is None or self.verify_build(manifest["request"], manifest) is not True:+ raise ChannelError("Bootstrap requires release qualification")+ if publish:+ if manifest is not None:+ self._write(build_prefix(manifest["request"]["buildId"]) + "request.json", manifest["request"])+ self._write(record["head"]["manifestKey"], manifest)+ self._write(channel_key(record["name"]), record)+ return record++ def promote(self, build_id: str) -> dict:+ return self._promote(build_id)++ def promote_protected(self, build_id: str, *, policy: str, release_gate) -> dict:+ return self._promote(build_id, policy=policy, release_gate=release_gate)++ def _promote(self, build_id: str, *, policy: str | None = None, release_gate=None) -> dict:+ request = self.request(build_id)+ key = build_prefix(build_id) + "build.json"+ found = self.store.get(key)+ if found is None:+ raise ChannelNotFound("Complete build manifest not found")+ raw = found[0]+ manifest = decode_json(raw)+ if manifest.get("request") != request:+ raise ChannelError("Build manifest differs from immutable admitted request")+ head = {"buildId": build_id, "sequence": request["sequence"], "manifestKey": key,+ "sha256": hashlib.sha256(raw).hexdigest()}+ for _ in range(16):+ current = self._read(request["channel"])+ if current is None:+ raise ChannelNotFound("Publication channel not found")+ record, etag = current+ if policy is None:+ self._preview("promote", record)+ else:+ self._protected("promote-protected", record, request, policy, release_gate)+ if record["identity"] != request["identity"] or request["sequence"] >= record["nextSequence"]:+ raise ChannelError("Request channel identity or allocation mismatch")+ candidate = {**record, "head": head, "revision": record["revision"] + 1}+ validate_manifest(manifest, candidate, self.public_base)+ if record["head"] is not None and record["head"]["sequence"] >= request["sequence"]:+ if record["head"] == head:+ self.reader.read_bytes(key, head["sha256"])+ return record+ raise ChannelError("A newer build is published; stale completion refused")+ if policy is not None and record["head"] is not None:+ from scripts.releases.semver import compare+ from scripts.releases.stable import windows_version+ previous_head = record["head"]+ previous = self.store.get(previous_head["manifestKey"])+ if previous is None or hashlib.sha256(previous[0]).hexdigest() != previous_head["sha256"]:+ raise ChannelError("Previous protected manifest is unavailable or changed")+ previous_request = validate_manifest(decode_json(previous[0]), record, self.public_base)["request"]+ if (compare(request["version"], previous_request["version"]) <= 0+ or windows_version(request["windowsVersion"]) <= windows_version(previous_request["windowsVersion"])):+ raise ChannelError("Protected native versions must increase; stale completion refused")+ if self.verify_build is None or self.verify_build(request, manifest) is not True:+ raise ChannelError("Publication requires complete native build qualification")+ self.reader.read_bytes(key, head["sha256"])+ try:+ self._write(channel_key(record["name"]), candidate, etag)+ except ChannelConflict:+ continue+ return candidate+ 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:+ validate_name(destination)+ if name == destination:+ raise ChannelError("Channel retirement cycle")+ current = self._read(name)+ if current is None:+ raise ChannelNotFound(f"Channel not found: {name}")+ record, etag = current+ self._preview("retire", record)+ target_read = self._read(destination)+ if target_read is None:+ raise ChannelNotFound("Retirement destination not found")+ 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")+ 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,+ "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 self._read(destination) != (target, target_etag):+ raise ChannelConflict("Retirement destination changed; re-qualify")+ if publish:+ self._write(channel_key(name), retired, etag)+ return retireddiff --git a/scripts/releases/darwin.py b/scripts/releases/darwin.pyindex 89fdbf6cf31..2b129726942 100644--- a/scripts/releases/darwin.py+++ b/scripts/releases/darwin.py@@ -1,8 +1,6 @@"""Validate and conditionally publish macOS update feeds."""from __future__ import annotations-import json-from pathlib import Pathimport refrom typing import Any, Callable@@ -15,12 +13,11 @@ _TAG_PATTERN = re.compile(r"^v\d+\.\d+\.\d+(?:-canary\.\d{14})?$")def _darwin_feed(channel: str, light: bool = False) -> dict[str, Any]:- """Read the same feed facts as the desktop runtime."""- with (Path(__file__).resolve().parents[2] / "apps/desktop/update-feed.json").open(encoding="utf-8-sig") as file:- feeds = json.load(file)- if channel not in feeds:- raise TypeError(f"Unknown update channel: {channel}")- return feeds[channel]["light" if light else "bundled"]+ """Legacy URL shape only, not a channel existence registry."""+ if not isinstance(channel, str) or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", channel):+ raise ValueError("Invalid legacy feed path component")+ return {"directory": f"releases/darwin/{'light/' if light else ''}{channel}",+ "channel": channel, "fileName": f"{channel}-mac.yml"}# ---------------------------------------------------------------------------diff --git a/scripts/releases/handoff.py b/scripts/releases/handoff.pyindex 594df040e74..3972d86aa5e 100644--- a/scripts/releases/handoff.py+++ b/scripts/releases/handoff.py@@ -92,10 +92,68 @@ def _receipt_file_rows(selected: dict[str, Path]) -> list[dict]:for path, file in sorted(selected.items())]+def channel_prefix(request: dict) -> str:+ """A channel build is an allocation, never a source SHA alias."""+ from hermes_cli.release_channels import build_prefix, validate_request+ return build_prefix(validate_request(request)["buildId"])+++def validate_channel_receipt(receipt: dict, request: dict, name: str) -> list[dict]:+ channel_prefix(request)+ validate_commit_identity(request["commit"], name)+ if (not isinstance(receipt, dict) or receipt.get("schema") != 3+ or receipt.get("request") != request or receipt.get("commit") != request["commit"]+ or receipt.get("name") != name or "tag" in receipt):+ raise ValueError("Channel handoff request identity mismatch")+ return validate_receipt_files(receipt)+++def _prefix(receipt: dict) -> str:+ if "request" in receipt:+ return channel_prefix(receipt["request"])+ return (r2.staging_key_for(receipt["tag"], "") if "tag" in receipt+ else r2.commit_prefix_for(receipt["commit"]))+++def stage_channel_build(request: dict, name: str, root: Path, includes: list[str]) -> dict:+ channel_prefix(request)+ validate_commit_identity(request["commit"], name)+ selected = _select_files(root, includes)+ receipt = {"schema": 3, "request": request, "commit": request["commit"], "name": name,+ "files": _receipt_file_rows(selected)}+ validate_channel_receipt(receipt, request, name)+ return _stage(receipt, selected)+++def read_channel_receipt(request: dict, name: str, *, public_base: str | None = None) -> dict:+ validate_commit_identity(request["commit"], name)+ key = channel_prefix(request) + receipt_name(name)+ try:+ if public_base is not None:+ receipt = r2.read_public_receipt(public_base, key)+ else:+ creds, base, bucket = r2.credentials()+ text = r2.get_object(creds, base, bucket, key, r2.amz_timestamp())+ if text is None:+ raise MissingReceipt(f"Missing channel handoff: {name}")+ receipt = json.loads(text)+ except r2.R2RequestError as err:+ if err.status == 404:+ raise MissingReceipt(f"Missing channel handoff: {name}") from err+ raise+ validate_channel_receipt(receipt, request, name)+ return receipt+++def fetch_channel_build(request: dict, names: list[str], root: Path,+ includes: list[str] | None = None, *, public_base: str | None = None) -> list[dict]:+ receipts = [read_channel_receipt(request, name, public_base=public_base) for name in names]+ return _fetch_receipts(receipts, root, includes, public_base=public_base)++def _stage(receipt: dict, selected: dict[str, Path]) -> dict:"""Publish completion only after every immutable artifact upload succeeds."""- prefix = (r2.staging_key_for(receipt["tag"], "") if "tag" in receipt- else r2.commit_prefix_for(receipt["commit"]))+ prefix = _prefix(receipt)for row in receipt["files"]:r2.put(tag=receipt.get("tag", ""), key=prefix + row["path"],file=str(selected[row["path"]]), key_is_full=True, immutable=True)@@ -180,8 +238,7 @@ def _fetch_receipts(receipts: list[dict], root: Path,root = root.resolve()selected = {}for receipt in receipts:- prefix = (r2.staging_key_for(receipt["tag"], "") if "tag" in receipt- else r2.commit_prefix_for(receipt["commit"]))+ prefix = _prefix(receipt)for row in receipt["files"]:if includes and not any(fnmatch.fnmatchcase(row["path"], pattern) for pattern in includes):continue@@ -219,6 +276,7 @@ def main(argv: list[str] | None = None) -> None:parser.add_argument("--commit-build", default=os.environ.get("HERMES_BUILD_COMMIT"),help="Commit-only mode: stage/fetch under releases/commit/<sha>/ ""with schema-2 receipts (no tag; exact full SHA required)")+ parser.add_argument("--channel-request", type=Path, help="Pinned admitted channel request JSON")parser.add_argument("--commit", default=None,help="Artifact commit. Must equal --commit-build when both are supplied.")parser.add_argument("--name", action="append", required=True)@@ -228,6 +286,17 @@ def main(argv: list[str] | None = None) -> None:args = parser.parse_args(argv)if args.public_base is not None and args.command != 'fetch':parser.error('--public-base is only supported for fetch')+ if args.channel_request:+ request = json.loads(args.channel_request.read_text(encoding="utf-8-sig"))+ if args.tag or args.commit_build or (args.commit and args.commit != request.get("commit")):+ parser.error("Channel requests cannot select a tag or another commit")+ if args.command == "stage":+ if len(args.name) != 1 or not args.include:+ parser.error("stage needs one name and at least one include pattern")+ stage_channel_build(request, args.name[0], args.root, args.include)+ else:+ fetch_channel_build(request, args.name, args.root, args.include, public_base=args.public_base)+ returnif args.commit_build:if args.tag:parser.error("--commit-build and --tag are mutually exclusive")diff --git a/scripts/releases/r2.py b/scripts/releases/r2.pyindex 1e1ec728f80..5848e972ff4 100644--- a/scripts/releases/r2.py+++ b/scripts/releases/r2.py@@ -532,6 +532,10 @@ def feed_dir_for(platform: str, channel: str) -> str:def cache_control_for(key: str) -> str | None:"""APT indexes are mutable; by-hash indexes and versioned packages are not."""+ if key.startswith("releases/channels/"):+ return "no-store"+ if key.startswith(("releases/channel-builds/", "releases/channel-identities/")):+ return "public, max-age=31536000, immutable"if key.endswith((".appinstaller", ".html")) or key.startswith("releases/stable/") or (key.startswith("releases/darwin/") and key.endswith("-mac.yml")):return "no-store"if not key.startswith("releases/termux/"):diff --git a/scripts/releases/r2_scope.py b/scripts/releases/r2_scope.pynew file mode 100644index 00000000000..739c5d1c8dc--- /dev/null+++ b/scripts/releases/r2_scope.py@@ -0,0 +1,89 @@+"""Disposable CI namespaces at the object-key boundary, never in bucket names."""+from __future__ import annotations++from dataclasses import dataclass+import os+import re+++def require_run(value: str) -> str:+ if not isinstance(value, str) or not re.fullmatch(r"[1-9][0-9]{0,19}-[1-9][0-9]{0,5}", value):+ raise ValueError("Disposable R2 run must be <run-id>-<attempt>")+ return value+++@dataclass(frozen=True)+class R2Scope:+ prefix: str = ""++ def __post_init__(self):+ if self.prefix and not re.fullmatch(+ r"ci-disposable/[1-9][0-9]{0,19}/[1-9][0-9]{0,19}-[1-9][0-9]{0,5}/", self.prefix):+ raise ValueError("Invalid disposable R2 namespace")++ @classmethod+ def configured(cls, repository: str | None = None) -> R2Scope:+ run = os.environ.get("R2_DISPOSABLE_RUN", "")+ if not run:+ authority = repository if repository is not None else (+ os.environ.get("GITHUB_REPOSITORY", "") if os.environ.get("GITHUB_ACTIONS") == "true" else None)+ if authority is not None and authority.casefold() != "nousresearch/hermes-agent":+ raise ValueError("Fork channel operations require a disposable R2 run")+ return cls()+ require_run(run)+ repository_id = os.environ.get("GITHUB_REPOSITORY_ID", "")+ if not re.fullmatch(r"[1-9][0-9]{0,19}", repository_id):+ raise ValueError("Disposable R2 requires the GitHub repository ID")+ return cls(f"ci-disposable/{repository_id}/{run}/")++ def key(self, key: str) -> str:+ if not self.prefix:+ return key+ from scripts.releases.r2 import relative_artifact_path+ return self.prefix + relative_artifact_path(key)++ def listing_prefix(self, prefix: str) -> str:+ if not prefix:+ return self.prefix+ return self.key(prefix.removesuffix("/")) + ("/" if prefix.endswith("/") else "")++ def logical_key(self, key: str) -> str:+ if not key.startswith(self.prefix):+ raise ValueError("R2 listing escaped the disposable namespace")+ return key[len(self.prefix):]++ def bucket_url(self, base: str, bucket: str) -> str:+ # A bucket-with-slash silently scopes object calls but NOT ListObjectsV2.+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]*", bucket):+ raise ValueError("Invalid R2 bucket name")+ return f"{base.rstrip('/')}/{bucket}"++ def object_url(self, base: str, bucket: str, key: str) -> str:+ from scripts.releases.r2 import encode_key_path+ return f"{self.bucket_url(base, bucket)}/{encode_key_path(self.key(key))}"++ def public_base(self, base: str) -> str:+ root = base.rstrip("/")+ if self.prefix:+ from scripts.releases.r2 import public_artifact_url+ public_artifact_url(root, "scope-check")+ # The configured environment supplies the root. Callers cannot substitute+ # a different origin or a production-looking URL for scoped objects.+ if "/ci-disposable/" in root + "/":+ raise ValueError("Configured R2 public root must not contain a disposable namespace")+ return root + "/" + self.prefix.rstrip("/")+ return root+++def channel_public_base(explicit: str | None = None) -> str:+ scope = R2Scope.configured()+ configured = os.environ.get("CLOUDFLARE_R2_PUBLIC_URL", "")+ if scope.prefix:+ if not configured:+ raise ValueError("Disposable channels require the configured R2 public root")+ expected = scope.public_base(configured)+ if explicit is not None and explicit.rstrip("/") != expected:+ raise ValueError("Disposable channel archive authority mismatch")+ return expected+ from hermes_cli.release_channels import public_base+ return public_base(explicit if explicit is not None else configured)diff --git a/scripts/render-builds-table.py b/scripts/render-builds-table.pyindex f97d89d8b3e..075300e1de5 100644--- a/scripts/render-builds-table.py+++ b/scripts/render-builds-table.py@@ -553,8 +553,29 @@ def splice(body: str, block: str) -> str:return body.replace(MARKER, block, 1)+def render_channel_summary(manifest: dict) -> str:+ request = manifest["request"]+ rows = []+ for platform in ("darwin", "win32"):+ for arch in ("arm64", "x64"):+ selected = [row for row in manifest["packages"] if row["platform"] == platform+ and row["arch"] == arch and row["variant"] == "bundled"]+ label = f"{platform} {arch}"+ if len(selected) != 1:+ rows.append(f"| {label} | Unavailable | — |")+ continue+ item = selected[0]+ url = r2.public_url_for(request["publicBase"], item["artifact"]["key"])+ rows.append(f"| {label} | {item['version']} | [Download]({url}) |")+ return (f"## Channel `{request['channel']}` build `{request['buildId']}`\n\n"+ f"Source `{request['commit']}` ({request['sourceVersion']}); sequence {request['sequence']}.\n\n"+ "| Native package | Version | Download |\n|---|---|---|\n" + "\n".join(rows) + "\n")++def main() -> int:parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--channel-build")+ parser.add_argument("--channel-request-sha256")parser.add_argument("--tag", required=False, help="Release tag to render the release-body table for")parser.add_argument("--candidate-manifest-sha256", default=None,help="Stable promotion: render smoke admission from this pinned candidate, not RELEASE_NEEDS")@@ -594,6 +615,19 @@ def main() -> int:if args.summary_commit and (args.tag or args.pending_run_url):parser.error("--summary-commit cannot be combined with release-body arguments")+ if args.channel_build:+ from hermes_cli.release_channels import ChannelReader+ from scripts.releases.channel_publish import read_request+ if args.tag or args.summary_commit or not args.summary_out or not args.r2_base_url:+ parser.error("Channel summary needs --summary-out and --r2-base-url; no tag/commit mode")+ request = read_request(args.channel_build, args.channel_request_sha256, args.r2_base_url, args.repo)+ resolved = ChannelReader(args.r2_base_url, repository=args.repo).resolve(request["channel"])+ if resolved.manifest is None or resolved.manifest["request"] != request:+ raise ValueError("Channel head no longer names this build; refusing stale download summary")+ with open(args.summary_out, "a", encoding="utf-8") as stream:+ stream.write(render_channel_summary(resolved.manifest))+ return 0+candidate = Noneif args.candidate_manifest_sha256 is not None or args.candidate_commit is not None:if (args.candidate_manifest_sha256 is None or args.candidate_commit is Nonediff --git a/scripts/stage-msixbundle.mjs b/scripts/stage-msixbundle.mjsindex dd973c00228..d99fb7f9ef6 100644--- a/scripts/stage-msixbundle.mjs+++ b/scripts/stage-msixbundle.mjs@@ -10,7 +10,7 @@ import path from 'node:path'import { fileURLToPath } from 'node:url'import { parseArgs } from 'node:util'-import { appIdentity } from './msix-shared.mjs'+import { appIdentity, channelBuildRequest } from './msix-shared.mjs'import { ensureWindowsBundleTools } from '../apps/desktop/scripts/windows-bundle-tools.mjs'@@ -19,7 +19,11 @@ const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..const { values } = parseArgs({ options: {tag: { type: 'string' }, commit: { type: 'string' }, version: { type: 'string' },variant: { type: 'string' }, 'no-upload': { type: 'boolean' }, candidate: { type: 'boolean' },+ 'channel-request': { type: 'string' },} })+const channelRequest = values['channel-request']+ ? channelBuildRequest({ ...process.env, HERMES_DESKTOP_VARIANT: values.variant || 'bundled',+ _HERMES_CHANNEL_REQUEST_JSON: fs.readFileSync(values['channel-request'], 'utf8') }) : nullconst tag = values.tagconst commitBuild = values.commit || ''const commitVersion = values.version || ''@@ -27,10 +31,14 @@ const noUpload = values['no-upload'] === trueconst candidate = values.candidate === trueconst variant = values.variant || process.env.HERMES_DESKTOP_VARIANT || 'bundled'+if (channelRequest && (tag || commitBuild || values.version || candidate || variant !== 'bundled'+ || process.env.HERMES_PAYLOAD_TAG || process.env.HERMES_BUILD_COMMIT)) {+ throw new Error('Channel requests cannot select tag, commit, Store or candidate inputs')+}if (commitBuild && (tag || process.env.HERMES_PAYLOAD_TAG || candidate)) {throw new Error('Commit builds cannot select a release tag or candidate mode')}-if (!commitBuild && (values.version !== undefined || noUpload)) {+if (!commitBuild && !channelRequest && (values.version !== undefined || noUpload)) {throw new Error('--version and --no-upload require --commit')}@@ -60,7 +68,7 @@ if (commitBuild) {}process.env.HERMES_BUILD_COMMIT = commitBuildprocess.env.HERMES_PAYLOAD_VERSION = commitVersion-} else if (!tag) {+} else if (!tag && !channelRequest) {console.error('[stage-msixbundle] --tag=<vX.Y.Z> is required')process.exit(1)}@@ -74,11 +82,13 @@ if (process.platform !== 'win32') {}const canary = /-canary\./.test(tag)-if (!commitBuild && !canary && !candidate) throw new Error('Stable bundles must use the staged stable-release workflow')+if (!commitBuild && !channelRequest && !canary && !candidate) throw new Error('Stable bundles must use the staged stable-release workflow')const desktop = path.join(REPO_ROOT, 'apps', 'desktop')const releaseDir = path.join(desktop, 'release')-const { version, name, fileVersion } = appIdentity(desktop, tag)+const { version, name, fileVersion } = channelRequest+ ? { version: channelRequest.windowsVersion, name: channelRequest.identity.artifactNamePascal, fileVersion: channelRequest.version }+ : appIdentity(desktop, tag)// Per-arch .msix files are found by the name electron-builder gave them// (appInfo.version = the 3-part or full-canary string, NOT the 4-part feeddiff --git a/scripts/write_install_stamp.py b/scripts/write_install_stamp.pyindex 23f10b51d9a..549f32f4a58 100644--- a/scripts/write_install_stamp.py+++ b/scripts/write_install_stamp.py@@ -146,6 +146,7 @@ def build_stamp(source: str = "local",distribution: str | None = None,runtime_dir: str | None = None,+ channel_request: dict | None = None,) -> dict:"""Build a stamp dict from explicit args, filling gaps from git/env.@@ -172,6 +173,20 @@ def build_stamp(if base_version is None:base_version = _base_version+ if channel_request is not None:+ from scripts.bundles.desktop_prepare import git, require_source, validate_channel_request+ channel_request = validate_channel_request(channel_request)+ if os.environ.get("HERMES_BUILD_COMMIT") or os.environ.get("HERMES_PAYLOAD_TAG"):+ raise ValueError("channel request conflicts with commit-build or tag identity")+ if os.environ.get("HERMES_DESKTOP_VARIANT") != "bundled" or update_mechanism not in {"electron-updater", "app-installer"}:+ raise ValueError("channel builds require a bundled native update owner")+ if _run_git("rev-parse", "HEAD", cwd=_REPO_ROOT) != channel_request["commit"] or commit not in (None, channel_request["commit"]):+ raise ValueError("channel build identity does not match checkout HEAD")+ require_source(_REPO_ROOT, channel_request["commit"])+ commit, source, base_version = channel_request["commit"], "channel-build", channel_request["sourceVersion"]+ dirty, distance = False, 0+ commit_date = int(git(_REPO_ROOT, "log", "-1", "--format=%ct", "HEAD"))+commit_build = os.environ.get("HERMES_BUILD_COMMIT")if commit_build:from scripts.releases.commit_build import require_commit@@ -195,11 +210,11 @@ def build_stamp(source = "fallback"# Branch: explicit > CI env > git- if commit_build:+ if commit_build or channel_request is not None:branch = Noneelif branch is None:branch = _resolve_branch_from_env()- if branch is None and not commit_build:+ if branch is None and not commit_build and channel_request is None:branch = _resolve_branch_from_git()# Dirty: explicit > git@@ -245,7 +260,7 @@ def build_stamp(tag = os.environ.get("HERMES_PAYLOAD_TAG") or None_stable_tag = re.compile(r"^v(0|[1-9]\d{0,2})\.\d+\.\d+$")- if payload != "bootstrap" and not commit_build and not (+ if payload != "bootstrap" and not commit_build and channel_request is None and not (tag and (_stable_tag.match(tag) or update_channel.is_canary_tag(tag))):raise SystemExit(@@ -269,6 +284,9 @@ def build_stamp("payload": payload,"tag": tag if payload != "bootstrap" else None,}+ if channel_request is not None:+ stamp["channelBuild"] = channel_request+ stamp["displayVersion"] = f'{base_version} ({channel_request["channel"]} #{channel_request["sequence"]}, {commit[:7]})'if runtime_dir is not None:stamp["runtimeDir"] = runtime_dirreturn stamp@@ -286,6 +304,7 @@ def write_stamp(output: str | Path, **kwargs) -> dict:def main() -> int:parser = argparse.ArgumentParser(description="Write install-stamp.json")parser.add_argument("--output", "-o", required=True, help="Output file path")+ parser.add_argument("--channel-request", type=Path, help="Immutable admitted channel request JSON")parser.add_argument("--commit", default=None, help="Override commit SHA")parser.add_argument("--branch", default=None, help="Override branch name")parser.add_argument("--dirty", action="store_true", default=None, help="Mark as dirty")@@ -328,6 +347,7 @@ def main() -> int:source=args.source,distribution=args.distribution,runtime_dir=args.runtime_dir,+ channel_request=json.loads(args.channel_request.read_text(encoding="utf-8-sig")) if args.channel_request else None,)commit_short = stamp["commit"][:12]diff --git a/tests-js/bundle-smoke-metadata.test.mjs b/tests-js/bundle-smoke-metadata.test.mjsindex 06742974b9e..8940c29086e 100644--- a/tests-js/bundle-smoke-metadata.test.mjs+++ b/tests-js/bundle-smoke-metadata.test.mjs@@ -3,8 +3,10 @@ import fs from 'node:fs'import os from 'node:os'import path from 'node:path'import { execFileSync, spawnSync } from 'node:child_process'-import { bundleIdentity, verifyBundleStamp } from '../tests/install/e2e-assets/bundle-smoke-metadata.mjs'+import { bundleIdentity, verifyBundleStamp, verifyMacMetadata } from '../tests/install/e2e-assets/bundle-smoke-metadata.mjs'import { stampAssertions } from '../tests/install/e2e-assets/mac-bundled-manifest.cjs'+import { randomBytes } from 'node:crypto'+import { buildStampPayload } from '../apps/desktop/scripts/write-build-stamp.mjs'const commit = 'a'.repeat(40)@@ -38,11 +40,77 @@ test('identity uses the production bundled variant and exact input tokens, not iexpect(() => bundleIdentity(bad)).toThrow('commit')}expect(() => bundleIdentity(commit, 'v1.2.3 ')).toThrow('tag')- const hostileEnvironment = { ...process.env, HERMES_DESKTOP_VARIANT: 'store', HERMES_BUILD_COMMIT: 'b'.repeat(40), HERMES_PAYLOAD_TAG: 'v9.9.9' }+ const hostileEnvironment = { ...process.env, HERMES_DESKTOP_VARIANT: 'store', HERMES_BUILD_COMMIT: 'b'.repeat(40), HERMES_PAYLOAD_TAG: 'v9.9.9', _HERMES_CHANNEL_REQUEST_JSON: '{"invalid":"inherited"}' }const cli = path.resolve(import.meta.dirname, '../tests/install/e2e-assets/bundle-smoke-metadata.mjs')expect(JSON.parse(execFileSync(process.execPath, [cli, 'identity', '--commit', commit], { env: hostileEnvironment, encoding: 'utf8' }))).toEqual(tagless)})+test('channel smoke binds the complete admitted request, not a commit-build identity or display version', () => {+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'channel-smoke-'))+ const token = randomBytes(8).toString('hex'), sequence = 65537+ const request = { schema: 1, buildId: randomBytes(16).toString('hex'), channel: `smoke-${token}`,+ repository: 'NousResearch/hermes-agent', publicBase: 'https://releases.example.test', commit,+ sourceVersion: '1.2.3', sequence, version: `0.0.${sequence}`,+ windowsVersion: `0.${Math.floor(sequence / 65536)}.${sequence % 65536}.0`, bundleEnv: {},+ identity: { token, displayName: 'Smoke Channel', appId: `com.example.preview-${token}`,+ appNamePascal: `Smoke${token}`, artifactNamePascal: `Artifact${token}`,+ msixAppIdWithOrg: `Example.Smoke${token}`, cliName: `smoke-${token}`, windowsExecutableName: `smoke-${token}` } }+ const cli = path.resolve(import.meta.dirname, '../tests/install/e2e-assets/bundle-smoke-metadata.mjs')+ const requestPath = path.join(temp, 'request.json'), stampPath = path.join(temp, 'stamp.json')+ const run = (command, args = []) => spawnSync(process.execPath,+ [cli, command, '--commit', commit, '--channel-request', requestPath, ...args], { encoding: 'utf8' })+ try {+ fs.writeFileSync(requestPath, JSON.stringify(request))+ const identity = run('identity')+ expect(identity.status, identity.stderr).toBe(0)+ expect(JSON.parse(identity.stdout)).toMatchObject({ appId: request.identity.appId,+ msixIdentity: request.identity.msixAppIdWithOrg, applicationId: request.identity.appNamePascal,+ windowsVersion: request.windowsVersion })+ const env = { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled', HERMES_BUILD_COMMIT: '',+ HERMES_PAYLOAD_TAG: '', HERMES_PAYLOAD_VERSION: '', _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(request) }+ for (const platform of ['darwin', 'win32']) {+ const stamp = buildStampPayload({ commit, dirty: false }, env, platform,+ { runtime: { commands: { hermes: 'bin/hermes' } } })+ fs.writeFileSync(stampPath, JSON.stringify(stamp))+ const result = run('stamp', ['--platform', platform, '--stamp', stampPath])+ expect(result.status, result.stderr).toBe(0)+ expect(JSON.parse(result.stdout)).toBe(platform === 'darwin' ? request.version : request.windowsVersion)+ const options = { commit, platform, channelRequest: request }+ for (const key of Object.keys(request)) {+ const changed = { ...stamp, channelBuild: { ...request, [key]: null } }+ expect(() => verifyBundleStamp(changed, options), key).toThrow('channelBuild')+ }+ for (const [key, value] of [['source', 'commit-build'], ['tag', 'v1.2.3'], ['branch', 'main'],+ ['dirty', true], ['updateMechanism', 'external'], ['displayVersion', request.version], ['baseVersion', request.version]]) {+ expect(() => verifyBundleStamp({ ...stamp, [key]: value }, options), key).toThrow(key)+ }+ expect(() => verifyBundleStamp(stamp, { commit, platform })).toThrow()+ if (platform === 'darwin') {+ const plist = { CFBundleIdentifier: request.identity.appId, CFBundleShortVersionString: request.version,+ CFBundleVersion: request.version, CFBundleExecutable: request.identity.displayName }+ expect(verifyMacMetadata(plist, stamp, options)).toBe(request.version)+ for (const key of ['CFBundleIdentifier', 'CFBundleShortVersionString', 'CFBundleVersion']) {+ expect(() => verifyMacMetadata({ ...plist, [key]: 'wrong' }, stamp, options)).toThrow(key)+ }+ expect(stampAssertions(stamp, { commit, tag: null, channelRequest: request })).toEqual([])+ expect(stampAssertions(stamp, { commit, tag: null }).join(';')).toContain('channelBuild')+ expect(stampAssertions({ ...stamp, channelBuild: { ...request, bundleEnv: { HERMES_MODEL: 'other' } } },+ { commit, tag: null, channelRequest: request }).join(';')).toContain('channelBuild')+ }+ }+ expect(run('identity', ['--tag', 'v1.2.3']).status).not.toBe(0)+ for (const raw of ['', JSON.stringify(request).replace('{', '{"channel":"duplicate",')]) {+ fs.writeFileSync(requestPath, raw)+ expect(run('identity').status).not.toBe(0)+ }+ for (const invalid of [{ ...request, commit: 'b'.repeat(40) }, { ...request, channel: 'smoke/invalid' },+ { ...request, windowsVersion: '1.2.3.0' }, { ...request, identity: { token } }]) {+ fs.writeFileSync(requestPath, JSON.stringify(invalid))+ expect(run('identity').status).not.toBe(0)+ }+ } finally { fs.rmSync(temp, { recursive: true, force: true }) }+}, 15_000)+test('workspace admission rejects reuse and symlink escapes before creating anything outside runner temp', () => {const temp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-paths-')))const cli = path.resolve(import.meta.dirname, '../tests/install/e2e-assets/bundle-smoke-metadata.mjs')diff --git a/tests/ci/test_channel_build_publication.py b/tests/ci/test_channel_build_publication.pynew file mode 100644index 00000000000..81035d2a827--- /dev/null+++ b/tests/ci/test_channel_build_publication.py@@ -0,0 +1,312 @@+"""Execute channel workflow seams and receipt transport; fixture bytes are not native qualification."""+from __future__ import annotations++import copy+import hashlib+import json+import os+from pathlib import Path+import shlex+import subprocess+import sys+import xml.etree.ElementTree as ET+import zipfile++import hermes_yaml+import pytest++from hermes_cli.release_channels import canonical_json+from scripts.releases import channel_publish, handoff, r2+from scripts.releases.channels import preview_identity+from tests.ci.test_desktop_release_tag_admission import _seed_repo, _git+from tests.scripts.test_release_r2 import r2_server # noqa: F401++ROOT = Path(__file__).resolve().parents[2]+++def request_for(base):+ return {"schema": 1, "buildId": "a" * 32, "channel": "unknown-at-build-time", "sequence": 7,+ "repository": "fixture/repo", "commit": "b" * 40, "sourceVersion": "1.2.3",+ "version": "0.0.7", "windowsVersion": "0.0.7.0", "identity": preview_identity("unknown-at-build-time", "c" * 16),+ "bundleEnv": {"FEATURE": "different from the prior request"}, "publicBase": base}+++def staged_channel(tmp_path, r2_server):+ base = f"http://127.0.0.1:{r2_server.server_port}/hermes-releases"+ request = request_for(base)+ _origin, clone = _seed_repo(tmp_path)+ request.update(commit=_git("rev-parse", "HEAD", cwd=clone), sourceVersion="0.1.2")+ build = tmp_path / "build"+ build.mkdir()+ name = request["identity"]["artifactNamePascal"]+ for platform in ("darwin", "win32"):+ for arch in ("arm64", "x64"):+ native = "macos" if platform == "darwin" else "windows"+ 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 platform == "darwin":+ metadata["teamId"] = "ABCDEFGHIJ"+ 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())+ else:+ metadata.update(publisher="CN=Fixture", applicationId=request["identity"]["appNamePascal"])+ files = [f"{name}-0.0.7-win-{arch}.msix"]+ stamp = {"commit": request["commit"], "source": "channel-build", "channelBuild": request}+ with zipfile.ZipFile(build / files[0], "w") as package:+ package.writestr("AppxManifest.xml", '<Package><Identity Name="' + metadata["identity"]+ + f'" Publisher="CN=Fixture" Version="0.0.7.0" ProcessorArchitecture="{arch}"/>'+ + '<Applications><Application Id="' + metadata["applicationId"] + '"/></Applications></Package>')+ package.writestr("app/resources/install-stamp.json", json.dumps(stamp))+ metadata_name = f"metadata-{native}-{arch}.json"+ (build / metadata_name).write_text(json.dumps(metadata), encoding="utf-8")+ handoff.stage_channel_build(request, f"{platform}-{arch}", build, [*files, metadata_name])+ bundle_name = f"{name}-0.0.7.0-win.msixbundle"+ with zipfile.ZipFile(build / bundle_name, "w") as archive:+ archive.writestr("AppxMetadata/AppxBundleManifest.xml", '<Bundle><Identity Name="'+ + request["identity"]["msixAppIdWithOrg"] + '" Publisher="CN=Fixture" Version="0.0.7.0"/>'+ + '<Packages><Package Type="application" Architecture="arm64"/>'+ + '<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"')+ return request, build+++def test_channel_handoff_binds_full_request_and_feed_bytes(tmp_path, r2_server, staged_channel):+ request, build = staged_channel+ digest = hashlib.sha256(canonical_json(request)).hexdigest()+ assert channel_publish.read_request(request["buildId"], digest, request["publicBase"], request["repository"]) == request+ with pytest.raises(ValueError, match="SHA256|digest"):+ channel_publish.read_request(request["buildId"], "f" * 64, request["publicBase"], request["repository"])+ fetched = tmp_path / "fetched"+ handoff.fetch_channel_build(request, list(channel_publish.NATIVE_LEGS), fetched, public_base=request["publicBase"])+ needs = {name: {"result": "success"} for name in channel_publish.REQUIRED_JOBS}+ manifest, feeds = channel_publish.assemble(request, fetched, needs=needs)+ assert {(p["platform"], p["arch"]) for p in manifest["packages"]} == {+ (platform, arch) for platform in ("darwin", "win32") for arch in ("arm64", "x64")}+ xml = ET.parse(next(p for p in feeds if p.suffix == ".appinstaller")).getroot()+ assert xml.find("{*}UpdateSettings") is None+ assert xml.find("{*}MainBundle").get("Name") == request["identity"]["msixAppIdWithOrg"]+ feed = hermes_yaml.safe_load(next(p for p in feeds if p.suffix == ".yml").read_text(encoding="utf-8"))+ assert feed["version"] == request["version"]+ for file in feed["files"]:+ filename = file["url"].rsplit("/", 1)[-1]+ assert file["size"] == (build / filename).stat().st_size+ changed = copy.deepcopy(request)+ changed["bundleEnv"]["FEATURE"] = "other packaging input"+ with pytest.raises(ValueError, match="identity"):+ handoff.fetch_channel_build(changed, ["win32-x64"], tmp_path / "wrong", public_base=request["publicBase"])+ assert not (tmp_path / "wrong").exists()+ for name in channel_publish.REQUIRED_JOBS:+ for result in ("failure", "skipped", "cancelled", None):+ bad = copy.deepcopy(needs)+ if result is None:+ del bad[name]+ else:+ bad[name]["result"] = result+ with pytest.raises(ValueError, match=name):+ channel_publish.assemble(request, fetched, needs=bad)+ receipt_path = fetched / "handoff-win32-x64.json"+ receipt = json.loads(receipt_path.read_text(encoding="utf-8"))+ missing = {**receipt, "files": [row for row in receipt["files"] if not row["path"].startswith("metadata-")]}+ receipt_path.write_text(json.dumps(missing), encoding="utf-8")+ with pytest.raises(ValueError, match="omits required"):+ channel_publish.assemble(request, fetched, needs=needs)+ receipt_path.write_text(json.dumps(receipt), encoding="utf-8")+ metadata = fetched / "metadata-windows-x64.json"+ metadata.write_text("{}", encoding="utf-8")+ with pytest.raises(ValueError, match="receipt"):+ channel_publish.assemble(request, fetched, needs=needs)+++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)+++def run_shell(tmp_path, r2_server, script, env, *, cwd=None):+ tools = tmp_path / "tools"+ tools.mkdir(exist_ok=True)+ driver = tools / "python-driver.py"+ driver.write_text('import runpy,sys\n' + f'sys.path.insert(0, {str(ROOT)!r})\n'+ + 'from scripts.releases import r2\n'+ + f'r2.s3_endpoint=lambda _: "http://127.0.0.1:{r2_server.server_port}"\n'+ + 'args=sys.argv[1:]\n'+ + 'if args[0]=="-m":\n sys.argv=args[1:]\n runpy.run_module(args[1],run_name="__main__")\n'+ + 'elif args[0]=="-c":\n sys.argv=args[1:]\n exec(args[1])\n'+ + 'elif args[0]=="-":\n sys.argv=args\n exec(compile(sys.stdin.read(),"workflow","exec"))\n'+ + f'else:\n sys.argv=args\n runpy.run_path({str(ROOT)!r}+"/"+args[0],run_name="__main__")\n', encoding="utf-8")+ python = tools / "python"+ python.write_text(f'#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(driver))} "$@"\n', encoding="utf-8")+ python.chmod(0o755)+ gh = tools / "gh"+ gh.write_text('#!/bin/sh\n[ "$1" = api ] || exit 3\nprintf "write\\n"\n', encoding="utf-8")+ gh.chmod(0o755)+ return subprocess.run(["bash", "-e", "-o", "pipefail", "-c", script], cwd=cwd or tmp_path,+ env={**os.environ, **env, "PATH": str(tools) + os.pathsep + os.environ["PATH"]},+ capture_output=True, text=True, encoding="utf-8", timeout=60)++[email protected]("posix")+def test_real_workflow_admission_and_public_smoke_fetch(tmp_path, r2_server, staged_channel):+ request, _ = staged_channel+ clone = tmp_path / "clone"+ prefix = handoff.channel_prefix(request)+ r2_server.store[prefix + "request.json"] = (canonical_json(request), '"request"')+ digest = hashlib.sha256(canonical_json(request)).hexdigest()+ env = {"CHANNEL_BUILD": request["buildId"], "CHANNEL_REQUEST_SHA256": digest, "CLOUDFLARE_R2_PUBLIC_URL": request["publicBase"],+ "DEFAULT_BRANCH": "main", "GITHUB_REPOSITORY": "fixture/repo", "GITHUB_REF": "refs/heads/main",+ "GITHUB_WORKFLOW_REF": "fixture/repo/.github/workflows/desktop-bundled-release.yml@refs/heads/main",+ "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_SHA": request["commit"], "GITHUB_ACTOR": "fixture",+ "GITHUB_TRIGGERING_ACTOR": "fixture", "GITHUB_OUTPUT": str(tmp_path / "outputs"),+ "TAG": "", "BUILD_COMMIT": "", "RELEASE_PHASE": "", "UPLOAD_RELEASE": "false", "BUNDLE_ENV_JSON": "{}"}+ script = workflow_step("desktop-bundled-release.yml", "validate", "Validate tag shape, pyproject lockstep, and ancestry on origin/main")+ result = run_shell(tmp_path, r2_server, script, env, cwd=clone)+ assert result.returncode == 0, result.stdout + result.stderr+ assert f"sha={request['commit']}" in (tmp_path / "outputs").read_text(encoding="utf-8")+ for overrides in ({"GITHUB_REF": "refs/heads/feature"}, {"TAG": "v0.1.2"}, {"TERMUX_ONLY": "true"},+ {"CHANNEL_REQUEST_SHA256": "f" * 64}):+ failed = run_shell(tmp_path, r2_server, script, {**env, **overrides}, cwd=clone)+ assert failed.returncode != 0+ # Re-stage a real ZIP-format MSIX fixture bound to the new admitted commit.+ package_root = tmp_path / "package"+ package_root.mkdir()+ filename = request["identity"]["artifactNamePascal"] + "-0.0.7-win-x64.msix"+ (package_root / filename).write_bytes(b"inert HTTP download fixture, not a native smoke")+ r2_server.store.pop(prefix + "handoff-win32-x64.json")+ r2_server.store.pop(prefix + filename)+ handoff.stage_channel_build(request, "win32-x64", package_root, [filename])+ fetch = workflow_step("desktop-bundle-smoke.yml", "windows", "Fetch one exact downloadable artifact")+ smoke = tmp_path / "smoke"+ env.update(SMOKE_ROOT=str(smoke), PUBLIC_BASE=request["publicBase"], RELEASE_TAG="", RELEASE_COMMIT=request["commit"],+ COMMIT_BUILD="false", PLATFORM="win32", ARCH="x64", FORMAT="msix")+ result = run_shell(tmp_path, r2_server, fetch, env)+ assert result.returncode == 0, result.stdout + result.stderr+ evidence = json.loads((smoke / "out/download.json").read_text(encoding="utf-8"))+ assert evidence["request"] == request+ assert (smoke / "download" / filename).read_bytes() == (package_root / filename).read_bytes()+ r2_server.store[prefix + filename] = (b"corrupt", '"corrupt"')+ failed = run_shell(tmp_path, r2_server, fetch, env)+ assert failed.returncode != 0+ assert (smoke / "download" / filename).read_bytes() == (package_root / filename).read_bytes()++[email protected]("posix")+def test_workflow_promotion_missing_native_gate_does_not_write(tmp_path, r2_server, staged_channel):+ request, _ = staged_channel+ script = workflow_step("desktop-bundled-release.yml", "publish-channel", "Publish immutable feeds and manifest, then CAS channel head")+ env = {"CHANNEL_BUILD": request["buildId"], "CHANNEL_REQUEST_SHA256": hashlib.sha256(canonical_json(request)).hexdigest(),+ "CLOUDFLARE_R2_PUBLIC_URL": request["publicBase"], "GITHUB_REPOSITORY": request["repository"],+ "RUNNER_TEMP": str(tmp_path), "RELEASE_NEEDS": "{}"}+ before = dict(r2_server.store)+ result = run_shell(tmp_path, r2_server, script, env)+ assert result.returncode != 0 and "successful jobs" in result.stderr+ assert dict(r2_server.store) == before++[email protected]("posix")+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"+ record = {"schema": 1, "name": request["channel"], "repository": request["repository"],+ "policy": "preview", "state": "active", "revision": 1, "nextSequence": 8,+ "identity": request["identity"], "head": None}+ r2_server.store[channel_key] = (canonical_json(record), '"record"')+ script = workflow_step("desktop-bundled-release.yml", "publish-channel", "Publish immutable feeds and manifest, then CAS channel head")+ env = {"CHANNEL_BUILD": request["buildId"], "CHANNEL_REQUEST_SHA256": hashlib.sha256(canonical_json(request)).hexdigest(),+ "CLOUDFLARE_R2_PUBLIC_URL": request["publicBase"], "GITHUB_REPOSITORY": request["repository"],+ "RUNNER_TEMP": str(tmp_path), "GITHUB_STEP_SUMMARY": str(tmp_path / "summary.md"),+ "RELEASE_NEEDS": json.dumps({name: {"result": "success"} for name in channel_publish.REQUIRED_JOBS}),+ "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)+ 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"')+ result = run_shell(tmp_path, r2_server, script, env, cwd=tmp_path / "clone")+ assert result.returncode != 0 and "checksum mismatch" in result.stderr+ assert json.loads(r2_server.store[channel_key][0])["head"] is None+ assert prefix + "build.json" not in r2_server.store+ r2_server.store[artifact_key] = saved+ result = run_shell(tmp_path, r2_server, script, env, cwd=tmp_path / "clone")+ assert result.returncode == 0, result.stdout + result.stderr+ stored = json.loads(r2_server.store[channel_key][0])+ manifest_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)+ assert manifest["request"] == request+ summary = (tmp_path / "summary.md").read_text(encoding="utf-8")+ for package in manifest["packages"]:+ assert request["publicBase"] + "/" + package["artifact"]["key"] in summary+ puts = [path for method, path, _ in r2_server.requests if method == "PUT"]+ assert puts[-1].endswith(channel_key)+ # 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}+ 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+ assert json.loads(r2_server.store[channel_key][0]) == retired++[email protected]("posix")+def test_channel_windows_record_stage_and_assembly_handoff_shell(tmp_path, r2_server, staged_channel):+ import shutil+ request, build = staged_channel+ release = tmp_path / "apps/desktop/release"+ release.mkdir(parents=True)+ filename = request["identity"]["artifactNamePascal"] + "-0.0.7-win-x64.msix"+ shutil.copy2(build / filename, release / filename)+ request_file = tmp_path / "channel-request.json"+ request_file.write_text(json.dumps(request), encoding="utf-8")+ env = {"GITHUB_WORKSPACE": str(tmp_path), "RUNNER_TEMP": str(tmp_path), "TARGET": "win32-x64",+ "RELEASE_COMMIT": request["commit"], "CHANNEL_BUILD": request["buildId"],+ "HERMES_PAYLOAD_TAG": "", "HERMES_BUILD_COMMIT": ""}+ # This test owns the first metadata publication for this leg; the setup's+ # transport metadata is deliberately not a native recorder output.+ prefix = handoff.channel_prefix(request)+ for key in ("metadata-windows-x64.json", "handoff-win32-x64.json"):+ r2_server.store.pop(prefix + key)+ script = workflow_step("desktop-bundled-release.yml", "build-win32-commit", "Record and stage channel windows packages")+ result = run_shell(tmp_path, r2_server, script, env)+ assert result.returncode == 0, result.stdout + result.stderr+ receipt_key = handoff.channel_prefix(request) + "handoff-win32-x64.json"+ receipt = json.loads(r2_server.store[receipt_key][0])+ assert receipt["request"] == request+ metadata = json.loads((release / "metadata-windows-x64.json").read_text(encoding="utf-8"))+ assert metadata["identity"] == request["identity"]["msixAppIdWithOrg"]+ assert metadata["applicationId"] == request["identity"]["appNamePascal"]+ fetch = workflow_step("desktop-bundled-release.yml", "assemble-win32-bundle", "Retrieve Windows packages from R2")+ result = run_shell(tmp_path, r2_server, fetch, env)+ assert result.returncode == 0, result.stdout + result.stderr+ assert 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, "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("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)+ assert result.returncode != 0 and "provenance" in result.stderr+ assert dict(r2_server.store) == before+ gate = workflow_step("desktop-bundle-smoke.yml", "validate", "Reject empty or unsupported native smoke jobs")+ for target, expected in (("darwin/arm64/dmg", 0), ("win32/x64/msixbundle", 0), ("//", 1), ("linux/x64/zip", 1)):+ result = run_shell(tmp_path, r2_server, gate, {"TARGET": target})+ assert result.returncode == expected+++def test_pinned_xml_retains_legacy_automatic_policy(tmp_path):+ from scripts.bundles.release_artifacts import write_appinstaller+ for policy in ("automatic", "pinned"):+ out = tmp_path / f"{policy}.appinstaller"+ write_appinstaller(out, identity="Fixture.App", publisher="CN=Fixture", version="0.0.7.0",+ self_uri="https://archive.example/build/stable.appinstaller",+ artifact_uri="https://archive.example/build/app.msixbundle", update_policy=policy)+ xml = ET.parse(out).getroot()+ assert (xml.find("{*}UpdateSettings/{*}OnLaunch") is not None) == (policy == "automatic")+ assert xml.find("{*}UpdateSettings/{*}ForceUpdateFromAnyVersion") is Nonediff --git a/tests/ci/test_desktop_release_tag_admission.py b/tests/ci/test_desktop_release_tag_admission.pyindex 00707b3dae2..44396258848 100644--- a/tests/ci/test_desktop_release_tag_admission.py+++ b/tests/ci/test_desktop_release_tag_admission.py@@ -39,14 +39,6 @@ def _admission_script() -> str:return scripts[0]["run"]-def _checkout_refs(job: dict) -> list[str | None]:- refs = []- for step in job.get("steps", []) or []:- if isinstance(step, dict) and "checkout" in step.get("uses", ""):- refs.append(step.get("with", {}).get("ref"))- return refs--# ---------------------------------------------------------------------------# Structure: the admitted SHA is the only build input privileged jobs see.# ---------------------------------------------------------------------------@@ -59,7 +51,7 @@ def test_validate_exports_the_admitted_sha_as_a_job_output():assert "steps.admission.outputs.sha" in outputs["sha"]-def test_every_signing_job_checks_out_the_admitted_sha_not_the_tag():+def test_signing_jobs_pin_source_and_controller_revisions_not_mutable_tags():wf = _workflow()privileged = {name: job@@ -69,11 +61,18 @@ def test_every_signing_job_checks_out_the_admitted_sha_not_the_tag():assert privileged, "walk broken: no release-signing jobs found"for name, job in privileged.items():- refs = _checkout_refs(job)- for ref in refs:- assert ref == "${{ needs.validate.outputs.sha }}", (+ for step in job.get("steps", []):+ if "checkout" not in step.get("uses", ""):+ continue+ ref = step.get("with", {}).get("ref")+ expected = "${{ needs.validate.outputs.sha }}"+ if name == "publish-channel" or step.get("if") == "inputs.channel_build != ''":+ expected = "${{ github.sha }}"+ 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 SHA validate admitted, never the tag ref"+ "the admitted source or explicitly selected trusted controller, never a mutable tag")# jobs that need the SHA must actually need validatefor name, job in privileged.items():diff --git a/tests/ci/test_protected_canary_publication.py b/tests/ci/test_protected_canary_publication.pynew file mode 100644index 00000000000..eb22068a815--- /dev/null+++ b/tests/ci/test_protected_canary_publication.py@@ -0,0 +1,188 @@+"""Execute protected canary workflow/controller with local Git and HTTP only.++The packages and codesign/GitHub executables are transport fixtures, not native+qualification. No admission, metadata recorder or channel publisher is mocked.+"""+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import plistlib+import shlex+import subprocess+import sys+import zipfile++import hermes_yaml+import pytest++from hermes_cli.release_channels import ChannelReader+from scripts.releases import channel_releases, handoff+from tests.ci.test_desktop_release_tag_admission import _git, _seed_repo+from tests.scripts.test_release_r2 import r2_server # noqa: F401++ROOT = Path(__file__).resolve().parents[2]+pytestmark = pytest.mark.platforms("posix")+++def workflow_job(name):+ return hermes_yaml.safe_load((ROOT / ".github/workflows/desktop-bundled-release.yml").read_text())["jobs"][name]+++def step_script(job, name):+ return next(step["run"] for step in workflow_job(job)["steps"] if step.get("name") == name)+++def canary(tmp_path, r2_server, monkeypatch):+ _, clone = _seed_repo(tmp_path)+ commit = _git("rev-parse", "HEAD", cwd=clone)+ tag = "v0.1.3-canary.20260913001000"+ _git("tag", tag, cwd=clone)+ _git("push", "origin", tag, cwd=clone)+ desktop = clone / "apps/desktop"+ desktop.mkdir(parents=True)+ (desktop / "product-identity.cjs").symlink_to(ROOT / "apps/desktop/product-identity.cjs")+ monkeypatch.chdir(clone)+ identity = channel_releases.product_identity(tag)+ tools = tmp_path / "tools"+ tools.mkdir()+ driver = tools / "driver.py"+ driver.write_text(+ "import runpy,sys\n"+ f"sys.path.insert(0, {str(ROOT)!r})\n"+ "from scripts.releases import r2\n"+ f"r2.s3_endpoint=lambda _: 'http://127.0.0.1:{r2_server.server_port}'\n"+ "args=sys.argv[1:]\nsys.argv=args[1:]\n"+ "assert args[0]=='-m', args\nrunpy.run_module(args[1],run_name='__main__')\n"+ )+ python = tools / "python"+ python.write_text(f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(driver))} \"$@\"\n")+ python.chmod(0o755)+ release_state = tmp_path / "github-release.json"+ release_state.write_text(json.dumps({"tagName": tag, "isDraft": False, "isPrerelease": True}))+ gh = tools / "gh"+ gh.write_text(+ f"#!{sys.executable}\nimport json,os,sys\nfrom pathlib import Path\n"+ "args=sys.argv[1:]\nstate=Path(os.environ['FIXTURE_RELEASE'])\n"+ "if args[:1]==['api']: print('main')\n"+ "elif args[:2]==['release','view']: print(state.read_text())\n"+ "elif args[:2]==['release','edit']:\n"+ " data=json.loads(state.read_text());data['isDraft']=False;state.write_text(json.dumps(data))\n"+ "else: raise SystemExit('unexpected gh call: '+repr(args))\n"+ )+ gh.chmod(0o755)+ # Only the signing command is a fixture boundary; real macOS CI owns its proof.+ codesign = tools / "codesign"+ codesign.write_text('#!/bin/sh\nprintf "TeamIdentifier=ABCDEFGHIJ\\n" >&2\n')+ 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",+ "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,+ "RELEASE_COMMIT": commit, "RELEASE_PHASE": "", "HERMES_DESKTOP_VARIANT": "bundled",+ "HERMES_BUILD_COMMIT": "", "CHANNEL_BUILD": "", "R2_DISPOSABLE_RUN": "",+ "CLOUDFLARE_R2_PUBLIC_URL": base,+ "RELEASE_NEEDS": json.dumps({name: {"result": "success"} for name in workflow_job("publish-canary")["needs"]})}++ def run(script, **overrides):+ return subprocess.run(["bash", "-e", "-o", "pipefail", "-c", script], cwd=clone,+ env={**env, **overrides}, capture_output=True, text=True, timeout=60)++ return clone, identity, env, run+++def native_leg(root, identity, env, platform, arch):+ root.mkdir(parents=True, exist_ok=True)+ version = env["RELEASE_TAG"][1:]+ stamp = {"tag": env["RELEASE_TAG"], "commit": env["RELEASE_COMMIT"]}+ 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("app/resources/install-stamp.json", json.dumps(stamp))+ else:+ name = f"{artifact}-{version}-mac-{arch}"+ (root / f"mac-{arch}/{artifact}.app").mkdir(parents=True)+ 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))+ for suffix in ("dmg", "dmg.blockmap", "zip.blockmap"):+ (root / f"{name}.{suffix}").write_bytes(b"unsigned transport fixture")++[email protected]("platform", ["win32", "darwin"])+def test_canary_metadata_is_recorded_and_receipt_bound(canary, r2_server, platform):+ clone, identity, env, run = canary+ 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")+ assert result.returncode == 0, result.stdout + result.stderr+ prefix = 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"+ entry = 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:])+++def test_published_canary_workflow_advances_only_after_every_gate(canary, r2_server):+ clone, identity, env, run = canary+ root = clone / "apps/desktop/release"+ # Stage independent per-architecture job workspaces through the actual shell.+ import shutil+ for platform in ("darwin", "win32"):+ for arch in ("arm64", "x64"):+ if root.exists():+ shutil.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}")+ assert result.returncode == 0, result.stdout + result.stderr+ bundle = root / f"{identity['artifactNamePascal']}-0.1.3.10-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"')+ assert result.returncode == 0, result.stdout + result.stderr+ 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"):+ needs = json.loads(env["RELEASE_NEEDS"])+ needs[job] = {"result": outcome}+ result = run(script, RELEASE_NEEDS=json.dumps(needs))+ assert result.returncode != 0 and job in result.stderr+ assert r2_server.store == before+ release = Path(env["FIXTURE_RELEASE"])+ published = json.loads(release.read_text())+ for bad in ({**published, "isDraft": True}, {**published, "isPrerelease": False}):+ release.write_text(json.dumps(bad))+ result = run(script)+ assert result.returncode != 0 and "published" in result.stderr+ assert r2_server.store == before+ release.write_text(json.dumps(published))+ result = run(script)+ assert result.returncode == 0, result.stdout + result.stderr+ resolved = ChannelReader(env["CLOUDFLARE_R2_PUBLIC_URL"], repository=env["GITHUB_REPOSITORY"]).resolve("canary")+ assert resolved.manifest["request"]["windowsVersion"] == "0.1.3.10"+ assert resolved.manifest["request"]["commit"] == env["RELEASE_COMMIT"]+ assert len(resolved.manifest["packages"]) == 4+ after = dict(r2_server.store)+ assert run(script).returncode == 0+ 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)+ _git("push", "--force", "origin", env["RELEASE_TAG"], cwd=clone)+ result = run(script)+ assert result.returncode != 0 and "moved" in result.stderr+ assert r2_server.store == afterdiff --git a/tests/hermes_cli/test_backup_migration.py b/tests/hermes_cli/test_backup_migration.pynew file mode 100644index 00000000000..d2217b3c69e--- /dev/null+++ b/tests/hermes_cli/test_backup_migration.py@@ -0,0 +1,169 @@+"""Regression coverage for the retirement snapshot fixes.++Pins the retained-link inventory contract (plugins/skills links stay live and+rechecked, never followed), empty-directory preservation during relocation,+and fail-closed behavior for links into the removal footprint.+"""+import json+import os+import socket+import sqlite3+from pathlib import Path++import pytest++from hermes_cli.backup_migration import (+ LINK_INVENTORY,+ retained_link,+ snapshot_migration_home,+ verify_retained_links,+)+++def _make_minimal_home(root: Path) -> None:+ root.mkdir(parents=True, exist_ok=True)+ (root / "config.yaml").write_text("model:\n provider: openrouter\n")+ with sqlite3.connect(root / "state.db") as conn:+ conn.execute("CREATE TABLE witness(value)")+ conn.execute("INSERT INTO witness VALUES ('kept')")+ (root / "profiles" / "default").mkdir(parents=True)+ (root / "profiles" / "default" / "config.yaml").write_text("profile: default\n")+++def _symlink_or_skip(link: Path, target: Path) -> None:+ try:+ link.symlink_to(target)+ except OSError as exc:+ pytest.skip(f"symlinks unavailable in test environment: {exc}")+++class TestRetainedLinkInventory:+ def test_classifies_plugins_and_skills_links_only(self, tmp_path):+ payload = tmp_path / "payload"+ link = payload / "profiles" / "default" / "plugins" / "mnemosyne-wrapper" / "runtime"+ link.parent.mkdir(parents=True)+ target = payload / "shared-runtime"+ target.mkdir()+ _symlink_or_skip(link, target)++ row = retained_link(link, link.relative_to(payload), ())+ assert row["path"] == "profiles/default/plugins/mnemosyne-wrapper/runtime"+ assert row["target"] == str(target)+ assert row["resolved"] == str(target.resolve())++ def test_rejects_links_outside_plugins_and_skills(self, tmp_path):+ link = tmp_path / "config.yaml.link"+ target = tmp_path / "config.yaml.target"+ target.write_text("x")+ _symlink_or_skip(link, target)+ with pytest.raises(ValueError, match="cannot be a link"):+ retained_link(link, Path("config.yaml.link"), ())++ def test_rejects_links_resolving_into_the_removal_footprint(self, tmp_path):+ home = tmp_path / "home"+ removal = tmp_path / "preview-app"+ (removal / "inner").mkdir(parents=True)+ link = home / "plugins" / "runtime"+ link.parent.mkdir(parents=True)+ _symlink_or_skip(link, removal / "inner")+ with pytest.raises(ValueError, match="removal footprint"):+ retained_link(link, Path("plugins/runtime"), (removal,))++ def test_verify_detects_a_link_that_changed_after_snapshot(self, tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ target = tmp_path / "runtime-target"+ target.mkdir()+ link = home / "plugins" / "runtime"+ link.parent.mkdir(parents=True)+ _symlink_or_skip(link, target)+ snapshot = tmp_path / "snapshot"+ snapshot.mkdir()+ drifted = {+ "path": "plugins/runtime",+ "target": str(tmp_path / "elsewhere"),+ "resolved": str(target.resolve()),+ }+ (snapshot / LINK_INVENTORY).write_text(json.dumps([drifted]))+ with pytest.raises(ValueError, match="changed during migration"):+ verify_retained_links(home, snapshot, ())+++class TestSnapshotMigrationHome:+ def test_preserves_empty_plugin_and_skill_directories(self, tmp_path, monkeypatch):+ home = tmp_path / "home"+ snapshot = tmp_path / "snapshot"+ _make_minimal_home(home)+ (home / "profiles" / "default" / "plugins" / "empty-plugin").mkdir(parents=True)+ (home / "skills" / "empty-skill").mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ snapshot_migration_home(home, snapshot)+ assert (snapshot / "profiles" / "default" / "plugins" / "empty-plugin").is_dir()+ assert (snapshot / "skills" / "empty-skill").is_dir()++ def test_rejects_relocation_links_without_explicit_preservation(self, tmp_path, monkeypatch):+ home = tmp_path / "home"+ snapshot = tmp_path / "snapshot"+ _make_minimal_home(home)+ target = tmp_path / "runtime-target"+ target.mkdir()+ link = home / "plugins" / "runtime-link"+ link.parent.mkdir(parents=True)+ _symlink_or_skip(link, target)+ monkeypatch.setenv("HERMES_HOME", str(home))+ with pytest.raises(ValueError, match="explicit external preservation"):+ snapshot_migration_home(home, snapshot)++ def test_rejects_links_into_removal_footprint_even_with_roots(self, tmp_path, monkeypatch):+ home = tmp_path / "home"+ snapshot = tmp_path / "snapshot"+ _make_minimal_home(home)+ removal = home / "preview-home"+ (removal / "inner").mkdir(parents=True)+ link = home / "plugins" / "runtime"+ link.parent.mkdir(parents=True)+ _symlink_or_skip(link, removal / "inner")+ monkeypatch.setenv("HERMES_HOME", str(home))+ with pytest.raises(ValueError, match="removal footprint"):+ snapshot_migration_home(home, snapshot, retained_removal_roots=(removal,))++ def test_retains_plugins_and_skills_links_with_verified_inventory(self, tmp_path, monkeypatch):+ home = tmp_path / "home"+ snapshot = tmp_path / "snapshot"+ _make_minimal_home(home)+ removal = home / "preview-home"+ removal.mkdir()+ runtime_target = tmp_path / "runtime-target"+ runtime_target.mkdir()+ skill_target = tmp_path / "skill-target"+ skill_target.mkdir()+ runtime_link = home / "plugins" / "runtime-link"+ runtime_link.parent.mkdir(parents=True)+ _symlink_or_skip(runtime_link, runtime_target)+ skill_link = home / "skills" / "shared-skill"+ skill_link.parent.mkdir(parents=True)+ _symlink_or_skip(skill_link, skill_target)+ monkeypatch.setenv("HERMES_HOME", str(home))+ snapshot_migration_home(home, snapshot, retained_removal_roots=(removal,))+ inventory = json.loads((snapshot / LINK_INVENTORY).read_text())+ assert {row["path"] for row in inventory} == {+ "plugins/runtime-link",+ "skills/shared-skill",+ }+ # Links stay live in the source home; the snapshot never contains copies.+ assert runtime_link.is_symlink()+ assert not (snapshot / "plugins" / "runtime-link").exists()+ verify_retained_links(home, snapshot, (removal,))++ @pytest.mark.platforms("linux")+ def test_rejects_unix_domain_sockets(self, tmp_path, monkeypatch):+ home = tmp_path / "home"+ snapshot = tmp_path / "snapshot"+ _make_minimal_home(home)+ monkeypatch.setenv("HERMES_HOME", str(home))+ # AF_UNIX paths cap at ~108 bytes; bind by relative name from inside ``home``.+ monkeypatch.chdir(home)+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as gateway_socket:+ gateway_socket.bind("runtime.sock")+ with pytest.raises(ValueError, match="special file"):+ snapshot_migration_home(home, snapshot)diff --git a/tests/hermes_cli/test_banner_release_channel.py b/tests/hermes_cli/test_banner_release_channel.pyindex 5bef6af8b0e..8aa823032f3 100644--- a/tests/hermes_cli/test_banner_release_channel.py+++ b/tests/hermes_cli/test_banner_release_channel.py@@ -6,10 +6,11 @@ from unittest.mock import Mockimport pytestfrom hermes_cli import banner, source_check+from hermes_cli.source_releases import SourceTargetfrom hermes_cli.update_channel import install_id[email protected]("channel", ["stable", "canary"])[email protected]("channel", ["stable", "canary", "preview-from-r2"])def test_release_channel_never_compares_main_or_reuses_main_cache(tmp_path, monkeypatch, channel):from hermes_constants import get_hermes_home@@ -28,8 +29,8 @@ def test_release_channel_never_compares_main_or_reuses_main_cache(tmp_path, monk(get_hermes_home() / ".update_check").write_text(json.dumps({"rev": None, "ver": banner.VERSION, "head": head, "behind": 99, "ts": 10**12,}))- resolve = Mock(return_value=("v1.2.3" if channel == "stable" else "v1.2.4-canary.20260911", target))- monkeypatch.setattr(source_check, "resolve_source_release", resolve)+ resolve = Mock(return_value=SourceTarget(channel, channel, "example/fork", commit=target, version="1.2.3"))+ monkeypatch.setattr(source_check, "resolve_source_target", resolve)main = Mock(side_effect=AssertionError("release must not check a branch"))monkeypatch.setattr(source_check, "_branch_tip", main)status = source_check.check_for_updates(passive=True)diff --git a/tests/hermes_cli/test_release_channels.py b/tests/hermes_cli/test_release_channels.pynew file mode 100644index 00000000000..3ae211422d5--- /dev/null+++ b/tests/hermes_cli/test_release_channels.py@@ -0,0 +1,183 @@+"""Public channel resolution is strict, pinned, and independent of name registries."""+from copy import deepcopy+import hashlib+import json+from pathlib import Path+import importlib.util++import pytest++# The HTTP fixture is shared without making tests/ an importable package.+_spec = importlib.util.spec_from_file_location("channel_http_fixture", Path(__file__).parents[1] / "scripts/test_release_channels.py")+_fixture = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_fixture)+object_server, publisher = _fixture.object_server, _fixture.publisher+++def seed_manifest(pub, request, objects):+ from hermes_cli.release_channels import build_prefix, canonical_json+ key = build_prefix(request["buildId"]) + "build.json"+ manifest = {"schema": 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"}}]}+ body = canonical_json(manifest)+ objects[key] = body+ head = {"buildId": request["buildId"], "sequence": request["sequence"], "manifestKey": key, "sha256": hashlib.sha256(body).hexdigest()}+ record_key = f"releases/channels/{request['channel']}.json"+ record = json.loads(objects[record_key])+ record["head"] = head+ objects[record_key] = canonical_json(record)+ return manifest, record+++def test_resolve_verifies_exact_manifest_and_preserves_retirement_constraints():+ from hermes_cli.release_channels import ChannelReader, ChannelError, canonical_json+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ for name in ("old-preview", "next-preview"):+ pub.create(name)+ request = pub.allocate("next-preview", "a" * 40, "1.2.3")+ manifest, record = seed_manifest(pub, request, objects)+ reader = ChannelReader(url + "/bucket", repository="example/hermes-agent")+ assert reader.resolve("next-preview").manifest == manifest+ old = 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"] = raw+ old.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)+ 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"+ # Retirement pins the qualified destination, not an unqualified later head.+ newer = pub.allocate("next-preview", "b" * 40, "1.3.0")+ seed_manifest(pub, newer, objects)+ after_advance = reader.resolve("old-preview")+ assert after_advance.manifest == manifest+ assert after_advance.terminal["head"]["buildId"] == newer["buildId"]+ objects[record["head"]["manifestKey"]] += b" "+ with pytest.raises(ChannelError, match="SHA256"):+ reader.resolve("old-preview")++[email protected]("name", ["X", "../x", "two--parts", "a/b", "a%2fb", "a_1", "con", "nul", "x-", "x" * 33, " a", "a\n"])+def test_names_are_validated_without_normalizing(name):+ from hermes_cli.release_channels import ChannelError, validate_name+ with pytest.raises(ChannelError):+ validate_name(name)+++def test_reader_rejects_cycles_identity_substitution_and_cross_authority():+ from hermes_cli.release_channels import ChannelReader, ChannelError, canonical_json+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ pub.create("alpha")+ request = pub.allocate("alpha", "a" * 40, "1.2.3")+ manifest, record = seed_manifest(pub, request, objects)+ reader = ChannelReader(url + "/bucket", repository="example/hermes-agent")+ substituted = deepcopy(manifest)+ substituted["request"]["identity"]["appId"] = "ai.other.identity"+ raw = canonical_json(substituted)+ objects[record["head"]["manifestKey"]] = raw+ record["head"]["sha256"] = hashlib.sha256(raw).hexdigest()+ objects["releases/channels/alpha.json"] = canonical_json(record)+ with pytest.raises(ChannelError, match="identity"):+ reader.resolve("alpha")+ record["repository"] = "other/hermes-agent"+ objects["releases/channels/alpha.json"] = canonical_json(record)+ with pytest.raises(ChannelError, match="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)+ objects["releases/channels/alpha.json"] = canonical_json(record)+ with pytest.raises(ChannelError, match="cycle"):+ reader.resolve("alpha")+++def test_legacy_bootstrap_uses_real_archive_keys_and_source_main_has_no_bundle():+ from hermes_cli.release_channels import canonical_json, ChannelError+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url, verify_build=lambda request, manifest: True)+ preview = pub.create("temporary")+ request = pub.allocate("temporary", "a" * 40, "2.0.0")+ manifest, _ = seed_manifest(pub, request, objects)+ 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")+ 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"+ record = dict(preview, name=name, policy=policy, nextSequence=2,+ head={"buildId": legacy["request"]["buildId"], "sequence": 1,+ "manifestKey": "releases/channel-builds/" + legacy["request"]["buildId"] + "/build.json",+ "sha256": hashlib.sha256(canonical_json(legacy)).hexdigest()})+ pub.bootstrap(record, legacy, publish=True)+ assert pub.reader.resolve(name).manifest == legacy+ assert pub.request(legacy["request"]["buildId"]) == legacy["request"]+ with pytest.raises(ChannelError, match="Protected"):+ pub.promote(legacy["request"]["buildId"])+ with pytest.raises(ChannelError, match="Protected"):+ pub.allocate(name, "a" * 40, "2.0.0")++[email protected]("sequence", [1, 65535, 65536, 2**32 - 1])+def test_sequence_versions_remain_monotonic_at_native_rollover(sequence):+ from hermes_cli.release_channels import package_versions+ version, windows = package_versions(sequence)+ assert version == f"0.0.{sequence}"+ quad = tuple(map(int, windows.split(".")))+ assert quad[1] * 65536 + quad[2] == sequence and max(quad) <= 65535+ if sequence > 1:+ assert quad > tuple(map(int, package_versions(sequence - 1)[1].split(".")))++[email protected]("sequence", [0, -1, True, 2**32, "1"])+def test_sequence_exhaustion_never_wraps(sequence):+ from hermes_cli.release_channels import package_versions, ChannelError+ with pytest.raises(ChannelError):+ package_versions(sequence)+++def test_malformed_record_and_unqualified_retirement_never_resolve():+ from hermes_cli.release_channels import ChannelError, canonical_json+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ pub.create("preview")+ record = pub._read("preview")[0]+ malformed = dict(record)+ del malformed["head"]+ objects["releases/channels/preview.json"] = canonical_json(malformed)+ with pytest.raises(ChannelError):+ pub.reader.resolve("preview")+ objects["releases/channels/preview.json"] = canonical_json(record)+ pub.create("destination")+ request = pub.allocate("destination", "a" * 40, "1.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+ record.update(state="retired", destination="destination", minimumVersion="2.0.0", lastHead=None,+ compatibilityKey=key, compatibilitySha256=hashlib.sha256(raw).hexdigest())+ objects["releases/channels/preview.json"] = canonical_json(record)+ with pytest.raises(ChannelError, match="minimum version"):+ pub.reader.resolve("preview")++[email protected]("field,value", [("policy", []), ("state", {}), ("revision", True), ("head", []), ("identity", None)])+def test_malformed_wire_types_are_channel_errors(field, value):+ from hermes_cli.release_channels import validate_record, ChannelError+ from scripts.releases.channels import preview_identity+ record = {"schema": 1, "name": "arbitrary", "repository": "example/hermes-agent", "policy": "preview",+ "state": "active", "revision": 1, "nextSequence": 1, "head": None,+ "identity": preview_identity("arbitrary", "a" * 16)}+ record[field] = value+ with pytest.raises(ChannelError):+ validate_record(record)diff --git a/tests/hermes_cli/test_source_channel_integration.py b/tests/hermes_cli/test_source_channel_integration.pynew file mode 100644index 00000000000..64803c7c534--- /dev/null+++ b/tests/hermes_cli/test_source_channel_integration.py@@ -0,0 +1,497 @@+"""Source channel tracers through real HTTP, Git, and completion boundaries."""+import argparse+from copy import deepcopy+import json+from pathlib import Path+import subprocess+from types import SimpleNamespace++import pytest++from hermes_cli import main, source_releases, update_cmd+from hermes_cli.subcommands.update import build_update_parser+from hermes_cli.update_channel import channel_record, set_install_channel+from hermes_cli.config import require_readable_config_before_write+++def git(root, *args):+ return subprocess.run(["git", *args], cwd=root, check=True, capture_output=True,+ text=True, stdin=subprocess.DEVNULL).stdout.strip()+++def source(tmp_path, monkeypatch):+ home, origin, checkout = (tmp_path / name for name in ("home", "origin", "checkout"))+ home.mkdir()+ origin.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_INSTALL_ROOT", str(checkout))+ monkeypatch.delenv("HERMES_MANAGED", raising=False)+ git(origin, "init", "-b", "main")+ git(origin, "config", "user.name", "Channel Fixture")+ git(origin, "config", "user.email", "[email protected]")+ git(origin, "config", "commit.gpgsign", "false")+ commits = []+ for label in ("installed", "published", "unpublished"):+ (origin / "content.txt").write_text(label)+ git(origin, "add", "content.txt")+ git(origin, "commit", "-m", label)+ commits.append(git(origin, "rev-parse", "HEAD"))+ git(tmp_path, "clone", str(origin), str(checkout))+ git(checkout, "checkout", "--detach", commits[0])+ monkeypatch.setattr(main, "PROJECT_ROOT", checkout)+ monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: checkout)+ parser = argparse.ArgumentParser()+ build_update_parser(parser.add_subparsers(), cmd_update=main.cmd_update)+ opts = update_cmd._UpdateOptions(pre_update_version=None, gw_input_fn=None,+ assume_yes=True, keep_stash=False, switch_branch=False, discard_local_changes=False)+ monkeypatch.setattr(update_cmd, "_resolve_update_options", lambda *_: opts)+ monkeypatch.setattr(update_cmd, "_begin_update_receipt_and_plan", lambda *_: None)+ monkeypatch.setattr(main, "_run_pre_update_backup", lambda *_: None)+ monkeypatch.setattr(main, "_pause_windows_gateways_for_update", lambda: None)+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (False, ["git"], False))+ return SimpleNamespace(home=home, origin=origin, root=checkout, commits=commits, parser=parser)+++def record(name, *, repository="NousResearch/hermes-agent", state="active", destination=None):+ return {"schema": 1, "name": name, "repository": repository, "policy": "preview",+ "state": state, "identity": {}, "nextSequence": 2, "head": None,+ **({"destination": destination} if destination else {})}+++def reader_result(source, name, destination=None, repository="NousResearch/hermes-agent"):+ requested = record(name, repository=repository,+ state="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={+ "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": {},+ "publicBase": "https://hermes-assets.nousresearch.com"}, "packages": []})+++def install_reader(monkeypatch, result):+ # This is the single documented adapter to ChannelReader.resolve's validated+ # result. No source caller should depend on tag tuples or protocol internals.+ monkeypatch.setattr(source_releases, "_resolve_channel", lambda name, repository: deepcopy(result), raising=False)+++def saved(source):+ return channel_record(require_readable_config_before_write(source.home / "config.yaml"), source.root)+++def test_tagless_channel_check_apply_is_pinned_not_branch_tip(source, monkeypatch, capsys):+ name = "preview-unknown-at-build"+ set_install_channel(name, source.root)+ install_reader(monkeypatch, reader_result(source, name))+ update_cmd._cmd_update_check()+ assert name in capsys.readouterr().out+ assert git(source.root, "rev-parse", "HEAD") == source.commits[0]+ completed = []+ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda request: completed.append(deepcopy(request)))+ args = source.parser.parse_args(["update", "--channel", name, "--yes"])+ update_cmd._cmd_update_impl(args, False)+ assert git(source.root, "rev-parse", "HEAD") == source.commits[1]+ assert (source.root / "content.txt").read_text() == "published"+ assert git(source.root, "tag", "--list") == ""+ assert completed[0]["expected_sha"] == source.commits[1]+ assert saved(source)["channel"] == name++[email protected]("outcome", ["success", "failed", "concurrent", "transient", "already-current"])+def test_retirement_adopts_destination_only_after_success(source, monkeypatch, outcome):+ name = "preview-retiring"+ set_install_channel(name, source.root)+ original = deepcopy(saved(source))+ install_reader(monkeypatch, reader_result(source, name, "stable"))+ if outcome == "already-current":+ git(source.root, "checkout", "--detach", source.commits[1])+ requests = []++ def completion(request):+ requests.append(deepcopy(request))+ assert saved(source) == original+ assert git(source.root, "rev-parse", "HEAD") == source.commits[1]+ if outcome == "concurrent":+ set_install_channel("my-new-choice", source.root)+ return {"exit_code": 1 if outcome == "failed" else 0, "receipt": None,+ "windows_resume": None}++ monkeypatch.setattr(update_cmd, "run_completion", completion)+ monkeypatch.setattr(update_cmd, "_write_fleet_restart_pending_marker", lambda **kw: None)+ flags = ["--channel", name] if outcome == "transient" else []+ args = source.parser.parse_args(["update", "--yes", *flags])+ if outcome == "failed":+ with pytest.raises(SystemExit):+ update_cmd._cmd_update_impl(args, False)+ else:+ update_cmd._cmd_update_impl(args, False)+ expected = {"success": "stable", "already-current": "stable", "failed": name,+ "transient": name, "concurrent": "my-new-choice"}[outcome]+ assert saved(source)["channel"] == expected+ assert len(requests) == 1++[email protected]("channel", ["preview-not-registered", "stable", "canary", "main"])+def test_missing_channel_cannot_fall_back_to_main(source, monkeypatch, channel):+ from hermes_cli import source_check++ set_install_channel(channel, source.root)+ def missing(name, repository):+ raise ValueError("Channel does not exist")+ monkeypatch.setattr(source_releases, "_resolve_channel", missing)+ status = source_check.check_for_updates(install_root=source.root, home=source.home, force=True)+ assert status["error"] == "release-unavailable"+ assert "targetSha" not in status+ before = git(source.root, "rev-parse", "HEAD")+ with pytest.raises(SystemExit):+ update_cmd._cmd_update_impl(source.parser.parse_args(["update", "--yes"]), False)+ assert git(source.root, "rev-parse", "HEAD") == before+++def test_passive_check_reports_retirement_without_adopting_it(source, monkeypatch):+ from hermes_cli import source_check, banner++ name = "preview-retiring"+ set_install_channel(name, source.root)+ before = saved(source)+ install_reader(monkeypatch, reader_result(source, name, "stable"))+ status = source_check.check_for_updates(install_root=source.root, home=source.home, force=True)+ assert status["channel"] == name+ assert status["targetSha"] == source.commits[1]+ assert status["retirement"] == {"destination": "stable", "sourceOnly": True}+ assert status["updateAvailable"] is True+ assert saved(source) == before+ assert name in banner.format_banner_version_label()+++def test_fork_channel_cannot_select_official_source(source, monkeypatch):+ url = "https://github.com/Fixture/fork.git"+ git(source.root, "config", "remote.origin.url", url)+ git(source.root, "config", f"url.{source.origin}.insteadOf", url)+ install_reader(monkeypatch, reader_result(source, "preview"))+ with pytest.raises(ValueError, match="repository"):+ source_releases.resolve_source_target("preview", ["git"], source.root)+ install_reader(monkeypatch, reader_result(source, "preview", repository="Fixture/fork"))+ target = source_releases.resolve_source_target("preview", ["git"], source.root)+ assert target.repository == "Fixture/fork"+ assert target.commit == source.commits[1]+++def channel_archive(source, monkeypatch):+ from functools import partial+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+ from threading import Thread++ archive = source.home / "archive"+ archive.mkdir()+ class Handler(SimpleHTTPRequestHandler):+ def log_message(self, *args):+ pass+ server = ThreadingHTTPServer(("127.0.0.1", 0), partial(Handler, directory=str(archive)))+ thread = Thread(target=server.serve_forever, daemon=True)+ thread.start()+ base = f"http://127.0.0.1:{server.server_port}"+ monkeypatch.setattr(source_releases, "_PUBLIC_BASE", base)+ try:+ yield archive, base+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+++def publish_channel_build(channel_archive, name, build_id, commit, *, sequence=1, stable=False):+ from hashlib import sha256+ from hermes_cli.release_channels import canonical_json++ archive, base = channel_archive+ prefix = f"releases/channel-builds/{build_id}/"+ identity = {"token": "a" * 16, "displayName": "Preview fixture", "appNamePascal": "Fixture",+ "artifactNamePascal": "Fixture", "appId": "ai.fixture.preview",+ "msixAppIdWithOrg": "Fixture.Preview", "cliName": "fixture-preview",+ "windowsExecutableName": "Fixture"}+ version = f"1.2.{sequence}" if stable else f"0.0.{sequence}"+ request = {"schema": 1, "channel": name, "buildId": build_id, "sequence": sequence,+ "repository": "NousResearch/hermes-agent", "commit": commit,+ "sourceVersion": f"1.2.{sequence}", "version": version, "windowsVersion": version + ".0",+ "identity": identity, "bundleEnv": {}, "publicBase": base}+ if stable:+ request["releaseTag"] = "v" + version+ manifest = {"schema": 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",+ "feed": {"key": prefix + "darwin/stable.yml", "channel": "stable"}}]}+ body = canonical_json(manifest)+ channel = {"schema": 1, "name": name, "repository": request["repository"],+ "policy": "stable-release" if stable else "preview", "state": "active", "identity": identity,+ "revision": sequence, "nextSequence": sequence + 1, "head": {"buildId": build_id,+ "sequence": sequence, "manifestKey": prefix + "build.json", "sha256": sha256(body).hexdigest()}}+ for key, content in [(prefix + "build.json", body),+ (f"releases/channels/{name}.json", canonical_json(channel))]:+ path = archive / key+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(content)+ return channel+++def test_real_http_reader_resolves_tagless_build_through_cli(source, monkeypatch, channel_archive):+ archive, _ = channel_archive+ name = "http-preview-351"+ channel = publish_channel_build(channel_archive, name, "b" * 32, source.commits[1])+ from hermes_cli import source_check+ status = source_check.check_for_updates(install_root=source.root, home=source.home,+ channel=name, force=True)+ assert status.get("targetSha") == source.commits[1], status+ completed = []+ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda req: completed.append(req))+ update_cmd._cmd_update_impl(source.parser.parse_args(["update", "--channel", name]), False)+ assert git(source.root, "rev-parse", "HEAD") == source.commits[1]+ assert completed[0]["expected_sha"] == source.commits[1]+ # A mutated immutable manifest is refused, never substituted by main.+ path = archive / channel["head"]["manifestKey"]+ path.write_bytes(path.read_bytes() + b" ")+ with pytest.raises(ValueError, match="SHA256"):+ source_releases.resolve_source_target(name, ["git"], source.root)+++def retired_channel_archive(source, channel_archive):+ from hashlib import sha256+ from hermes_cli.release_channels import canonical_json++ archive, _ = channel_archive+ name = "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"])+ (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)++[email protected]("fault", [None, "binding", "manifest"])+def test_offline_retirement_uses_qualified_build_before_current_stable(+ source, monkeypatch, retired_channel_archive, fault):+ from hashlib import sha256+ from hermes_cli import source_check+ from hermes_cli.release_channels import canonical_json++ fixture = retired_channel_archive+ original = deepcopy(saved(source))+ completed = []+ def completion(request):+ completed.append(deepcopy(request))+ assert git(source.root, "rev-parse", "HEAD") == request["expected_sha"]+ return {"exit_code": 0, "receipt": None, "windows_resume": None}+ 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.archive / f"releases/channels/{fixture.name}.json").write_bytes(canonical_json(fixture.retired))+ elif fault == "manifest":+ path = fixture.archive / fixture.qualified["head"]["manifestKey"]+ path.write_bytes(path.read_bytes() + b" ")+ status = source_check.check_for_updates(install_root=source.root, home=source.home, force=True)+ args = source.parser.parse_args(["update", "--yes"])+ if fault:+ assert status["error"] == "release-unavailable"+ with pytest.raises(SystemExit):+ update_cmd._cmd_update_impl(args, False)+ assert git(source.root, "rev-parse", "HEAD") == source.commits[0]+ assert saved(source) == original and not completed+ return+ assert status.get("targetSha") == source.commits[1], status+ assert status["buildId"] == fixture.qualified["head"]["buildId"]+ assert saved(source) == original+ update_cmd._cmd_update_impl(args, False)+ assert git(source.root, "rev-parse", "HEAD") == source.commits[1]+ assert saved(source)["channel"] == "stable"+ status = source_check.check_for_updates(install_root=source.root, home=source.home, force=True)+ assert status["targetSha"] == source.commits[2], status+ update_cmd._cmd_update_impl(args, False)+ assert git(source.root, "rev-parse", "HEAD") == source.commits[2]+ assert [request["expected_sha"] for request in completed] == source.commits[1:]+ assert "channel_retirement" not in completed[1]++[email protected]("transport", ["git", "shallow", "zip"])+def test_retirement_refuses_to_downgrade_newer_source(+ source, monkeypatch, retired_channel_archive, transport):+ git(source.root, "checkout", "--detach", source.commits[2])+ if transport == "shallow":+ import shutil+ shutil.rmtree(source.root)+ git(source.root.parent, "clone", "--depth=1", source.origin.as_uri(), str(source.root))+ if transport == "zip":+ (source.root / "pyproject.toml").write_text('[project]\nversion = "1.2.2"\n')+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (True, ["git"], False))+ original = deepcopy(saved(source))+ completed = []+ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda request: completed.append(request))+ with pytest.raises(ValueError, match="newer|downgrade"):+ source_releases.resolve_source_target(retired_channel_archive.name,+ None if transport == "zip" else ["git"], source.root)+ with pytest.raises(SystemExit):+ update_cmd._cmd_update_impl(source.parser.parse_args(["update", "--yes"]), False)+ assert git(source.root, "rev-parse", "HEAD") == source.commits[2]+ assert saved(source) == original and not completed++[email protected]("dirty", [False, True])+def test_tagless_zip_apply_uses_pinned_source_archive(source, monkeypatch, dirty):+ import urllib.request+ from hermes_cli import update_cmd_zip++ name = "zip-preview"+ set_install_channel(name, source.root)+ install_reader(monkeypatch, reader_result(source, name, "stable"))+ archive = source.home / "source.zip"+ git(source.origin, "archive", "--format=zip", "--prefix=hermes-agent-fixture/",+ "--output=" + str(archive), source.commits[1])+ urls = []+ def download(url, filename):+ import shutil+ urls.append(url)+ shutil.copyfile(archive, filename)+ monkeypatch.setattr(urllib.request, "urlretrieve", download)+ monkeypatch.setattr(update_cmd, "_prepare_git_command", lambda: (True, ["git"], False))+ completed = []+ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda req: completed.append(deepcopy(req)))+ if dirty:+ (source.root / "notes.txt").write_text("do not remove")+ with pytest.raises(SystemExit):+ update_cmd._cmd_update_impl(source.parser.parse_args(["update"]), False)+ assert not urls and not completed+ assert (source.root / "content.txt").read_text() == "installed"+ assert (source.root / "notes.txt").read_text() == "do not remove"+ else:+ update_cmd._cmd_update_impl(source.parser.parse_args(["update"]), False)+ assert urls == [f"https://github.com/NousResearch/hermes-agent/archive/{source.commits[1]}.zip"]+ assert (source.root / "content.txt").read_text() == "published"+ assert completed[0]["expected_sha"] == source.commits[1]+ assert completed[0]["channel_retirement"]["destination"] == "stable"+ assert saved(source)["channel"] == name++[email protected]("outcome", ["success", "failure", "uncorrelated", "missing"])+def test_retirement_waits_for_correlated_completion_process(source, monkeypatch, outcome):+ from hermes_cli import update_receipt++ name = "process-retiring"+ set_install_channel(name, source.root)+ original = deepcopy(saved(source))+ # This child is the completion transport fixture, not a simulated PM install.+ # The existing completion-process suite exercises fresh PM/selected Python.+ script = source.root / "hermes_cli/update_completion.py"+ script.parent.mkdir()+ script.write_text(+ "import json, pathlib, sys\n"+ "request = json.loads(pathlib.Path(sys.argv[1]).read_text())\n"+ "pathlib.Path(request['home'], 'child-request.json').write_text(json.dumps(request))\n"+ f"outcome = {outcome!r}\n"+ "code = 17 if outcome == 'failure' else 0\n"+ "receipt = dict(request['receipt'], finished_at='fixture', outcome='failed' if code else 'success')\n"+ "result = dict(schema=1, exit_code=code, receipt=receipt, windows_resume=None, update_id=receipt['update_id'])\n"+ "if outcome == 'uncorrelated': result['update_id'] = 'another-update'\n"+ "if outcome != 'missing': pathlib.Path(sys.argv[2]).write_text(json.dumps(result))\n"+ "raise SystemExit(code)\n"+ )+ update_receipt.begin_update_receipt()+ request = {"schema": 1, "source": str(source.root), "home": str(source.home),+ "expected_sha": source.commits[1], "windows_resume": None,+ "receipt": deepcopy(update_receipt._current.get().data),+ "channel_retirement": {"original": original, "destination": "stable"}}+ monkeypatch.setattr(update_cmd, "_write_fleet_restart_pending_marker", lambda **kw: None)+ if outcome == "success":+ update_cmd._complete_source_update(request)+ else:+ with pytest.raises(SystemExit):+ update_cmd._complete_source_update(request)+ assert saved(source)["channel"] == ("stable" if outcome == "success" else name)+ child_request = json.loads((source.home / "child-request.json").read_text())+ assert child_request["channel_retirement"]["original"] == original+ assert child_request["expected_sha"] == source.commits[1]+++def test_source_branch_record_has_no_bundle_and_explicit_branch_is_separate(source, monkeypatch):+ from hermes_cli import source_check++ branch_record = record("main")+ branch_record.update(policy="source-branch", identity=None,+ delivery={"kind": "source-branch", "branch": "main"})+ install_reader(monkeypatch, SimpleNamespace(requested=branch_record,+ terminal=branch_record, manifest=None))+ target = source_releases.resolve_source_target("main", ["git"], source.root)+ assert target.branch == "main" and target.commit is None+ status = source_check.check_for_updates(install_root=source.root, home=source.home, force=True)+ assert status["targetSha"] == source.commits[2], status+ assert "buildId" not in status+ # Explicit --branch remains usable without a channel record or release host.+ def forbidden(*args):+ pytest.fail("explicit source branch contacted channel authority")+ monkeypatch.setattr(source_releases, "_resolve_channel", forbidden)+ set_install_channel("unavailable-preview", source.root)+ completed = []+ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda request: completed.append(request))+ update_cmd._cmd_update_impl(source.parser.parse_args(["update", "--branch", "main"]), False)+ assert git(source.root, "rev-parse", "HEAD") == source.commits[2]+ assert "channel_retirement" not in completed[0]+ assert saved(source)["channel"] == "unavailable-preview"+++def test_changed_checkout_cannot_repin_selected_channel_during_apply(source, monkeypatch):+ set_install_channel("preview", source.root)+ install_reader(monkeypatch, reader_result(source, "preview", "stable"))+ pull = update_cmd._pull_updates+ def moved(*args, **kwargs):+ before = pull(*args, **kwargs)+ git(source.root, "checkout", "--detach", source.commits[2])+ return before+ monkeypatch.setattr(update_cmd, "_pull_updates", moved)+ completed = []+ monkeypatch.setattr(update_cmd, "_complete_source_update", lambda req: completed.append(req))+ with pytest.raises(SystemExit):+ update_cmd._cmd_update_impl(source.parser.parse_args(["update"]), False)+ assert not completed+ assert 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]+ if fault == "floor":+ constraint["minimumVersion"] = "9.0.0"+ constraint["qualification"]["minimumVersion"] = "9.0.0"+ elif fault == "qualification":+ constraint["qualification"]["source"] = "another-preview"+ elif fault == "build":+ resolved.manifest["request"]["buildId"] = "another-build"+ elif fault == "chain":+ constraint["destination"] = "intermediate"+ else:+ resolved.constraints = ()+ install_reader(monkeypatch, resolved)+ with pytest.raises(ValueError, match="retirement|Retirement"):+ source_releases.resolve_source_target("preview", ["git"], source.root)diff --git a/tests/hermes_cli/test_source_check.py b/tests/hermes_cli/test_source_check.pyindex ea7544bbc76..1744d2ce0bd 100644--- a/tests/hermes_cli/test_source_check.py+++ b/tests/hermes_cli/test_source_check.py@@ -5,12 +5,24 @@ import threadingimport urllib.requestfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom urllib.parse import urlsplit+from uuid import uuid4import pytest+MAIN_CHANNEL = "/releases/channels/main.json"+++def source_channel(name, repository, branch="main"):+ return {"schema": 1, "name": name, "repository": repository, "policy": "source-branch",+ "state": "active", "revision": 1, "nextSequence": 1, "identity": None, "head": None,+ "delivery": {"kind": "source-branch", "branch": branch}}++@pytest.fixturedef installation(tmp_path, monkeypatch):+ from hermes_cli import source_releases+root = tmp_path / "checkout"root.mkdir()home = tmp_path / "profile"@@ -18,6 +30,8 @@ def installation(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(home))monkeypatch.delenv("HERMES_REVISION", raising=False)monkeypatch.delenv("HERMES_MANAGED", raising=False)+ # Git probes may use real local remotes, never the external network.+ monkeypatch.setenv("GIT_ALLOW_PROTOCOL", "file")def git(*args, cwd=root):return subprocess.check_output([@@ -33,13 +47,16 @@ def installation(tmp_path, monkeypatch):git("remote", "add", "origin", "https://github.com/fixture/fork.git")linked = tmp_path / "linked"git("worktree", "add", "-b", "feature/gui", str(linked))- responses = {}+ responses = {MAIN_CHANNEL: (200, lambda: source_channel(+ "main", source_releases.source_repository(["git"], root)))}requests = []class Handler(BaseHTTPRequestHandler):def do_GET(self):requests.append(self.path)code, body = responses.get(self.path, (404, {}))+ if callable(body):+ body = body()self.send_response(code)self.end_headers()self.wfile.write((body if isinstance(body, str) else json.dumps(body)).encode())@@ -50,6 +67,7 @@ def installation(tmp_path, monkeypatch):server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)thread = threading.Thread(target=server.serve_forever, daemon=True)thread.start()+ monkeypatch.setattr(source_releases, "_PUBLIC_BASE", f"http://127.0.0.1:{server.server_port}")original = urllib.request.urlopendef local(request, *args, **kwargs):@@ -89,7 +107,8 @@ def test_target_worktree_owns_admission_and_fork_comparison(installation, monkeyassert status["behind"] == 3assert status["hermesRoot"] == str(linked)assert check_for_updates(install_root=root, home=home, cache_path=cache)["supported"] is False- assert len(requests) == 2+ assert requests == [MAIN_CHANNEL, "/repos/fixture/fork/commits/feature%2Fgui",+ f"/repos/fixture/fork/compare/{head}...{target}"]assert all(not any(arg in {"fetch", "checkout", "reset", "update-ref", "stash"} for arg in cmd) for cmd in commands)assert git("rev-parse", "HEAD", cwd=linked) == headassert {str(p.relative_to(root)): p.read_bytes() for p in (root / ".git").rglob("*") if p.is_file()} == before@@ -111,7 +130,7 @@ def test_counts_are_honest_without_fetch(installation, tip_kind, compare, expectassert status["behind"] == expectedassert status["updateAvailable"] is (expected != 0)if tip_kind != "unknown":- assert len(requests) == 1+ assert requests == [MAIN_CHANNEL, "/repos/fixture/fork/commits/main"]def test_cache_force_expiry_and_passive_opt_out(installation, monkeypatch):@@ -130,26 +149,26 @@ def test_cache_force_expiry_and_passive_opt_out(installation, monkeypatch):responses[url] = (503, {})(root / "dirty.txt").write_text("carried work")assert check()["dirty"] is True- assert len(requests) == 1+ assert requests.count(url) == requests.count(MAIN_CHANNEL) == 1assert check(force=True)["error"] == "fetch-failed"clock[0] += 3599assert check()["error"] == "fetch-failed"- assert len(requests) == 2+ assert requests.count(url) == requests.count(MAIN_CHANNEL) == 2clock[0] += 2responses[url] = (200, head)assert check()["behind"] == 0- assert len(requests) == 3+ assert requests.count(url) == requests.count(MAIN_CHANNEL) == 3clock[0] += 86401assert check()["behind"] == 0- assert len(requests) == 4+ assert requests.count(url) == requests.count(MAIN_CHANNEL) == 4(home / "config.yaml").write_text("updates: {check: false}")assert check(passive=True)["behind"] is Noneassert check()["behind"] == 0- assert len(requests) == 4+ assert requests.count(url) == requests.count(MAIN_CHANNEL) == 4git("commit", "--allow-empty", "-m", "moved")responses[url] = (200, git("rev-parse", "HEAD"))assert check()["behind"] == 0- assert len(requests) == 5+ assert requests.count(url) == requests.count(MAIN_CHANNEL) == 5def test_explicit_and_current_branch_heal_only_after_confirmed_absence(installation, monkeypatch):@@ -165,7 +184,74 @@ def test_explicit_and_current_branch_heal_only_after_confirmed_absence(installatassert failed["branch"] == "deleted"assert failed["error"] == "fetch-failed"assert git("branch", "--show-current", cwd=linked) == "feature/gui"- assert requests == []+ assert requests == [MAIN_CHANNEL]++[email protected]("selection", ["explicit", "configured", "current", "detached"])+def test_dynamic_source_channel_preserves_branch_precedence(installation, selection):+ from hermes_cli.source_check import check_for_updates++ root, linked, home, base, head, responses, requests, git = installation+ name = "branch-" + uuid4().hex[:12]+ channel_path = f"/releases/channels/{name}.json"+ responses[channel_path] = (200, source_channel(name, "fixture/fork", "channel-default"))+ branch_file = home / "desktop-update.json"+ if selection in {"explicit", "configured"}:+ branch_file.write_text(json.dumps({"branch": "desktop-choice"}))+ if selection == "detached":+ git("checkout", "--detach", cwd=linked)+ expected = {"explicit": "explicit-choice", "configured": "desktop-choice",+ "current": "feature/gui", "detached": "channel-default"}[selection]+ branch_path = f"/repos/fixture/fork/commits/{expected.replace('/', '%2F')}"+ responses[branch_path] = (200, head)++ status = check_for_updates(install_root=linked, home=home, channel=name,+ branch="explicit-choice" if selection == "explicit" else None,+ branch_config_path=branch_file)+ assert status.get("branch") == expected, status+ assert status.get("targetSha") == head, status+ assert status["behind"] == 0+ assert requests == ([] if selection == "explicit" else [channel_path]) + [branch_path]++[email protected]("name,failure", [+ ("main", "missing"), ("stable", "missing"), ("canary", "missing"),+ (None, "missing"), (None, "malformed"), (None, "foreign"), (None, "unpublished"),+])+def test_channel_failure_never_probes_or_heals_a_branch(installation, name, failure):+ from hermes_cli.source_check import check_for_updates++ root, linked, home, base, head, responses, requests, git = installation+ name = name or "preview-" + uuid4().hex[:12]+ channel_path = f"/releases/channels/{name}.json"+ body = source_channel(name, "fixture/fork")+ code = 200+ if failure == "missing":+ code = 404+ elif failure == "malformed":+ body = "not JSON"+ elif failure == "foreign":+ body["repository"] = "NousResearch/hermes-agent"+ else:+ body["policy"] = "preview"+ del body["delivery"]+ body["identity"] = {+ "token": "a" * 16, "displayName": "Fixture", "appNamePascal": "Fixture",+ "artifactNamePascal": "Fixture", "appId": "ai.fixture.preview",+ "msixAppIdWithOrg": "Fixture.Preview", "cliName": "fixture-preview",+ "windowsExecutableName": "Fixture",+ }+ responses[channel_path] = (code, body)+ responses["/repos/fixture/fork/commits/main"] = (200, head)+ branch_file = home / "desktop-update.json"+ branch_file.write_text(json.dumps({"branch": "deleted"}))+ status = check_for_updates(install_root=linked, home=home, channel=name,+ branch_config_path=branch_file)+ assert status.get("error") == "release-unavailable", status+ assert "targetSha" not in status+ assert status["behind"] is None+ assert requests == [channel_path]+ assert json.loads(branch_file.read_text())["branch"] == "deleted"def test_running_revision_is_not_applied_to_an_explicit_target(installation, monkeypatch):@@ -177,6 +263,7 @@ def test_running_revision_is_not_applied_to_an_explicit_target(installation, monassert check_for_updates(install_root=linked, home=home)["currentSha"] == head# Default invocation retains the Nix revision probe even without a Git checkout.monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: home)+ responses[MAIN_CHANNEL] = (200, source_channel("main", "NousResearch/hermes-agent"))responses["/repos/NousResearch/hermes-agent/commits/main"] = (200, "e" * 40)assert check_for_updates(home=home)["behind"] == 0@@ -218,7 +305,8 @@ def test_source_admission_is_stamp_owned_not_path_owned(installation, mechanism)responses["/repos/fixture/fork/commits/feature%2Fgui"] = (200, head)status = check_for_updates(install_root=linked, home=home)assert status["supported"] is (mechanism in ("self", None))- assert len(requests) == (1 if status["supported"] else 0)+ assert requests == ([MAIN_CHANNEL, "/repos/fixture/fork/commits/feature%2Fgui"]+ if status["supported"] else [])empty = home / "no-source"empty.mkdir()(empty / "install-stamp.json").write_text(json.dumps({"updateMechanism": mechanism, "distribution": "nix" if mechanism == "external" else "source"}))@@ -231,6 +319,7 @@ def test_embedded_revision_keeps_https_ref_advertisement_recovery(installation,monkeypatch.setenv("HERMES_REVISION", head)monkeypatch.setattr("hermes_cli.config.get_project_root", lambda: home)monkeypatch.setattr("hermes_cli.config.detect_install_method", lambda root: "nix")+ responses[MAIN_CHANNEL] = (200, source_channel("main", "NousResearch/hermes-agent"))original = subprocess.runprobes = []@@ -263,7 +352,8 @@ def test_malformed_optional_changelog_and_cache_do_not_hide_the_update(installatdata["status"] = Nonecache.write_text(json.dumps(data))assert check_for_updates(install_root=root, home=home, cache_path=cache)["behind"] == 2- assert len(requests) == 4+ assert requests == [MAIN_CHANNEL, "/repos/fixture/fork/commits/main",+ f"/repos/fixture/fork/compare/{head}...{'a' * 40}"] * 2@pytest.mark.parametrize("repository,heals", [("NousResearch/hermes-agent", True), ("fixture/fork", False)])diff --git a/tests/hermes_cli/test_source_release_channels.py b/tests/hermes_cli/test_source_release_channels.pyindex dfb57fda4c5..cddd16fa32b 100644--- a/tests/hermes_cli/test_source_release_channels.py+++ b/tests/hermes_cli/test_source_release_channels.py@@ -90,6 +90,20 @@ def releases(tmp_path, monkeypatch, request):+ (f"?{parsed.query}" if parsed.query else ""), *args, **kwargs)monkeypatch.setattr(urllib.request, "urlopen", local_urlopen)+ # Legacy pointer tests below retain their HTTP/tag boundary. New CLI callers+ # consume the protocol reader, whose complete schema is tested independently.+ from hermes_cli import source_releases+ def resolve_channel(name, repository):+ record = {"name": name, "repository": repository, "state": "active",+ "policy": "source-branch" if name == "main" else "preview"}+ manifest = None+ if name == "main":+ record["delivery"] = {"kind": "source-branch", "branch": "main"}+ else:+ manifest = {"request": {"commit": commits[1 if name == "stable" else 2],+ "sourceVersion": tags[name].removeprefix("v"), "buildId": "legacy-fixture"}}+ return SimpleNamespace(requested=record, terminal=record, manifest=manifest)+ monkeypatch.setattr(source_releases, "_resolve_channel", resolve_channel)yield SimpleNamespace(root=checkout, origin=origin, commits=commits,tags=tags, responses=responses, requests=requests)server.shutdown()diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.pyindex 6d6f7a3d5c5..5877276d9a5 100644--- a/tests/hermes_cli/test_update_channel.py+++ b/tests/hermes_cli/test_update_channel.py@@ -41,6 +41,32 @@ def _config_for(root: Path, channel: str) -> dict:}+def test_dynamic_channel_parser_and_per_install_round_trip(tmp_path, monkeypatch):+ import argparse+ import hermes_yaml as yaml+ from hermes_cli.subcommands.update import build_update_parser++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ parser = argparse.ArgumentParser()+ build_update_parser(parser.add_subparsers(), cmd_update=lambda args: None)+ root = tmp_path / "source"+ root.mkdir()+ name = "new-preview-493"+ args = parser.parse_args(["update", "--set-channel", name])+ set_install_channel(args.set_channel, root)+ saved = yaml.safe_load((tmp_path / "home/config.yaml").read_text())+ assert resolve_update_channel(saved, root) == name+ assert parser.parse_args(["update", "--channel", name]).channel == name+ assert resolve_update_channel(saved, tmp_path / "other") == "main"+ for invalid in (" New-preview", "PREVIEW", "preview/other", "preview--other", ""):+ with pytest.raises(ValueError):+ set_install_channel(invalid, root)+ with pytest.raises(ValueError):+ resolve_update_channel(_config_for(root, invalid), root)+ with pytest.raises(SystemExit):+ parser.parse_args(["update", "--channel", invalid])++class TestInstallId:def test_path_derived_and_stable(self, tmp_path):"""The id hashes the canonical PATH — same path, same id, no matter@@ -72,6 +98,15 @@ class TestInstallId:class TestResolve:+ def test_channel_bundle_keeps_baked_subscription_in_its_cli(self, tmp_path):+ (tmp_path / 'install-stamp.json').write_text(json.dumps({+ 'payload': 'bundled', 'source': 'channel-build',+ 'updateMechanism': 'electron-updater', 'tag': None,+ 'channelBuild': {'channel': 'r2-preview'},+ }), encoding='utf-8')+ assert default_channel(tmp_path) == 'r2-preview'+ assert resolve_update_channel(_config_for(tmp_path, 'stable'), tmp_path) == 'r2-preview'+def test_multi_install_isolation(self, tmp_path):"""Two installs, one config: each resolves its own record and amissing record falls to the mechanism default — never the sibling's."""@@ -88,7 +123,7 @@ class TestResolve:('self', 'v1.2.3-canary.20260818', None, None, 'main'),(None, None, None, None, 'main'),('self', None, None, 'canary', 'canary'),- ('self', None, None, 'yolo', 'main'),+ ('self', None, None, 'yolo', 'yolo'),('electron-updater', 'v1.2.3', None, None, 'stable'),('electron-updater', 'v1.2.3-canary.20260819171926', None, 'stable', 'canary'),('app-installer', 'v1.2.3-canary.20260819171926', None, None, 'canary'),@@ -108,7 +143,7 @@ class TestResolve:(tmp_path / 'install-stamp.json').write_text(json.dumps(stamp), encoding='utf-8')config = _config_for(tmp_path, record) if record else {}assert resolve_update_channel(config, tmp_path) == expected- if not (mechanism == 'self' and record == 'canary'):+ if record is None or mechanism != 'self':assert default_channel(tmp_path) == expected@@ -167,8 +202,8 @@ class TestSetChannel:self._home(tmp_path, monkeypatch)root = tmp_path / "install"_stamp(root, "self")- with pytest.raises(ValueError, match="unknown channel"):- set_install_channel("beta", root)+ with pytest.raises(ValueError, match="Invalid channel name"):+ set_install_channel("../beta", root)class TestSetChannelCLI:@@ -292,7 +327,7 @@ class TestSetChannelCLI:before = b"# retain user comment\nmodel:\n provider: fixture\n"cfg.write_bytes(before)for mechanism, channel, message in (- ("self", "bogus", "unknown channel"),+ ("self", "../bogus", "Invalid channel name"),("external", "stable", "owned by"),("app-installer", "canary", "owned by"),):diff --git a/tests/hermes_cli/test_update_channel_stable.py b/tests/hermes_cli/test_update_channel_stable.pyindex 9411de4dd1d..b042dbfe2cd 100644--- a/tests/hermes_cli/test_update_channel_stable.py+++ b/tests/hermes_cli/test_update_channel_stable.py@@ -1,7 +1,10 @@"""Source-update channel selection policy."""+import jsonfrom unittest.mock import patch+import pytest+from hermes_cli.update_cmd import _source_update_channel@@ -20,7 +23,7 @@ class TestSourceUpdateChannel:def test_transient_channel_flag_wins(self):"""--channel is the per-invocation override (--set-channel persists);no config read happens when it is present."""- with patch("hermes_cli.config.load_config") as load_config:+ with patch("hermes_cli.config.require_readable_config_before_write") as load_config:for channel in ("stable", "main", "canary"):assert _source_update_channel(_Args(channel=channel)) == channelassert _source_update_channel(channel=channel) == channel@@ -40,8 +43,11 @@ class TestSourceUpdateChannel:import hermes_cli.update_cmd as update_cmdmonkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", root)- with patch("hermes_cli.config.load_config", return_value=config):- assert _source_update_channel(_Args()) == "stable"+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ (home / "config.yaml").write_text(json.dumps(config), encoding="utf-8")+ assert _source_update_channel(_Args()) == "stable"def test_no_record_stays_main(self, tmp_path, monkeypatch):root = tmp_path / "install"@@ -52,9 +58,11 @@ class TestSourceUpdateChannel:import hermes_cli.update_cmd as update_cmdmonkeypatch.setattr(update_cmd._m(), "PROJECT_ROOT", root)- with patch("hermes_cli.config.load_config", return_value={"update": {"installs": {}}}):- assert _source_update_channel(_Args()) == "main"+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ assert _source_update_channel(_Args()) == "main"- def test_config_failure_defaults_to_main(self):- with patch("hermes_cli.config.load_config", side_effect=RuntimeError("boom")):- assert _source_update_channel(_Args()) == "main"+ def test_config_failure_never_changes_the_subscription(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "config.yaml").write_text("update: [broken", encoding="utf-8")+ with pytest.raises(RuntimeError, match="not valid YAML"):+ _source_update_channel(_Args())diff --git a/tests/install/channel-retirement-controller.py b/tests/install/channel-retirement-controller.pynew file mode 100644index 00000000000..e02d0195c72--- /dev/null+++ b/tests/install/channel-retirement-controller.py@@ -0,0 +1,181 @@+#!/usr/bin/env python3+"""Sequence a disposable native journey; the native child has no publisher keys."""+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import time++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))++from hermes_cli.release_channels import ( # noqa: E402+ ChannelError, canonical_json, channel_key, decode_json, require_commit,+ require_sha256, validate_manifest,+)+from scripts.bundles.release_artifacts import write_appinstaller # noqa: E402+from scripts.releases import r2 # noqa: E402+from scripts.releases.channel_disposable import require_receiver_scope # noqa: E402+from scripts.releases.channel_releases import product_identity # noqa: E402+from scripts.releases.channels import ChannelPublisher, R2ChannelStore # noqa: E402+from scripts.releases.r2_scope import R2Scope, channel_public_base # noqa: E402+++def admitted_publisher(env: dict[str, str]) -> ChannelPublisher:+ repository = env["GITHUB_REPOSITORY"]+ branch = env["DEFAULT_BRANCH"]+ expected = f"{repository}/.github/workflows/install-e2e.yml@refs/heads/{branch}"+ if (env.get("GITHUB_ACTIONS") != "true" or env.get("RUNNER_ENVIRONMENT") != "github-hosted"+ or env.get("GITHUB_EVENT_NAME") != "workflow_dispatch" or env.get("GITHUB_WORKFLOW_REF") != expected+ or env.get("GITHUB_REF") != f"refs/heads/{branch}"):+ raise ChannelError("Retirement requires the default-branch hosted dispatch")+ controller = require_commit(env["GITHUB_SHA"])+ head = subprocess.check_output(["gh", "api", f"repos/{repository}/commits/{branch}", "--jq", ".sha"],+ encoding="utf-8", timeout=60, stdin=subprocess.DEVNULL).strip()+ if head != controller:+ raise ChannelError("Controller no longer matches the default branch")+ store = R2ChannelStore(*r2.credentials(), scope=R2Scope.configured())+ def authorize(action: str, record: dict) -> None:+ require_receiver_scope(publisher)+ if action != "retire" or record["policy"] != "preview":+ raise ChannelError("Native coordinator only retires disposable previews")+ publisher = ChannelPublisher(store, repository, channel_public_base(), authorize=authorize)+ require_receiver_scope(publisher)+ return publisher+++def prepare(publisher: ChannelPublisher, journey: dict) -> None:+ require_receiver_scope(publisher)+ if journey["repository"] != publisher.repository or journey["controllerCommit"] != os.environ["GITHUB_SHA"]:+ raise ChannelError("Journey controller authority mismatch")+ for slot in ("A", "S", "T", *(["B"] if journey["route"] == "via-update" else [])):+ side = journey[slot]+ manifest = decode_json(publisher.reader.read_bytes(side["head"]["manifestKey"], side["head"]["sha256"]))+ request = manifest["request"]+ record = publisher._read(request["channel"])[0]+ validate_manifest(manifest, {**record, "head": side["head"]}, publisher.public_base)+ if manifest != side["manifest"] or publisher.request(request["buildId"]) != request:+ raise ChannelError("Journey differs from immutable admitted build")+ if slot in {"S", "T"} and (request["identity"] != product_identity(request["releaseTag"])+ or request.get("receiverCandidate") is not True or manifest.get("receiverProtocol") != 1):+ raise ChannelError("S/T require scoped official-identity receiver candidates")+ source = publisher._read(journey["A"]["manifest"]["request"]["channel"])[0]+ target = publisher._read("stable")[0]+ if source["state"] != "active" or target["head"] != journey["S"]["head"]:+ raise ChannelError("Journey requires active preview and exact S head")+ if journey["route"] == "via-update" and source["head"] not in (journey["A"]["head"], journey["B"]["head"]):+ raise ChannelError("A to B requires exact A or already-advertised B; no rewind is permitted")+ stable_feed(publisher, journey["S"], journey["platform"])+++def stable_feed(publisher: ChannelPublisher, side: dict, platform: str) -> None:+ """Use the existing native descriptor writer, always under the physical scope."""+ require_receiver_scope(publisher)+ pkg = next(row for row in side["manifest"]["packages"] if row["platform"] == platform)+ key = f"releases/{platform}/stable/" + ("stable-mac.yml" if platform == "darwin" else "stable.appinstaller")+ if platform == "darwin":+ body = publisher.reader.read_bytes(pkg["feed"]["key"])+ feed = decode_json(body)+ if feed["version"] != side["manifest"]["request"]["version"] or not feed.get("files"):+ raise ChannelError("Stable feed version/files differ")+ if any(not item["url"].startswith(publisher.public_base + "/releases/") for item in feed["files"]):+ raise ChannelError("Stable feed escaped disposable authority")+ else:+ with tempfile.TemporaryDirectory() as directory:+ file = Path(directory) / "stable.appinstaller"+ write_appinstaller(file, identity=pkg["identity"], publisher=pkg["publisher"], version=pkg["version"],+ self_uri=f"{publisher.public_base}/{key}",+ artifact_uri=f"{publisher.public_base}/{pkg['artifact']['key']}", update_policy="pinned")+ body = file.read_bytes()+ prior = publisher.store.get(key)+ publisher.store.put(key, body, prior[1] if prior else None)+ if publisher.reader.read_bytes(key) != body:+ raise ChannelError("Stable descriptor public readback differs")+++def advance(publisher: ChannelPublisher, journey: dict, phase: str) -> dict:+ require_receiver_scope(publisher)+ source_name = journey["A"]["manifest"]["request"]["channel"]+ if phase == "retire":+ if publisher._read("stable")[0]["head"] != journey["S"]["head"]:+ raise ChannelError("Pinned S changed before retirement")+ return publisher.retire(source_name, "stable", journey["minimumVersion"])+ if phase == "preview-update" and journey["route"] == "via-update":+ name, before, after = source_name, journey["A"]["head"], journey["B"]["head"]+ elif phase == "stable-update":+ name, before, after = "stable", journey["S"]["head"], journey["T"]["head"]+ else:+ raise ChannelError("Unexpected journey stage")+ current, etag = publisher._read(name)+ # The ordinary B build may have already advertised its head. A is installed+ # from pinned bytes and the driver still waits for OLD chat before clicking.+ if phase == "preview-update" and current["state"] == "active" and current["head"] == after:+ return current+ if current["state"] != "active" or current["head"] != before or after["sequence"] >= current["nextSequence"]:+ raise ChannelError("Head changed or target was not allocated")+ if phase == "stable-update":+ stable_feed(publisher, journey["T"], journey["platform"])+ result = {**current, "head": after, "revision": current["revision"] + 1}+ publisher._write(channel_key(name), result, etag)+ return result+++def run(args: argparse.Namespace) -> None:+ body = args.manifest.read_bytes()+ if hashlib.sha256(body).hexdigest() != require_sha256(args.sha256):+ raise ChannelError("Controller input digest mismatch")+ journey = json.loads(body)+ if sys.platform not in {"darwin", "win32"} or journey["platform"] != sys.platform or journey["arch"] != args.arch:+ raise ChannelError("Native host/architecture must match journey")+ args.work = args.work.resolve()+ if not args.work.is_relative_to(Path(os.environ["RUNNER_TEMP"]).resolve()):+ raise ChannelError("Native work must remain under RUNNER_TEMP")+ publisher = admitted_publisher(dict(os.environ))+ args.work.mkdir()+ # Validate/stage without credentials before making any journey writes.+ environment = {key: value for key, value in os.environ.items()+ if not any(word in key.upper() for word in ("KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL"))+ and not key.upper().startswith(("CLOUDFLARE", "AWS_", "R2_", "HERMES_", "PYTHON", "VIRTUAL_ENV", "NODE_", "ELECTRON_"))}+ subprocess.run(["node", str(ROOT / "tests/install/e2e-assets/channel-retirement-inputs.mjs"),+ "--manifest", str(args.manifest), "--manifest-sha256", args.sha256, "--platform", sys.platform,+ "--arch", args.arch, "--out", str(args.work / "inputs")], env=environment, check=True, stdin=subprocess.DEVNULL)+ prepare(publisher, journey)+ driver = ROOT / "tests/install" / ("macos-bundled-e2e.sh" if sys.platform == "darwin" else "windows-bundled-e2e.ps1")+ command = (["bash", str(driver), "--phase", "retirement", "--retirement-work", str(args.work), "--arch", args.arch]+ if sys.platform == "darwin" else ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(driver), "-RetirementWork", str(args.work), "-Arch", args.arch])+ child = subprocess.Popen(command, env=environment, stdin=subprocess.DEVNULL)+ try:+ for phase in (["preview-update"] if journey["route"] == "via-update" else []) + ["retire", "stable-update"]:+ request = args.work / f"{phase}.request.json"+ deadline = time.monotonic() + 1200+ while not request.exists():+ if child.poll() is not None or time.monotonic() > deadline:+ raise ChannelError(f"Native driver did not reach {phase}")+ time.sleep(0.5)+ if json.loads(request.read_text()) != {"phase": phase, "controllerCommit": journey["controllerCommit"]}:+ raise ChannelError("Native stage gate mismatch")+ result = advance(publisher, journey, phase)+ temporary = args.work / f"{phase}.ready.partial"+ temporary.write_bytes(canonical_json(result))+ temporary.replace(args.work / f"{phase}.ready.json")+ if child.wait(timeout=1200) != 0:+ raise ChannelError("Native journey failed")+ finally:+ if child.poll() is None:+ child.terminate()+ child.wait(timeout=30)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--manifest", type=Path, required=True)+ parser.add_argument("--sha256", required=True)+ parser.add_argument("--work", type=Path, required=True)+ parser.add_argument("--arch", choices=("arm64", "x64"), required=True)+ run(parser.parse_args())diff --git a/tests/install/channel-retirement-e2e.md b/tests/install/channel-retirement-e2e.mdnew file mode 100644index 00000000000..e40ed866ef2--- /dev/null+++ b/tests/install/channel-retirement-e2e.md@@ -0,0 +1,80 @@+# Native bundled retirement acceptance++`install-e2e.yml` route `channel-retirement` runs the existing native bundled+entrypoints with a retirement phase. One shared lifecycle uses installed-chat,+update UI and process observers; there is no publication receipt/certification graph.++## Inputs and dispatch++Supply one digest-pinned journey per **fresh disposable authority**:++- `schema: 1`, `repository`, exact `controllerCommit`, native `platform: darwin|win32`,+ `arch: arm64|x64`, `route: direct|via-update`, `stable: absent|running`, `home: shared`.+- `minimumVersion` is the stable payload source-version floor.+- `A`, `S`, `T`, and `B` only for `via-update`: each `{head, manifest}` with the original+ immutable manifest bytes referenced by `{buildId, sequence, manifestKey, sha256}`.+- A/B have one persistent preview identity and increasing native versions. S/T use+ the official stable identity, increasing native versions, and manifest+ `receiverProtocol: 1`. Test S/T requests carry the existing scoped+ `receiverCandidate: true` marker; this is not native success evidence.+- Every request, artifact and descriptor belongs to the same+ `ci-disposable/<repository-id>/<allocation-run-attempt>/` authority. No tags or+ releases are fabricated. Normal signed candidate build/smoke gates produce S/T.++The source must be active at A or B for `via-update`; the driver installs pinned A+and clicks Update only after its first chat. If B is already advertised, the gate+reads it without rewriting the head. `direct` uses old A while its channel can be+newer. Stable must be at S; T is archived but not promoted. The controller never+rewinds a head or resets a retired channel. On the direct route, A stays closed+while retirement pins S and stable advances to T. A must then install pinned S,+not substitute T; S takes T through its ordinary stable updater.++```sh+gh workflow run install-e2e.yml --repo OWNER/hermes-agent --ref main \+ -f route=channel-retirement -f retirement-platform=darwin -f retirement-arch=arm64 \+ -f retirement-manifest=https://TRUSTED_HOST/journey.json \+ -f retirement-sha256=EXACT_SHA256 -f disposable-run=ALLOCATION_RUN_ID-ATTEMPT+```++This is an example, not a command executed locally. The signing environment must+supply the existing R2 credentials/root and GitHub must provide repository ID.+Default-branch hosted dispatch only; the exact default-branch SHA is checked.+Native children receive no publisher credentials. The scoped coordinator calls+`ChannelPublisher.retire()` directly and reads back channel/descriptor writes.+Windows descriptors use the existing App Installer writer with a scoped canonical+self URI and pinned immutable bundle URL. Stable S follows that feed to T.++## Observations and limits++Both native drivers route `A → B → S → T` and offline `A → S → T`, with absent or+running S and a shared persistent natural home. They reject emulation, existing+user state, missing artifacts, invalid signatures/identities, mismatched native+versions, stale PIDs, failed chats, and incomplete cleanup.++Automatic activation is verified **before any driver-owned reopen**: exact+installed bytes/signature/stamp, process executable/PID/birth, installed backend+listener and selected home; S also requires the authenticated completed private+journal and durable home/profile choice. Existing running S must retain its PID+and birth. After this observation, the ordinary harness pattern closes/reopens+the verified app for shared Playwright chat. These are explicitly post-transition+chat checks, not claims of chat in the OS-activated absent-S/T renderer. No HOME or+userData override is passed on reopen, so it also checks cold-launch adoption.++State checks retain real SQLite messages/integrity, marker bytes and the existing+plugin/profile/external-link fixtures. Preview removal roots and owned launchers+must disappear without test cleanup making them pass. Windows checks canonical+App Installer registration and Start-menu removal. Diagnostics contain selected+non-secret facts only, never the private journal/token or whole user home.++**Native execution has not been performed on Linux.** Real signed A/B/S/T and+native Actions runs remain necessary. Custom/distinct/removal-scoped homes,+remote connection migration, receiver cancellation/conflicts, retained newer+stable, interruption and cleanup-retry are not claimed by this shared-home journey;+those need their respective native/runtime acceptance cases. A test S/T build+must actually have stable receiver provenance and normal stable update ownership;+an official-looking identity on a preview-stamped candidate is not accepted.++Local checks: `node --test tests/install/e2e-assets/channel-retirement-manifest.test.cjs`+exercises real loopback downloads and rejects corruption, plus portable input+contracts for both platforms. Syntax, workflow lint and helper import checks do+not count as native installation or migration success.diff --git a/tests/install/channel-retirement-e2e.mjs b/tests/install/channel-retirement-e2e.mjsnew file mode 100644index 00000000000..031abbbd6a9--- /dev/null+++ b/tests/install/channel-retirement-e2e.mjs@@ -0,0 +1,265 @@+#!/usr/bin/env node+// Retirement phase of the bundled native drivers. Observations are not release admission.+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import assert from 'node:assert/strict'+import { createHash } from 'node:crypto'+import { execFileSync, spawnSync } from 'node:child_process'+import { parseArgs } from 'node:util'+import { extractFile } from '@electron/asar'+import { validateJourney } from './e2e-assets/channel-retirement-manifest.cjs'+import * as mac from './e2e-assets/channel-retirement-macos.mjs'+import { samePath, mainProcesses, assertInstalled } from './e2e-assets/channel-retirement-windows-observations.mjs'+import { launch, chat, transition, close } from './e2e-assets/channel-retirement-window.mjs'+import { smokeEnvironment } from './e2e-assets/desktop-smoke.ts'+import { readNativeProcesses, descendants, localBackendProcess, assertBackendOrigin } from '../../tests-js/scripts/desktop-smoke-process.ts'+import { writeMockProviderConfig, writeEnvFile } from '../../tests-js/scripts/mock-provider-config.ts'+import { startMockServer } from '../../tests-js/scripts/mock-server.ts'++/** @typedef {import('./e2e-assets/channel-retirement-manifest.cjs').Side} Side */+/** @typedef {{pid: number, executable: string, birth: string}} Observed */+/** @typedef {import('./e2e-assets/channel-retirement-window.mjs').Installed & {+ * appPath: string, executable: string, packageFamilyName?: string, packageFullName?: string}} Installed */++const { values } = parseArgs({ options: { work: { type: 'string' }, arch: { type: 'string' } } })+assert.ok(['darwin', 'win32'].includes(process.platform), 'Native Windows or macOS required')+assert.equal(process.env.GITHUB_ACTIONS, 'true')+assert.equal(process.env.RUNNER_ENVIRONMENT, 'github-hosted')+assert.equal(process.arch, values.arch, 'Emulation is not native acceptance')+const work = fs.realpathSync(values.work)+assert.ok(work.startsWith(fs.realpathSync(process.env.RUNNER_TEMP) + path.sep))+const assets = path.join(import.meta.dirname, 'e2e-assets')+const windows = process.platform === 'win32'+const journey = validateJourney(JSON.parse(fs.readFileSync(path.join(work, 'inputs/journey-inputs.json'))), process.platform, process.arch)+assert.equal(journey.repository, process.env.GITHUB_REPOSITORY)+assert.equal(journey.controllerCommit, process.env.GITHUB_SHA)+const base = journey.A.manifest.request.publicBase+assert.match(base, /\/ci-disposable\/[1-9][0-9]*\/[1-9][0-9]*-[1-9][0-9]*$/)+const out = path.join(work, 'observations'); fs.mkdirSync(out)+const observations = {}+/** @param {string} operation @param {object} input */+function win(operation, input) {+ return JSON.parse(execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File',+ path.join(assets, 'channel-retirement-windows-native.ps1'), '-Operation', operation], {+ input: JSON.stringify(input), encoding: 'utf8', windowsHide: true, timeout: 600_000,+ stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 8 * 1024 * 1024,+ }).replace(/^\uFEFF/, ''))+}+const account = windows ? win('preflight', { arch: process.arch, identities: [journey.A.package.identity, journey.S.package.identity] })+ : { home: fs.realpathSync(os.userInfo().homedir), appData: path.join(os.userInfo().homedir, 'Library/Application Support') }+assert.equal(fs.realpathSync(os.homedir()), account.home, 'OS activation requires the natural account home')+const home = windows ? path.join(account.localAppData, 'hermes') : path.join(account.home, '.hermes')+const journal = path.join(account.home, '.hermes-desktop-retirement')+for (const file of [home, journal]) assert.equal(fs.existsSync(file), false, 'Existing user state refused: ' + file)+const apps = path.join(work, 'apps'); fs.mkdirSync(apps)+/** @param {Side} side */+const appPath = side => path.join(apps, side.manifest.request.identity.displayName + '.app')+const stableFeed = `${base}/releases/win32/stable/stable.appinstaller`+const python = windows ? 'python' : 'python3'+/** @param {string[]} args */+const run = args => execFileSync(python, args, { encoding: 'utf8', windowsHide: true, timeout: 60_000, stdio: ['ignore', 'pipe', 'pipe'] })+const plugin = path.join(assets, 'verify-plugin-preservation.py')+const marker = `retirement-${process.env.GITHUB_RUN_ID}-${process.env.GITHUB_RUN_ATTEMPT}`+const ownedLaunchers = new Set()++/** @param {Side} side @param {boolean} [install] @returns {Installed} */+function installed(side, install = false) {+ let result+ if (windows) {+ result = win(install ? 'install' : 'installed', { side, arch: process.arch,+ feedUri: side.manifest.request.channel === 'stable' ? stableFeed : `${base}/${side.package.feed.key}` })+ assertInstalled(result, side, process.arch)+ } else {+ const target = appPath(side)+ if (install) {+ const dir = path.join(work, 'extract-' + side.head.buildId); fs.mkdirSync(dir)+ for (const name of mac.native('/usr/bin/unzip', ['-Z1', side.artifactPath]).split('\n')) {+ assert.ok(!name.startsWith('/') && !name.includes('\\') && !name.split('/').includes('..'), 'Unsafe ZIP path')+ }+ mac.native('/usr/bin/ditto', ['-x', '-k', side.artifactPath, dir])+ const entries = fs.readdirSync(dir).filter(name => name.endsWith('.app'))+ assert.equal(entries.length, 1)+ assert.equal(fs.existsSync(target), false)+ fs.renameSync(path.join(dir, entries[0]), target)+ }+ const verified = mac.verifyApp(target, side, process.arch)+ result = { ...verified, appPath: target, resources: path.join(target, 'Contents/Resources') }+ }+ const pkg = JSON.parse(extractFile(path.join(result.resources, 'app.asar'), 'package.json'))+ const name = side.manifest.request.releaseTag ? pkg.productName || pkg.name : side.manifest.request.identity.appNamePascal+ return { ...result, exe: result.executable, userData: path.join(account.appData, name), commit: side.manifest.request.commit }+}+/** @param {string} exe */+function processes(exe) { return windows ? mainProcesses(readNativeProcesses(), exe) : mac.processes(exe) }+/** @param {Installed} app @param {Observed} [prior] @returns {Promise<Observed>} */+async function observe(app, prior) {+ const observed = await mac.until(() => {+ const rows = processes(app.exe).filter(row => row.pid !== prior?.pid)+ assert.ok(rows.length <= 1, 'Ambiguous installed main process')+ if (!rows.length) return null+ return windows ? win('process', rows[0]) : mac.processIdentity(rows[0])+ }, 'automatic native activation')+ if (prior) assert.notEqual(observed.birth, prior.birth, 'Process birth did not change')+ return observed+}+/** @param {Installed} app @param {Observed} observed */+async function healthy(app, observed) {+ const root = path.join(app.resources, 'agent-payload')+ const stamp = JSON.parse(fs.readFileSync(path.join(app.resources, 'install-stamp.json')))+ const site = fs.realpathSync(path.join(root, stamp.runtime.sitePackages))+ assert.ok(site.startsWith(fs.realpathSync(root) + path.sep), 'Observer dependencies escaped installed payload')+ return mac.until(async () => {+ const children = descendants(readNativeProcesses(), observed.pid).filter(row => row.executable.toLowerCase().startsWith(root.toLowerCase() + path.sep))+ let ports = []+ if (windows) ports = win('listeners', {}).filter(row => row.LocalAddress === '127.0.0.1' && children.some(child => child.pid === row.OwningProcess)).map(row => row.LocalPort)+ else for (const child of children) {+ const result = spawnSync('/usr/sbin/lsof', ['-nP', '-a', '-p', String(child.pid), '-iTCP', '-sTCP:LISTEN', '-Fn'], { encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'] })+ if (result.error || ![0, 1].includes(result.status)) throw new Error('Native listener observation failed')+ ports.push(...[...result.stdout.matchAll(/^n127\.0\.0\.1:(\d+)$/gm)].map(match => Number(match[1])))+ }+ for (const port of ports) {+ const backend = localBackendProcess(port, observed.pid)+ assertBackendOrigin(backend, root, 'bundled')+ const selected = windows ? JSON.parse(execFileSync(backend.executable, ['-I', '-B', '-c',+ 'import json,sys; sys.path.insert(0,sys.argv[2]); import psutil; print(json.dumps(psutil.Process(int(sys.argv[1])).environ().get("HERMES_HOME")))', String(backend.pid), site],+ { encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }))+ : /(?:^|\s)HERMES_HOME=(.*?)(?=\s+[A-Za-z_][A-Za-z_0-9]*=|$)/.exec(mac.native('/bin/ps', ['eww', '-p', String(backend.pid), '-o', 'args=']))?.[1]+ assert.equal(fs.realpathSync(selected), fs.realpathSync(home), 'Automatic backend selected a different home')+ const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(10_000) })+ assert.equal(response.status, 200)+ return { pid: backend.pid, executable: backend.executable, home: selected }+ }+ return null+ }, 'automatically activated bundled backend', 180_000)+}+/** @param {string} phase */+async function gate(phase) {+ mac.write(path.join(work, phase + '.request.json'), { phase, controllerCommit: journey.controllerCommit })+ const record = await mac.until(() => {+ const file = path.join(work, phase + '.ready.json')+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file)) : null+ }, 'controller ' + phase)+ const response = await fetch(`${base}/releases/channels/${record.name}.json`, { cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(30_000) })+ assert.equal(response.status, 200); assert.deepEqual(await response.json(), record)+ if (phase === 'retire') { assert.deepEqual(record.destinationHead, journey.S.head); assert.equal(record.receiverProtocol, 1) }+ observations[phase] = record+}+const environment = smokeEnvironment(process.env, home, path.join(work, 'unused'))+for (const key of ['HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'HERMES_HOME', 'HERMES_DESKTOP_USER_DATA_DIR',+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'GITHUB_SHA', 'GITHUB_REF', 'GITHUB_REF_NAME']) delete environment[key]+environment.HOME = account.home+for (const key of ['USERPROFILE', 'APPDATA', 'LOCALAPPDATA']) if (process.env[key]) environment[key] = process.env[key]+const prompts = []+function preservation() {+ run([plugin, 'verify', '--home', home, '--snapshot', path.join(work, 'plugins.json'), '--report', path.join(out, 'plugins-' + prompts.length + '.json')])+ assert.equal(fs.readFileSync(path.join(home, 'retirement-marker.txt'), 'utf8'), marker)+ run(['-c', 'import sqlite3,sys,json,pathlib; c=sqlite3.connect(pathlib.Path(sys.argv[1]).as_uri()+"?mode=ro",uri=True); assert c.execute("pragma integrity_check").fetchone()[0]=="ok"; assert all(c.execute("select count(*) from messages where role=\'user\' and content like ?",("%"+p+"%",)).fetchone()[0]>0 for p in json.loads(sys.argv[2]))', path.join(home, 'state.db'), JSON.stringify(prompts)])+}+/** @param {Installed} app */+async function start(app) { assert.equal(processes(app.exe).length, 0); return launch(app, environment) }+/** @param {Installed} app @param {Observed} observed */+async function reopen(app, observed) {+ if (windows) win('quit', observed); else await mac.quit(observed)+ await mac.until(() => !processes(app.exe).length, 'verified app normal quit', 60_000)+ return start(app)+}+const mock = await startMockServer()+try {+ for (const side of [journey.A, ...(journey.B ? [journey.B] : []), journey.S, journey.T]) {+ assert.equal(fs.statSync(side.artifactPath).size, side.package.artifact.size)+ const hash = createHash('sha256')+ for await (const chunk of fs.createReadStream(side.artifactPath)) hash.update(chunk)+ assert.equal(hash.digest('hex'), side.package.artifact.sha256)+ if (windows) win('artifact', { side, arch: process.arch })+ }+ fs.mkdirSync(home, { mode: 0o700 })+ writeMockProviderConfig(home, mock.url, undefined, `updates:\n desktop_feed_base_url: ${base}\n`)+ writeEnvFile(home); fs.writeFileSync(path.join(home, 'retirement-marker.txt'), marker, { flag: 'wx' })+ run([plugin, 'seed', '--home', home, '--external', path.join(work, 'external-plugin')])+ run([plugin, 'snapshot', '--home', home, '--out', path.join(work, 'plugins.json')])+ let sourceApp = installed(journey.A, true)+ assert.equal(fs.existsSync(sourceApp.userData), false, 'Existing desktop state refused')+ let existing+ if (journey.stable === 'running') {+ const stable = installed(journey.S, true)+ assert.equal(fs.existsSync(stable.userData), false)+ existing = await start(stable)+ await chat(existing, mock.url, path.join(out, 'preexisting'))+ }+ let source = await start(sourceApp)+ prompts.push(await chat(source, mock.url, path.join(out, 'A')))+ if (journey.B) {+ const before = await observe(sourceApp)+ await gate('preview-update'); await transition(source, 'update', out)+ if (windows) await mac.until(() => win('available', { side: journey.B, arch: process.arch }), 'B installed')+ const observed = await observe(windows ? installed(journey.B) : sourceApp, before)+ sourceApp = installed(journey.B)+ observations.B = { process: observed, backend: await healthy(sourceApp, observed) }+ mac.write(path.join(out, 'automatic-B.json'), observations.B)+ source = await reopen(sourceApp, observed)+ prompts.push(await chat(source, mock.url, path.join(out, 'B')))+ }+ preservation()+ if (!windows) {+ const dir = path.join(account.home, '.local/bin')+ if (fs.existsSync(dir)) for (const name of fs.readdirSync(dir)) {+ const file = path.join(dir, name)+ if (fs.lstatSync(file).isSymbolicLink() && path.resolve(dir, fs.readlinkSync(file)).startsWith(sourceApp.appPath + path.sep)) ownedLaunchers.add(file)+ }+ }+ if (journey.route === 'direct') await close(source)+ await gate('retire')+ if (journey.route === 'direct') {+ await gate('stable-update')+ source = await start(sourceApp)+ prompts.push(await chat(source, mock.url, path.join(out, 'offline-A')))+ }+ const before = await observe(sourceApp)+ const existingProcess = existing ? await observe(existing.installed) : null+ await transition(source, 'retire', out)+ const stable = await mac.until(() => {+ if (windows ? !win('available', { side: journey.S, arch: process.arch }) : !fs.existsSync(appPath(journey.S))) return null+ return installed(journey.S)+ }, 'stable installed')+ const ready = await mac.until(() => mac.completedJournal(journal, sourceApp.appPath, stable.appPath,+ journey.S.head.sha256, sourceApp.packageFullName), 'authenticated retirement completion')+ const observed = await observe(stable)+ assert.equal(observed.pid, ready.pid); assert.equal(ready.home, home)+ assert.ok(windows ? samePath(observed.executable, ready.executable) : observed.executable === ready.executable)+ if (existingProcess) assert.deepEqual(observed, existingProcess, 'Running stable instance was replaced')+ observations.S = { process: observed, backend: await healthy(stable, observed), retirement: ready }+ assert.equal(processes(before.executable).length, 0)+ assert.notEqual(stable.userData, sourceApp.userData)+ const preference = JSON.parse(fs.readFileSync(path.join(stable.userData, 'active-profile.json')))+ assert.equal(fs.realpathSync(preference.home), fs.realpathSync(home)); assert.equal(preference.profile, ready.profile)+ for (const removal of ready.removalRoots) assert.equal(fs.existsSync(removal), false, 'Preview root survived')+ for (const file of ownedLaunchers) assert.equal(fs.lstatSync(file, { throwIfNoEntry: false }), undefined, 'Owned CLI launcher survived')+ if (windows) {+ const removed = win('removed', { side: journey.A, arch: process.arch, family: sourceApp.packageFamilyName })+ assert.equal(removed.registered, false); assert.deepEqual(removed.startApps, [])+ assert.equal(win('registration', { side: journey.S, arch: process.arch }).uri, stableFeed)+ }+ mac.write(path.join(out, 'automatic-S.json'), observations.S)+ const stableWindow = existing ?? await reopen(stable, observed)+ prompts.push(await chat(stableWindow, mock.url, path.join(out, 'S'))); preservation()+ if (journey.route !== 'direct') await gate('stable-update')+ const prior = await observe(stable)+ await transition(stableWindow, 'update', out)+ if (windows) await mac.until(() => win('available', { side: journey.T, arch: process.arch }), 'T installed')+ const nextProcess = await observe(windows ? installed(journey.T) : stable, prior)+ const next = installed(journey.T)+ observations.T = { process: nextProcess, backend: await healthy(next, nextProcess) }+ if (windows) assert.equal(win('registration', { side: journey.T, arch: process.arch }).uri, stableFeed)+ mac.write(path.join(out, 'automatic-T.json'), observations.T)+ const cold = await reopen(next, nextProcess)+ prompts.push(await chat(cold, mock.url, path.join(out, 'T'))); preservation()+ await close(cold)+ mac.write(path.join(out, 'lifecycle.json'), observations)+} catch (error) {+ mac.write(path.join(out, 'failure.json'), { message: String(error.message), phases: Object.keys(observations) })+ process.exitCode = 1+} finally { await mock.close() }+// Do not invoke ElectronApplication.close on old update owners: inherited pipes+// can outlive the source, and Playwright cleanup must not kill native receivers.+process.exit(process.exitCode ?? 0)diff --git a/tests/install/e2e-assets/bundle-smoke-metadata.mjs b/tests/install/e2e-assets/bundle-smoke-metadata.mjsindex 384bd5845d9..9e76bb6c7e7 100644--- a/tests/install/e2e-assets/bundle-smoke-metadata.mjs+++ b/tests/install/e2e-assets/bundle-smoke-metadata.mjs@@ -4,33 +4,57 @@ import path from 'node:path'import { execFileSync, spawnSync } from 'node:child_process'import { parseArgs } from 'node:util'import { fileURLToPath } from 'node:url'-import { OUT_OF_STORE_PUBLISHER } from '../../../scripts/msix-shared.mjs'-import { codesignTeam } from './mac-bundled-manifest.cjs'+import { OUT_OF_STORE_PUBLISHER, channelBuildRequest } from '../../../scripts/msix-shared.mjs'+import { codesignTeam, channelStampAssertions } from './mac-bundled-manifest.cjs'const identityModule = fileURLToPath(new URL('../../../apps/desktop/product-identity.cjs', import.meta.url))-export function bundleIdentity(commit, tag = '') {+function admitChannelRequest(request, commit, tag) {+ if (tag || request?.commit !== commit) throw new Error('Channel request conflicts with commit or tag')+ return channelBuildRequest({ ...process.env, HERMES_DESKTOP_VARIANT: 'bundled',+ HERMES_BUILD_COMMIT: '', HERMES_PAYLOAD_TAG: '', HERMES_PAYLOAD_VERSION: '',+ _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(request) })+}++export function bundleIdentity(commit, tag = '', channelRequest = null) {if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error('Expected exact full lowercase commit SHA')if (tag && !/^v\d+\.\d+\.\d+(?:-canary\.20\d{6}(?:\d{6})?)?$/.test(tag)) throw new Error('Invalid release tag')+ if (channelRequest !== null) {+ const request = admitChannelRequest(channelRequest, commit, tag)+ return { appId: request.identity.appId, msixIdentity: request.identity.msixAppIdWithOrg,+ applicationId: request.identity.appNamePascal, publisher: OUT_OF_STORE_PUBLISHER,+ windowsVersion: request.windowsVersion }+ }// The production module reads build flags at require-time. A child avoids// mutating the driver's environment or returning a cached variant identity.const identity = JSON.parse(execFileSync(process.execPath, ['-e','console.log(JSON.stringify(require(process.argv[1])))', identityModule], {encoding: 'utf8', env: { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled',- HERMES_PAYLOAD_TAG: tag, HERMES_BUILD_COMMIT: tag ? '' : commit },+ HERMES_PAYLOAD_TAG: tag, HERMES_BUILD_COMMIT: tag ? '' : commit, _HERMES_CHANNEL_REQUEST_JSON: '' },}))return { appId: identity.appId, msixIdentity: identity.msixAppIdWithOrg,applicationId: identity.appNamePascal, publisher: OUT_OF_STORE_PUBLISHER }}-export function verifyBundleStamp(stamp, { commit, tag = '', platform }) {+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,- updateMechanism: tag ? { darwin: 'electron-updater', win32: 'app-installer' }[platform] : 'external' }- if (!tag) Object.assign(expected, { source: 'commit-build', branch: null })+ 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)) {if (stamp?.[key] !== value) throw new Error(`stamp.${key}: ${JSON.stringify(stamp?.[key])} != ${JSON.stringify(value)}`)}+ if (request) {+ const problems = channelStampAssertions(stamp, request)+ if (problems.length) throw new Error(problems.join('; '))+ return platform === 'darwin' ? request.version : request.windowsVersion+ }+ return legacyBundleVersion(stamp, tag)+}++function legacyBundleVersion(stamp, tag) {+ if (stamp.channelBuild != null) throw new Error('Unexpected stamp.channelBuild without an admitted request')const version = tag ? tag.slice(1) : stamp.displayVersionif (!tag && !/^\d+\.\d+\.\d+$/.test(version)) throw new Error('stamp.displayVersion must be a commit-build semver')return version@@ -42,8 +66,18 @@ function childPath(root, relative) {return full}-function verifyMac(app, commit, tag, arch) {- const expected = bundleIdentity(commit, tag)+export function verifyMacMetadata(plist, stamp, { commit, tag, channelRequest }) {+ const expected = bundleIdentity(commit, tag, channelRequest)+ if (plist.CFBundleIdentifier !== expected.appId) throw new Error('CFBundleIdentifier disagrees with product identity')+ const version = verifyBundleStamp(stamp, { commit, tag, platform: 'darwin', channelRequest })+ if (plist.CFBundleShortVersionString !== version) throw new Error('CFBundleShortVersionString disagrees with stamp/tag/request')+ if (channelRequest && plist.CFBundleVersion !== channelRequest.version) throw new Error('CFBundleVersion disagrees with channel request')+ if (!plist.CFBundleExecutable || /[/\\]/.test(plist.CFBundleExecutable)) throw new Error('Invalid CFBundleExecutable')+ return version+}++function verifyMac(app, commit, tag, arch, channelRequest) {+ const expected = bundleIdentity(commit, tag, channelRequest)execFileSync('/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=2', app], { stdio: 'inherit' })const display = spawnSync('/usr/bin/codesign', ['-dv', '--verbose=4', app], { encoding: 'utf8' })@@ -55,11 +89,8 @@ function verifyMac(app, commit, tag, arch) {if (/^Identifier=(.+)$/m.exec(display.stderr)?.[1] !== expected.appId) throw new Error('Signing identifier disagrees with product identity')const plist = JSON.parse(execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-',path.join(app, 'Contents/Info.plist')], { encoding: 'utf8' }))- if (plist.CFBundleIdentifier !== expected.appId) throw new Error('CFBundleIdentifier disagrees with product identity')const stamp = JSON.parse(fs.readFileSync(childPath(app, 'Contents/Resources/install-stamp.json'), 'utf8'))- const version = verifyBundleStamp(stamp, { commit, tag, platform: 'darwin' })- if (plist.CFBundleShortVersionString !== version) throw new Error('CFBundleShortVersionString disagrees with stamp/tag')- if (!plist.CFBundleExecutable || /[/\\]/.test(plist.CFBundleExecutable)) throw new Error('Invalid CFBundleExecutable')+ const version = verifyMacMetadata(plist, stamp, { commit, tag, channelRequest })const exe = childPath(app, `Contents/MacOS/${plist.CFBundleExecutable}`)fs.accessSync(exe, fs.constants.X_OK)const archs = execFileSync('/usr/bin/lipo', ['-archs', exe], { encoding: 'utf8' }).trim().split(/\s+/)@@ -98,11 +129,18 @@ function prepareDirectories(work, out) {function main() {const [command, ...args] = process.argv.slice(2)const { values } = parseArgs({ args, options: Object.fromEntries(- ['commit', 'tag', 'platform', 'stamp', 'app', 'arch', 'out', 'work'].map(key => [key, { type: 'string' }])) })+ ['commit', 'tag', 'platform', 'stamp', 'app', 'arch', 'out', 'work', 'channel-request'].map(key => [key, { type: 'string' }])) })+ if (values['channel-request'] !== undefined) {+ // Preserve the raw JSON for the protocol decoder's duplicate-key checks.+ const raw = fs.readFileSync(values['channel-request'], 'utf8')+ if (!raw) throw new Error('Empty channel request')+ values.channelRequest = channelBuildRequest({ ...process.env, HERMES_DESKTOP_VARIANT: 'bundled',+ HERMES_BUILD_COMMIT: '', HERMES_PAYLOAD_TAG: '', HERMES_PAYLOAD_VERSION: '', _HERMES_CHANNEL_REQUEST_JSON: raw })+ }const commands = {- identity: () => bundleIdentity(values.commit, values.tag),+ identity: () => bundleIdentity(values.commit, values.tag, values.channelRequest),stamp: () => verifyBundleStamp(JSON.parse(fs.readFileSync(values.stamp, 'utf8')), values),- 'verify-mac': () => verifyMac(values.app, values.commit, values.tag, values.arch),+ 'verify-mac': () => verifyMac(values.app, values.commit, values.tag, values.arch, values.channelRequest),prepare: () => prepareDirectories(values.work, values.out),}if (!commands[command]) throw new Error(`Unknown command: ${command}`)diff --git a/tests/install/e2e-assets/channel-retirement-inputs.mjs b/tests/install/e2e-assets/channel-retirement-inputs.mjsnew file mode 100644index 00000000000..86fe3a5b684--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-inputs.mjs@@ -0,0 +1,70 @@+#!/usr/bin/env node+// Stage pinned archive bytes only. This command never publishes or installs.+import { createHash } from 'node:crypto'+import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'+import path from 'node:path'+import { pathToFileURL } from 'node:url'+import { parseArgs } from 'node:util'+import { downloadArtifact } from './bundle-inputs.mjs'+import { validateJourney, verifyManifest } from './channel-retirement-manifest.cjs'++/** @param {string} url @param {string} sha256 @returns {Promise<Buffer>} */+async function readObject(url, sha256) {+ const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(60_000), cache: 'no-store' })+ if (!response.ok || !response.body) throw new Error(`Archive read failed: HTTP ${response.status}`)+ const chunks = []+ let size = 0+ for await (const chunk of response.body) {+ size += chunk.length+ if (size > 4 * 1024 * 1024) throw new Error('Archive metadata exceeds limit')+ chunks.push(chunk)+ }+ const bytes = Buffer.concat(chunks)+ if (createHash('sha256').update(bytes).digest('hex') !== sha256) throw new Error('Archive metadata SHA256 mismatch')+ return bytes+}+++/** @param {{manifest: string, manifestSha256: string, platform: string, arch: string, out: string}} options */+export async function stageJourney({ manifest, manifestSha256, platform, arch, out }) {+ if (!/^[a-f0-9]{64}$/.test(manifestSha256)) throw new Error('Exact journey SHA256 is required')+ const bytes = await readFile(manifest)+ if (createHash('sha256').update(bytes).digest('hex') !== manifestSha256) throw new Error('Journey SHA256 mismatch')+ const journey = validateJourney(JSON.parse(bytes), platform, arch)+ // Exclusive directory creation rejects stale inputs and receipts from another run.+ await mkdir(out)+ const base = journey.A.manifest.request.publicBase+ const slots = ['A', ...(journey.B ? ['B'] : []), 'S', 'T']++ for (const name of slots) {+ const side = journey[name]+ const archived = await readObject(`${base}/${side.head.manifestKey}`, side.head.sha256)+ verifyManifest(archived, side)+ await writeFile(path.join(out, `${name}-manifest.json`), archived, { flag: 'wx' })+ }+ for (const name of slots) {+ const side = journey[name]+ const artifact = side.package.artifact+ const extension = platform === 'darwin' ? '.zip' : '.msixbundle'+ if (!artifact.key.endsWith(extension)) throw new Error(`Native journey needs ${extension}`)+ const target = path.resolve(out, name + extension)+ await downloadArtifact({ url: `${base}/${artifact.key}`, sha256: artifact.sha256 }, target)+ if ((await stat(target)).size !== artifact.size) throw new Error('Native artifact size mismatch')+ side.artifactPath = target+ }+ // Deliberately not receipt.json: download validation is not native evidence.+ const target = path.join(out, 'journey-inputs.json')+ await writeFile(target, JSON.stringify(journey, null, 2) + '\n', { flag: 'wx' })+ return target+}++if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {+ const { values } = parseArgs({ options: {+ manifest: { type: 'string' }, 'manifest-sha256': { type: 'string' },+ platform: { type: 'string' }, arch: { type: 'string' }, out: { type: 'string' },+ } })+ if (!values.manifest || !values['manifest-sha256'] || !values.platform || !values.arch || !values.out) {+ throw new Error('--manifest, --manifest-sha256, --platform, --arch and --out are required')+ }+ console.log(await stageJourney({ ...values, manifestSha256: values['manifest-sha256'] }))+}diff --git a/tests/install/e2e-assets/channel-retirement-macos.mjs b/tests/install/e2e-assets/channel-retirement-macos.mjsnew file mode 100644index 00000000000..154141b37dd--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-macos.mjs@@ -0,0 +1,117 @@+// Native observations for the retirement journey. No destination launch or IPC apply.+import fs from 'node:fs'+import path from 'node:path'+import { execFileSync, spawnSync } from 'node:child_process'+import { createHash, createHmac } from 'node:crypto'+import assert from 'node:assert/strict'+import { codesignTeam, stampAssertions } from './mac-bundled-manifest.cjs'+import { readNativeProcesses } from '../../../tests-js/scripts/desktop-smoke-process.ts'++/** @returns {Promise<void>} */+export const pause = () => new Promise(resolve => setTimeout(resolve, 500))+/** @template T @param {() => T | Promise<T>} probe @param {string} description @param {number} [timeout] */+export async function until(probe, description, timeout = 900_000) {+ const deadline = Date.now() + timeout+ while (Date.now() < deadline) {+ const result = await probe()+ if (result) return result+ await pause()+ }+ throw new Error(`Timed out: ${description}`)+}+/** @param {string} command @param {string[]} args @returns {string} */+export function native(command, args) {+ return execFileSync(command, args, { encoding: 'utf8', timeout: 120_000, maxBuffer: 4 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }).trim()+}+/** @param {string} file @param {object} data */+export function write(file, data) {+ assert.equal(fs.existsSync(file), false, 'Refusing to overwrite prior evidence')+ const temporary = file + '.partial'+ fs.writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', { flag: 'wx', mode: 0o600 })+ fs.renameSync(temporary, file)+}+/** @param {string} app @returns {string} */+export function executable(app) {+ const name = native('/usr/bin/plutil', ['-extract', 'CFBundleExecutable', 'raw', '-o', '-', path.join(app, 'Contents/Info.plist')])+ if (!name || /[/\\]/.test(name)) throw new Error('Unsafe bundle executable')+ return path.join(app, 'Contents/MacOS', name)+}+/** @param {string} app @param {import("./channel-retirement-manifest.cjs").Side} side @param {string} arch */+export function verifyApp(app, side, arch) {+ native('/usr/bin/codesign', ['--verify', '--deep', '--strict', app])+ native('/usr/sbin/spctl', ['-a', '-vv', '-t', 'exec', app])+ const signature = spawnSync('/usr/bin/codesign', ['-dv', '--verbose=4', app], { encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'] })+ if (signature.status !== 0) throw new Error('codesign display failed')+ assert.equal(codesignTeam(signature.stderr), side.package.teamId)+ assert.equal(/^Identifier=(.+)$/m.exec(signature.stderr)?.[1], side.package.identity)+ const plist = JSON.parse(native('/usr/bin/plutil', ['-convert', 'json', '-o', '-', path.join(app, 'Contents/Info.plist')]))+ assert.equal(plist.CFBundleIdentifier, side.package.identity)+ assert.equal(plist.CFBundleShortVersionString, side.package.version)+ const bin = executable(app)+ assert.equal(native('/usr/bin/lipo', ['-archs', bin]), arch === 'arm64' ? 'arm64' : 'x86_64')+ const stamp = JSON.parse(fs.readFileSync(path.join(app, 'Contents/Resources/install-stamp.json')))+ const request = side.manifest.request+ const expected = { commit: request.commit, tag: request.releaseTag || null }+ if (!request.releaseTag) expected.channelRequest = request+ assert.deepEqual(stampAssertions(stamp, expected), [])+ // Stable release manifests wrap original signed release bytes, not restamped channel builds.+ return { executable: bin, app, commit: stamp.commit, identity: plist.CFBundleIdentifier,+ version: plist.CFBundleShortVersionString, teamId: side.package.teamId }+}+/** @param {string} bin */+export function processes(bin) { return readNativeProcesses().filter(row => row.executable === bin) }+/** @param {import("../../../tests-js/scripts/desktop-smoke-process.ts").NativeProcess} row */+export function processIdentity(row) {+ return { pid: row.pid, executable: row.executable, birth: native('/bin/ps', ['-p', String(row.pid), '-o', 'lstart=']) }+}+/** @param {{pid: number, executable: string, birth: string}} observed */+export function assertProcess(observed) {+ const found = processes(observed.executable).find(row => row.pid === observed.pid)+ assert.ok(found, 'Observed native application exited')+ assert.equal(processIdentity(found).birth, observed.birth, 'Native PID was reused')+}+/** @param {string} bin @param {number} [exceptPid] */+export async function observe(bin, exceptPid) {+ return until(() => {+ const rows = processes(bin).filter(row => row.pid !== exceptPid)+ if (rows.length > 1) throw new Error('Ambiguous installed application process')+ return rows.length === 1 ? processIdentity(rows[0]) : null+ }, `automatic activation at ${bin}`)+}+/** @param {{pid: number, executable: string, birth: string}} observed */+export async function quit(observed) {+ assertProcess(observed)+ native('/usr/bin/osascript', ['-l', 'JavaScript', '-e',+ 'ObjC.import("AppKit"); function run(args) { const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(args[0])); if (!app || !app.terminate) throw Error("Native Quit refused"); }', String(observed.pid)])+ await until(() => !processes(observed.executable).some(row => row.pid === observed.pid), 'normal native Quit', 60_000)+}+/** @param {string} root @param {string} source @param {string} destination+ * @param {string} manifestSha256 @param {string | undefined} sourcePackage */+export function completedJournal(root, source, destination, manifestSha256, sourcePackage) {+ if (!fs.existsSync(root)) return null+ const rows = fs.readdirSync(root).filter(name => /^[a-f0-9]{32}$/.test(name) && fs.existsSync(path.join(root, name, 'journal.json')))+ assert.ok(rows.length <= 1, 'Ambiguous retirement journals')+ if (!rows.length) return null+ const file = path.join(root, rows[0], 'journal.json')+ if (!fs.existsSync(file)) return null+ const record = JSON.parse(fs.readFileSync(file))+ if (record.stage !== 'complete') return null+ const normalize = value => sourcePackage ? path.win32.normalize(value).toLowerCase() : path.normalize(value)+ assert.equal(normalize(record.request.source.appPath), normalize(source))+ assert.equal(normalize(record.request.destination.appPath), normalize(destination))+ if (sourcePackage) assert.equal(record.request.source.packageFullName, sourcePackage)+ assert.equal(record.request.destinationManifestSha256, manifestSha256)+ const digest = createHash('sha256').update(JSON.stringify(record.request)).digest('hex')+ assert.equal(record.requestDigest, digest)+ const { mac, ...ready } = record.ready+ assert.equal(createHmac('sha256', Buffer.from(record.request.token, 'hex')).update(JSON.stringify(ready)).digest('hex'), mac)+ assert.equal(ready.requestDigest, digest)+ assert.equal(ready.id, record.request.id)+ assert.equal(ready.home, record.state.selectedHome)+ assert.equal(ready.commit, record.request.destination.commit)+ assert.equal(ready.connectionId, 'local')+ // Export only non-secret observed fields. Never persist the private request/token.+ return { id: ready.id, pid: ready.pid, executable: ready.executable, commit: ready.commit,+ home: ready.home, profile: ready.profile, stage: record.stage,+ removalRoots: record.request.source.removalRoots }+}diff --git a/tests/install/e2e-assets/channel-retirement-manifest.cjs b/tests/install/e2e-assets/channel-retirement-manifest.cjsnew file mode 100644index 00000000000..446393f2f32--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-manifest.cjs@@ -0,0 +1,65 @@+'use strict'+// Native journey inputs are exact archived builds, not a relaxed OLD/NEW manifest.+const { createHash } = require('node:crypto')+const { isDeepStrictEqual } = require('node:util')++function validateJourney(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)) {+ 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 (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')+ }+ 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')+ }+ return input+}++function verifyBytes(bytes, expected) {+ if (bytes.length !== expected.size || createHash('sha256').update(bytes).digest('hex') !== expected.sha256) {+ throw new Error('Immutable artifact size/hash mismatch')+ }+}++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')+ }+}++module.exports = { validateJourney, verifyBytes, verifyManifest }diff --git a/tests/install/e2e-assets/channel-retirement-manifest.test.cjs b/tests/install/e2e-assets/channel-retirement-manifest.test.cjsnew file mode 100644index 00000000000..8d774915af9--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-manifest.test.cjs@@ -0,0 +1,41 @@+const { test } = require('node:test')+const assert = require('node:assert/strict')+const { createHash } = require('node:crypto')+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') } }+ }+ 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') }+}++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('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/)+})diff --git a/tests/install/e2e-assets/channel-retirement-native-ui.ps1 b/tests/install/e2e-assets/channel-retirement-native-ui.ps1new file mode 100644index 00000000000..50898f54a05--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-native-ui.ps1@@ -0,0 +1,22 @@+# 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/channel-retirement-window.mjs b/tests/install/e2e-assets/channel-retirement-window.mjsnew file mode 100644index 00000000000..9637b1edc8b--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-window.mjs@@ -0,0 +1,66 @@+// Shared installed-chat/update controls; never launch an unobserved destination.+import fs from 'node:fs'+import path from 'node:path'+import { _electron } from '@playwright/test'+import { runUpdateWindowChat } from './update-window-chat.mjs'+import { pickAppWindow, openAbout, waitForUpdate } from './update-ui.cjs'+import { prepareWindowForInput } from './window-input.cjs'+import { observeProcessClose } from './process-close.cjs'++/** @typedef {{exe: string, resources: string, userData: string, commit: string}} Installed */+/** @typedef {{app: import('@playwright/test').ElectronApplication, page: import('@playwright/test').Page,+ * closed: (timeout?: number) => Promise<void>, installed: Installed}} Window */++/** @param {Installed} installed @param {NodeJS.ProcessEnv} env @returns {Promise<Window>} */+export async function launch(installed, env) {+ const app = await _electron.launch({ executablePath: installed.exe, cwd: env.HOME, env, timeout: 120_000 })+ const closed = observeProcessClose(app.process())+ const page = await pickAppWindow(app, console.log)+ await prepareWindowForInput(app, page)+ return { app, page, closed, installed }+}++/** @param {Window} window @param {string} mockUrl @param {string} out */+export async function chat(window, mockUrl, out) {+ const { app, page, installed } = window+ const close = page.getByRole('button', { name: 'Close settings', exact: true })+ if (await close.isVisible()) await close.click()+ // Assertion input only: the launched app receives no userData/home override.+ process.env.HERMES_DESKTOP_USER_DATA_DIR = installed.userData+ await runUpdateWindowChat(app, page, { mockUrl, outDir: out, expectCommit: installed.commit,+ origin: 'bundled', executable: installed.exe, root: path.join(installed.resources, 'agent-payload') })+ return JSON.parse(fs.readFileSync(path.join(out, 'desktop-chat-old.json'), 'utf8')).prompt+}++/** @param {Window} window @param {'update'|'retire'} action @param {string} out */+export async function transition(window, action, out) {+ const { app, page } = window+ const controls = { log: console.log, shot: (page, name) => page.screenshot({ path: path.join(out, name + '.png') }),+ prepare: () => prepareWindowForInput(app, page) }+ await openAbout(page, controls)+ if (action === 'update') {+ const button = await waitForUpdate(page, controls)+ await button.click()+ } else {+ const consent = page.getByRole('checkbox', { name: 'Install or update stable and remove this preview only after stable is ready.', exact: true })+ const deadline = Date.now() + 180_000+ while (!await consent.isVisible()) {+ const move = page.getByRole('button', { name: 'Move to stable', exact: true })+ if (await move.isVisible()) await move.click()+ else {+ const check = page.getByRole('button', { name: 'Check now', exact: true })+ if (await check.isVisible()) await check.click()+ }+ if (Date.now() > deadline) throw new Error('Retirement consent unavailable')+ await page.waitForTimeout(500)+ }+ if (await consent.isChecked()) throw new Error('Consent unexpectedly preselected')+ await page.getByRole('radio', { name: 'Open this preview workspace in stable', exact: true }).check()+ await consent.check()+ await page.getByRole('button', { name: 'Move to stable', exact: true }).click()+ }+ await window.closed(900_000)+}++/** @param {Window} window */+export async function close(window) { await window.app.close(); await window.closed(60_000) }diff --git a/tests/install/e2e-assets/channel-retirement-windows-native.ps1 b/tests/install/e2e-assets/channel-retirement-windows-native.ps1new file mode 100644index 00000000000..a9900b448fd--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-windows-native.ps1@@ -0,0 +1,113 @@+# Native AppX observations and initial install/activation only. JSON in, JSON out.+param([Parameter(Mandatory=$true)][ValidateSet('preflight','artifact','available','installed','install','quit','process','listeners','registration','removed')][string]$Operation)+$ErrorActionPreference = 'Stop'+Set-StrictMode -Version Latest+[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)+if ($env:GITHUB_ACTIONS -cne 'true' -or $env:RUNNER_ENVIRONMENT -cne 'github-hosted' -or $env:OS -cne 'Windows_NT') { throw 'Disposable GitHub-hosted Windows required' }+$p = [Console]::In.ReadToEnd() | ConvertFrom-Json+. (Join-Path $PSScriptRoot 'windows-bundle-metadata.ps1')+Add-Type -AssemblyName System.IO.Compression.FileSystem+function Emit($Value) { ConvertTo-Json -Compress -Depth 32 -InputObject $Value }+function Exact-Package([bool]$Required) {+ $packages = @(Get-AppxPackage -Name $p.side.package.identity | Where-Object { $_.Name -ceq $p.side.package.identity })+ if (-not $Required -and $packages.Count -eq 0) { return $null }+ if ($packages.Count -ne 1) { throw 'Expected exactly one current-user registration' }+ $pkg = $packages[0]+ if ($pkg.Publisher -cne $p.side.package.publisher -or $pkg.Architecture.ToString() -ine $p.arch -or+ $pkg.Status.ToString() -cne 'Ok' -or $pkg.SignatureKind.ToString() -cne 'Developer' -or+ $pkg.IsDevelopmentMode -or $pkg.NonRemovable -or $pkg.IsPartiallyStaged) { throw 'Package is not the expected trusted sideload' }+ return $pkg+}+function Assert-Artifact {+ $file = $p.side.artifactPath+ if ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.side.package.artifact.sha256 -or+ (Get-Item -LiteralPath $file).Length -ne $p.side.package.artifact.size) { throw 'Artifact bytes differ' }+ $signature = Get-AuthenticodeSignature -LiteralPath $file+ if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -cne $p.side.package.publisher) { throw 'Artifact signature/publisher invalid' }+ $expected = [pscustomobject]@{ msixIdentity=$p.side.package.identity; publisher=$p.side.package.publisher; windowsVersion=$p.side.package.version; applicationId=$p.side.manifest.request.identity.appNamePascal }+ Read-BundleSmokeMetadata $file $p.arch $expected | Out-Null+}+function Installed {+ $pkg = Exact-Package $true+ if ($pkg.Version.ToString() -cne $p.side.package.version) { throw 'Registered native version mismatch' }+ $manifest = Get-AppxPackageManifest -Package $pkg.PackageFullName+ $expected = [pscustomobject]@{ msixIdentity=$p.side.package.identity; publisher=$p.side.package.publisher; windowsVersion=$p.side.package.version; applicationId=$p.side.manifest.request.identity.appNamePascal }+ $metadata = Read-SmokePackageManifest $manifest $p.arch $expected+ $exe = [IO.Path]::GetFullPath((Join-Path $pkg.InstallLocation $metadata.Executable))+ if (-not $exe.StartsWith($pkg.InstallLocation.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) -or -not (Test-Path -LiteralPath $exe -PathType Leaf)) { throw 'Invalid installed executable' }+ $resources = Join-Path (Split-Path -Parent $exe) 'resources'+ $stamp = Get-Content -LiteralPath (Join-Path $resources 'install-stamp.json') -Raw | ConvertFrom-Json+ return @{ identity=$pkg.Name; publisher=$pkg.Publisher; version=$pkg.Version.ToString(); arch=$pkg.Architecture.ToString();+ executable=$exe; appPath=$pkg.InstallLocation; resources=$resources; applicationId=$expected.applicationId;+ packageFamilyName=$pkg.PackageFamilyName; packageFullName=$pkg.PackageFullName; stamp=$stamp }+}+function Updater($Package) {+ $manager=[Windows.Management.Deployment.PackageManager,Windows.Management.Deployment,ContentType=WindowsRuntime]::new()+ $native=$manager.FindPackageForUser('', $Package.PackageFullName)+ $info=$native.GetAppInstallerInfo()+ if (-not $info) { throw 'Missing native App Installer registration' }+ return $info.Uri.AbsoluteUri+}+switch ($Operation) {+ 'preflight' {+ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value+ $profile = (Get-ItemProperty -LiteralPath ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $sid)).ProfileImagePath+ $profile = [Environment]::ExpandEnvironmentVariables($profile)+ if ($profile -ine $env:USERPROFILE -or ($env:HOME -and $env:HOME -ine $profile)) { throw 'Account natural home differs from environment' }+ $local = [Environment]::GetFolderPath('LocalApplicationData')+ $roaming = [Environment]::GetFolderPath('ApplicationData')+ if ($env:LOCALAPPDATA -ine $local -or $env:APPDATA -ine $roaming) { throw 'Redirected AppData refused' }+ foreach ($scope in @('User','Machine')) {+ foreach ($key in @('HERMES_HOME','HERMES_DESKTOP_USER_DATA_DIR','HERMES_DATA_DIR_SUFFIX')) {+ if ([Environment]::GetEnvironmentVariable($key, $scope)) { throw 'Persistent workspace override refused' }+ }+ }+ $nativeArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()+ if ($nativeArch -cne $p.arch) { throw 'Host architecture differs (emulation is not native acceptance)' }+ if (-not [Environment]::UserInteractive -or (Get-Process -Id $PID).SessionId -eq 0) { throw 'Interactive Windows desktop required, not session zero' }+ Get-Command Set-AppxPackageAutoUpdateSettings -ErrorAction Stop | Out-Null+ if (-not (Get-AppxPackage -Name Microsoft.DesktopAppInstaller)) { throw 'OS App Installer unavailable' }+ foreach ($identity in $p.identities) {+ if (@(Get-AppxPackage -Name $identity | Where-Object { $_.Name -ceq $identity }).Count) { throw 'Existing package identity refused' }+ }+ foreach ($file in @((Join-Path $profile '.hermes'), (Join-Path $local 'hermes'), (Join-Path $profile '.hermes-desktop-retirement'))) {+ if (Test-Path -LiteralPath $file) { throw "Existing private state refused: $file" }+ }+ Emit @{ home=$profile; localAppData=$local; appData=$roaming; sid=$sid; arch=$nativeArch }+ }+ 'artifact' { Assert-Artifact; Emit @{ signature='Valid'; sha256=$p.side.package.artifact.sha256 } }+ 'available' {+ $pkg = Exact-Package $false+ Emit ($null -ne $pkg -and $pkg.Version.ToString() -ceq $p.side.package.version)+ }+ 'installed' { Emit (Installed) }+ 'install' {+ if (Exact-Package $false) { throw 'Initial installation may not replace an existing package' }+ Assert-Artifact+ Add-AppxPackage -Path $p.side.artifactPath -ErrorAction Stop+ $installed = Installed+ # Pin a real source registration without background deployment racing the+ # OLD chat. The product, not the driver, installs and registers B/S/T.+ Set-AppxPackageAutoUpdateSettings -PackageFamilyName $installed.packageFamilyName -AppInstallerUri $p.feedUri -Version $p.side.package.version -UpdateUris @() -RepairUris @() -OptionalPackages @() -DependencyPackages @() -EnableAutomaticBackgroundTask:$false -ForceUpdateFromAnyVersion:$false -DisableAutoRepairs -CheckOnLaunch:$false -ShowPrompt:$false -UpdateBlocksActivation:$false -UseSystemPolicySource:$false -HoursBetweenUpdateChecks 12 -ErrorAction Stop | Out-Null+ if ((Updater (Exact-Package $true)) -cne $p.feedUri) { throw 'Initial registration readback differs' }+ Emit $installed+ }+ 'registration' { Emit @{ uri=(Updater (Exact-Package $true)) } }+ 'quit' {+ $proc = Get-Process -Id $p.pid -ErrorAction Stop+ if ($proc.Path -ine $p.executable -or $proc.StartTime.ToUniversalTime().ToString('o') -cne $p.birth) { throw 'Process identity changed' }+ if (-not $proc.CloseMainWindow()) { throw 'Normal close refused' }+ Emit @{ requested=$true }+ }+ 'process' {+ $proc = Get-Process -Id $p.pid -ErrorAction Stop+ if ($proc.Path -ine $p.executable) { throw 'PID executable mismatch' }+ Emit @{ pid=$proc.Id; executable=$proc.Path; birth=$proc.StartTime.ToUniversalTime().ToString('o'); visible=($proc.MainWindowHandle -ne 0) }+ }+ 'listeners' { Emit @(Get-NetTCPConnection -State Listen -ErrorAction Stop | Select-Object LocalAddress,LocalPort,OwningProcess) }+ 'removed' {+ $package = Exact-Package $false+ $entries = @(Get-StartApps | Where-Object { $_.AppID.StartsWith($p.family + '!', [StringComparison]::OrdinalIgnoreCase) })+ Emit @{ registered=($null -ne $package); startApps=@($entries | Select-Object Name,AppID) }+ }+}diff --git a/tests/install/e2e-assets/channel-retirement-windows-observations.mjs b/tests/install/e2e-assets/channel-retirement-windows-observations.mjsnew file mode 100644index 00000000000..f1824bc58d8--- /dev/null+++ b/tests/install/e2e-assets/channel-retirement-windows-observations.mjs@@ -0,0 +1,30 @@+// Portable checks over native observations; none of these create acceptance receipts.+import assert from 'node:assert/strict'+import path from 'node:path'+import { channelStampAssertions } from './mac-bundled-manifest.cjs'++/** @param {string} left @param {string} right */+export const samePath = (left, right) => path.win32.normalize(left).toLowerCase() === path.win32.normalize(right).toLowerCase()+/** @param {import("../../../tests-js/scripts/desktop-smoke-process.ts").NativeProcess[]} rows @param {string} executable */+export function mainProcesses(rows, executable) {+ return rows.filter(row => row.executable && samePath(row.executable, executable) &&+ !/(?:^|\s)--type(?:=|\s)/.test(row.command))+}+/** @param {{identity: string, publisher: string, version: string, arch: string, applicationId: string, stamp: object}} observed+ * @param {import("./channel-retirement-manifest.cjs").Side} side @param {string} arch */+export function assertInstalled(observed, side, arch) {+ assert.equal(observed.identity, side.package.identity)+ assert.equal(observed.publisher, side.package.publisher)+ assert.equal(observed.version, side.package.version)+ assert.equal(observed.arch.toLowerCase(), arch)+ assert.equal(observed.applicationId, side.manifest.request.identity.appNamePascal)+ const stamp = observed.stamp+ assert.equal(stamp.payload, 'bundled')+ assert.equal(stamp.distribution, 'desktop-app')+ assert.equal(stamp.updateMechanism, 'app-installer')+ assert.equal(stamp.dirty, false)+ assert.equal(stamp.commit, side.manifest.request.commit)+ assert.equal(stamp.tag, side.manifest.request.releaseTag || null)+ if (side.manifest.request.releaseTag) assert.equal(stamp.channelBuild == null, true)+ else assert.deepEqual(channelStampAssertions(stamp, side.manifest.request), [])+}diff --git a/tests/install/e2e-assets/mac-bundled-manifest.cjs b/tests/install/e2e-assets/mac-bundled-manifest.cjsindex a2662f92b63..45507814612 100644--- a/tests/install/e2e-assets/mac-bundled-manifest.cjs+++ b/tests/install/e2e-assets/mac-bundled-manifest.cjs@@ -1,4 +1,13 @@// Independent native signature and installed-stamp assertions.+const { isDeepStrictEqual } = require('node:util')++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)})` }+ return Object.entries(expected).filter(([key, value]) => !isDeepStrictEqual(stamp?.[key], value))+ .map(([key]) => `stamp.${key} disagrees with admitted channel request`)+}/*** Parse the TeamIdentifier out of `codesign -dv` output. codesign prints* display output on STDERR, so pass stderr (or combined output) here.@@ -32,7 +41,9 @@ function stampAssertions(stamp, side) {if (stamp.tag !== side.tag) {problems.push(`stamp.tag ${JSON.stringify(stamp.tag)} != ${side.tag}`)}+ if (side.channelRequest) problems.push(...channelStampAssertions(stamp, side.channelRequest))+ else if (stamp.channelBuild != null) problems.push('Unexpected stamp.channelBuild without an admitted request')return problems}-module.exports = { codesignTeam, stampAssertions }+module.exports = { codesignTeam, stampAssertions, channelStampAssertions }diff --git a/tests/install/e2e-assets/windows-bundle-metadata.ps1 b/tests/install/e2e-assets/windows-bundle-metadata.ps1index 74fbcfc75a4..45d2904b9c3 100644--- a/tests/install/e2e-assets/windows-bundle-metadata.ps1+++ b/tests/install/e2e-assets/windows-bundle-metadata.ps1@@ -21,6 +21,9 @@ function Assert-SmokeIdentity($Identity, $Expected) {$version = $Identity.GetAttribute('Version')if ($version -cnotmatch '^\d+\.\d+\.\d+\.\d+$' -or@($version.Split('.') | Where-Object { [int]$_ -gt 65535 }).Count) { throw 'Invalid package version' }+ if ($Expected.PSObject.Properties['windowsVersion'] -and $version -cne $Expected.windowsVersion) {+ throw 'Package version disagrees with channel request'+ }return $version}diff --git a/tests/install/e2e-assets/windows-bundle-metadata.test.ps1 b/tests/install/e2e-assets/windows-bundle-metadata.test.ps1index 7fb39abd7ca..e1d9d67ec97 100644--- a/tests/install/e2e-assets/windows-bundle-metadata.test.ps1+++ b/tests/install/e2e-assets/windows-bundle-metadata.test.ps1@@ -41,5 +41,13 @@ try {Reject { Read-BundleSmokeMetadata $missing 'arm64' $expected }$duplicate = Archive 'duplicate.msixbundle' 'AppxMetadata/AppxBundleManifest.xml' ($bundle.Replace('Architecture="x64"', 'Architecture="arm64"')) @('x64.msix','arm64.msix')Reject { Read-BundleSmokeMetadata $duplicate 'arm64' $expected }+ $channel = [pscustomobject]@{ msixIdentity=$expected.msixIdentity; publisher=$expected.publisher;+ applicationId=$expected.applicationId; windowsVersion='0.1.1.0' }+ $channelFile = Archive 'channel.msix' 'AppxManifest.xml' ($xml.Replace('1.2.3.0', $channel.windowsVersion))+ if ((Read-BundleSmokeMetadata $channelFile 'arm64' $channel).Version -cne $channel.windowsVersion) { throw 'Channel version lost' }+ Reject { Read-BundleSmokeMetadata $file 'arm64' $channel }+ Reject { Read-SmokePackageManifest ([xml]$xml) 'arm64' $channel }+ $channelBundle = Archive 'channel.msixbundle' 'AppxMetadata/AppxBundleManifest.xml' ($bundle.Replace('1.2.3.0', $channel.windowsVersion)) @('x64.msix','arm64.msix')+ if ((Read-BundleSmokeMetadata $channelBundle 'arm64' $channel).Version -cne $channel.windowsVersion) { throw 'Channel bundle version lost' }Write-Output 'PASS: MSIX identity/executable and MSIXBUNDLE native-slice admission'} finally { Remove-Item -LiteralPath $temp -Recurse -Force }\ No newline at end of filediff --git a/tests/install/macos-bundle-smoke.sh b/tests/install/macos-bundle-smoke.shindex c7b62076d6d..87fe40c7c52 100644--- a/tests/install/macos-bundle-smoke.sh+++ b/tests/install/macos-bundle-smoke.sh@@ -5,12 +5,12 @@ fail() { printf '%s\n' "bundle smoke: $*" >&2; exit 1; }[[ ${GITHUB_ACTIONS:-} == true && ${RUNNER_ENVIRONMENT:-} == github-hosted && $(uname -s) == Darwin ]] ||fail 'Disposable native GitHub-hosted macOS runner required'-artifact= arch= commit= tag= work= out=+artifact= arch= commit= tag= channel_request= work= out=while (($#)); do(($# >= 2)) || fail "Missing value for $1"case "$1" in--artifact) artifact=$2;; --arch) arch=$2;; --commit) commit=$2;;- --tag) tag=$2;; --work) work=$2;; --out) out=$2;;+ --channel-request) channel_request=$2;; --tag) tag=$2;; --work) work=$2;; --out) out=$2;;*) fail "Unknown argument: $1";;esacshift 2@@ -31,6 +31,7 @@ node=$(command -v node)metadata=$assets/bundle-smoke-metadata.mjsidentity_args=(--commit "$commit")if [[ -n $tag ]]; then identity_args+=(--tag "$tag"); fi+if [[ -n $channel_request ]]; then identity_args+=(--channel-request "$channel_request"); fi"$node" "$metadata" identity "${identity_args[@]}" >/dev/null"$node" "$metadata" prepare --work "$work" --out "$out"exec > >(tee "$out/native-install.log") 2>&1diff --git a/tests/install/windows-bundle-smoke.ps1 b/tests/install/windows-bundle-smoke.ps1index f105240bc1f..6ed467cfbc5 100644--- a/tests/install/windows-bundle-smoke.ps1+++ b/tests/install/windows-bundle-smoke.ps1@@ -4,6 +4,7 @@ param([Parameter(Mandatory=$true)][ValidateSet('x64','arm64')][string]$Arch,[Parameter(Mandatory=$true)][string]$Commit,[string]$Tag = '',+ [string]$ChannelRequest = '',[Parameter(Mandatory=$true)][string]$Work,[Parameter(Mandatory=$true)][string]$Out)@@ -31,6 +32,7 @@ $nodeArch = Run-Node @('-p', 'process.arch')if ($nodeArch -cne $Arch) { throw 'Driver Node must also use the native architecture' }$identityArgs = @('--commit', $Commit)if ($Tag) { $identityArgs += @('--tag', $Tag) }+if ($ChannelRequest) { $identityArgs += @('--channel-request', $ChannelRequest) }$Expected = (Run-Node (@($Metadata, 'identity') + $identityArgs)) | ConvertFrom-JsonRun-Node @($Metadata, 'prepare', '--work', $Work, '--out', $Out). (Join-Path $Assets 'windows-bundle-metadata.ps1')@@ -74,9 +76,13 @@ try {$stampPath = Join-Path $resources 'install-stamp.json'$stamp = Get-Content -Raw -LiteralPath $stampPath | ConvertFrom-Json$displayVersion = (Run-Node (@($Metadata, 'stamp', '--platform', 'win32', '--stamp', $stampPath) + $identityArgs)) | ConvertFrom-Json- $semverBase = ($displayVersion -split '-')[0]- if (-not $pkg.Version.ToString().StartsWith($semverBase + '.', [StringComparison]::Ordinal)) { throw 'Package version disagrees with stamped semver' }- if (-not $Tag -and $pkg.Version.ToString() -cne ($displayVersion + '.0')) { throw 'Commit package must use stamped semver with zero revision' }+ if ($ChannelRequest) {+ if ($pkg.Version.ToString() -cne $displayVersion) { throw 'Package version disagrees with channel request' }+ } else {+ $semverBase = ($displayVersion -split '-')[0]+ if (-not $pkg.Version.ToString().StartsWith($semverBase + '.', [StringComparison]::Ordinal)) { throw 'Package version disagrees with stamped semver' }+ if (-not $Tag -and $pkg.Version.ToString() -cne ($displayVersion + '.0')) { throw 'Commit package must use stamped semver with zero revision' }+ }@{ packageFullName=$pkg.PackageFullName; publisher=$pkg.Publisher; architecture=$pkg.Architecture.ToString();version=$pkg.Version.ToString(); exe=$exe; root=$root; stamp=$stamp } |ConvertTo-Json -Depth 12 | Set-Content -LiteralPath (Join-Path $Out 'installed-identity.json')diff --git a/tests/scripts/test_channel_build_versions.py b/tests/scripts/test_channel_build_versions.pynew file mode 100644index 00000000000..0c57f1c1dcc--- /dev/null+++ b/tests/scripts/test_channel_build_versions.py@@ -0,0 +1,123 @@+"""A channel request is a complete, immutable input, not a commit flavor."""+from __future__ import annotations++import json+from pathlib import Path+import subprocess+import sys++import pytest++from scripts.bundles.desktop_prepare import BuildRequest+from tests.scripts.test_desktop_preparation import _project+++def channel_request(commit: str, sequence: int = 65536) -> dict:+ token = "ab12cd34ef56ab78"+ return {+ "schema": 1, "buildId": "a" * 32, "channel": "unregistered-preview",+ "sequence": sequence, "repository": "fixture/project", "commit": commit,+ "sourceVersion": "1.2.3", "version": f"0.0.{sequence}",+ "windowsVersion": f"0.{sequence // 65536}.{sequence % 65536}.0",+ "identity": {+ "token": token, "displayName": "Hermes unregistered-preview",+ "appId": f"com.nousresearch.hermes-channel-{token}",+ "appNamePascal": f"HermesChannel{token}", "artifactNamePascal": "HermesBundled",+ "cliName": "hermes-unregistered-preview", "windowsExecutableName": "hermes-unregistered-preview",+ "msixAppIdWithOrg": f"NousResearch.HermesChannel{token}",+ },+ "bundleEnv": {"HERMES_GUEST_ONBOARDING": "1", "HERMES_HOME": None},+ "publicBase": "https://builds.example.test",+ }+++def test_preparation_preserves_exact_channel_inputs_without_source_version_ordering(tmp_path):+ source, commit = _project(tmp_path)+ admitted = channel_request(commit)+ request = BuildRequest.create(source, tag=None, commit=commit, variant="bundled",+ work=tmp_path / "work", cache=tmp_path / "cache",+ bundle_env={}, channel_request=admitted)+ assert request.version == admitted["version"] != admitted["sourceVersion"]+ assert request.tag is None+ assert request.bundle_env == admitted["bundleEnv"]+ restored = BuildRequest.from_data(json.loads(json.dumps(request.data())))+ assert restored.channel_request == admitted+ admitted["identity"]["cliName"] = "changed"+ assert restored.channel_request == request.channel_request+ assert request.channel_request["identity"]["cliName"] != "changed"++ for changes in ({"sourceVersion": "0.9.0"}, {"commit": "b" * 40}, {"version": "1.2.3"},+ {"sequence": 2**32}, {"identity": {**channel_request(commit)["identity"], "cliName": "../bad"}}):+ invalid = {**channel_request(commit), **changes}+ with pytest.raises(ValueError):+ BuildRequest.create(source, tag=None, commit=commit, variant="bundled",+ work=tmp_path / "work", cache=tmp_path / "cache",+ bundle_env={}, channel_request=invalid)+ for variant in ("light", "store"):+ with pytest.raises(ValueError, match="bundled"):+ BuildRequest.create(source, tag=None, commit=commit, variant=variant,+ work=tmp_path / "work", cache=tmp_path / "cache",+ bundle_env={}, channel_request=channel_request(commit))+ for args in (["-c.extraMetadata.version=9.9.9"], ["--config.extraMetadata.shortVersionWindows=1.0.0.0"]):+ from scripts.bundles.desktop_inputs import validate_builder_identity+ with pytest.raises(ValueError, match="channel"):+ validate_builder_identity(request, args)+ assert not (tmp_path / "work").exists()+++def test_prepare_cli_accepts_request_path_but_refuses_mismatched_checkout_before_provisioning(tmp_path):+ source, commit = _project(tmp_path)+ request = channel_request(commit)+ request["commit"] = "b" * 40+ path = tmp_path / "channel.json"+ path.write_text(json.dumps(request), encoding="utf-8")+ repo = Path(__file__).resolve().parents[2]+ result = subprocess.run([sys.executable, str(repo / "scripts/bundles/desktop.py"),+ "--prepare-only", "--repo", str(source), "--channel-request", str(path)],+ capture_output=True, text=True, timeout=30)+ assert result.returncode != 0+ assert "unrecognized arguments" not in result.stderr+ assert "checkout" in result.stderr+ assert not (source / ".build").exists()+++def test_channel_environment_and_stamp_bind_the_request_not_ambient_oneoff_identity(tmp_path, monkeypatch):+ from scripts.bundles.desktop_inputs import identity_environment+ from scripts import write_install_stamp++ source, commit = _project(tmp_path)+ admitted = channel_request(commit)+ request = BuildRequest.create(source, tag=None, commit=None, variant="bundled",+ work=tmp_path / "work", cache=tmp_path / "cache",+ bundle_env={}, channel_request=admitted)+ inherited = {"HERMES_BUILD_COMMIT": "b" * 40, "HERMES_PAYLOAD_TAG": "v9.9.9",+ "GITHUB_SHA": "b" * 40, "GITHUB_REF_NAME": "workflow-branch", "BUILD_NUMBER": "999"}+ env = identity_environment(request, "bundled", inherited)+ assert json.loads(env["_HERMES_CHANNEL_REQUEST_JSON"]) == admitted+ assert env["HERMES_PAYLOAD_VERSION"] == admitted["version"]+ assert env["GITHUB_SHA"] == commit+ assert not {"HERMES_BUILD_COMMIT", "HERMES_PAYLOAD_TAG", "GITHUB_REF_NAME", "BUILD_NUMBER"} & env.keys()+ assert inherited["HERMES_BUILD_COMMIT"] == "b" * 40+ changed = request.data()+ changed["channel_request"]["bundleEnv"] = changed["bundle_env"] = {}+ assert BuildRequest.from_data(changed).identity_digest() != request.identity_digest()+ from scripts.bundles.desktop_prepare import PreparedDesktop+ prepared = PreparedDesktop(request, Path(sys.executable), Path(sys.executable), Path(sys.executable),+ tmp_path / "native", tmp_path / "packager", None, {}, "fixture",+ request.identity_digest())+ assert request.channel_request is not None+ request.channel_request["buildId"] = "c" * 32+ with pytest.raises(ValueError, match="identity changed"):+ prepared.validate()+ monkeypatch.setattr(write_install_stamp, "_REPO_ROOT", source)+ monkeypatch.setenv("HERMES_DESKTOP_VARIANT", "bundled")+ # Python receives the request explicitly, not a new runtime setting.+ stamp = write_install_stamp.build_stamp(update_mechanism="electron-updater", channel_request=admitted)+ assert stamp["source"] == "channel-build"+ assert stamp["dirty"] is False+ assert stamp["channelBuild"] == admitted+ assert stamp["tag"] is None and stamp["branch"] is None+ assert stamp["baseVersion"] == admitted["sourceVersion"]+ assert stamp["updateMechanism"] == "electron-updater"+ admitted["bundleEnv"].clear()+ assert stamp["channelBuild"]["bundleEnv"]diff --git a/tests/scripts/test_channel_qualification.py b/tests/scripts/test_channel_qualification.pynew file mode 100644index 00000000000..e991cceab81--- /dev/null+++ b/tests/scripts/test_channel_qualification.py@@ -0,0 +1,234 @@+"""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_channel_retirement_controller.py b/tests/scripts/test_channel_retirement_controller.pynew file mode 100644index 00000000000..688671550d2--- /dev/null+++ b/tests/scripts/test_channel_retirement_controller.py@@ -0,0 +1,123 @@+"""Loopback coordinator exercise, not native installation or release evidence."""+from contextlib import contextmanager+import hashlib+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import importlib.util+import json+import os+from pathlib import Path+import sys+from threading import Thread+import unittest+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+spec = importlib.util.spec_from_file_location("coordinator", ROOT / "tests/install/channel-retirement-controller.py")+assert spec is not None and spec.loader is not None+coordinator = importlib.util.module_from_spec(spec)+spec.loader.exec_module(coordinator)+from hermes_cli.release_channels import ChannelError, canonical_json # noqa: E402+from scripts.releases.channel_disposable import allocate_receivers # noqa: E402+from scripts.releases.channels import ChannelPublisher, R2ChannelStore # noqa: E402+from scripts.releases.r2_scope import R2Scope # noqa: E402+++@contextmanager+def archive():+ objects = {}+ class Handler(BaseHTTPRequestHandler):+ def log_message(self, format, *args):+ pass++ def do_GET(self):+ body = objects.get(self.path)+ self.send_response(404 if body is None else 200)+ if body is not None:+ self.send_header("ETag", hashlib.sha256(body).hexdigest())+ self.end_headers()+ self.wfile.write(body or b"")++ def do_PUT(self):+ old = objects.get(self.path)+ expected = hashlib.sha256(old).hexdigest() if old is not None else None+ if ((self.headers.get("If-None-Match") and old is not None)+ or (self.headers.get("If-Match") and self.headers["If-Match"] != expected)):+ self.send_response(412)+ else:+ objects[self.path] = self.rfile.read(int(self.headers["Content-Length"]))+ self.send_response(200)+ self.end_headers()+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = Thread(target=server.serve_forever)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}", objects+ finally:+ server.shutdown(); server.server_close(); thread.join()+++class CoordinatorTest(unittest.TestCase):+ def test_scoped_lifecycle_uses_real_retire_and_stable_descriptor(self):+ for platform in ("darwin", "win32"):+ for route in ("direct", "via-update"):+ with self.subTest(platform=platform, route=route), archive() as (url, objects):+ scope = R2Scope("ci-disposable/1/2-1/")+ base = scope.public_base(url + "/bucket")+ store = R2ChannelStore({"access_key_id": "fixture", "secret_key": "fixture"}, url, "bucket", scope=scope)+ pub = ChannelPublisher(store, "example/hermes", base, authorize=lambda *_: None)+ pub.create("preview")+ requests = {name: pub.allocate("preview", "a" * 40, "1.0.0") for name in ("A", "B")}+ requests.update(allocate_receivers(pub, "a" * 40, "1.0.0", "f" * 40))+ journey: dict = {"repository": pub.repository, "controllerCommit": "f" * 40, "route": route,+ "platform": platform, "minimumVersion": "1.0.0"}+ for name, request in requests.items():+ prefix = f"releases/channel-builds/{request['buildId']}/"+ key = prefix + ("stable-mac.yml" if platform == "darwin" else "stable.appinstaller")+ pkg = {"platform": platform, "arch": "arm64", "variant": "bundled",+ "identity": request["identity"]["appId" if platform == "darwin" else "msixAppIdWithOrg"],+ "version": request["version" if platform == "darwin" else "windowsVersion"],+ "teamId": "ABCDEFGHIJ", "publisher": "CN=Fixture",+ "artifact": {"key": prefix + "artifact.zip", "sha256": "a" * 64, "size": 1},+ "feed": {"key": key, "channel": "stable"}}+ manifest = {"schema": 1, "request": request, "receiverProtocol": 1, "packages": [pkg]}+ head = {"buildId": request["buildId"], "sequence": request["sequence"], "manifestKey": prefix + "build.json",+ "sha256": hashlib.sha256(canonical_json(manifest)).hexdigest()}+ pub._write(head["manifestKey"], manifest)+ pub._write(key, {"version": request["version"], "files": [{"url": base + "/" + pkg["artifact"]["key"]}]})+ journey[name] = {"head": head, "manifest": manifest}+ for channel, slot in (("preview", "A"), ("stable", "S")):+ current = pub._read(channel)+ assert current is not None+ record, etag = current+ pub._write(f"releases/channels/{channel}.json", {**record, "head": journey[slot]["head"]}, etag)+ if route == "direct":+ del journey["B"]+ with patch.dict(os.environ, {"GITHUB_SHA": "f" * 40}):+ coordinator.prepare(pub, journey)+ if route == "via-update":+ advanced = coordinator.advance(pub, journey, "preview-update")+ self.assertEqual(coordinator.advance(pub, journey, "preview-update"), advanced)+ with patch.dict(os.environ, {"GITHUB_SHA": "f" * 40}):+ coordinator.prepare(pub, journey)+ retired = coordinator.advance(pub, journey, "retire")+ self.assertEqual(retired["destinationHead"], journey["S"]["head"])+ coordinator.advance(pub, journey, "stable-update")+ self.assertEqual(pub.reader.resolve("stable").manifest, journey["T"]["manifest"])+ self.assertEqual(pub.reader.resolve("preview").manifest, journey["S"]["manifest"])+ feed_key = f"releases/{platform}/stable/" + ("stable-mac.yml" if platform == "darwin" else "stable.appinstaller")+ feed = pub.reader.read_bytes(feed_key).decode()+ self.assertIn(journey["T"]["manifest"]["request"]["version"], feed)+ self.assertIn(base + "/", feed)+ before = dict(objects)+ with self.assertRaises(ChannelError):+ coordinator.advance(pub, journey, "retire")+ self.assertEqual(objects, before)+ self.assertTrue(all(key.startswith("/bucket/" + scope.prefix) for key in objects))+ store.scope = R2Scope()+ with self.assertRaisesRegex(ValueError, "disposable"):+ coordinator.advance(pub, journey, "stable-update")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/scripts/test_commit_stamp_identity.py b/tests/scripts/test_commit_stamp_identity.pyindex cc6ea0823fd..5a7b71c75b4 100644--- a/tests/scripts/test_commit_stamp_identity.py+++ b/tests/scripts/test_commit_stamp_identity.py@@ -14,7 +14,7 @@ def test_stamp_uses_built_commit_even_with_dispatch_sha_and_refuses_mismatch(tmprepo = tmp_path / 'repo'repo.mkdir()for relative in ('scripts/write_install_stamp.py', 'scripts/releases/commit_build.py',- 'hermes_cli/__init__.py', 'hermes_cli/update_channel.py',+ 'hermes_cli/__init__.py', 'hermes_cli/update_channel.py', 'hermes_cli/release_channels.py','hermes_cli/runtime_paths.py', 'hermes_cli/steward.py', 'hermes_constants.py'):dest = repo / relativedest.parent.mkdir(parents=True, exist_ok=True)diff --git a/tests/scripts/test_release_build_commit.py b/tests/scripts/test_release_build_commit.pyindex a27062f7996..374ebf10a22 100644--- a/tests/scripts/test_release_build_commit.py+++ b/tests/scripts/test_release_build_commit.py@@ -31,8 +31,10 @@ def fixture_repo(tmp_path):git(repo, 'remote', 'set-url', 'origin', 'https://github.com/fixture-owner/fixture-repo.git')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','hermes_cli/__init__.py', 'hermes_cli/update_channel.py',+ 'hermes_cli/release_channels.py','hermes_cli/runtime_paths.py', 'hermes_constants.py'):dest = repo / relativedest.parent.mkdir(parents=True, exist_ok=True)diff --git a/tests/scripts/test_release_channel_build.py b/tests/scripts/test_release_channel_build.pynew file mode 100644index 00000000000..5aa7def0372--- /dev/null+++ b/tests/scripts/test_release_channel_build.py@@ -0,0 +1,120 @@+"""Channel dispatch freezes a real pushed Git commit before allocating inputs."""+import hashlib+import importlib.util+from pathlib import Path+import subprocess++import pytest++_spec = importlib.util.spec_from_file_location("channel_http_fixture", Path(__file__).with_name("test_release_channels.py"))+_fixture = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_fixture)+++def git(repo, *args):+ return subprocess.check_output(["git", *args], cwd=repo, text=True, encoding="utf-8").strip()+++def source(tmp_path):+ origin = tmp_path / "origin.git"+ repo = tmp_path / "source"+ origin.mkdir()+ repo.mkdir()+ git(origin, "init", "--bare", "--quiet")+ git(repo, "init", "--initial-branch=main", "--quiet")+ git(repo, "config", "user.name", "Test")+ git(repo, "config", "user.email", "[email protected]")+ (repo / "pyproject.toml").write_text('[project]\nname="fixture"\nversion="1.2.3"\n', encoding="utf-8")+ git(repo, "add", "pyproject.toml")+ git(repo, "commit", "--quiet", "-m", "Initial")+ git(repo, "remote", "add", "origin", str(origin))+ git(repo, "push", "--quiet", "-u", "origin", "main")+ return repo+++def test_dry_run_never_allocates_and_dispatch_is_bound_to_pushed_source(source):+ from scripts.releases.channel_build import prepare_build+ from hermes_cli.release_channels import canonical_json+ with _fixture.object_server() as (url, objects, headers, requests, faults):+ pub = _fixture.publisher(url)+ calls = []+ options = dict(name="custom-branch", revision="main", remote="origin", repo=source,+ repository="example/hermes-agent", default_branch="main", publisher=pub,+ dispatch=calls.append, bundle_env={"FEATURE": "a"}, controller_commit="c" * 40)+ dry = prepare_build(**options)+ assert dry["commit"] == git(source, "rev-parse", "HEAD")+ assert not calls and not objects+ admitted = prepare_build(**options, publish=True)+ request = admitted["request"]+ assert request["commit"] == dry["commit"] and request["sourceVersion"] == "1.2.3"+ command = calls.pop()+ assert "desktop-bundled-release.yml" in command+ assert "channel_build=" + request["buildId"] in command+ assert "channel_request_sha256=" + hashlib.sha256(canonical_json(request)).hexdigest() in command+ assert "--ref" in command and command[command.index("--ref") + 1] == "main"+ assert not any(value.startswith("build_commit=") for value in command)+ git(source, "commit", "--allow-empty", "--quiet", "-m", "Unpublished")+ with pytest.raises(ValueError, match="pushed"):+ prepare_build(**options, publish=True)+ assert not calls+ assert pub.request(request["buildId"])["commit"] == dry["commit"]+++def test_missing_controller_branch_is_rejected_without_channel_creation(source):+ from scripts.releases.channel_build import prepare_build+ from hermes_cli.release_channels import ChannelError+ with _fixture.object_server() as (url, objects, headers, requests, faults):+ pub = _fixture.publisher(url)+ with pytest.raises(ChannelError, match="default branch"):+ prepare_build(name="invalid-controller", revision="main", remote="origin", repo=source,+ repository="example/hermes-agent", default_branch="absent", publisher=pub,+ dispatch=lambda command: pytest.fail("must not dispatch"), publish=True)+ assert not objects+++def test_release_parser_preserves_plain_oneoff_dispatch(monkeypatch):+ import sys+ from scripts import release+ from scripts.releases import commit_build+ calls = []+ monkeypatch.setattr(commit_build, "cmd_build_commit", lambda args: calls.append(("oneoff", args.build_commit)))+ monkeypatch.setattr(sys, "argv", ["release.py", "--build-commit", "main"])+ release.main()+ assert calls == [("oneoff", "main")]+ monkeypatch.setattr(sys, "argv", ["release.py", "--channel", "bad/name", "--build-commit", "main"])+ with pytest.raises(SystemExit) as rejected:+ release.main()+ assert rejected.value.code == 2+ from scripts.releases import channel_build+ monkeypatch.setattr(channel_build, "cmd_channel", lambda args: calls.append(("channel", args.channel)))+ monkeypatch.setattr(sys, "argv", ["release.py", "--channel", "unknown-name", "--build-commit", "main"])+ release.main()+ assert calls[-1] == ("channel", "unknown-name")+ monkeypatch.setattr(sys, "argv", ["release.py", "--channels", "--bundle-env", "X=y"])+ with pytest.raises(SystemExit) as incompatible:+ release.main()+ assert incompatible.value.code == 2+ monkeypatch.setattr(channel_build, "cmd_channel", lambda args: calls.append(("resume", args.resume_channel_build)))+ monkeypatch.setattr(sys, "argv", ["release.py", "--resume-channel-build", "a" * 32, "--request-sha256", "b" * 64])+ release.main()+ assert calls[-1] == ("resume", "a" * 32)+++def test_dispatch_retry_uses_same_immutable_request_and_no_new_sequence(source):+ from scripts.releases import channel_build+ from hermes_cli.release_channels import canonical_json, ChannelError+ with _fixture.object_server() as (url, objects, headers, requests, faults):+ pub = _fixture.publisher(url)+ calls = []+ admitted = channel_build.prepare_build(name="resume", revision="main", remote="origin", repo=source,+ repository="example/hermes-agent", default_branch="main", publisher=pub,+ dispatch=calls.append, publish=True)+ request = admitted["request"]+ before = pub._read("resume")[0]+ digest = hashlib.sha256(canonical_json(request)).hexdigest()+ channel_build.resume_build(request["buildId"], digest, publisher=pub, default_branch="main", dispatch=calls.append)+ assert calls[-1] == calls[0]+ assert pub._read("resume")[0] == before+ with pytest.raises(ChannelError, match="SHA256"):+ channel_build.resume_build(request["buildId"], "0" * 64, publisher=pub, default_branch="main", dispatch=calls.append)diff --git a/tests/scripts/test_release_channels.py b/tests/scripts/test_release_channels.pynew file mode 100644index 00000000000..a4208871491--- /dev/null+++ b/tests/scripts/test_release_channels.py@@ -0,0 +1,488 @@+"""Exercise publisher/reader through the real signed HTTP transport."""+from __future__ import annotations++from contextlib import contextmanager+import hashlib+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import socket+from threading import Lock, Thread+from urllib.parse import parse_qs, urlsplit+import xml.sax.saxutils++import pytest+++@contextmanager+def object_server():+ objects, headers, requests = {}, {}, []+ lock = Lock()+ faults = {"lose_put": False, "stale_public": None, "conflict": None, "bad_pagination": False}++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ parsed = urlsplit(self.path)+ query = parse_qs(parsed.query)+ with lock:+ requests.append(("GET", self.path))+ if "list-type" in query:+ prefix = query.get("prefix", [""])[0]+ keys = sorted(k for k in objects if k.startswith(prefix))+ start = int(query.get("continuation-token", ["0"])[0])+ page = keys[start:start + 2]+ more = start + 2 < len(keys)+ body = ("<ListBucketResult>" + "".join(+ f"<Contents><Key>{xml.sax.saxutils.escape(k)}</Key></Contents>" for k in page)+ + f"<IsTruncated>{str(more).lower()}</IsTruncated>"+ + (f"<NextContinuationToken>{start + 2}</NextContinuationToken>" if more else "")+ + "</ListBucketResult>").encode()+ if faults["bad_pagination"]:+ body = b"<ListBucketResult><IsTruncated>true</IsTruncated></ListBucketResult>"+ etag = None+ else:+ key = parsed.path.removeprefix("/bucket/")+ body = objects.get(key)+ if not self.headers.get("Authorization") and faults["stale_public"] is not None:+ body = faults["stale_public"]+ etag = '"' + hashlib.sha256(body).hexdigest() + '"' if body is not None else None+ self.send_response(200 if body is not None else 404)+ if etag:+ self.send_header("ETag", etag)+ self.end_headers()+ if body is not None:+ self.wfile.write(body)++ def do_PUT(self):+ body = self.rfile.read(int(self.headers["Content-Length"]))+ key = self.path.removeprefix("/bucket/")+ with lock:+ requests.append(("PUT", key))+ if faults["conflict"]:+ conflict = faults["conflict"]+ faults["conflict"] = None+ conflict(objects, key)+ old = objects.get(key)+ etag = '"' + hashlib.sha256(old).hexdigest() + '"' if old is not None else None+ conflict = ((self.headers.get("If-None-Match") == "*" and old is not None)+ or (self.headers.get("If-Match") is not None and self.headers["If-Match"] != etag))+ if conflict:+ self.send_response(412)+ self.end_headers()+ return+ objects[key] = body+ headers[key] = dict(self.headers)+ if faults["lose_put"]:+ faults["lose_put"] = False+ self.connection.shutdown(socket.SHUT_RDWR)+ self.connection.close()+ return+ self.send_response(200)+ self.end_headers()++ 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}", objects, headers, requests, faults+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+++def publisher(url, **kwargs):+ from scripts.releases.channels import ChannelPublisher, R2ChannelStore+ store = R2ChannelStore({"access_key_id": "fixture", "secret_key": "fixture"}, url, "bucket")+ return ChannelPublisher(store, "example/hermes-agent", url + "/bucket",+ authorize=kwargs.pop("authorize", lambda action, record: None), **kwargs)+++def test_unknown_channel_created_over_http_retains_identity_and_immutable_requests():+ from hermes_cli.release_channels import ChannelReader, ChannelNotFound+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ reader = ChannelReader(url + "/bucket", repository="example/hermes-agent")+ with pytest.raises(ChannelNotFound):+ reader.resolve("not-registered-in-code")+ record = pub.create("not-registered-in-code")+ assert reader.resolve(record["name"]).manifest is None+ one = pub.allocate(record["name"], "a" * 40, "1.2.3", {"FEATURE": "one"})+ two = pub.allocate(record["name"], "a" * 40, "1.2.3", {"FEATURE": "two"})+ assert one["identity"] == two["identity"] == record["identity"]+ assert one["buildId"] != two["buildId"]+ assert one["sequence"] < two["sequence"]+ assert pub.request(one["buildId"]) == one+ assert reader.resolve(record["name"]).terminal["nextSequence"] == two["sequence"] + 1+ assert headers[f"releases/channels/{record['name']}.json"]["Cache-Control"] == "no-store"+ assert "immutable" in headers[f"releases/channel-builds/{one['buildId']}/request.json"]["Cache-Control"]+++def put_build(objects, request):+ from hermes_cli.release_channels import build_prefix, canonical_json+ 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",+ "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"}}]}+ objects[prefix + "build.json"] = canonical_json(manifest)+ return manifest+++def test_concurrent_allocations_reverse_completion_retirement_and_readback():+ from concurrent.futures import ThreadPoolExecutor+ from hermes_cli.release_channels import ChannelError, canonical_json+ from scripts.releases.channels import PublicVisibilityError+ with 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:+ created = list(pool.map(pub.create, ["race-preview"] * 2))+ assert created[0]["identity"] == created[1]["identity"]+ with ThreadPoolExecutor(max_workers=2) as pool:+ allocated = list(pool.map(lambda _: pub.allocate("race-preview", "a" * 40, "1.0.0"), range(2)))+ one, two = sorted(allocated, key=lambda r: r["sequence"])+ assert one["sequence"] != two["sequence"], "concurrent allocations must be distinct"+ for request in (one, two):+ put_build(objects, request)+ pub.promote(two["buildId"])+ with pytest.raises(ChannelError, match="newer|stale"):+ pub.promote(one["buildId"])+ assert pub.reader.resolve("race-preview").manifest["request"] == two+ # The protected destination is seeded from accepted existing metadata, not a preview masquerade.+ pub.create("destination")+ target = pub._read("destination")[0]+ target["policy"] = "stable-release"+ stable = dict(two, channel="destination", identity=target["identity"], releaseTag="v2.0.0", version="2.0.0", windowsVersion="2.0.0.0", sourceVersion="2.0.0", buildId="e" * 32)+ stable_manifest = put_build(objects, stable)+ 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())+ assert retired["lastHead"]["buildId"] == two["buildId"]+ with pytest.raises(ChannelError, match="Retired"):+ pub.promote(two["buildId"])+ with pytest.raises(ChannelError, match="Retired"):+ pub.create("race-preview")+ pub.create("visibility")+ faults["lose_put"] = True+ lost = pub.allocate("visibility", "b" * 40, "1.0.0")+ assert pub.request(lost["buildId"]) == lost+ faults["stale_public"] = b"{}"+ with pytest.raises(PublicVisibilityError, match="Committed"):+ pub.allocate("visibility", "b" * 40, "1.0.0")+ assert json.loads(objects["releases/channels/visibility.json"])["nextSequence"] > lost["sequence"] + 1+++def test_list_bootstrap_protected_roles_and_qualification_gate():+ from hermes_cli.release_channels import ChannelError+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ main = {"schema": 1, "name": "main", "repository": "example/hermes-agent", "policy": "source-branch", "state": "active", "revision": 1, "nextSequence": 1, "identity": None, "head": None, "delivery": {"kind": "source-branch", "branch": "main"}}+ assert pub.bootstrap(main) == main and not objects+ pub.bootstrap(main, publish=True)+ for name in ("first", "second", "third"):+ pub.create(name)+ assert {r["name"] for r in pub.list()} == {"main", "first", "second", "third"}+ assert any("continuation-token" in path for method, path in requests)+ faults["bad_pagination"] = True+ with pytest.raises(ChannelError, match="pagination"):+ pub.list()+ faults["bad_pagination"] = False+ assert pub.reader.resolve("main").manifest is None+ with pytest.raises(ChannelError, match="Protected"):+ pub.allocate("main", "a" * 40, "1.0.0")+ request = pub.allocate("first", "a" * 40, "1.0.0")+ put_build(objects, request)+ with pytest.raises(ChannelError, match="qualification"):+ pub.promote(request["buildId"])+ assert pub.reader.resolve("first").terminal["head"] is None+++def test_retirement_race_never_reuses_stale_qualification():+ from hermes_cli.release_channels import ChannelError, canonical_json+ from scripts.releases.channels import ChannelConflict+ with 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.create("preview")+ first = pub.allocate("preview", "a" * 40, "1.0.0")+ second = pub.allocate("preview", "b" * 40, "1.0.0")+ put_build(objects, first)+ put_build(objects, second)+ pub.promote(first["buildId"])+ pub.create("stable")+ target = pub._read("stable")[0]+ target["policy"] = "stable-release"+ stable = dict(first, channel="stable", identity=target["identity"], releaseTag="v2.0.0", version="2.0.0", windowsVersion="2.0.0.0", sourceVersion="2.0.0", buildId="f" * 32)+ 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+ record["head"] = {"buildId": second["buildId"], "sequence": second["sequence"], "manifestKey": "releases/channel-builds/" + second["buildId"] + "/build.json", "sha256": hashlib.sha256(store["releases/channel-builds/" + second["buildId"] + "/build.json"]).hexdigest()}+ store[object_key] = canonical_json(record)+ faults["conflict"] = race+ with pytest.raises(ChannelConflict):+ pub.retire("preview", "stable", "2.0.0", key, hashlib.sha256(raw).hexdigest())+ 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())+++def test_mutable_read_loss_recovery_never_clones_another_allocation():+ from scripts.releases.channels import ChannelConflict+ from hermes_cli.release_channels import canonical_json+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ pub.create("nonce-check")+ initial = pub._read("nonce-check")[0]+ def compete(store, key):+ winner = dict(initial, revision=2, nextSequence=2,+ lastAllocation={"buildId": "b" * 32, "sequence": 1})+ store[key] = canonical_json(winner)+ faults["conflict"] = compete+ request = pub.allocate("nonce-check", "a" * 40, "1.0.0")+ assert request["sequence"] == 2+ key = "releases/channel-builds/" + request["buildId"] + "/request.json"+ with pytest.raises(ChannelConflict):+ pub.store.put(key, canonical_json(dict(request, commit="b" * 40)))+ assert pub.request(request["buildId"]) == request+++def test_protected_releases_bootstrap_retry_and_refuse_late_or_ungated_promotion():+ from hermes_cli.release_channels import ChannelError, canonical_json+ from scripts.releases.channels import preview_identity+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url, verify_build=lambda request, manifest: True)+ accepted = True+ gate = lambda request: accepted+ identity = preview_identity("official", "1" * 16)++ def allocate(version, commit):+ return pub.allocate_protected(+ "official", commit, version, release_tag="v" + version,+ version=version, windows_version=version + ".0", identity=identity,+ policy="stable-release", release_gate=gate)++ # A failed request PUT followed by another release allocation must still+ # recover the original sequence, not reinterpret the same build ID.+ original_write = pub._write+ def lose_request(key, value, etag=None):+ if key.endswith("request.json"):+ raise OSError("request upload interrupted")+ return original_write(key, value, etag)+ pub._write = lose_request+ with pytest.raises(OSError):+ allocate("1.0.0", "a" * 40)+ reservation = pub._read("official")[0]["lastAllocation"]["request"]+ pub._write = original_write+ allocate("0.5.0", "e" * 40)+ first = allocate("1.0.0", "a" * 40)+ assert first == reservation+ assert allocate("1.0.0", "a" * 40) == first+ assert len(first["buildId"]) == 32+ assert pub.reader.resolve("official").manifest is None+ put_build(objects, first)+ accepted = False+ with pytest.raises(ChannelError, match="release gate"):+ pub.promote_protected(first["buildId"], policy="stable-release", release_gate=gate)+ assert pub.reader.resolve("official").manifest is None+ accepted = True+ pub.promote_protected(first["buildId"], policy="stable-release", release_gate=gate)+ second = allocate("2.0.0", "b" * 40)+ late = allocate("1.5.0", "c" * 40)+ for request in (second, late):+ put_build(objects, request)+ pub.promote_protected(second["buildId"], policy="stable-release", release_gate=gate)+ assert pub.promote_protected(second["buildId"], policy="stable-release", release_gate=gate)["head"]["buildId"] == second["buildId"]+ with pytest.raises(ChannelError, match="version|newer|stale"):+ pub.promote_protected(late["buildId"], policy="stable-release", release_gate=gate)+ with pytest.raises(ChannelError, match="Protected"):+ pub.promote(second["buildId"])+ assert pub.reader.resolve("official").manifest["request"] == second+ # A competing allocation must not turn a protected promotion into an overwrite.+ def contend(store, key):+ record = json.loads(store[key])+ record["revision"] += 1+ record["nextSequence"] += 1+ store[key] = canonical_json(record)+ third = allocate("3.0.0", "d" * 40)+ put_build(objects, third)+ faults["conflict"] = contend+ pub.promote_protected(third["buildId"], policy="stable-release", release_gate=gate)+ assert pub.reader.resolve("official").manifest["request"] == third+++def test_accepted_release_receipts_feed_the_protected_head_without_rebuilding(tmp_path, monkeypatch):+ from scripts.releases import channel_releases+ from hermes_cli.release_channels import ChannelError, canonical_json+ from scripts.releases.channels import preview_identity+ from scripts.releases.handoff import receipt_name+ from copy import deepcopy+ import zipfile+ identity = preview_identity("released", "2" * 16)+ tag, commit = "v2.0.0", "d" * 40+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ base = pub.public_base+ prefix = f"releases/tag/{tag}/"+ for platform in ("darwin", "win32"):+ for arch in ("arm64", "x64"):+ native = "macos" if platform == "darwin" else "windows"+ version = "2.0.0" if platform == "darwin" else "2.0.0.0"+ metadata = {"platform": native, "arch": arch, "tag": tag, "commit": commit,+ "version": version, "identity": identity["appId" if platform == "darwin" else "msixAppIdWithOrg"]}+ files = {}+ if platform == "darwin":+ metadata["teamId"] = "ABCDEFGHIJ"+ for suffix in ("zip", "dmg", "zip.blockmap", "dmg.blockmap"):+ name = f"{identity['artifactNamePascal']}-2.0.0-mac-{arch}.{suffix}"+ files[name] = (name + " fixture bytes").encode()+ metadata["filename"] = f"{identity['artifactNamePascal']}-2.0.0-mac-{arch}.zip"+ else:+ metadata.update(publisher="CN=Fixture", applicationId=identity["appNamePascal"])+ files[f"{identity['artifactNamePascal']}-2.0.0-win-{arch}.msix"] = b"fixture msix"+ files[f"metadata-{native}-{arch}.json"] = canonical_json(metadata)+ rows = []+ for name, body in files.items():+ objects[prefix + name] = body+ (tmp_path / name).write_bytes(body)+ rows.append({"path": name, "size": len(body), "sha256": hashlib.sha256(body).hexdigest()})+ receipt = {"schema": 1, "tag": tag, "commit": commit, "name": f"{platform}-{arch}", "files": rows}+ (tmp_path / receipt_name(receipt["name"])).write_bytes(canonical_json(receipt))+ objects[prefix + receipt_name(receipt["name"])] = canonical_json(receipt)+ bundle_name = f"{identity['artifactNamePascal']}-2.0.0.0-win.msixbundle"+ with zipfile.ZipFile(tmp_path / bundle_name, "w") as archive:+ archive.writestr("AppxMetadata/AppxBundleManifest.xml", f'<Bundle><Identity Name="{identity["msixAppIdWithOrg"]}" Publisher="CN=Fixture" Version="2.0.0.0"/><Packages><Package Type="application" Architecture="arm64"/><Package Type="application" Architecture="x64"/></Packages></Bundle>')+ body = (tmp_path / bundle_name).read_bytes()+ objects[prefix + bundle_name] = body+ receipt = {"schema": 1, "tag": tag, "commit": commit, "name": "windows-universal", "files": [{"path": bundle_name, "size": len(body), "sha256": hashlib.sha256(body).hexdigest()}]}+ (tmp_path / receipt_name(receipt["name"])).write_bytes(canonical_json(receipt))+ objects[prefix + receipt_name(receipt["name"])] = canonical_json(receipt)+ # An R2 policy record chooses this name, not the legacy default selector.+ record = {"schema": 1, "name": "released", "repository": pub.repository, "policy": "stable-release", "state": "active", "revision": 1, "nextSequence": 1, "head": None, "identity": identity}+ objects["releases/channels/released.json"] = canonical_json(record)+ assert 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)+ 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}})+ channel_releases.match_accepted_packages(manifest, accepted)+ wrong = deepcopy(accepted)+ wrong["packages"][0]["artifact"]["sha256"] = "0" * 64+ with pytest.raises(ChannelError, match="accepted"):+ channel_releases.match_accepted_packages(manifest, wrong)+ # 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).+ from scripts.releases import r2, commit_build+ monkeypatch.setattr(channel_releases, "admit_transaction", lambda policy, env: (tag, commit))+ monkeypatch.setattr(channel_releases, "accepted_stable", lambda *args: accepted)+ monkeypatch.setattr(channel_releases, "product_identity", lambda tag: dict(identity))+ monkeypatch.setattr(commit_build, "version_at", lambda *args: "2.0.0")+ monkeypatch.setattr(r2, "credentials", lambda: (pub.store.creds, url, "bucket"))+ monkeypatch.setattr(r2, "public_base_url", lambda: base)+ def put(**kwargs):+ pub.store.put(kwargs["key"], __import__("pathlib").Path(kwargs["file"]).read_bytes())+ monkeypatch.setattr(r2, "put", put)+ result = channel_releases.publish_release("stable-release", {"GITHUB_REPOSITORY": pub.repository}, tmp_path / "downloaded")+ assert result["name"] == "released"+ assert pub.reader.resolve("released").manifest == manifest+ before = dict(objects)+ assert channel_releases.publish_release("stable-release", {"GITHUB_REPOSITORY": pub.repository}, tmp_path / "retry") == result+ assert objects == before+ (tmp_path / bundle_name).write_bytes(b"corrupt")+ with pytest.raises(ChannelError, match="receipt"):+ channel_releases.read_native_receipts(tmp_path, tag, commit)+++def test_protected_transaction_refuses_custom_workflow_failed_gate_and_unpublished_release():+ from scripts.releases import channel_releases+ from hermes_cli.release_channels import ChannelError+ tag, commit = "v2.0.0", "a" * 40+ env = {"GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "workflow_dispatch",+ "GITHUB_REPOSITORY": "example/hermes-agent", "GITHUB_SHA": commit,+ "GITHUB_REF": "refs/tags/" + tag, "RELEASE_TAG": tag,+ "GITHUB_WORKFLOW_REF": "example/hermes-agent/.github/workflows/stable-release.yml@refs/tags/" + tag,+ "RELEASE_NEEDS": json.dumps({key: {"result": "success"} for key in channel_releases.STABLE_NEEDS})}+ published = {"tagName": tag, "isDraft": False, "isPrerelease": False}++ def run(command):+ if command[:3] == ["gh", "release", "view"]:+ return json.dumps(published)+ if command[:2] == ["git", "ls-remote"]:+ return commit + "\trefs/tags/" + tag+ if command[:2] == ["git", "rev-parse"]:+ return commit+ return ""++ assert channel_releases.admit_transaction("stable-release", env, run=run) == (tag, commit)+ published["isDraft"] = True+ with pytest.raises(ChannelError, match="published"):+ channel_releases.admit_transaction("stable-release", env, run=run)+ published["isDraft"] = False+ with pytest.raises(ChannelError, match="workflow"):+ channel_releases.admit_transaction("stable-release", dict(env, GITHUB_WORKFLOW_REF="custom.yml"), run=run)+ with pytest.raises(ValueError, match="blocked"):+ channel_releases.admit_transaction("stable-release", dict(env, RELEASE_NEEDS="{}"), run=run)+ from hermes_cli.release_channels import canonical_json+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ # Exercise HTTPS authority validation through the loopback transport.+ pub.public_base = "https://releases.example"+ candidate = {"schema": 2, "tag": tag, "commit": commit,+ "smoke_results": {job: {"result": "success"} for job in channel_releases.stable.SMOKE_JOBS},+ "packages": []}+ for platform in ("macos", "windows"):+ for arch in ("arm64", "x64"):+ candidate["packages"].append({"platform": platform, "arch": arch, "tag": tag, "commit": commit,+ "version": "2.0.0" if platform == "macos" else "2.0.0.0", "identity": "fixture.identity",+ "teamId": "ABCDEFGHIJ", "publisher": "CN=Fixture", "applicationId": "Fixture",+ "artifact": {"url": f"{pub.public_base}/releases/tag/{tag}/fixture-{arch}." + ("zip" if platform == "macos" else "msixbundle"), "sha256": "d" * 64}})+ raw = canonical_json(candidate)+ key = f"releases/tag/{tag}/release-candidates.json"+ objects[key] = raw+ candidate_env = {"CANDIDATE_MANIFEST_SHA256": hashlib.sha256(raw).hexdigest(), "CANDIDATE_MANIFEST_URL": pub.public_base + "/" + key}+ with pytest.raises(ChannelError, match="transaction"):+ channel_releases.accepted_stable(pub, candidate_env, tag, commit)+ objects["releases/stable/release-candidates.json"] = raw+ assert channel_releases.accepted_stable(pub, candidate_env, tag, commit) == candidate+ faults["stale_public"] = b"{}"+ with pytest.raises(ChannelError):+ channel_releases.accepted_stable(pub, candidate_env, tag, commit)+++def test_request_inputs_are_rejected_before_allocating():+ from hermes_cli.release_channels import ChannelError+ with object_server() as (url, objects, headers, requests, faults):+ pub = publisher(url)+ pub.create("validation")+ before = dict(objects)+ with pytest.raises(ValueError):+ pub.allocate("validation", "a" * 40, "1.0.0", [])+ assert objects == before+ with pytest.raises(ChannelError):+ pub.allocate("validation", "not-a-sha", "1.0.0")+ assert objects == beforediff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.mdindex a43cc2e0c4f..e4c04fc0cbc 100644--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@ -91,11 +91,15 @@ changes only that installation's configuration, then exits without applying anupdate. `--channel` is a one-run override. An explicit `--branch` takes precedencefor a source checkout.-Source `main` tracks the branch tip. Source `stable` and `canary` resolve the-published release for that channel and update the checkout to its exact Git-commit. Canary does not mean the current tip of `main`, and an unpublished tag-is not a release. Switching a source channel does not install a desktop package.-Per-install records live under `update.installs` in configuration, so one+Channel names are registered in the release archive on Cloudflare R2, not in a+fixed list shipped with Hermes. The `main` record selects source-branch delivery;+published-build channels select an exact Git commit. Custom preview channels use+the same source commands, for example `hermes update --set-channel pm-preview`.+The publisher must have created that channel before an update can resolve it.+An unavailable or invalid record reports an error rather than falling back to+`main` or another release. Switching a source channel does not install a desktop+package.+Per-install subscriptions live under `update.installs` in configuration, so onecheckout's choice does not change another installation's channel. The source-builtdesktop uses that same selection for checks and update handoffs; it does notreplace a selected release channel with its default branch.