The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): delete cross-package retirement migration machinery (round 3 slice 3)
ethernet5b30ae9991bf
diff --git a/.github/workflows/install-e2e.yml b/.github/workflows/install-e2e.ymlindex bde2699cdd9..0474b0bcb08 100644--- a/.github/workflows/install-e2e.yml+++ b/.github/workflows/install-e2e.yml@@ -51,29 +51,7 @@ on:required: falsetype: choicedefault: all- options: [all, both, update, installer, windows-desktop, macos-desktop, bundled, windows-bundled, macos-bundled, channel-retirement]- retirement-manifest:- description: 'HTTPS URL for one digest-pinned disposable native retirement journey.'- type: string- default: ''- retirement-sha256:- description: 'Exact SHA256 of retirement-manifest bytes.'- type: string- default: ''- disposable-run:- description: 'Existing allocation run-id-attempt; never a production namespace.'- type: string- default: ''- retirement-arch:- description: 'Native retirement host architecture.'- type: choice- options: [arm64, x64]- default: arm64- retirement-platform:- description: 'Native retirement OS (one fresh namespace per journey).'- type: choice- options: [darwin, win32]- default: darwin+ options: [all, both, update, installer, windows-desktop, macos-desktop, bundled, windows-bundled, macos-bundled]windows-bundle-manifest:description: 'HTTPS manifest pinning signed Windows OLD/NEW msixbundles; NEW must match this ref.'type: string@@ -153,87 +131,11 @@ permissions:# github.run_id so a parent rerun cannot kill this child mid-flight. The# scheduled/push runs keep ref-scoped collapse.concurrency:- group: install-e2e-${{ inputs.route == 'channel-retirement' && format('retirement-{0}', inputs.disposable-run) || inputs.release == true && github.run_id || github.ref }}- cancel-in-progress: ${{ inputs.release != true && inputs.route != 'channel-retirement' }}+ group: install-e2e-${{ inputs.release == true && github.run_id || github.ref }}+ cancel-in-progress: ${{ inputs.release != true }}jobs:- channel-retirement:- name: Native bundled retirement- if: >-- inputs.route == 'channel-retirement' && github.event_name == 'workflow_dispatch'- && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)- runs-on: ${{ inputs.retirement-platform == 'win32' && (inputs.retirement-arch == 'arm64' && 'windows-11-arm' || 'windows-latest') || (inputs.retirement-arch == 'x64' && 'macos-15-intel' || 'macos-15') }}- environment: release-signing- timeout-minutes: 75- permissions:- contents: read- defaults:- run:- shell: bash- steps:- - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- persist-credentials: false- - uses: ./.github/actions/setup-pm- with:- toolchain: node- - name: Install driver dependencies- run: |- node -e 'if (Number(process.versions.node.split(".")[0]) < 24) throw Error("Node 24+ required")'- npm ci --workspace apps/desktop --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund- - name: Fetch pinned controller input- # Portable admission checks are not native acceptance.- # Keep them in the native job so this coordinator cannot become an orphan.- # The real lifecycle still runs below against signed artifacts.- env:- MANIFEST_URL: ${{ inputs.retirement-manifest }}- MANIFEST_SHA256: ${{ inputs.retirement-sha256 }}- run: |- python3 -c 'import os,pathlib,hashlib,urllib.request; u=os.environ["MANIFEST_URL"]; assert u.startswith("https://"); b=urllib.request.urlopen(u,timeout=30).read(4194305); assert len(b)<=4194304 and hashlib.sha256(b).hexdigest()==os.environ["MANIFEST_SHA256"]; pathlib.Path(os.environ["RUNNER_TEMP"],"retirement-input.json").write_bytes(b)'- - name: Check coordinator and immutable input transport- run: |- node --test tests/install/e2e-assets/channel-retirement-manifest.test.cjs- - uses: ./.github/actions/e2e-screen-record- with:- mode: start- output: ${{ runner.temp }}/retirement-recording.mkv- - name: Run native journey with isolated publisher credentials- env:- GH_TOKEN: ${{ github.token }}- CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}- CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}- CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}- CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}- CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}- R2_DISPOSABLE_RUN: ${{ inputs.disposable-run }}- MANIFEST_SHA256: ${{ inputs.retirement-sha256 }}- RETIREMENT_ARCH: ${{ inputs.retirement-arch }}- DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}- run: |- python3 tests/install/channel-retirement-controller.py \- --manifest "$RUNNER_TEMP/retirement-input.json" --sha256 "$MANIFEST_SHA256" \- --work "$RUNNER_TEMP/retirement" --arch "$RETIREMENT_ARCH"- - uses: ./.github/actions/e2e-screen-record- if: always()- with:- mode: stop- output: ${{ runner.temp }}/retirement-recording.mkv-- - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1- if: always()- with:- name: retirement-observations-${{ github.run_id }}-${{ github.run_attempt }}- path: |- ${{ runner.temp }}/retirement/observations/- ${{ runner.temp }}/retirement-recording.mkv- if-no-files-found: warn- retention-days: 14-- # Which released versions do we test updating FROM? Resolved once,- # annotated with what each tag's own tree supports, and shared by every- # OS's matrix so all combos cover the same set.pick-releases:- if: inputs.route != 'channel-retirement'name: Pick release tagsruns-on: ubuntu-latesttimeout-minutes: 5@@ -326,7 +228,6 @@ jobs:--format markdown >> "$GITHUB_STEP_SUMMARY"bundle-inputs:- if: inputs.route != 'channel-retirement'name: Validate pinned bundle transitionsruns-on: ubuntu-latesttimeout-minutes: 5@@ -506,7 +407,7 @@ jobs:# the per-OS aggregates.report:name: Result chart- if: always() && inputs.route != 'channel-retirement'+ if: always()needs: [leg-player, pick-releases, linux, windows, macos, bundle-inputs, windows-bundled, macos-bundled]runs-on: ubuntu-latesttimeout-minutes: 5diff --git a/apps/desktop/electron/data-paths.ts b/apps/desktop/electron/data-paths.tsindex c4d4abf9591..c5515115d0f 100644--- a/apps/desktop/electron/data-paths.ts+++ b/apps/desktop/electron/data-paths.ts@@ -26,7 +26,6 @@ export function resolveDesktopUserData(defaultPath: string, env: NodeJS.ProcessEinterface HermesHomeOptions {home: string- adoptedHome?: stringenv?: NodeJS.ProcessEnvplatform?: NodeJS.PlatformdirectoryExists?: (directory: string) => boolean@@ -35,7 +34,6 @@ interface HermesHomeOptions {export function resolveDesktopHermesHome({home,- adoptedHome,env = process.env,platform = process.platform,directoryExists = (): boolean => false,@@ -52,12 +50,6 @@ 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.tsindex f8b24c1bfdb..80507e7d086 100644--- a/apps/desktop/electron/desktop-boot-preference.test.ts+++ b/apps/desktop/electron/desktop-boot-preference.test.ts@@ -5,38 +5,17 @@ import path from 'node:path'import { test } from 'vitest'-import { resolveDesktopHermesHome } from './data-paths'-import { adoptDesktopHome, readDesktopBootPreference, writeDesktopProfile } from './desktop-boot-preference'+import { readDesktopBootPreference, writeDesktopProfile } from './desktop-boot-preference'-test('an adopted home survives profile changes and cold boot without overriding explicit launch state', (): void => {+test('profile writes preserve other-owned fields and never adopt a broken file', (): 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')+ assert.equal(stored?.profile, 'research')writeFileSync(preference, '{broken', 'utf8')assert.throws(() => writeDesktopProfile(preference, 'preview'), /preference/)assert.equal(readFileSync(preference, 'utf8'), '{broken')diff --git a/apps/desktop/electron/desktop-boot-preference.ts b/apps/desktop/electron/desktop-boot-preference.tsindex dd2fb8cf234..25846684130 100644--- a/apps/desktop/electron/desktop-boot-preference.ts+++ b/apps/desktop/electron/desktop-boot-preference.ts@@ -1,29 +1,12 @@import { randomUUID } from 'node:crypto'import { closeSync, fsyncSync, mkdirSync, openSync, 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)}@@ -60,14 +43,6 @@ function parseDesktopBootPreference(text: string): DesktopBootPreference {const preference: DesktopBootPreference = { ...parsed, profile: typeof profile === 'string' ? profile : null }- if ('home' in parsed) {- if (typeof parsed.home !== 'string' || !path.isAbsolute(parsed.home)) {- throw new Error('Invalid home in desktop boot preference')- }-- preference.home = parsed.home- }-if ('_migrated' in parsed) {if (typeof parsed._migrated !== 'boolean') {throw new Error('Invalid migration marker in desktop boot preference')@@ -123,18 +98,3 @@ export function writeDesktopProfile(file: string, profile: string | null): strinreturn 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/main.ts b/apps/desktop/electron/main.tsindex 31fadee3886..8bbebaedb8c 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -446,14 +446,8 @@ import { createChannelAppInstallerStrategy } from './updater/app-installer'import { ChannelResolver, type ChannelTarget } from './updater/channel'import { ChannelStrategy } from './updater/channel-strategy'import { UpdateOperation } from './updater/operation'-import { inspectRunningChannelApp } from './updater/retirement-discovery'+import { inspectRunningChannelApp } from './updater/channel-native'import { verifyPreparedChannelInstaller } from './updater/channel-windows-host'-import { RetirementHost, prepareRetirementStartup, forwardRetiredPreview, type RetirementReception } from './updater/retirement-host'-import { retirementConnection, type RetirementConnectionSelection } from './updater/retirement-connections'-import type { RetirementConsent } from './updater/retirement-state'-import { confirmRetirementWorkspace } from './updater/retirement-dialog'-import type { RetirementExistingSelection, RetirementWorkspaceConflict } from './updater/retirement-receiver'-import { readStartupDesktopPreference } from './desktop-boot-preference'import { type ConsumedRelaunch, consumePendingRelaunch, registerUpdateRelaunch, type RelaunchRegistration } from './updater/relaunch'import { startRelaunchWaiter } from './updater/relaunch-waiter'import { preflightStateDb } from './updater/state-db-preflight'@@ -756,25 +750,8 @@ const DESKTOP_PROFILE_CONFIG_PATH: string = path.join(app.getPath('userData'), '// 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),- confirmWorkspaceConflict: (conflict: RetirementWorkspaceConflict) => confirmRetirementWorkspace(conflict, {- ready: async (): Promise<void> => { await app.whenReady() }, showMessageBox: dialog.showMessageBox- })-}).catch(async (error: Error): Promise<null> => {- await app.whenReady()- dialog.showErrorBox('Migration paused — preview preserved', error.message)- 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')})@@ -3056,11 +3033,7 @@ async function createPackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {return new ChannelStrategy({build, mechanism,resolver: new ChannelResolver({ build, platform: process.platform, arch: process.arch, signer: installed.signer }),- nativeFactory: (target: ChannelTarget): UpdaterStrategy => createNativePackagedStrategy(mechanism, target),- retirement: new RetirementHost({ home: HERMES_HOME, userData: app.getPath('userData'), payload,- profile: primaryProfileKey, connection: selectedRetirementConnection, stop: teardownBundledBackend,- restore: restoreBundledBackend, quit: (): void => app.quit(),- progress: (message: string): void => emitUpdateProgress({ stage: 'prepare', message, percent: null }) })+ nativeFactory: (target: ChannelTarget): UpdaterStrategy => createNativePackagedStrategy(mechanism, target)})}@@ -3811,16 +3784,14 @@ async function releaseBackendLock(updateRoot: string, tag: string): Promise<{ un//// Detection (checkUpdates / commit changelog / "N behind") stays in the UI;// only this apply action changed.-async function applyUpdates(retirementConsent?: RetirementConsent): Promise<UpdaterApplyResultWire> {+async function applyUpdates(): Promise<UpdaterApplyResultWire> {return updateOperation.apply(async (): Promise<UpdaterApplyResultWire> => {updateInFlight = truelet handedOff: boolean = falsetry {const strategy: UpdaterStrategy = await resolvePackagedUpdateStrategy() ?? resolveCheckoutUpdateStrategy()- const result: UpdaterApplyResultWire = retirementConsent- ? strategy instanceof ChannelStrategy ? await strategy.applyRetirement(retirementConsent) : { ok: false, error: 'No retirement offer is selected.' }- : await strategy.apply()+ const result: UpdaterApplyResultWire = await strategy.apply()handedOff = result.handedOff === truereturn result@@ -16595,14 +16566,6 @@ 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: Partial<RetirementConsent>): Promise<UpdaterApplyResultWire> => {- if (consent?.installStable !== true || consent?.removePreview !== true) { return { ok: false, error: 'Explicit installation and preview-removal consent required.' } }- if (consent.workspaceChoice !== 'keep-stable' && consent.workspaceChoice !== 'open-preview') { return { ok: false, error: 'Choose which workspace stable should open.' } }-- return applyUpdates({ installStable: true, removePreview: true, workspaceChoice: consent.workspaceChoice })- .catch((error: Error): UpdaterApplyResultWire => ({ ok: false, error: 'retirement-blocked', message: error.message }))-})-ipcMain.handle('hermes:updates:branch:set', async (_event: Electron.IpcMainInvokeEvent, name: unknown): Promise<{ branch: string }> => {assertSourceUpdateChannel(INSTALL_STAMP)const branch: string = typeof name === 'string' && name.trim() ? name.trim() : DEFAULT_UPDATE_BRANCH@@ -17095,39 +17058,6 @@ ipcMain.handle('hermes:deep-link-ready', () => {return { ok: true }})-function selectedRetirementConnection(): RetirementConnectionSelection {- const registry = readDesktopConnectionsRegistry()- const route = resolveDesktopRemoteRoute({ config: readDesktopConnectionConfig(), registry, profile: primaryProfileKey(),- env: { token: process.env.HERMES_DESKTOP_REMOTE_TOKEN, url: process.env.HERMES_DESKTOP_REMOTE_URL } })- if (!route) { return { id: 'local' } }- const entry = registry.connections.find(connection => connection.id === route.connectionId)- if (!entry) { throw new Error('Save the selected remote connection before migration; environment-only credentials cannot transfer') }- return { id: entry.id, settings: retirementConnection(entry) }-}--async function finishDesktopRetirement(reception: RetirementReception): Promise<void> {- const result = await reception.complete({- home: HERMES_HOME, profile: primaryProfileKey, connectionId: (): string => selectedRetirementConnection().id,- rendererMounted: (): boolean => Boolean(_rendererReadyForDeepLink && mainWindow && !mainWindow.isDestroyed()),- backend: async (): Promise<void> => {- await startHermes()- await handleHermesApiRequest({ path: '/api/sessions', timeoutMs: 5000 })- const connection = await ensureBackend(primaryProfileKey())- const wsUrl: string | null = await resolveTestWsUrl(connection.baseUrl, normAuthMode(connection.authMode), connection.token, {- mintTicket: (url: string) => mintGatewayWsTicket(url, connection.headers || {})- })- if (!wsUrl) { throw new Error('Stable connection has no authenticated WebSocket URL') }- const probe: { ok: boolean; reason?: string } = await probeGatewayWebSocket(wsUrl, {- WebSocketImpl: globalThis.WebSocket, headers: connection.headers || {}- })- if (!probe.ok) { throw new Error(probe.reason || 'Stable connection authentication is incomplete') }- }- })- if (result.status === 'cleanup-pending') {- 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) {@@ -17160,20 +17090,6 @@ 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),- confirmWorkspaceConflict: (conflict: RetirementWorkspaceConflict) => confirmRetirementWorkspace(conflict, {- ready: async (): Promise<void> => { await app.whenReady() }, showMessageBox: dialog.showMessageBox- }),- runningSelection: (): Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'> => ({- home: HERMES_HOME, profile: primaryProfileKey(), connectionId: selectedRetirementConnection().id- })- }).then(async (reception: RetirementReception | null): Promise<void> => {- if (reception) { await finishDesktopRetirement(reception) }- }).catch((error: Error): void => dialog.showErrorBox('Migration paused — preview preserved', error.message))- return- }const url = _extractDeepLink(argv)if (url) {@@ -17284,7 +17200,6 @@ 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 6c8daabdc7a..225232b1a55 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -1,8 +1,5 @@import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'-import type { UpdaterApplyResultWire } from './updater/index'-import type { RetirementConsent } from './updater/retirement-state'-// Which translucency the OS can back. Asked synchronously because the renderer// needs it before its first paint, and answered by main because deciding it// needs `os.release()` — a sandboxed preload may only require electron, events,@@ -539,7 +536,6 @@ contextBridge.exposeInMainWorld('hermesDesktop', {updates: {check: opts => ipcRenderer.invoke('hermes:updates:check', opts),apply: opts => ipcRenderer.invoke('hermes:updates:apply', opts),- retire: (consent: RetirementConsent): Promise<UpdaterApplyResultWire> => ipcRenderer.invoke('hermes:updates:retire', consent),getBranch: () => ipcRenderer.invoke('hermes:updates:branch:get'),setBranch: name => ipcRenderer.invoke('hermes:updates:branch:set', name),onProgress: callback => {diff --git a/apps/desktop/electron/updater/channel-artifact-lifetime.test.ts b/apps/desktop/electron/updater/channel-artifact-lifetime.test.tsnew file mode 100644index 00000000000..426f9611bf1--- /dev/null+++ b/apps/desktop/electron/updater/channel-artifact-lifetime.test.ts@@ -0,0 +1,66 @@+import { createHash } from 'node:crypto'+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'+import { createServer } from 'node:http'+import { once } from 'node:events'+import os from 'node:os'+import path from 'node:path'++import { afterEach, expect, test } from 'vitest'++import { downloadPinnedArtifact } from './artifact'+import { verifyPreparedChannelInstaller } from './channel-windows-host'+import type { ChannelTarget } from './channel'+import type { NativeCommandResult } from './channel-native'++const directories: string[] = []+afterEach(async (): Promise<void> => {+ for (const directory of directories.splice(0)) {+ await rm(directory, { recursive: true, force: true })+ }+})++test('ordinary Windows preparation owns temporary bytes while a resumable download retains its durable file', async (): Promise<void> => {+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-artifact-lifetime-'))+ directories.push(directory)+ const bytes: Buffer = Buffer.from('digest-bound download')+ const server = createServer((_request, response): void => { response.end(bytes) })+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ const address = server.address()+ if (!address || !(address instanceof Object)) { throw new Error('Expected TCP server') }+ const url: string = `http://127.0.0.1:${address.port}/stable.msixbundle`+ const identity = { token: 'a'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview', appNamePascal: 'Preview',+ artifactNamePascal: 'Preview', cliName: 'preview', windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }+ const target: ChannelTarget = {+ channel: { schema: 1, state: 'active', name: 'preview', repository: 'NousResearch/hermes-agent', policy: 'preview',+ revision: 1, nextSequence: 2, head: null, identity },+ manifest: { schema: 1, packages: [], request: { schema: 1, buildId: 'b'.repeat(32), channel: 'preview', sequence: 1,+ repository: 'NousResearch/hermes-agent', commit: 'c'.repeat(40), sourceVersion: '1.0.0', version: '0.0.1',+ windowsVersion: '0.0.1.0', identity, bundleEnv: {}, publicBase: 'https://example.com' } },+ package: { platform: 'win32', arch: 'x64', variant: 'bundled', version: '0.0.1.0', identity: identity.msixAppIdWithOrg,+ publisher: 'CN=Test', artifact: { key: 'stable.msixbundle', sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length },+ feed: { key: 'stable.appinstaller', channel: 'stable' } },+ artifactUrl: url, feedUrl: 'https://example.com/stable.appinstaller', manifestSha256: 'd'.repeat(64)+ }+ try {+ const file: string = path.join(directory, 'stable.appinstaller')+ await writeFile(file, 'native descriptor checked by command')+ const command = async (_script: string, input: string): Promise<NativeCommandResult> => {+ const payload: { artifact: string } = JSON.parse(input)+ expect(await readFile(payload.artifact)).toEqual(bytes)+ return { stdout: '', stderr: '' }+ }+ await verifyPreparedChannelInstaller(file, target, command)+ expect(await readdir(directory)).toEqual(['stable.appinstaller'])+ await expect(verifyPreparedChannelInstaller(file, target, async (): Promise<never> => {+ throw new Error('native signature refused')+ })).rejects.toThrow('signature refused')+ expect(await readdir(directory)).toEqual(['stable.appinstaller'])+ const durable: string = path.join(directory, 'durable-download')+ await mkdir(durable, { mode: 0o700 })+ const artifact = { url, sha256: target.package.artifact.sha256, size: bytes.length, format: 'msixbundle' as const }+ const downloaded: string = await downloadPinnedArtifact(durable, artifact)+ expect(await downloadPinnedArtifact(durable, artifact)).toBe(downloaded)+ expect(await readFile(downloaded)).toEqual(bytes)+ } finally { server.close(); await once(server, 'close') }+})diff --git a/apps/desktop/electron/updater/channel-native.ts b/apps/desktop/electron/updater/channel-native.tsindex f536c443124..5dc3b0c1e70 100644--- a/apps/desktop/electron/updater/channel-native.ts+++ b/apps/desktop/electron/updater/channel-native.ts@@ -1,7 +1,9 @@+import { execFile } from 'node:child_process'import { createHash } from 'node:crypto'-import { open } from 'node:fs/promises'+import { open, realpath } from 'node:fs/promises'+import path from 'node:path'-import type { ChannelPackage } from './channel-protocol'+import type { ChannelBuild, 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> {@@ -15,3 +17,114 @@ export async function verifyChannelDownload(files: string[], artifact: ChannelPaif (digest.digest('hex') !== artifact.sha256) { throw new Error('Channel artifact digest mismatch') }} finally { await file.close() }}++export interface NativeCommandResult {+ stdout: string+ stderr: string+}++/** Run one native (codesign / PowerShell) command with bounded output and timeout. */+export function runChannelCommand(+ 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 channel operation failed: ${file}: ${stderr}`, { cause: error }))++ return+ }++ resolve({ stdout, stderr })+ }+ )++ child.stdin?.end(input)+ })+}++export async function runChannelPowerShell(script: string, input: string = ''): Promise<NativeCommandResult> {+ if (process.platform !== 'win32') { throw new Error('This operation requires Windows') }+ return runChannelCommand(+ 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+ )+}++/** Resolve symlinks to the canonical on-disk path, tolerating a not-yet-created tail. */+export async function canonicalChannelPath(candidate: string): Promise<string> {+ if (!path.isAbsolute(candidate) || candidate.includes('\0')) {+ throw new Error('Channel operations require 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 canonicalChannelPath(parent), path.basename(candidate))+ }+}++export interface RunningChannelApp {+ identity: string+ signer: string+ appPath: string+ nativeVersion: string+ executable: string+ applicationId: string | null+ packageFullName: string | null+ packageFamilyName: string | null+ removalRoots: string[]+}++/** Derive trust from the signed running application, never from an R2 document. */+export async function inspectRunningChannelApp(build: ChannelBuild): Promise<RunningChannelApp> {+ const executable: string = await canonicalChannelPath(process.execPath)+ if (process.platform === 'darwin') {+ const appPath: string = path.resolve(executable, '../../..')+ await runChannelCommand('/usr/bin/codesign', ['--verify', '--deep', '--strict', appPath])+ const signature: NativeCommandResult = await runChannelCommand('/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 runChannelPowerShell(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: RunningChannelApp = 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+}diff --git a/apps/desktop/electron/updater/channel-strategy.ts b/apps/desktop/electron/updater/channel-strategy.tsindex 30a09394521..c5d5c62ea69 100644--- a/apps/desktop/electron/updater/channel-strategy.ts+++ b/apps/desktop/electron/updater/channel-strategy.ts@@ -1,28 +1,22 @@-import type { ChannelResolver, ChannelRetirement, ChannelTarget } from './channel'+import type { ChannelResolver, ChannelTarget } from './channel'import type { ChannelBuild } from './channel-protocol'-import type { RetirementConsent } from './retirement-state'import type { UpdaterApplyResultWire, UpdaterStatusWire, UpdaterStrategy } from './index'export interface ChannelRetirementStatus {- state: 'available' | 'waiting' | 'incompatible' | 'conflict' | 'migrating' | 'cleanup-pending' | 'complete' | 'discontinued'+ state: 'discontinued'destination: stringversion: stringmessage?: string}-export interface ChannelRetirementCallbacks {- check: (retirement: ChannelRetirement) => Promise<Pick<ChannelRetirementStatus, 'state' | 'message'>>- apply: (retirement: ChannelRetirement, consent: RetirementConsent) => Promise<UpdaterApplyResultWire>-}export interface ChannelStrategyDeps {resolver: Pick<ChannelResolver, 'resolve'>build: ChannelBuildmechanism: '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'] }+interface RetirementSelection { kind: 'retirement'; value: unknown; state: ChannelRetirementStatus['state'] }type Selection = NativeSelection | RetirementSelection | { kind: 'empty' }/** One selection owns a check/apply operation; background checks cannot retarget it. */@@ -114,21 +108,4 @@ export class ChannelStrategy implements UpdaterStrategy {return { ok: true, mechanism: this.mechanism }} finally { this.busy = false }}-- /** Only the explicit migration action may call this method. */- async applyRetirement(consent: RetirementConsent): Promise<UpdaterApplyResultWire> {- this.enter()-- try {- if (this.selection?.kind !== 'retirement' || !this.deps.retirement) {- return { ok: false, error: 'Check the retirement offer before accepting migration.' }- }-- if (this.selection.state !== 'available' && this.selection.state !== 'cleanup-pending') {- return { ok: false, error: 'Retirement is blocked; resolve the reported issue and retry.' }- }-- return await this.deps.retirement.apply(this.selection.value, consent)- } finally { this.busy = false }- }}diff --git a/apps/desktop/electron/updater/channel-windows-host.ts b/apps/desktop/electron/updater/channel-windows-host.tsindex 954f6d440bc..7dcc0a9aa93 100644--- a/apps/desktop/electron/updater/channel-windows-host.ts+++ b/apps/desktop/electron/updater/channel-windows-host.ts@@ -2,14 +2,13 @@ import path from 'node:path'import { mkdtemp, rm } from 'node:fs/promises'import type { ChannelTarget } from './channel'-import { runRetirementPowerShell } from './retirement-discovery'+import { runChannelPowerShell, type NativeCommandResult } from './channel-native'import { downloadPinnedArtifact } from './artifact'-import type { NativeCommandResult } from './retirement-native'/** Verify downloaded bytes and native metadata before App Installer can stop the backend. */export async function verifyPreparedChannelInstaller(file: string, target: ChannelTarget,- command: (script: string, input: string) => Promise<NativeCommandResult> = runRetirementPowerShell+ command: (script: string, input: string) => Promise<NativeCommandResult> = runChannelPowerShell): Promise<void> {const pkg = target.packageif (pkg.platform !== 'win32' || !pkg.publisher) { throw new Error('Expected a publisher-bound Windows package') }diff --git a/apps/desktop/electron/updater/channel.test.ts b/apps/desktop/electron/updater/channel.test.tsindex f13b8da3416..7de50b96157 100644--- a/apps/desktop/electron/updater/channel.test.ts+++ b/apps/desktop/electron/updater/channel.test.ts@@ -9,7 +9,6 @@ import { ChannelResolver } from './channel'import type { ChannelBuild, ChannelManifest, ChannelRecord, RetiredChannel } from './channel-protocol'import { decodeChannelRecord, sameChannelIdentity } from './channel-protocol'import { ChannelStrategy } from './channel-strategy'-import type { RetirementConsent } from './retirement-state'const servers: Server[] = []afterEach(async (): Promise<void> => {@@ -242,13 +241,7 @@ test('in-place retirement resolves with the receiver kind and routes through thereturn { supported: true, updateAvailable: true } },apply: async () => { nativeCalls.push('apply');return { ok: true, handedOff: true } }- }),- retirement: {- check: async () => { retirementChecks += 1;- return { state: 'available' } },- apply: async () => { retirementApplies += 1;- return { ok: true, handedOff: true } }- }+ })})// Same surface as a stable update: available, no retirement status block.@@ -277,13 +270,7 @@ test('discontinued retirement surfaces the notice and never downloads or appliesconst strategy = new ChannelStrategy({resolver, build: f.build, mechanism: 'electron-updater',- nativeFactory: (): never => { throw new Error('Discontinued retirement must never reach the native updater') },- retirement: {- check: async () => { migrationCalls.push('check');- return { state: 'available' } },- apply: async () => { migrationCalls.push('apply');- return { ok: true, handedOff: true } }- }+ nativeFactory: (): never => { throw new Error('Discontinued retirement must never reach the native updater') }})const status = await strategy.check()@@ -300,33 +287,19 @@ test('discontinued retirement surfaces the notice and never downloads or appliesexpect(await strategy.apply()).toMatchObject({ ok: false })})-test('discontinued retirement never consults the migration callbacks; the consented path is refused', async (): Promise<void> => {+test('discontinued retirement never consults the migration callbacks; the apply path is refused', async (): Promise<void> => {const f = await retiredFixture()- let applied = false- const consents: RetirementConsent[] = []const strategy = new ChannelStrategy({resolver: new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }),build: f.build, mechanism: 'electron-updater',- nativeFactory: (): never => { throw new Error('Not a same-identity update') },- retirement: {- check: async () => { throw new Error('Discontinued retirement must not reach the migration host') },- apply: async (_retirement, consent: RetirementConsent) => { consents.push(consent); applied = true;-- return { ok: true, handedOff: true } }- }+ nativeFactory: (): never => { throw new Error('Not a same-identity update') }})const status = await strategy.check()expect(status.updateAvailable).toBeUndefined()expect(status.retirement).toMatchObject({ state: 'discontinued', destination: 'stable' })- expect(applied).toBe(false)expect(await strategy.apply()).toMatchObject({ ok: false })- expect(applied).toBe(false)- const consent: RetirementConsent = { installStable: true, removePreview: true, workspaceChoice: 'keep-stable' }- expect(await strategy.applyRetirement(consent)).toMatchObject({ ok: false })- expect(applied).toBe(false)- expect(consents).toEqual([])})test.each(['hash', 'identity', 'repository', 'signer', 'escape', 'schema', 'version'] as const)('rejects untrusted %s without falling back', async (fault): Promise<void> => {diff --git a/apps/desktop/electron/updater/retirement-compatibility.ts b/apps/desktop/electron/updater/retirement-compatibility.tsdeleted file mode 100644index 3f82d0a909b..00000000000--- a/apps/desktop/electron/updater/retirement-compatibility.ts+++ /dev/null@@ -1,44 +0,0 @@-import type { PayloadInfo } from '../payload-backend'--import { runRetirementCommand } from './retirement-native'-import type { RetirementSnapshotTools } from './retirement-preservation'-import type { RetirementRecord } from './retirement-state'--const compatibilityProbe: string = `import os, pathlib, sys-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 hermes_yaml-from hermes_cli.config import validate_config_structure-config_file = home / 'config.yaml'-config = hermes_yaml.safe_load(config_file.read_text(encoding='utf-8')) if config_file.exists() else {}-if not isinstance(config, dict): raise RuntimeError('Configuration must be a mapping')-issues = validate_config_structure(config)-if any(issue.severity == 'error' for issue in issues): raise RuntimeError('Snapshot configuration is incompatible; run hermes doctor in the preview')-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()-`--/** Exercise destination readers before any live migrations; not a universal compatibility proof. */-export async function probeRetirementSnapshot(record: RetirementRecord, payload: PayloadInfo): Promise<void> {- await runRetirementCommand(payload.storePython, ['-c', compatibilityProbe,- payload.repoDir, payload.sitePackages, record.state.snapshotHome, record.request.source.profile], 120_000)-}--export function retirementSnapshotTools(payload: PayloadInfo): RetirementSnapshotTools {- return { python: payload.storePython, repo: payload.repoDir, sitePackages: payload.sitePackages }-}diff --git a/apps/desktop/electron/updater/retirement-connections.test.ts b/apps/desktop/electron/updater/retirement-connections.test.tsdeleted file mode 100644index 6b116ebea4b..00000000000--- a/apps/desktop/electron/updater/retirement-connections.test.ts+++ /dev/null@@ -1,79 +0,0 @@-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.tsdeleted file mode 100644index 1467b44b84e..00000000000--- a/apps/desktop/electron/updater/retirement-connections.ts+++ /dev/null@@ -1,137 +0,0 @@-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.tsdeleted file mode 100644index 378006c1ee6..00000000000--- a/apps/desktop/electron/updater/retirement-dialog.ts+++ /dev/null@@ -1,44 +0,0 @@-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.tsdeleted file mode 100644index 10d10b1634f..00000000000--- a/apps/desktop/electron/updater/retirement-discovery.test.ts+++ /dev/null@@ -1,96 +0,0 @@-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.tsdeleted file mode 100644index 765d6c20bc2..00000000000--- a/apps/desktop/electron/updater/retirement-discovery.ts+++ /dev/null@@ -1,130 +0,0 @@-import path from 'node:path'--import type { ChannelBuild } from './channel-protocol'-import type { ChannelTarget } from './channel'-import { discoverMacRetirementPath, type MacRetirementDiscovery } from './retirement-macos'-import { runRetirementCommand, type NativeCommandResult } from './retirement-native'-import { canonicalRetirementPath, 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' }-}--interface RetirementDiscovery {- mac?: MacRetirementDiscovery- windows?: (target: ChannelTarget, source: RetirementSource, family: string) => Promise<string>-}--async function discoverWindowsDestination(target: ChannelTarget, source: RetirementSource, family: string): Promise<string> {- const result: NativeCommandResult = await runRetirementPowerShell(String.raw`-$ErrorActionPreference='Stop'-$p=[Console]::In.ReadToEnd() | ConvertFrom-Json-$packages=@(Get-AppxPackage -Name $p.identity | Where-Object { $_.Name -ceq $p.identity })-if ($packages.Count -gt 1) { throw 'Stable package is not uniquely registered' }-if ($packages.Count) {- $pkg=$packages[0]- if ($pkg.Publisher -cne $p.signer -or $pkg.PackageFamilyName -cne $p.family -or $pkg.Architecture.ToString() -ine $p.arch -or $pkg.Status.ToString() -cne 'Ok') { throw 'Stable native identity/status mismatch' }- if ($pkg.SignatureKind.ToString() -cne 'Developer' -or $pkg.IsDevelopmentMode -or $pkg.NonRemovable -or $pkg.IsPartiallyStaged) { throw 'Stable is owned by another installation steward' }- $manifest=Get-AppxPackageManifest -Package $pkg.PackageFullName- if (@($manifest.Package.Applications.Application | Where-Object { $_.Id -ceq $p.applicationId }).Count -ne 1) { throw 'Stable registered application identity mismatch' }- if ($pkg.Version.ToString() -ceq $p.version) { $pkg.InstallLocation | ConvertTo-Json -Compress; exit }- $store=Split-Path -Parent $pkg.InstallLocation-} else {- $volume=Get-AppxDefaultVolume- if (-not $volume -or $volume.IsOffline) { throw 'No online default package volume' }- $store=$volume.PackageStorePath-}-if (-not $store) { throw 'Native package store location missing' }-Join-Path $store ($p.identity+'_'+$p.version+'_'+$p.arch+'__'+$p.publisherId) | ConvertTo-Json -Compress-`, JSON.stringify({ identity: target.package.identity, version: target.package.version, arch: target.package.arch,- signer: source.signer, family, publisherId: family.split('_').at(-1), applicationId: target.manifest.request.identity.appNamePascal }))- const appPath: string = JSON.parse(result.stdout)- return canonicalRetirementPath(appPath)-}--export async function discoverRetirementDestination(- target: ChannelTarget, source: RetirementSource, discovery: RetirementDiscovery = {}-): Promise<RetirementDestination> {- const pkg = target.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') {- const proposed: RetirementDestination = { ...common,- appPath: path.join(path.dirname(source.appPath), `${target.manifest.request.identity.displayName}.app`),- applicationId: null, packageFamilyName: null }- return { ...proposed, appPath: await discoverMacRetirementPath(proposed, discovery.mac) }- }- if (!source.packageFullName) { throw new Error('Missing running package identity') }- const publisherId: string = source.packageFullName.split('_').at(-1) || ''- if (!/^[a-z0-9]{13}$/.test(publisherId)) { throw new Error('Invalid native publisher ID') }- const packageFamilyName: string = `${pkg.identity}_${publisherId}`- const appPath: string = await (discovery.windows ?? discoverWindowsDestination)(target, source, packageFamilyName)- const applicationId: string = target.manifest.request.identity.appNamePascal- if (!applicationId) { throw new Error('Missing native application ID') }- return { ...common, appPath, packageFamilyName, applicationId }-}diff --git a/apps/desktop/electron/updater/retirement-host.test.ts b/apps/desktop/electron/updater/retirement-host.test.tsdeleted file mode 100644index b513a0d298c..00000000000--- a/apps/desktop/electron/updater/retirement-host.test.ts+++ /dev/null@@ -1,358 +0,0 @@-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 { resolveDesktopHermesHome } from '../data-paths'-import { readDesktopBootPreference, readStartupDesktopPreference } from '../desktop-boot-preference'-import type { PayloadInfo } from '../payload-backend'--import { prepareRetirementStartup, type RetirementStartupOptions } from './retirement-host'-import { adoptRetirementConnection, retirementConnection, retirementSelectedConnection } from './retirement-connections'-import { MacRetirementAdapter } from './retirement-macos'-import type { RetirementWorkspaceConflict } from './retirement-receiver'-import { retirementArgument } from './retirement-receiver'-import { retirementDigest, RetirementJournal, type RetirementRequest } from './retirement-state'--class TestDestination extends MacRetirementAdapter {- removed: boolean = false- override async verifyDestination(): Promise<void> {}- override async removePreview(): Promise<void> { this.removed = true }- override async isPreviewRemoved(): Promise<boolean> { return this.removed }- override async verifyRunningDestination(request: RetirementRequest): Promise<string> {- return path.join(request.destination.appPath, 'Contents/MacOS/Hermes')- }-}--async function fixture(- directory: string-): Promise<{ options: RetirementStartupOptions; file: string; journal: RetirementJournal }> {- 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 },- destinationManifestSha256: 'e'.repeat(64),- sourceBuild: {- buildId: '1'.repeat(32), channel: 'preview', sequence: 1, repository: 'NousResearch/hermes-agent',- commit: 'f'.repeat(40), version: '0.0.1', sourceVersion: '1.2.2', windowsVersion: '0.0.1.0',- publicBase: 'https://example.com', bundleEnv: {},- identity: { token: '2'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview',- appNamePascal: 'Preview', artifactNamePascal: 'Preview', cliName: 'preview',- windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }- },- consent: { install: true, removePreview: true, replaceExistingStable: false }- }-- const journalRoot: string = path.join(directory, 'transactions')- const journal = await RetirementJournal.open(journalRoot, request.id)- await journal.write({- request,- requestDigest: retirementDigest(request),- stage: 'destination-installed',- state: { snapshotHome: path.join(directory, 'snapshot'), selectedHome: home },- receiverApplied: false,- receiverStarted: false,- previousSelection: null,- ready: null- })-- const payload: PayloadInfo = {- root: directory,- shim: '/unused',- repoDir: directory,- toolsDir: directory,- storePython: '/unused',- sitePackages: directory,- commands: {}- }-- return {- file: path.join(userData, 'active-profile.json'),- journal,- options: {- argv: [retirementArgument(request.id, request.token)],- userData,- defaultHome: path.join(directory, 'default-home'),- operatorOverride: false,- payload,- journalRoot,- adapter: new TestDestination(),- assertAdmitted: async (): Promise<void> => {},- probeSnapshot: async (): Promise<void> => {}- }- }-}--test('receiver durably adopts before resolving home, is idempotent, and preserves a conflicting stable preference', async (): Promise<void> => {- const directory = await mkdtemp(path.join(os.tmpdir(), 'retirement-host-'))-- try {- const { file, journal, options } = await fixture(directory)- expect(await prepareRetirementStartup(options)).not.toBeNull()- const preference = readDesktopBootPreference(file)- expect(resolveDesktopHermesHome({ home: directory, env: {}, adoptedHome: preference?.home })).toBe(- path.join(directory, 'preview-home')- )- 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.each(['keep-stable', 'open-preview'] as const)(- 'explicit %s consent binds the current stable workspace without merging settings',- async (choice): Promise<void> => {- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-consent-'))-- try {- const { file, journal, options } = await fixture(directory)- const stableHome: string = path.join(directory, 'stable-home')- await mkdir(stableHome)- const original: string = JSON.stringify({ home: stableHome, profile: 'work', customSetting: 'preserve' })- await writeFile(file, original)- const connectionFile: string = path.join(options.userData, 'connections.json')- await writeFile(connectionFile, '{"primary":"local","saved":[{"id":"remote-saved"}]}')- const prompts: RetirementWorkspaceConflict[] = []-- options.confirmWorkspaceConflict = async (conflict: RetirementWorkspaceConflict): Promise<typeof choice> => {- prompts.push(conflict)-- return choice- }-- if (choice === 'keep-stable') {- options.runningSelection = () => ({ home: stableHome, profile: 'work', connectionId: 'local' })- }-- const reception = await prepareRetirementStartup(options)- expect(reception).not.toBeNull()- expect(prompts).toHaveLength(1)- expect(prompts[0].current).toEqual({- home: stableHome,- profile: 'work',- connectionId: 'local',- operatorOverride: false- })- expect(prompts[0].canOpenPreview).toBe(choice === 'open-preview')- const record = await journal.read()- expect(record.request.selection.choice).toBe(choice)- expect(record.previousSelection?.home).toBe(stableHome)- expect(record.request.selection.conflictConsent).toEqual(prompts[0].current)- expect(record.state.selectedHome).toBe(choice === 'keep-stable' ? stableHome : record.request.source.home)-- if (choice === 'keep-stable') {- expect(await readFile(file, 'utf8')).toBe(original)- } else {- expect(JSON.parse(await readFile(file, 'utf8')).customSetting).toBe('preserve')- }-- expect(await readFile(connectionFile, 'utf8')).toBe('{"primary":"local","saved":[{"id":"remote-saved"}]}')- await prepareRetirementStartup(options)- expect(prompts).toHaveLength(1)- expect(record.ready).toBeNull()- expect(record.stage).toBe('destination-installed')- } finally {- await rm(directory, { recursive: true, force: true })- }- }-)--test.each(['before-write', 'after-write'] as const)(- 'receiver resumes %s interruption without asking again or losing stable settings',- async (interruption): Promise<void> => {- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-adoption-retry-'))-- try {- const { file, journal, options } = await fixture(directory)- const stableHome: string = path.join(directory, 'stable-home')- await mkdir(stableHome)- await writeFile(file, JSON.stringify({ home: stableHome, profile: 'work', customSetting: 'preserved' }))- const record = await journal.read()- const previous = { home: stableHome, profile: 'work', connectionId: 'local', operatorOverride: false }- record.request.selection.conflictConsent = previous- record.previousSelection = previous- record.receiverStarted = true- record.requestDigest = retirementDigest(record.request)- await journal.write(record)-- if (interruption === 'after-write') {- await writeFile(- file,- JSON.stringify({ home: record.request.selection.home, profile: 'default', customSetting: 'preserved' })- )- }-- options.confirmWorkspaceConflict = async (): Promise<never> => {- throw new Error('Must reuse prior consent')- }-- expect(await prepareRetirementStartup(options)).not.toBeNull()- expect((await journal.read()).receiverApplied).toBe(true)- expect((await journal.read()).previousSelection).toEqual(previous)- expect(JSON.parse(await readFile(file, 'utf8')).customSetting).toBe('preserved')- } finally {- await rm(directory, { recursive: true, force: true })- }- }-)--test('cancel, stale consent and running stable reject retargeting before any preference write', async (): Promise<void> => {- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-consent-stale-'))-- try {- const { file, journal, options } = await fixture(directory)- const stableHome: string = path.join(directory, 'stable-home')- await mkdir(stableHome)- const original: string = JSON.stringify({ home: stableHome, profile: 'work' })- await writeFile(file, original)- options.confirmWorkspaceConflict = async (): Promise<null> => null- await expect(prepareRetirementStartup(options)).rejects.toThrow('cancelled')-- options.confirmWorkspaceConflict = async (): Promise<'open-preview'> => {- await writeFile(file, JSON.stringify({ home: stableHome, profile: 'changed' }))-- return 'open-preview'- }-- await expect(prepareRetirementStartup(options)).rejects.toThrow('changed')- await writeFile(file, original)- options.runningSelection = () => ({ home: stableHome, profile: 'work', connectionId: 'local' })- options.confirmWorkspaceConflict = async (): Promise<'open-preview'> => 'open-preview'- await expect(prepareRetirementStartup(options)).rejects.toThrow('Close stable')- expect(await readFile(file, 'utf8')).toBe(original)- let activeProfile: string = 'work'- options.runningSelection = () => ({ home: stableHome, profile: activeProfile, connectionId: 'local' })-- options.confirmWorkspaceConflict = async (): Promise<'keep-stable'> => {- activeProfile = 'changed'-- return 'keep-stable'- }-- await expect(prepareRetirementStartup(options)).rejects.toThrow('changed')- expect((await journal.read()).receiverStarted).toBe(false)- expect((await journal.read()).ready).toBeNull()- } finally {- await rm(directory, { recursive: true, force: true })- }-})--test('remote adoption strips credentials, survives an interrupted write and waits for authenticated readiness', async (): Promise<void> => {- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-remote-'))- try {- const { file, journal, options } = await fixture(directory)- const record = await journal.read()- record.request.selection.connectionId = 'retired-remote'- record.request.selection.reauthenticate = true- record.request.selection.connection = retirementConnection({ id: 'remote', kind: 'remote', label: 'Research',- url: 'https://gateway.example', authMode: 'token', token: { ciphertext: 'private-preview-secret' }, headers: { Authorization: 'private-proxy-secret' } })- record.previousSelection = { home: options.defaultHome, profile: 'default', connectionId: 'local', operatorOverride: false }- record.receiverStarted = true- record.requestDigest = retirementDigest(record.request)- await journal.write(record)- adoptRetirementConnection(options.userData, 'retired-remote', 'default', record.request.selection.connection)- const reception = await prepareRetirementStartup(options)- if (!reception || !(options.adapter instanceof TestDestination)) { throw new Error('Receiver did not start') }- expect(readDesktopBootPreference(file)?.home).toBe(record.request.selection.home)- expect(retirementSelectedConnection(options.userData, 'default')).toBe('retired-remote')- const stored: string = await readFile(path.join(options.userData, 'connections.json'), 'utf8')- expect(stored).not.toContain('private-preview-secret')- expect(stored).not.toContain('private-proxy-secret')- const adapter: TestDestination = options.adapter- let attempts: number = 0- const outcome = await reception.complete({ home: record.request.selection.home, profile: (): string => 'default',- connectionId: (): string => retirementSelectedConnection(options.userData, 'default'), rendererMounted: (): boolean => true,- backend: async (): Promise<void> => {- expect(adapter.removed).toBe(false)- if (attempts++ === 0) { throw new Error('reauthentication required') }- } })- expect(outcome.status).toBe('complete')- expect((await journal.read()).stage).toBe('complete')- expect(adapter.removed).toBe(true)- expect(retirementSelectedConnection(options.userData, 'default')).toBe('retired-remote')- } finally { await rm(directory, { recursive: true, force: true }) }-})--test('a removed package home stays adopted on cold boot', async (): Promise<void> => {- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'retirement-relocated-'))- try {- const { file, journal, options } = await fixture(directory)- const record = await journal.read()- const relocated: string = path.join(journal.directory, 'home')- await mkdir(relocated)- await writeFile(path.join(relocated, 'witness'), 'preserved')- record.request.source.removalRoots.push(record.request.source.home)- record.request.selection.home = relocated- record.state.selectedHome = relocated- record.requestDigest = retirementDigest(record.request)- await journal.write(record)- await prepareRetirementStartup(options)- await rm(record.request.source.home, { recursive: true })- expect(resolveDesktopHermesHome({ home: directory, env: {}, adoptedHome: readDesktopBootPreference(file)?.home })).toBe(relocated)- expect(await readFile(path.join(relocated, 'witness'), 'utf8')).toBe('preserved')- await prepareRetirementStartup(options)- expect((await journal.read()).receiverApplied).toBe(true)- } finally { await rm(directory, { recursive: true, force: true }) }-})--test('malformed legacy preferences keep ordinary boot usable but block migration without overwriting bytes', async (): Promise<void> => {- const directory = await mkdtemp(path.join(os.tmpdir(), 'retirement-preference-'))-- try {- const { file, journal, options } = await fixture(directory)- await writeFile(file, '{bad-json')- const warnings: string[] = []- expect(- readStartupDesktopPreference(file, (message: string): void => {- warnings.push(message)- })- ).toBeNull()- expect(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.tsdeleted file mode 100644index 94a48c0fc81..00000000000--- a/apps/desktop/electron/updater/retirement-host.ts+++ /dev/null@@ -1,404 +0,0 @@-import { readdir } from 'node:fs/promises'-import path from 'node:path'--import { adoptDesktopHome, type DesktopBootPreference, readDesktopBootPreference } from '../desktop-boot-preference'-import type { PayloadInfo } from '../payload-backend'--import { ChannelResolver, type ChannelRetirement } from './channel'-import type { ChannelRetirementCallbacks, ChannelRetirementStatus } from './channel-strategy'-import {- awaitRetirementCleanup, prepareRetirement, resumeRetirement, type RetirementDependencies,- type RetirementOutcome, type RetirementReadinessProbe, verifyRetirementReadiness-} from './retirement'-import { probeRetirementSnapshot, retirementSnapshotTools } from './retirement-compatibility'-import { adoptRetirementConnection, assertRetirementConnection, prepareRetirementConnection, type RetirementConnectionSelection, retirementSelectedConnection } from './retirement-connections'-import {- discoverRetirementDestination,- discoverRetirementSource-} from './retirement-discovery'-import { MacRetirementAdapter } from './retirement-macos'-import { retirementPathExists } from './retirement-native'-import { snapshotRetirementHome } from './retirement-preservation'-import {- completeRetirementReception,- parseRetirementArgument,- receiveRetirement,- type RetirementExistingSelection,- type RetirementReceiverDependencies-} from './retirement-receiver'-import {- canonicalRetirementPath,- defaultRetirementRoot,- insideRetirementRoot,- newRetirementCorrelation,- type RetirementConsent,- RetirementJournal,- type RetirementRecord,- type RetirementRequest,- type RetirementSelection,- type RetirementWorkspaceChoice-} from './retirement-state'-import { WindowsRetirementAdapter } from './retirement-windows'--import type { UpdaterApplyResultWire } from './index'--export type RetirementAdapter = MacRetirementAdapter | WindowsRetirementAdapter--export function nativeRetirementAdapter(): RetirementAdapter {- if (process.platform === 'darwin') {- return new MacRetirementAdapter()- }-- if (process.platform === 'win32') {- return new WindowsRetirementAdapter()- }-- throw new Error('Native retirement requires macOS or Windows')-}--export async function assertRetirementAdmitted(request: RetirementRequest): Promise<void> {- const build = request.sourceBuild- const resolved = await new ChannelResolver({- build,- platform: request.source.platform,- arch: request.source.architecture,- signer: request.source.signer- }).resolve()-- if (- resolved.kind !== 'retirement' ||- resolved.retirement.target.manifest.request.commit !== request.destination.commit ||- resolved.retirement.target.package.artifact.sha256 !== request.destination.artifact.sha256 ||- resolved.retirement.target.package.identity !== request.destination.identity ||- resolved.retirement.target.manifestSha256 !== request.destinationManifestSha256- ) {- throw new Error('The pinned retirement destination is no longer available')- }-}--export interface RetirementStartupOptions {- argv: readonly string[]- userData: string- defaultHome: string- operatorOverride: boolean- payload: PayloadInfo | null- /** A live stable process cannot silently retarget already-open databases. */- runningSelection?: () => Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'>- confirmWorkspaceConflict?: RetirementReceiverDependencies['confirmWorkspaceConflict']- journalRoot?: string- adapter?: RetirementAdapter- assertAdmitted?: (request: RetirementRequest) => Promise<void>- probeSnapshot?: (record: RetirementRecord, payload: PayloadInfo) => Promise<void>-}-export interface RetirementReception {- complete(probe: RetirementReadinessProbe): Promise<RetirementOutcome>-}---/** 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.receiverStarted && insideRetirementRoot(record.request.destination.appPath, process.execPath)- )-- if (pending) {- correlation = { id: pending.id, token: (await pending.read()).request.token }- }- }-- if (!correlation) {- return null- }-- if (!options.payload) {- throw new Error('The retirement receiver requires the bundled stable application')- }-- 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 = {- runningSelection: options.runningSelection,- confirmWorkspaceConflict: options.confirmWorkspaceConflict,- verifyRunningDestination: async (request: RetirementRequest): Promise<string> => {- const executable: string = await adapter.verifyRunningDestination(request)- await (options.assertAdmitted ?? assertRetirementAdmitted)(request)-- return executable- },- assertCompatibleSnapshot: async (record: RetirementRecord): Promise<void> => {- await (options.probeSnapshot ?? probeRetirementSnapshot)(record, options.payload!)- },- prepareConnection: (selection: RetirementSelection): RetirementSelection => {- if (!selection.connection) { return selection }- const resolved: RetirementConnectionSelection = prepareRetirementConnection(options.userData, selection.connectionId, selection.connection)- return { ...selection, connectionId: resolved.id, connection: resolved.settings }- },- readSelection: async (): Promise<RetirementExistingSelection | null> => {- expected = readDesktopBootPreference(file)-- const running: Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'> | undefined =- options.runningSelection?.()--- if (running) {- return { ...running, operatorOverride: options.operatorOverride }- }-- const configured: boolean = !(- !expected &&- !options.operatorOverride &&- !(await retirementPathExists(path.join(options.defaultHome, 'config.yaml'))) &&- retirementSelectedConnection(options.userData, 'default') === 'local'- )-- const selection: RetirementExistingSelection = {- home: options.operatorOverride ? options.defaultHome : (expected?.home ?? options.defaultHome),- profile: expected?.profile ?? 'default',- connectionId: retirementSelectedConnection(options.userData, expected?.profile ?? 'default'),- operatorOverride: options.operatorOverride- }- if (!configured) { selection.configured = false }- return selection- },- adoptSelection: async (record: RetirementRecord): Promise<void> => {- const selection = record.request.selection- const current: string = retirementSelectedConnection(options.userData, selection.profile)- if (current !== selection.connectionId && current !== record.previousSelection?.connectionId) {- throw new Error('Stable connection changed while awaiting adoption; review the migration again')- }- adoptRetirementConnection(options.userData, selection.connectionId, selection.profile, selection.connection)- adoptDesktopHome(file, { home: selection.home, profile: selection.profile }, expected)- },- // Bound below only after the real renderer and backend have started.- assertReady: async (): Promise<never> => {- throw new Error('Destination renderer and backend have not reported readiness')- }- }-- await receiveRetirement(journal, correlation.token, dependencies)-- const token: string = correlation.token- return {- complete: (probe: RetirementReadinessProbe): Promise<RetirementOutcome> => awaitRetirementCleanup(async () => {- dependencies.assertReady = (record: RetirementRecord): Promise<void> => verifyRetirementReadiness(record, probe)- const record: RetirementRecord = await journal.read()- if (record.request.selection.choice === 'open-preview' && record.request.selection.connection) {- assertRetirementConnection(options.userData, record.request.selection.connectionId, record.request.selection.connection)- }- await dependencies.assertReady(record)- if (record.stage === 'destination-installed') {- await completeRetirementReception(journal, token, dependencies)- }- return resumeRetirement(journal, {- native: adapter,- assertAdmitted: options.assertAdmitted ?? assertRetirementAdmitted,- // Native cleanup checks all source package processes, not just this app's child.- assertSourceQuiescent: async (): Promise<void> => {},- assertDestinationReady: dependencies.assertReady- }, 'destination')- })- }-}--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 assertRetirementAdmitted(record.request)- await nativeRetirementAdapter().activate(record.request, pending)-- return true-}--export interface RetirementHostOptions {- home: string- userData: string- payload: PayloadInfo- profile: () => string- connection: () => RetirementConnectionSelection- 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.sourceBuild.commit === retirement.source.commit- )- await this.request(retirement)-- return { state: 'available' }- } catch (error) {- return { state: 'conflict', message: error instanceof Error ? error.message : String(error) }- }- }-- private async request(- retirement: ChannelRetirement,- choice: RetirementWorkspaceChoice = 'open-preview'- ): Promise<RetirementRequest> {- const connection = this.options.connection()- const source = await discoverRetirementSource(- retirement.source,- this.options.home,- this.options.userData,- this.options.profile()- )- source.connectionId = connection.id- const keyPath: string | null = connection.settings?.keyPath ? await canonicalRetirementPath(connection.settings.keyPath) : null- if (keyPath && source.removalRoots.some(root => insideRetirementRoot(root, keyPath))) {- throw new Error('The SSH key is inside package-private storage. Move it to persistent storage and update the saved connection before migration')- }-- const destination = await discoverRetirementDestination(retirement.target, source)- const correlation = newRetirementCorrelation()- const home: string = source.removalRoots.some(root => insideRetirementRoot(root, source.home))- ? path.join(defaultRetirementRoot(), correlation.id, 'home') : source.home- if (home !== source.home && (source.platform !== 'win32' || insideRetirementRoot(source.appPath, source.home))) {- throw new Error('A workspace inside the application bundle needs a complete external archive before migration; preview preserved')- }- const connectionId: string = connection.id === 'local' ? 'local' : `retired-${retirement.source.identity.token}-${connection.id}`-- return {- protocol: 1,- ...correlation,- source,- destination,- selection: { home, profile: source.profile, connectionId, choice,- connection: connection.settings, reauthenticate: connection.id !== 'local' },- sourceBuild: retirement.source,- destinationManifestSha256: retirement.target.manifestSha256,- consent: { install: true, removePreview: true, replaceExistingStable: true }- }- }-- async apply(retirement: ChannelRetirement, consent: RetirementConsent): Promise<UpdaterApplyResultWire> {- let stopped: boolean = false-- try {- if (- consent.installStable !== true ||- consent.removePreview !== true ||- !['open-preview', 'keep-stable'].includes(consent.workspaceChoice)- ) {- throw new Error('Explicit retirement consent and workspace choice are required')- }-- const previous: RetirementRecord | null =- this.journal && (await retirementPathExists(path.join(this.journal.directory, 'journal.json')))- ? await this.journal.read()- : null-- const request: RetirementRequest = previous?.request ?? (await this.request(retirement, consent.workspaceChoice))-- if (this.journal && !previous) {- request.id = this.journal.id- if (request.selection.home !== request.source.home) {- request.selection.home = path.join(this.journal.directory, 'home')- }- }-- this.journal ??= await RetirementJournal.open(defaultRetirementRoot(), request.id)- const journal: RetirementJournal = this.journal-- const deps: RetirementDependencies = {- native: nativeRetirementAdapter(),- assertAdmitted: assertRetirementAdmitted,- assertSourceQuiescent: async (): Promise<void> => {- await this.options.stop()- stopped = true- },- assertDestinationReady: async (): Promise<never> => {- throw new Error('Only the destination process may acknowledge readiness')- },- prepareState: async (): Promise<{ snapshotHome: string; selectedHome: string }> => {- const tools = retirementSnapshotTools(this.options.payload)- const snapshotHome: string = await snapshotRetirementHome(request.source.home, path.join(journal.directory, 'snapshot'), tools)- if (request.selection.home !== request.source.home) {- await snapshotRetirementHome(request.source.home, request.selection.home, tools)- }- return { snapshotHome, selectedHome: request.selection.home }- }- }-- this.options.progress('Preparing a private state snapshot before installing stable…')- await prepareRetirement(journal, request, deps)- // Preparation can be resumed; never reopen preview readers after stable admission.- await this.options.stop()- stopped = true- this.options.progress('Installing and opening the pinned stable application…')- await resumeRetirement(journal, deps, 'source')- this.options.quit()-- return { ok: true, handedOff: true }- } catch (error) {- const record: RetirementRecord | null =- this.journal && (await retirementPathExists(path.join(this.journal.directory, 'journal.json')))- ? await this.journal.read()- : null-- if (stopped && !record?.receiverStarted) {- await this.options.restore()- }-- const 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.tsdeleted file mode 100644index 651149da85f..00000000000--- a/apps/desktop/electron/updater/retirement-macos.ts+++ /dev/null@@ -1,368 +0,0 @@-import { constants } from 'node:fs'-import { access, lstat, mkdir, mkdtemp, readdir, readFile, rename } from 'node:fs/promises'-import os from 'node:os'-import path from 'node:path'-import { downloadPinnedArtifact } from './artifact'--import type * as Electron from 'electron'--import { removeBundleCliLinks } from '../cli-provision'--import { assertNativeRetirementRemoval, type RetirementNativeAdapter } from './retirement'-import {- assertRetirementStamp,- assertRunningRetirementStamp,- 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-}--export interface MacRetirementDiscovery {- roots?: string[]- registered?: (identity: string) => Promise<string[]>- inspect?: (app: string, target: RetirementDestination) => Promise<{ identity: string }>-}--async function registeredMacBundles(identity: string): Promise<string[]> {- requireMac()- const result: NativeCommandResult = await runRetirementCommand('/usr/bin/mdfind', [- '-0', `kMDItemCFBundleIdentifier == '${identity}'`- ])- return result.stdout.split('\0').filter(Boolean)-}--async function inspectMacDestination(app: string, target: RetirementDestination): Promise<{ identity: string }> {- requireMac()- const result: NativeCommandResult = await runRetirementCommand('/usr/bin/plutil', [- '-convert', 'json', '-o', '-', path.join(app, 'Contents/Info.plist')- ])- const plist: MacInfoPlist = JSON.parse(result.stdout)- if (plist.CFBundleIdentifier === target.identity) {- await assertOwnedBundle(app)- await verifyMacBundle({ ...target, appPath: app, nativeVersion: plist.CFBundleShortVersionString })- const stamp: MacSourceStamp = JSON.parse(await readFile(path.join(app, 'Contents/Resources/install-stamp.json'), 'utf8'))- if (stamp.distribution !== 'desktop-app' || stamp.payload !== 'bundled' || stamp.updateMechanism !== 'electron-updater') {- throw new Error('Existing stable has a different installation steward')- }- }- return { identity: plist.CFBundleIdentifier }-}--/** Search by native identity, including renamed bundles; never silently create a duplicate. */-export async function discoverMacRetirementPath(target: RetirementDestination, discovery: MacRetirementDiscovery = {}): Promise<string> {- const roots: string[] = discovery.roots ?? [path.dirname(target.appPath), '/Applications', path.join(os.homedir(), 'Applications')]- const candidates: Set<string> = new Set(await (discovery.registered ?? registeredMacBundles)(target.identity))- for (const root of new Set(roots)) {- if (!(await retirementPathExists(root))) { continue }- for (const entry of await readdir(root, { withFileTypes: true })) {- if (entry.name.endsWith('.app')) { candidates.add(path.join(root, entry.name)) }- }- }- const matches: Set<string> = new Set()- for (const candidate of candidates) {- if (!(await retirementPathExists(candidate))) { continue }- // Ignore incomplete directories; an identified matching bundle must pass- // signature and ownership checks rather than silently falling through.- if (!(await retirementPathExists(path.join(candidate, 'Contents/Info.plist')))) { continue }- const app: string = await canonicalRetirementPath(candidate)- const inspected = await (discovery.inspect ?? inspectMacDestination)(app, target)- if (inspected.identity === target.identity) { matches.add(app) }- }- if (matches.size > 1) { throw new Error('Multiple stable applications found; choose one through its installation steward') }- const existing: string | undefined = [...matches][0]- if (existing) { return existing }- if (await retirementPathExists(target.appPath)) { throw new Error('Stable install location belongs to another application') }- return canonicalRetirementPath(target.appPath)-}--async function assertNoBundleProcesses(app: string): Promise<void> {- const result: NativeCommandResult = await runRetirementCommand('/bin/ps', ['-axo', 'comm='])-- 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 downloadPinnedArtifact(journal.directory, request.destination.artifact)-- 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 assertOwnedBundle(request.destination.appPath)- 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.sourceBuild.commit ||- stamp.distribution !== 'desktop-app' ||- stamp.payload !== 'bundled'- ) {- throw new Error('Preview source stamp changed before removal')- }-- await assertNoBundleProcesses(source)- removeBundleCliLinks(path.join(source, 'Contents/Resources/agent-payload'), path.join(os.homedir(), '.local/bin'))- const { shell }: typeof Electron = await import('electron')- await shell.trashItem(source)- }-- 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.tsdeleted file mode 100644index ebe45682ae5..00000000000--- a/apps/desktop/electron/updater/retirement-native.test.ts+++ /dev/null@@ -1,163 +0,0 @@-import { createHash } from 'node:crypto'-import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'-import { createServer } from 'node:http'-import { once } from 'node:events'-import os from 'node:os'-import path from 'node:path'-import { DatabaseSync } from 'node:sqlite'--import { afterEach, expect, test } from 'vitest'--import { assertRetirementStamp, assertRunningRetirementStamp } from './retirement-native'-import { downloadPinnedArtifact, verifyPinnedArtifact } from './artifact'-import { verifyPreparedChannelInstaller } from './channel-windows-host'-import type { ChannelTarget } from './channel'-import type { NativeCommandResult } from './retirement-native'-import { snapshotRetirementHome } from './retirement-preservation'-import type { RetirementDestination } from './retirement-state'--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',- repo: path.resolve('../..'), sitePackages: ''- })-- 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('ordinary Windows preparation owns temporary bytes while retirement retains its resumable download', async (): Promise<void> => {- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-artifact-lifetime-'))- directories.push(directory)- const bytes: Buffer = Buffer.from('digest-bound download')- const server = createServer((_request, response): void => { response.end(bytes) })- server.listen(0, '127.0.0.1')- await once(server, 'listening')- const address = server.address()- if (!address || !(address instanceof Object)) { throw new Error('Expected TCP server') }- const url: string = `http://127.0.0.1:${address.port}/stable.msixbundle`- const identity = { token: 'a'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview', appNamePascal: 'Preview',- artifactNamePascal: 'Preview', cliName: 'preview', windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }- const target: ChannelTarget = {- channel: { schema: 1, state: 'active', name: 'preview', repository: 'NousResearch/hermes-agent', policy: 'preview',- revision: 1, nextSequence: 2, head: null, identity },- manifest: { schema: 1, packages: [], request: { schema: 1, buildId: 'b'.repeat(32), channel: 'preview', sequence: 1,- repository: 'NousResearch/hermes-agent', commit: 'c'.repeat(40), sourceVersion: '1.0.0', version: '0.0.1',- windowsVersion: '0.0.1.0', identity, bundleEnv: {}, publicBase: 'https://example.com' } },- package: { platform: 'win32', arch: 'x64', variant: 'bundled', version: '0.0.1.0', identity: identity.msixAppIdWithOrg,- publisher: 'CN=Test', artifact: { key: 'stable.msixbundle', sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length },- feed: { key: 'stable.appinstaller', channel: 'stable' } },- artifactUrl: url, feedUrl: 'https://example.com/stable.appinstaller', manifestSha256: 'd'.repeat(64)- }- try {- const file: string = path.join(directory, 'stable.appinstaller')- await writeFile(file, 'native descriptor checked by command')- const command = async (_script: string, input: string): Promise<NativeCommandResult> => {- const payload: { artifact: string } = JSON.parse(input)- expect(await readFile(payload.artifact)).toEqual(bytes)- return { stdout: '', stderr: '' }- }- await verifyPreparedChannelInstaller(file, target, command)- expect(await readdir(directory)).toEqual(['stable.appinstaller'])- await expect(verifyPreparedChannelInstaller(file, target, async (): Promise<never> => {- throw new Error('native signature refused')- })).rejects.toThrow('signature refused')- expect(await readdir(directory)).toEqual(['stable.appinstaller'])- const durable: string = path.join(directory, 'retirement')- await mkdir(durable, { mode: 0o700 })- const artifact = { url, sha256: target.package.artifact.sha256, size: bytes.length, format: 'msixbundle' as const }- const downloaded: string = await downloadPinnedArtifact(durable, artifact)- expect(await downloadPinnedArtifact(durable, artifact)).toBe(downloaded)- expect(await readFile(downloaded)).toEqual(bytes)- } finally { server.close(); await once(server, 'close') }-})--test('native preparation rejects bytes changed after download and wrong stamped commit or owner', async (): Promise<void> => {- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-native-retirement-'))- directories.push(directory)- 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(verifyPinnedArtifact(artifact, target.artifact)).resolves.toBeUndefined()- await writeFile(artifact, Buffer.alloc(bytes.length))- await expect(verifyPinnedArtifact(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,- receiverProtocol: 1,- source: 'build',- tag: 'v1.0.0',- updateMechanism: 'electron-updater'- })- )- await expect(assertRetirementStamp(stamp, target)).resolves.toBeUndefined()- const accepted = JSON.parse(await readFile(stamp, 'utf8'))- for (const invalid of [{ tag: null }, { tag: 'v1.0.0-canary.20260913' }, { source: 'channel-build' }, { channelBuild: {} }]) {- await writeFile(stamp, JSON.stringify({ ...accepted, ...invalid }))- await expect(assertRetirementStamp(stamp, target)).rejects.toThrow('stamp')- }- await writeFile(- stamp,- JSON.stringify({- 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.tsdeleted file mode 100644index 7d913c465c4..00000000000--- a/apps/desktop/electron/updater/retirement-native.ts+++ /dev/null@@ -1,91 +0,0 @@-import { execFile } from 'node:child_process'-import { lstat, readFile } from 'node:fs/promises'--import { INSTALL_STAMP, type InstallStamp } from '../install-stamp'--import type { RetirementDestination } 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)- })-}---type NativeInstallStamp = Pick<InstallStamp,- 'commit' | 'payload' | 'distribution' | 'dirty' | 'receiverProtocol' | 'updateMechanism' | 'tag' | 'source' | 'channelBuild'>--function stableOwned(stamp: NativeInstallStamp): boolean {- return /^v\d+\.\d+\.\d+$/.test(stamp.tag ?? '') && !stamp.channelBuild &&- stamp.source !== 'channel-build' && stamp.source !== 'commit-build'-}--export function assertRunningRetirementStamp(target: RetirementDestination): void {- if (- !INSTALL_STAMP ||- !stableOwned(INSTALL_STAMP) ||- INSTALL_STAMP.commit !== target.commit ||- INSTALL_STAMP.payload !== 'bundled' ||- INSTALL_STAMP.distribution !== 'desktop-app' ||- INSTALL_STAMP.dirty ||- INSTALL_STAMP.receiverProtocol !== 1 ||- INSTALL_STAMP.updateMechanism !== (target.platform === 'darwin' ? 'electron-updater' : 'app-installer')- ) {- throw new Error('Running destination baked stamp is not the pinned official stable release')- }-}--export async function assertRetirementStamp(file: string, target: RetirementDestination): Promise<void> {- const stamp: NativeInstallStamp = JSON.parse(await readFile(file, 'utf8'))-- if (- !stableOwned(stamp) ||- stamp.commit !== target.commit ||- stamp.payload !== 'bundled' ||- stamp.distribution !== 'desktop-app' ||- stamp.dirty !== false ||- stamp.receiverProtocol !== 1 ||- stamp.updateMechanism !== (target.platform === 'darwin' ? 'electron-updater' : 'app-installer')- ) {- throw new Error('Destination stamp does not identify the pinned stable bundled release')- }-}--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.tsdeleted file mode 100644index abfc2ec7f98..00000000000--- a/apps/desktop/electron/updater/retirement-preservation.test.ts+++ /dev/null@@ -1,93 +0,0 @@-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.tsdeleted file mode 100644index 71ea4cd3cb6..00000000000--- a/apps/desktop/electron/updater/retirement-preservation.ts+++ /dev/null@@ -1,79 +0,0 @@-import { lstat, open, rename, rm } 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- repo: string- sitePackages: string-}--const migrationSnapshot: string = `import os, pathlib, sys-repo, site, source, target = sys.argv[1:]-sys.path[:0] = [repo, site]-os.environ['HERMES_HOME'] = source-os.environ['HERMES_SHARED_AUTH_DIR'] = str(pathlib.Path(source) / 'shared')-from hermes_cli.backup_migration import snapshot_migration_home-snapshot_migration_home(pathlib.Path(source), pathlib.Path(target))-`---async function assertPrivateDirectory(directory: string): Promise<void> {- const info: Awaited<ReturnType<typeof lstat>> = await lstat(directory)-- if (- !info.isDirectory() ||- info.isSymbolicLink() ||- (process.platform !== 'win32' && ((info.mode & 0o077) !== 0 || info.uid !== process.getuid?.()))- ) {- throw new Error('Snapshot staging must be a private owned directory')- }-}--async function discardInterruptedSnapshot(directory: string): Promise<void> {- try {- await assertPrivateDirectory(directory)- } catch (error) {- if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {- return- }-- throw error- }-- await rm(directory, { recursive: true })-}--/** Caller holds journal.exclusive and has not published the prepared journal yet. */-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')- }-- if (target !== path.resolve(destination)) {- throw new Error('Snapshot staging must be a private owned directory')- }-- await assertPrivateDirectory(path.dirname(target))- const partial: string = `${target}.partial`- // Neither tree is authoritative until preparation publishes its journal.- await discardInterruptedSnapshot(partial)- await discardInterruptedSnapshot(target)- await runRetirementCommand(tools.python, ['-c', migrationSnapshot, tools.repo, tools.sitePackages, source, partial])- await rename(partial, target)- if (process.platform !== 'win32') {- const parent = await open(path.dirname(target), 'r')- try { await parent.sync() } finally { await parent.close() }- }-- return target-}diff --git a/apps/desktop/electron/updater/retirement-receiver.ts b/apps/desktop/electron/updater/retirement-receiver.tsdeleted file mode 100644index 9f776c103f0..00000000000--- a/apps/desktop/electron/updater/retirement-receiver.ts+++ /dev/null@@ -1,280 +0,0 @@-import { randomBytes, timingSafeEqual } from 'node:crypto'--import {- canonicalRetirementPath,- type RetirementCorrelation,- retirementDigest,- type RetirementJournal,- type RetirementReady,- type RetirementRecord,- type RetirementRequest,- type RetirementSelection,- type RetirementWorkspaceChoice,- signRetirementReady-} from './retirement-state'--export interface RetirementExistingSelection {- home: string- profile: string- connectionId: string- operatorOverride: boolean- configured?: boolean-}--export interface RetirementWorkspaceConflict {- current: RetirementExistingSelection- requested: RetirementSelection- canOpenPreview: boolean-}--export interface RetirementReceiverDependencies {- /** The destination is already using this workspace; it cannot change homes in place. */- runningSelection?: () => Pick<RetirementExistingSelection, 'home' | 'profile' | 'connectionId'>- confirmWorkspaceConflict?: (conflict: RetirementWorkspaceConflict) => Promise<RetirementWorkspaceChoice | null>- /** Check process.execPath, native signature, baked commit and stable update owner. */- verifyRunningDestination(request: RetirementRequest): Promise<string>- /** Real destination readers on the disposable snapshot, before live migrations. */- assertCompatibleSnapshot(record: RetirementRecord): Promise<void>- prepareConnection?: (selection: RetirementSelection) => RetirementSelection- 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: Pick<RetirementSelection, 'home' | 'profile' | 'connectionId'>,- selection: Pick<RetirementSelection, 'home' | 'profile' | 'connectionId'>-): boolean {- return (- current.home === selection.home &&- current.profile === selection.profile &&- current.connectionId === selection.connectionId- )-}--async function readCurrentSelection(deps: RetirementReceiverDependencies): Promise<RetirementExistingSelection | null> {- const current: RetirementExistingSelection | null = await deps.readSelection()-- return current ? { ...current, home: await canonicalRetirementPath(current.home) } : null-}--async function consentToWorkspace(- record: RetirementRecord,- current: RetirementExistingSelection | null,- deps: RetirementReceiverDependencies-): Promise<void> {- if (!current || current.configured === false) {- if (record.request.selection.choice === 'keep-stable') {- throw new Error('There is no configured stable workspace to keep')- }-- return- }-- if (sameSelection(current, record.request.selection)) {- return- }-- const consent: RetirementSelection['conflictConsent'] = record.request.selection.conflictConsent-- const consentMatches: boolean = Boolean(- consent && sameSelection(current, consent) && consent.operatorOverride === current.operatorOverride- )-- if (record.receiverStarted && !consentMatches) {- if (interruptedAdoption(record, current)) { return }- throw new Error('Stable workspace changed after retirement admission; explicit forward recovery is required')- }-- const canOpenPreview: boolean = !deps.runningSelection && !current.operatorOverride- let choice: RetirementWorkspaceChoice = record.request.selection.choice-- if (!consentMatches) {- if (!deps.confirmWorkspaceConflict) {- throw new Error('Stable workspace conflict: explicit selection consent is required')- }-- const confirmed: RetirementWorkspaceChoice | null = await deps.confirmWorkspaceConflict({- current: { ...current },- requested: { ...record.request.selection },- canOpenPreview- })-- if (!confirmed) {- throw new Error('Workspace migration cancelled; preview preserved')- }-- const latest: RetirementExistingSelection | null = await readCurrentSelection(deps)-- if (!latest || !sameSelection(current, latest) || latest.operatorOverride !== current.operatorOverride) {- throw new Error('Stable workspace changed while awaiting consent; review the migration again')- }-- choice = confirmed- }-- if (choice === 'open-preview' && !canOpenPreview) {- throw new Error(- 'Close stable and remove any explicit home override before opening the preview workspace, then retry. Both workspaces are preserved.'- )- }-- const selected: Pick<RetirementSelection, 'home' | 'profile' | 'connectionId'> =- choice === 'keep-stable' ? current : record.request.selection-- record.request.selection = { ...record.request.selection, ...selected, choice, conflictConsent: { ...current } }- record.state.selectedHome = selected.home- record.requestDigest = retirementDigest(record.request)-}--function interruptedAdoption(record: RetirementRecord, current: RetirementExistingSelection): boolean {- const previous = record.previousSelection- // Home and connection have different normal writers. A crash between them- // may leave exactly this transaction's old/new pair, never a third choice.- return Boolean(previous && current.operatorOverride === previous.operatorOverride &&- (current.home === previous.home || current.home === record.request.selection.home) &&- (current.profile === previous.profile || current.profile === record.request.selection.profile) &&- (current.connectionId === previous.connectionId || current.connectionId === record.request.selection.connectionId))-}--/** Invoke before normal home selection, and on the existing stable second-instance path. */-export async function receiveRetirement(- journal: RetirementJournal,- 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' &&- record.stage !== 'preview-removed'- ) {- 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 readCurrentSelection(deps)-- 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)- if (!record.receiverStarted && record.request.selection.choice === 'open-preview' && deps.prepareConnection) {- record.request.selection = deps.prepareConnection(record.request.selection)- record.requestDigest = retirementDigest(record.request)- }- const current: RetirementExistingSelection | null = await readCurrentSelection(deps)- await consentToWorkspace(record, current, deps)- await journal.assertPaths(record.request)-- if (!record.receiverStarted) {- record.previousSelection = current- record.receiverStarted = true- await journal.write(record)- }-- if (record.request.selection.choice === 'open-preview') {- 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 journal.exclusive(async (): Promise<void> => {- const current: RetirementRecord = await journal.read()- if (current.stage !== 'destination-installed' || !current.receiverStarted || current.requestDigest !== record.requestDigest) {- throw new Error('Receiver admission changed before readiness')- }- current.ready = ready- current.stage = 'destination-ready'- await journal.write(current)- })-- return ready-}diff --git a/apps/desktop/electron/updater/retirement-state.ts b/apps/desktop/electron/updater/retirement-state.tsdeleted file mode 100644index bc086c5b93a..00000000000--- a/apps/desktop/electron/updater/retirement-state.ts+++ /dev/null@@ -1,451 +0,0 @@-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 type { ChannelBuild } from './channel-protocol'-import type { PinnedArtifact } from './artifact'-import type { RetirementConnection } from './retirement-connections'-import { runRetirementCommand } from './retirement-native'--export type RetirementStage =- 'prepared' | 'destination-installed' | 'destination-ready' | 'preview-removed' | 'complete'-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: PinnedArtifact- commit: string-}--export type RetirementWorkspaceChoice = 'open-preview' | 'keep-stable'--export interface RetirementConsent {- installStable: true- removePreview: true- workspaceChoice: RetirementWorkspaceChoice-}--export interface RetirementSelection {- home: string- profile: string- connectionId: string- choice: RetirementWorkspaceChoice- reauthenticate: boolean- connection?: RetirementConnection- conflictConsent?: { home: string; profile: string; connectionId: string; operatorOverride: boolean }-}--export interface RetirementRequest {- protocol: 1- id: string- token: string- source: RetirementSource- destination: RetirementDestination- selection: RetirementSelection- sourceBuild: ChannelBuild- destinationManifestSha256: string- 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 (!['open-preview', 'keep-stable'].includes(request.selection.choice)) {- throw new Error('Explicit retirement workspace choice required')- }-- if (!request.selection.connectionId || !request.source.removalRoots.length) {- throw new Error('Incomplete retirement state inventory')- }-}--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 (- !/^[a-f0-9]{64}$/.test(request.destinationManifestSha256) ||- !/^[a-f0-9]{40}$/.test(request.sourceBuild.commit)- ) {- throw new Error('Missing pinned retirement build')- }-}--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]) {- 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 sourceHome: string = await canonicalRetirementPath(request.source.home)- if (roots.some(root => insideRetirementRoot(root, sourceHome))) {- const relocated = await lstat(path.join(this.directory, 'home'))- if (!relocated.isDirectory() || relocated.isSymbolicLink()) {- throw new Error('Removal-scoped home has not been preserved')- }- }- // Windows archives all package-private bytes before removal. No other- // adapter may claim preservation of an Electron credential store it deletes.- if (request.source.platform !== 'win32' && roots.some(root => insideRetirementRoot(root, request.source.userData))) {- throw new Error('Desktop credentials are inside the removal footprint')- }-- const sourceApp: string = await canonicalRetirementPath(request.source.appPath)- const destinationApp: string = await canonicalRetirementPath(request.destination.appPath)-- 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.tsdeleted file mode 100644index d569d24e753..00000000000--- a/apps/desktop/electron/updater/retirement-windows.test.ts+++ /dev/null@@ -1,90 +0,0 @@-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.tsdeleted file mode 100644index 742ef66f2e0..00000000000--- a/apps/desktop/electron/updater/retirement-windows.ts+++ /dev/null@@ -1,273 +0,0 @@-import { runRetirementPowerShell } from './retirement-discovery'-import { downloadPinnedArtifact } from './artifact'-import { channelPublicBase } from './channel-protocol'-import { win32AppInstallerFeedPath } from '../app-updater'--import { assertNativeRetirementRemoval, type RetirementNativeAdapter } from './retirement'-import {- assertRunningRetirementStamp,- type NativeCommandResult-} 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' | 'register-updater' | 'verify' | 'activate' | 'remove' | 'removed'--// AppX cmdlets and manifest/signature checks follow windows-bundle-smoke.ps1.-// The activation COM ABI is IApplicationActivationManager from shobjidl_core.h.-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-Updater($pkg) {- $manager=[Windows.Management.Deployment.PackageManager,Windows.Management.Deployment,ContentType=WindowsRuntime]::new()- $native=$manager.FindPackageForUser('', $pkg.PackageFullName)- $source=$native.GetAppInstallerInfo()- if (-not $source -or $source.Uri.AbsoluteUri -cne $p.appInstallerUri) { throw 'Stable App Installer update source mismatch' }-}-function Register-Updater {- $pkg=Get-ExactPackage $d $true- Assert-Sideload $pkg- # Register metadata only: never open a mutable .appinstaller during the- # pinned handoff. Automatic deployment stays off until an ordinary update.- Set-AppxPackageAutoUpdateSettings -PackageFamilyName $d.packageFamilyName -AppInstallerUri $p.appInstallerUri -Version $d.nativeVersion -UpdateUris @() -RepairUris @() -OptionalPackages @() -DependencyPackages @() -EnableAutomaticBackgroundTask:$false -ForceUpdateFromAnyVersion:$false -DisableAutoRepairs -CheckOnLaunch:$false -ShowPrompt:$false -UpdateBlocksActivation:$false -UseSystemPolicySource:$false -HoursBetweenUpdateChecks 12 -ErrorAction Stop | Out-Null- Assert-Updater $pkg-}-function Assert-Destination([bool]$requireUpdater=$true) {- $pkg = Get-ExactPackage $d $true- Assert-Sideload $pkg- if ($requireUpdater) { Assert-Updater $pkg }- if ($pkg.Version.ToString() -cne $d.nativeVersion -or $pkg.PackageFamilyName -cne $d.packageFamilyName -or $pkg.InstallLocation -ine $d.appPath) { throw 'Installed destination binding mismatch' }- $manifest = Get-AppxPackageManifest -Package $pkg.PackageFullName- $apps = @($manifest.Package.Applications.Application | Where-Object { $_.Id -ceq $d.applicationId })- 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.receiverProtocol -ne 1 -or $stamp.updateMechanism -cne 'app-installer') { throw 'Destination stamp mismatch' }- return @{ executable=$exe; packageFullName=$pkg.PackageFullName; appPath=$pkg.InstallLocation }-}-$d = $p.request.destination-switch ($p.operation) {- 'install' {- Get-Command Set-AppxPackageAutoUpdateSettings -ErrorAction Stop | Out-Null- $existing = Get-ExactPackage $d $false- if ($existing -and $existing.Version.ToString() -ceq $d.nativeVersion) {- Assert-Destination $false | 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- $volumes=@(Get-AppxVolume | Where-Object { $_.PackageStorePath.TrimEnd('\') -ieq (Split-Path -Parent $d.appPath) -and -not $_.IsOffline })- if ($volumes.Count -ne 1) { throw 'Pinned native destination volume is unavailable' }- Add-AppxPackage -Path $p.artifact -Volume $volumes[0] -ErrorAction Stop- Assert-Destination $false | ConvertTo-Json -Compress- }- 'register-updater' {- Assert-Destination $false | Out-Null- Register-Updater- }- 'verify' { Assert-Destination | ConvertTo-Json -Compress }- 'activate' {- $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.sourceBuild.commit -or $sourceStamp.distribution -cne 'desktop-app' -or $sourceStamp.payload -cne 'bundled' -or $sourceStamp.updateMechanism -cne 'app-installer') { throw 'Preview source stamp mismatch' }- Assert-NoProcesses $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- }-}-`--function retirementAppInstallerUri(request: RetirementRequest): string {- const build = request.sourceBuild- const base: string = channelPublicBase(build.publicBase)- if (!request.destination.artifact.url.startsWith(`${base}/`) ||- new URL(request.destination.artifact.url).origin !== new URL(base).origin) {- throw new Error('Retirement artifact authority mismatch')- }- return `${base}/releases/${win32AppInstallerFeedPath('stable', false)}stable.appinstaller`-}--export class WindowsRetirementAdapter implements RetirementNativeAdapter {- constructor(private readonly command: (script: string, input: string) => Promise<NativeCommandResult> = runRetirementPowerShell) {}- private async run(- operation: WindowsOperation,- request: RetirementRequest,- artifact: string | null = null,- journalDirectory: string | null = null- ): Promise<string> {- if (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,- appInstallerUri: retirementAppInstallerUri(request),- argument: retirementArgument(request.id, request.token),- receiverExecutable: process.execPath- })-- const script: string = `$p = [Console]::In.ReadToEnd() | ConvertFrom-Json\n${windowsNativeScript}`-- const result: NativeCommandResult = await this.command(script, payload)-- return result.stdout.trim()- }-- async install(request: RetirementRequest, journal: RetirementJournal): Promise<void> {- const artifact: string = await downloadPinnedArtifact(journal.directory, request.destination.artifact)- await this.run('install', request, artifact)- await this.run('register-updater', request)- await this.verifyDestination(request)- }-- async verifyDestination(request: RetirementRequest): Promise<void> {- 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.tsdeleted file mode 100644index 9d49ee260fd..00000000000--- a/apps/desktop/electron/updater/retirement.test.ts+++ /dev/null@@ -1,299 +0,0 @@-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 },- destinationManifestSha256: 'e'.repeat(64),- sourceBuild: {- buildId: '1'.repeat(32), channel: 'preview', sequence: 1, repository: 'NousResearch/hermes-agent',- commit: 'f'.repeat(40), version: '0.0.1', sourceVersion: '1.2.2', windowsVersion: '0.0.1.0',- publicBase: 'https://example.com', bundleEnv: {},- identity: { token: '2'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview',- appNamePascal: 'Preview', artifactNamePascal: 'Preview', cliName: 'preview',- windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }- },- consent: { install: true, removePreview: true, replaceExistingStable: false }- }-- const calls: string[] = []- const store: RetirementJournal = await RetirementJournal.open(path.join(directory, 'transactions'), request.id)-- const deps: RetirementDependencies = {- assertAdmitted: async (): Promise<void> => {- calls.push('qualified')- },- prepareState: async (): Promise<{ snapshotHome: string; selectedHome: string }> => {- calls.push('snapshot')-- return { snapshotHome: snapshot, selectedHome: home }- },- 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.each(['preview-removed', 'complete'] as const)(- 'activation can enter the receiver and interruption before %s does not remove twice',- async (failedStage): Promise<void> => {- const { store, request, calls, deps } = await fixture()- await prepareRetirement(store, request, deps)- const receiver: RetirementReceiverDependencies = receiverDeps(request, calls)-- deps.native.activate = async (): Promise<void> => {- await receiveRetirement(store, request.token, receiver)- }-- 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 === failedStage) {- 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(failedStage === 'preview-removed' ? 'destination-ready' : 'preview-removed')- store.write = write- const reopened: RetirementJournal = await RetirementJournal.open(store.root, request.id)- await receiveRetirement(reopened, request.token, receiver)- expect((await resumeRetirement(reopened, deps, 'destination')).status).toBe('complete')- expect(calls.filter((call: string): boolean => call === 'remove')).toHaveLength(1)- }-)--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.tsdeleted file mode 100644index d8f985c4607..00000000000--- a/apps/desktop/electron/updater/retirement.ts+++ /dev/null@@ -1,238 +0,0 @@-import { setTimeout as delay } from 'node:timers/promises'--import {- assertRetirementReady,- canonicalRetirementPath,- insideRetirementRoot,- retirementDigest,- type RetirementJournal,- 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- /** Revalidate the authority's immutable receiver pin. */- assertAdmitted(request: RetirementRequest): Promise<void>- /** Quiesced private snapshot plus preservation of any removal-scoped state. */- prepareState(request: RetirementRequest, journal: RetirementJournal): Promise<RetirementStateSnapshot>- /** 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 interface RetirementReadinessProbe {- home: string- profile: () => string- connectionId: () => string- rendererMounted: () => boolean- /** Must exercise the selected authenticated backend, not its public health endpoint. */- backend: () => Promise<void>-}--export async function verifyRetirementReadiness(record: RetirementRecord, probe: RetirementReadinessProbe): Promise<void> {- if (probe.home !== record.state.selectedHome || probe.profile() !== record.request.selection.profile ||- probe.connectionId() !== record.request.selection.connectionId) {- throw new Error('The destination is not using the consented workspace and connection')- }- if (!probe.rendererMounted()) { throw new Error('Waiting for the stable renderer to mount') }- await probe.backend()-}--/** One bounded recovery loop covers both backend startup and lagging native release. */-export async function awaitRetirementCleanup(complete: () => Promise<RetirementOutcome>): Promise<RetirementOutcome> {- const deadline: number = Date.now() + 120_000- let message: string = 'Stable did not become ready'- while (Date.now() < deadline) {- try {- const result: RetirementOutcome = await complete()- if (result.status !== 'cleanup-pending') { return result }- message = result.error- } catch (error) { message = error instanceof Error ? error.message : String(error) }- await delay(1000)- }- return { status: 'cleanup-pending', forwardOnly: true, error: message }-}--export async function prepareRetirement(- journal: RetirementJournal,- request: RetirementRequest,- deps: RetirementDependencies-): Promise<RetirementRecord> {- validateRetirementRequest(request)-- if (request.id !== journal.id) {- throw new Error('Retirement transaction ID mismatch')- }-- await deps.assertAdmitted(request)-- return journal.exclusive(async (): Promise<RetirementRecord> => {- let existing: RetirementRecord | null = null- try {- existing = await journal.read()-- if (existing.requestDigest !== retirementDigest(request)) {- throw new Error('Transaction already binds another request')- }-- if (existing.receiverStarted) { return existing }- } catch (error) {- if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') {- throw error- }- }-- 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: existing?.stage ?? 'prepared',- state,- receiverStarted: false,- receiverApplied: false,- previousSelection: null,- ready: null- }-- await journal.write(record)-- return record- })-}--/** Source stops after activation. Stable owns cleanup, outside the source package. */-export async function resumeRetirement(- journal: RetirementJournal,- deps: Omit<RetirementDependencies, 'prepareState'>,- 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.assertAdmitted(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)- 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)-- 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)-}diff --git a/apps/desktop/scripts/commit-stamp-identity.test.mjs b/apps/desktop/scripts/commit-stamp-identity.test.mjsindex 7e66f7694e9..fa6c6744711 100644--- a/apps/desktop/scripts/commit-stamp-identity.test.mjs+++ b/apps/desktop/scripts/commit-stamp-identity.test.mjs@@ -17,6 +17,9 @@ test('desktop stamp uses the admitted checkout rather than the dispatch SHA', ()fs.mkdirSync(scripts, { recursive: true })for (const name of ['write-build-stamp.mjs', 'utils.mjs']) fs.copyFileSync(path.join(root, 'apps/desktop/scripts', name), path.join(scripts, name))fs.copyFileSync(path.join(root, 'apps/desktop/product-identity.cjs'), path.join(repo, 'apps/desktop/product-identity.cjs'))+ fs.mkdirSync(path.join(repo, 'scripts'), { recursive: true })+ fs.copyFileSync(path.join(root, 'scripts/msix-shared.mjs'), path.join(repo, 'scripts/msix-shared.mjs'))+ fs.copyFileSync(path.join(root, 'scripts/release-content-types.json'), path.join(repo, 'scripts/release-content-types.json'))git('init', '-q', '-b', 'main')git('config', 'user.name', 'Fixture')git('config', 'user.email', '[email protected]')diff --git a/apps/desktop/src/app/retirement-view.test.tsx b/apps/desktop/src/app/retirement-view.test.tsxindex 0543c3b2027..718bdff9c78 100644--- a/apps/desktop/src/app/retirement-view.test.tsx+++ b/apps/desktop/src/app/retirement-view.test.tsx@@ -7,7 +7,7 @@ import { I18nProvider } from '@/i18n'import { en } from '@/i18n/en'import { $updateStatus, resetUpdateApplyState } from '@/store/updates'-import { DiscontinuedNotice, RetirementView } from './retirement-view'+import { DiscontinuedNotice } from './retirement-view'afterEach((): void => {cleanup()@@ -16,43 +16,6 @@ afterEach((): void => {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 })- })- }-)-test('discontinued retirement shows the uninstall notice and persists dismissal per revision', async (): Promise<void> => {const dismissed: string[] = []const stored = new Map<string, string>()@@ -80,10 +43,9 @@ test('discontinued retirement shows the uninstall notice and persists dismissal)// The notice carries the "no longer supported — uninstall" copy, and offers- // no download, install, or migration action — only the dismissal.+ // no download or install action — only the dismissal.expect(screen.getByText(en.updates.discontinuedTitle)).toBeTruthy()expect(screen.getByText(en.updates.discontinuedBody)).toBeTruthy()- expect(screen.queryByRole('button', { name: en.updates.retirementAction })).toBeNull()expect(screen.queryByRole('button', { name: en.updates.updateNow })).toBeNull()expect(screen.queryByRole('checkbox')).toBeNull()diff --git a/apps/desktop/src/app/retirement-view.tsx b/apps/desktop/src/app/retirement-view.tsxindex 62670698440..4b1ba334f68 100644--- a/apps/desktop/src/app/retirement-view.tsx+++ b/apps/desktop/src/app/retirement-view.tsx@@ -1,10 +1,9 @@-import { type ReactElement, useState } from 'react'+import { type ReactElement } from 'react'import { Button } from '@/components/ui/button'import { DialogDescription, DialogTitle } from '@/components/ui/dialog'-import type { DesktopRetirementConsent, DesktopUpdateStatus } from '@/global'+import type { DesktopUpdateStatus } from '@/global'import { useI18n } from '@/i18n'-import { applyRetirement } from '@/store/updates'/*** The discontinued tier of retirement: a suffixed-identity build (canary /@@ -32,82 +31,3 @@ export function DiscontinuedNotice({</div>)}--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 [workspaceChoice, setWorkspaceChoice] = useState<DesktopRetirementConsent['workspaceChoice'] | null>(null)- const available: boolean = retirement.state === 'available' || retirement.state === 'cleanup-pending'-- return (- <div className="space-y-4 p-6">- <DialogTitle>{t.updates.retirementTitle}</DialogTitle>- <DialogDescription>{t.updates.retirementBody}</DialogDescription>- <p className="text-sm font-medium">- {retirement.destination} · {retirement.version}- </p>- {retirement.message && (- <p className="text-sm text-muted-foreground" role="status">- {retirement.message}- </p>- )}- {available ? (- <div className="space-y-3 text-sm">- <label className="flex items-start gap-2">- <input- checked={workspaceChoice === 'keep-stable'}- name="retirement-workspace"- onChange={() => setWorkspaceChoice('keep-stable')}- type="radio"- />- {t.updates.retirementKeepStable}- </label>- <label className="flex items-start gap-2">- <input- checked={workspaceChoice === 'open-preview'}- name="retirement-workspace"- onChange={() => setWorkspaceChoice('open-preview')}- type="radio"- />- {t.updates.retirementOpenPreview}- </label>- <label className="flex items-start gap-2">- <input checked={consented} onChange={event => setConsented(event.currentTarget.checked)} type="checkbox" />- {t.updates.retirementConsent}- </label>- </div>- ) : (- <p className="text-sm">- {retirement.state === 'complete' ? t.updates.retirementComplete : t.updates.retirementBlocked}- </p>- )}- <div className="flex justify-end gap-2">- <Button onClick={onLater} variant="text">- {t.updates.maybeLater}- </Button>- {available ? (- <Button- disabled={!consented || !workspaceChoice}- onClick={() => {- if (workspaceChoice) {- void applyRetirement(workspaceChoice)- }- }}- >- {t.updates.retirementAction}- </Button>- ) : (- <Button onClick={onRetry}>{t.updates.tryAgain}</Button>- )}- </div>- </div>- )-}diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsxindex 69baf503135..e465d1c6a3f 100644--- a/apps/desktop/src/app/updates-overlay.tsx+++ b/apps/desktop/src/app/updates-overlay.tsx@@ -50,7 +50,7 @@ import {type UpdateApplyState} from '@/store/updates'-import { DiscontinuedNotice, RetirementView } from './retirement-view'+import { DiscontinuedNotice } from './retirement-view'function totalItems(groups: readonly CommitGroup[]) {return groups.reduce((sum, g) => sum + g.items.length, 0)@@ -149,9 +149,6 @@ export function UpdatesOverlay() {retirement={status.retirement}/>)}- {phase === 'idle' && !isBackend && status?.retirement && status.retirement.state !== 'discontinued' && (- <RetirementView onLater={() => handleClose(false)} onRetry={() => void check()} retirement={status.retirement} />- )}{phase === 'idle' && (isBackend || !status?.retirement) && (<IdleViewbehind={behind}diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsxindex 5be220b3ecf..76a7f1e65ba 100644--- a/apps/desktop/src/components/update-status.tsx+++ b/apps/desktop/src/components/update-status.tsx@@ -43,15 +43,8 @@ function retirementStatus(supported: boolean,u: Translations['updates']): UpdateStatusView {- if (retirement.state === 'discontinued') {- // Suffixed-identity build: nothing to download or migrate — just the notice.- return { applying, supported, updateAvailable: false, tone: 'error', line: u.discontinuedTitle, error: u.discontinuedBody }- }-- const available: boolean = retirement.state === 'available' || retirement.state === 'cleanup-pending'- const line: string = applying ? u.retirementMoving : retirement.state === 'complete' ? u.retirementComplete : u.retirementTitle-- return { applying, supported, updateAvailable: false, tone: available ? 'available' : 'error', line, error: retirement.message }+ // Suffixed-identity build: nothing to download or migrate — just the notice.+ return { applying, supported, updateAvailable: false, tone: 'error', line: u.discontinuedTitle, error: u.discontinuedBody }}/**@@ -228,19 +221,14 @@ export function VersionHero({}interface UpdateActionsProps {- retirement: booleantarget: UpdateTargetu: Translations['updates']view: UpdateStatusView}-function UpdateActions({ retirement, target, u, view }: UpdateActionsProps): ReactElement | null {+function UpdateActions({ target, u, view }: UpdateActionsProps): ReactElement | null {if (view.applying) { return null }- if (retirement) {- return <Button onClick={() => openUpdateOverlayFor('client')} size="sm">{u.retirementAction}</Button>- }-if (!view.updateAvailable || !view.supported) { return null }return (@@ -321,7 +309,6 @@ export function UpdateStatusCard({</Button><UpdateActions- retirement={!isBackend && status?.retirement?.state !== undefined && status.retirement.state !== 'discontinued'}target={target}u={u}view={view}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex f99be271566..8f22966a5f5 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -558,7 +558,6 @@ declare global {updates: {check: (opts?: { force?: boolean }) => Promise<DesktopUpdateStatus>apply: (opts?: DesktopUpdateApplyOptions) => Promise<DesktopUpdateApplyResult>- retire: (consent: DesktopRetirementConsent) => Promise<DesktopUpdateApplyResult>getBranch: () => Promise<{ branch: string }>setBranch: (name: string) => Promise<{ branch: string }>onProgress: (callback: (payload: DesktopUpdateProgress) => void) => () => void@@ -755,16 +754,10 @@ export type UpdaterMechanismClient =| 'posix-handoff'| 'manual'-export interface DesktopRetirementConsent {- installStable: true- removePreview: true- workspaceChoice: 'keep-stable' | 'open-preview'-}-export interface DesktopUpdateStatus {supported: booleanretirement?: {- state: 'available' | 'waiting' | 'incompatible' | 'conflict' | 'migrating' | 'cleanup-pending' | 'complete' | 'discontinued'+ state: 'discontinued'destination: stringversion: stringmessage?: stringdiff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 61603212826..fc93d775424 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2243,8 +2243,6 @@ export const ar = defineLocale({}},updates: {- retirementKeepStable: 'الاحتفاظ بمساحة العمل الحالية للإصدار المستقر',- retirementOpenPreview: 'فتح مساحة عمل هذا الإصدار التجريبي في الإصدار المستقر',channels: { stable: 'مستقر', canary: 'تجريبي' },bundleSwapPending: 'أعد التشغيل لإكمال التحديث',bundleSwapPendingDesc: 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex bdb8c8ea4c1..7763e4ade98 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3082,15 +3082,6 @@ export const en: Translations = {},updates: {- retirementTitle: 'This preview channel has closed',- retirementBody: 'Move to the official stable app. Both workspaces stay in place. Stable must open your chosen workspace successfully before this preview is removed. Saved remote credentials are not copied.',- retirementAction: 'Move to stable',- retirementConsent: 'Install or update stable and remove this preview only after stable is ready.',- retirementKeepStable: 'Keep stable’s existing workspace',- retirementOpenPreview: 'Open this preview workspace in stable',- retirementBlocked: 'Migration paused — preview preserved',- retirementMoving: 'Moving to stable…',- retirementComplete: 'Stable is ready',discontinuedTitle: 'This build of Hermes is no longer supported',discontinuedBody: 'This build of Hermes is no longer supported and may break — uninstall it. Your data stays on disk.',channels: { stable: 'Stable', canary: 'Canary' },diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 7182ba75c4d..a4f664089d0 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2610,8 +2610,6 @@ export const ja = defineLocale({},updates: {- retirementKeepStable: '安定版の既存のワークスペースを維持する',- retirementOpenPreview: 'このプレビュー版のワークスペースを安定版で開く',channels: { stable: '安定版', canary: '先行版' },bundleSwapPending: '再起動して更新を完了',bundleSwapPendingDesc: '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 21876332e44..847bf743cb1 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2657,15 +2657,6 @@ export interface Translations {}updates: {- retirementTitle: string- retirementBody: string- retirementAction: string- retirementConsent: string- retirementKeepStable: string- retirementOpenPreview: string- retirementBlocked: string- retirementMoving: string- retirementComplete: stringdiscontinuedTitle: stringdiscontinuedBody: stringchannels: { stable: string; canary: string }diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 44a5cd07115..f56bbe89b62 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2521,8 +2521,6 @@ export const zhHant = defineLocale({},updates: {- retirementKeepStable: '保留穩定版現有的工作區',- retirementOpenPreview: '在穩定版中開啟此預覽版工作區',channels: { stable: '穩定版', canary: '預覽版' },bundleSwapPending: '重新啟動以完成更新',bundleSwapPendingDesc: '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex ffba565c213..bac6756a0b4 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3238,8 +3238,6 @@ export const zh = defineLocale({},updates: {- retirementKeepStable: '保留稳定版现有的工作区',- retirementOpenPreview: '在稳定版中打开此预览版工作区',channels: { stable: '稳定版', canary: '预览版' },bundleSwapPending: '重启以完成更新',bundleSwapPendingDesc: '更新后的应用已安装完成,只需重启 Hermes 即可加载新版本。聊天记录和设置不会受到影响。',diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.tsindex 47ba6a4b53f..578a56e8817 100644--- a/apps/desktop/src/store/updates.test.ts+++ b/apps/desktop/src/store/updates.test.ts@@ -1508,7 +1508,7 @@ describe('discontinued retirement notice', () => {// The generic update entry point refuses instead of dispatching an apply.const result = await applyUpdates()- expect(result).toMatchObject({ ok: false, error: 'retirement-consent-required' })+ expect(result).toMatchObject({ ok: false, error: 'retirement-blocked' })expect(applyMock).not.toHaveBeenCalled()})diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.tsindex 6cc24bb680a..19278c8763c 100644--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@ -7,7 +7,6 @@ import { atom } from 'nanostores'import { connectionScoped, profileScoped } from '@/api/client'import type {- DesktopRetirementConsent,DesktopUpdateApplyOptions,DesktopUpdateApplyResult,@@ -513,7 +512,7 @@ export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promisif ($updateStatus.get()?.retirement) {openUpdateOverlayFor('client')- return { ok: false, error: 'retirement-consent-required' }+ return { ok: false, error: 'retirement-blocked' }}const bridge = window.hermesDesktop?.updates@@ -620,35 +619,6 @@ export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promis}}-/** Only the dedicated consent view calls the retirement IPC; ordinary update stays separate. */-export async function applyRetirement(workspaceChoice: DesktopRetirementConsent['workspaceChoice']): 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, workspaceChoice })-- if (result.handedOff) { return result }- $updateApply.set(IDLE)- $updateStatus.set({ ...status, retirement: { ...status.retirement, state: result.ok ? 'complete' : 'conflict',- message: result.message ?? result.error } })-- return result- } catch (error) {- const message: string = error instanceof Error ? error.message : String(error)- $updateApply.set(IDLE)- $updateStatus.set({ ...status, retirement: { ...status.retirement, state: 'conflict', message } })-- return { ok: false, error: 'retirement-blocked', message }- }-}-const BACKEND_ACTION_POLL_MS = 1500const BACKEND_ACTION_MAX_MS = 6 * 60 * 1000const BACKEND_RETURN_MAX_MS = 4 * 60 * 1000diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 86c753687af..b057fd17ea2 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -287,18 +287,14 @@ def _should_exclude(rel_path: Path) -> bool:return name in _EXCLUDED_NAMES or name.startswith(_EXCLUDED_PREFIXES) or name.endswith(_EXCLUDED_SUFFIXES)-def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optional[set] = None, *, strict: bool = False):+def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optional[set] = None):"""Yield ``(abs_path, rel_path)`` for every file a full backup should hold.The one owner of the walk policy (directory pruning so os.walk never descends a multi-GBexcluded tree, the root-only ``hermes-agent`` carve-out, root runtime trees, per-file rules),- shared by ``hermes backup`` and the pre-update / pre-migration path so they can never drift.+ shared by ``hermes backup`` and the pre-update path so they can never drift."""- def walk_error(error: OSError) -> None:- if strict:- raise error-- for dirpath, dirnames, filenames in os.walk(hermes_root, followlinks=False, onerror=walk_error):+ for dirpath, dirnames, filenames in os.walk(hermes_root, followlinks=False):rel_dir = Path(dirpath).relative_to(hermes_root)is_root = rel_dir == Path(".")kept = [@@ -307,10 +303,7 @@ def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optionaland not _in_excluded_root_dir(rel_dir / d)]if skipped_dirs is not None:skipped_dirs.update(str(rel_dir / d) for d in set(dirnames) - set(kept))- if strict:- for name in kept:- yield Path(dirpath) / name, rel_dir / name- # Migration inventories links themselves; no walk may follow a junction.+ # No walk may follow a junction.dirnames[:] = [name for name in kept if not _is_link_path(Path(dirpath) / name)]for fname in filenames:rel = rel_dir / fname@@ -319,7 +312,7 @@ def _iter_backup_files(hermes_root: Path, out_path: Path, skipped_dirs: Optional# copy data from outside HERMES_HOME; never archive the output zip into itself.if _should_exclude(rel):continue- if not strict and _is_non_regular_path(fpath):+ if _is_non_regular_path(fpath):continuewith suppress(OSError, ValueError):if fpath.resolve() == out_path.resolve():diff --git a/hermes_cli/backup_migration.py b/hermes_cli/backup_migration.pydeleted file mode 100644index 2618bc79049..00000000000--- a/hermes_cli/backup_migration.py+++ /dev/null@@ -1,114 +0,0 @@-"""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/tests/hermes_cli/test_backup_migration.py b/tests/hermes_cli/test_backup_migration.pydeleted file mode 100644index d2217b3c69e..00000000000--- a/tests/hermes_cli/test_backup_migration.py+++ /dev/null@@ -1,169 +0,0 @@-"""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_backup_zip_serialization.py b/tests/hermes_cli/test_backup_zip_serialization.pyindex 341148dfb18..9c945c1148e 100644--- a/tests/hermes_cli/test_backup_zip_serialization.py+++ b/tests/hermes_cli/test_backup_zip_serialization.py@@ -48,40 +48,3 @@ def test_zip_captures_live_wal_and_cleans_failed_staging(tmp_path, monkeypatch,monkeypatch.setattr(zipfile.ZipFile, "write", refuse_write)run()assert sorted(output.iterdir()) == [archive], "a failed write must not leak a private database snapshot"---def test_strict_migration_snapshot_preserves_full_inventory_and_reports_read_failures(tmp_path, monkeypatch):- from hermes_cli.backup_migration import snapshot_migration_home-- home = tmp_path / 'home'- home.mkdir()- monkeypatch.setenv('HERMES_HOME', str(home))- for relative in ['skills/custom/SKILL.md', 'profiles/work/sessions/transcript.jsonl', 'cache/images/photo.png']:- file = home / relative- file.parent.mkdir(parents=True, exist_ok=True)- file.write_text(relative)- (home / 'models').mkdir()- (home / 'models/regenerable').write_text('not a migration payload')- with closing(sqlite3.connect(home / 'state.db')) as writer:- writer.executescript("PRAGMA journal_mode=WAL; CREATE TABLE witness(value); INSERT INTO witness VALUES ('WAL')")- snapshot = tmp_path / 'snapshot'- snapshot_migration_home(home, snapshot)- with closing(sqlite3.connect(snapshot / 'state.db')) as reader:- assert reader.execute('SELECT value FROM witness').fetchall() == [('WAL',)]- assert (snapshot / 'skills/custom/SKILL.md').read_text() == 'skills/custom/SKILL.md'- assert (snapshot / 'profiles/work/sessions/transcript.jsonl').exists()- assert (snapshot / 'cache/images/photo.png').exists()- assert not (snapshot / 'models').exists()- assert not (snapshot / 'state.db-wal').exists()-- original = Path.open-- def unreadable(self, *args, **kwargs):- if self == home / 'skills/custom/SKILL.md':- raise PermissionError('source became unreadable')- return original(self, *args, **kwargs)-- monkeypatch.setattr(Path, 'open', unreadable)- with pytest.raises(PermissionError, match='unreadable'):- snapshot_migration_home(home, tmp_path / 'failed-snapshot')- assert (snapshot / 'skills/custom/SKILL.md').exists()diff --git a/tests/install/channel-retirement-controller.py b/tests/install/channel-retirement-controller.pydeleted file mode 100644index e02d0195c72..00000000000--- a/tests/install/channel-retirement-controller.py+++ /dev/null@@ -1,181 +0,0 @@-#!/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.mddeleted file mode 100644index e40ed866ef2..00000000000--- a/tests/install/channel-retirement-e2e.md+++ /dev/null@@ -1,80 +0,0 @@-# 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.mjsdeleted file mode 100644index 031abbbd6a9..00000000000--- a/tests/install/channel-retirement-e2e.mjs+++ /dev/null@@ -1,265 +0,0 @@-#!/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/channel-retirement-inputs.mjs b/tests/install/e2e-assets/channel-retirement-inputs.mjsdeleted file mode 100644index 86fe3a5b684..00000000000--- a/tests/install/e2e-assets/channel-retirement-inputs.mjs+++ /dev/null@@ -1,70 +0,0 @@-#!/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.mjsdeleted file mode 100644index 154141b37dd..00000000000--- a/tests/install/e2e-assets/channel-retirement-macos.mjs+++ /dev/null@@ -1,117 +0,0 @@-// 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.cjsdeleted file mode 100644index c3a66878b8f..00000000000--- a/tests/install/e2e-assets/channel-retirement-manifest.cjs+++ /dev/null@@ -1,160 +0,0 @@-'use strict'-// Cross-identity journey input only; ordinary bundle validation stays strict.-const { createHash } = require('node:crypto')-const { isDeepStrictEqual } = require('node:util')-const semver = require('semver')--/** @typedef {import('../../../apps/desktop/electron/updater/channel-protocol.ts').ChannelManifest} Manifest */-/** @typedef {{manifest: Manifest, head: import('../../../apps/desktop/electron/updater/channel-protocol.ts').ChannelHead,- * package: import('../../../apps/desktop/electron/updater/channel-protocol.ts').ChannelPackage, artifactPath?: string}} Side */-/** @typedef {{schema: 1, platform: 'darwin'|'win32', arch: 'arm64'|'x64', repository: string,- * controllerCommit: string, route: 'direct'|'via-update', stable: 'absent'|'running', home: 'shared',- * minimumVersion: string, A: Side, B?: Side, S: Side, T: Side}} Journey */--const SHA256 = /^[a-f0-9]{64}$/-const COMMIT = /^[a-f0-9]{40}$/-const SLUG = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/--function archiveBase(value) {- const url = new URL(value)- if (!['https:', 'http:'].includes(url.protocol) ||- (url.protocol === 'http:' && url.hostname !== '127.0.0.1') ||- url.username || url.password || url.search || url.hash ||- /[%\\;\s]/.test(value) || value.endsWith('/') ||- value.split('/').some(part => part === '.' || part === '..')) {- throw new Error('Archive must use canonical HTTPS or explicit loopback without credentials')- }- return value-}--function objectKey(key) {- if (!/^releases\/[A-Za-z0-9_./+-]+$/.test(key) || key.split('/').some(part =>- !part || part === '.' || part === '..' || part.endsWith('.') || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) {- throw new Error('Invalid immutable object key')- }- return key-}---function validateScenario(input, platform, arch) {- if (input.schema !== 1 || input.platform !== platform || input.arch !== arch ||- !['darwin', 'win32'].includes(platform) || !['arm64', 'x64'].includes(arch)) {- throw new Error('Native journey platform/architecture mismatch')- }- if (!COMMIT.test(input.controllerCommit) || !/^[\w-]+\/[\w.-]+$/.test(input.repository)) {- throw new Error('Missing controller authority')- }- if (!['direct', 'via-update'].includes(input.route) || !['absent', 'running'].includes(input.stable) ||- input.home !== 'shared') throw new Error('Unsupported journey scenario')- if ((input.route === 'direct') !== (input.B === undefined)) throw new Error('B is required only for via-update')- if (!semver.valid(input.minimumVersion) || semver.prerelease(input.minimumVersion)) throw new Error('Invalid stable version floor')-}--function validateBinding(side, name, repository) {- const request = side?.manifest?.request- const head = side?.head- if (!request || !head || side.manifest.schema !== 1 || request.schema !== 1 ||- !/^[a-f0-9]{32}$/.test(request.buildId) || !COMMIT.test(request.commit) ||- request.repository !== repository || !Number.isSafeInteger(request.sequence) || request.sequence < 1) {- throw new Error(`Invalid ${name} immutable build binding`)- }- if (head.buildId !== request.buildId || head.sequence !== request.sequence ||- head.manifestKey !== `releases/channel-builds/${request.buildId}/build.json` || !SHA256.test(head.sha256)) {- throw new Error(`Invalid ${name} immutable head binding`)- }- if (!SLUG.test(request.channel) || request.channel.length > 32) throw new Error('Invalid channel name')- archiveBase(request.publicBase)- return request-}--function validatePackage(side, request, platform, arch) {- const packages = side.manifest.packages.filter(p => p.platform === platform && p.arch === arch && p.variant === 'bundled')- if (packages.length !== 1) throw new Error('Missing unique native package')- const pkg = packages[0]- const darwin = platform === 'darwin'- if (pkg.identity !== request.identity[darwin ? 'appId' : 'msixAppIdWithOrg'] ||- pkg.version !== request[darwin ? 'version' : 'windowsVersion'] ||- !SHA256.test(pkg.artifact.sha256) || !Number.isSafeInteger(pkg.artifact.size) || pkg.artifact.size <= 0) {- throw new Error('Invalid native artifact')- }- const signer = darwin ? pkg.teamId : pkg.publisher- if (!signer || (darwin && !/^[A-Z0-9]{10}$/.test(signer))) throw new Error('Missing native signing identity')- const prefixes = [`releases/channel-builds/${request.buildId}/`]- if (request.releaseTag) prefixes.push(`releases/tag/${request.releaseTag}/`)- for (const key of [pkg.artifact.key, pkg.feed.key]) {- if (!prefixes.some(prefix => objectKey(key).startsWith(prefix))) throw new Error('Artifact/feed outside immutable build')- }- if (pkg.feed.channel !== 'stable' || !pkg.feed.key.endsWith(darwin ? '/stable-mac.yml' : '.appinstaller')) {- throw new Error('Invalid immutable native feed')- }- return { ...side, package: pkg }-}--function validatePreview(side, platform) {- const request = side.manifest.request- const version = platform === 'darwin' ? `0.0.${request.sequence}`- : `0.${Math.floor(request.sequence / 65536)}.${request.sequence % 65536}.0`- if (request.releaseTag || request.sequence > 0xffffffff || side.package.version !== version) {- throw new Error('Preview package must use its allocated native sequence')- }-}--function validateStable(side) {- const request = side.manifest.request- if (!semver.valid(request.version) || semver.prerelease(request.version) || request.releaseTag !== `v${request.version}`) {- throw new Error('Destination must be a stable release')- }- if (request.channel !== 'stable' || side.manifest.receiverProtocol !== 1) throw new Error('Missing stable receiver support')-}--function assertAdvance(before, after, description) {- if (before.manifest.request.channel !== after.manifest.request.channel ||- !isDeepStrictEqual(before.manifest.request.identity, after.manifest.request.identity) ||- after.head.sequence <= before.head.sequence) throw new Error(`${description} must advance within one identity`)- const left = before.package.version.split('.').map(Number)- const right = after.package.version.split('.').map(Number)- if (left.length !== right.length || [...left, ...right].some(n => !Number.isSafeInteger(n) || n < 0)) {- throw new Error('Native versions must be numeric')- }- const index = left.findIndex((n, i) => n !== right[i])- if (index < 0 || right[index] <= left[index]) throw new Error(`${description} native version did not advance`)-}--function validateJourney(input, platform, arch) {- validateScenario(input, platform, arch)- const journey = { ...input }- for (const name of ['A', 'S', 'T', ...(input.route === 'via-update' ? ['B'] : [])]) {- const request = validateBinding(input[name], name, input.repository)- journey[name] = validatePackage(input[name], request, platform, arch)- if (request.publicBase !== input.A.manifest.request.publicBase) throw new Error('Journey archive authority differs')- }- validatePreview(journey.A, platform)- if (journey.B) validatePreview(journey.B, platform)- validateStable(journey.S)- validateStable(journey.T)- if (journey.A.package.identity === journey.S.package.identity ||- journey.A.manifest.request.channel === journey.S.manifest.request.channel || journey.A.manifest.request.releaseTag) {- throw new Error('Retirement must enter a distinct stable release identity')- }- const signer = platform === 'darwin' ? 'teamId' : 'publisher'- for (const name of ['S', 'T', ...(journey.B ? ['B'] : [])]) {- if (journey[name].package[signer] !== journey.A.package[signer]) throw new Error('Journey signing authority differs')- }- if (journey.B) assertAdvance(journey.A, journey.B, 'A to B')- assertAdvance(journey.S, journey.T, 'S to T')- if (semver.lt(journey.S.manifest.request.sourceVersion, input.minimumVersion)) throw new Error('Stable is below compatibility floor')- return journey-}--function verifyBytes(bytes, expected) {- 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 = { archiveBase, objectKey, validateJourney, verifyBytes, verifyManifest }diff --git a/tests/install/e2e-assets/channel-retirement-manifest.test.cjs b/tests/install/e2e-assets/channel-retirement-manifest.test.cjsdeleted file mode 100644index fdb153589ca..00000000000--- a/tests/install/e2e-assets/channel-retirement-manifest.test.cjs+++ /dev/null@@ -1,143 +0,0 @@-const { test } = require('node:test')-const assert = require('node:assert/strict')-const { createHash, createHmac } = require('node:crypto')-const http = require('node:http')-const fs = require('node:fs/promises')-const os = require('node:os')-const path = require('node:path')-const { validateJourney, verifyBytes, verifyManifest } = require('./channel-retirement-manifest.cjs')--const digest = bytes => createHash('sha256').update(bytes).digest('hex')-// Protocol fixtures only. These bytes are never installed or called native proof.-function fixture(base = 'https://archive.example.test/disposable') {- const objects = new Map()- function put(key, value) {- const bytes = Buffer.isBuffer(value) ? value : Buffer.from(JSON.stringify(value))- objects.set('/disposable/' + key, bytes)- return { key, sha256: digest(bytes), size: bytes.length }- }- function side(id, nativeIdentity, sequence, version, channel, releaseTag) {- const buildId = id.repeat(32)- const identity = { appId: nativeIdentity, appNamePascal: nativeIdentity === 'preview.app' ? 'Preview' : 'Stable' }- const request = { schema: 1, buildId, sequence, commit: id.repeat(40), repository: 'example/hermes', channel,- publicBase: base, version, sourceVersion: version, identity }- if (releaseTag) request.releaseTag = releaseTag- const prefix = `releases/channel-builds/${buildId}/`- const artifact = put(prefix + 'app.zip', Buffer.from(`not a native package: ${id}`))- const manifest = { schema: 1, request, packages: [{ platform: 'darwin', arch: 'arm64', variant: 'bundled',- identity: nativeIdentity, version, teamId: 'ABCDEFGHIJ', artifact, feed: { key: prefix + 'stable-mac.yml', channel: 'stable' } }] }- if (releaseTag) manifest.receiverProtocol = 1- const ref = put(prefix + 'build.json', manifest)- return { manifest, head: { buildId, sequence, manifestKey: ref.key, sha256: ref.sha256 } }- }- const journey = { schema: 1, platform: 'darwin', arch: 'arm64', repository: 'example/hermes', controllerCommit: 'f'.repeat(40),- route: 'via-update', stable: 'running', home: 'shared', minimumVersion: '1.0.0',- A: side('a', 'preview.app', 1, '0.0.1', 'test-preview'), B: side('b', 'preview.app', 2, '0.0.2', 'test-preview'),- S: side('c', 'stable.app', 1, '1.0.0', 'stable', 'v1.0.0'), T: side('d', 'stable.app', 2, '1.1.0', 'stable', 'v1.1.0') }- return { journey, objects }-}--test('lifecycle inputs bind distinct identities, native ordering and receiver support', () => {- const { journey } = fixture()- const validated = validateJourney(journey, 'darwin', 'arm64')- assert.equal(validated.S.package.identity, 'stable.app')- assert.equal(journey.S.package, undefined, 'validation must not mutate the signed input')- const direct = structuredClone(journey)- direct.route = 'direct'; delete direct.B- validateJourney(direct, 'darwin', 'arm64')- const cases = [- [j => { delete j.T }, /binding/],- [j => { delete j.S.manifest.receiverProtocol }, /receiver/],- [j => { j.T.manifest.request.version = j.S.manifest.request.version; j.T.manifest.request.releaseTag = 'v1.0.0'; j.T.manifest.packages[0].version = j.S.manifest.request.version }, /native version/],- [j => { j.B.manifest.request.identity.extra = 'different' }, /identity/],- [j => { j.S.head.buildId = 'e'.repeat(32) }, /binding/],- [j => { j.S.manifest.request.publicBase = 'https://another.example' }, /authority/],- [j => { j.S.manifest.packages[0].artifact.key = 'releases/../foreign.zip' }, /object key/],- [j => { j.S.manifest.packages[0].teamId = '0123456789' }, /signing/],- [j => { j.home = 'invented' }, /scenario/],- ]- for (const [mutate, error] of cases) {- const bad = structuredClone(journey); mutate(bad)- assert.throws(() => validateJourney(bad, 'darwin', 'arm64'), error)- }- assert.throws(() => validateJourney(journey, 'win32', 'arm64'), /platform/)- // Platform is manifest data here, not a mocked native host.- const windows = structuredClone(journey)- windows.platform = 'win32'- for (const name of ['A', 'B', 'S', 'T']) {- const side = windows[name]- const request = side.manifest.request- const pkg = side.manifest.packages[0]- request.identity.msixAppIdWithOrg = pkg.identity- request.windowsVersion = request.releaseTag ? `${request.version}.0` : `0.0.${request.sequence}.0`- pkg.version = request.windowsVersion- pkg.platform = 'win32'; pkg.publisher = 'CN=Test fixture'- pkg.artifact.key = pkg.artifact.key.replace('.zip', '.msixbundle')- pkg.feed.key = pkg.feed.key.replace('stable-mac.yml', 'update.appinstaller')- }- validateJourney(windows, 'win32', 'arm64')- windows.T.manifest.packages[0].publisher = 'CN=Foreign fixture'- assert.throws(() => validateJourney(windows, 'win32', 'arm64'), /signing/)- const body = Buffer.from(JSON.stringify(journey.A.manifest))- verifyManifest(body, journey.A)- verifyBytes(body, { size: body.length, sha256: digest(body) })- assert.throws(() => verifyManifest(Buffer.from('{}'), journey.A), /manifest/)- assert.throws(() => verifyBytes(body, { size: body.length + 1, sha256: digest(body) }), /hash/)-})--test('staging uses real HTTP bytes, refuses tampering and never emits native receipts', async () => {- const { stageJourney } = await import('./channel-retirement-inputs.mjs')- let objects = new Map()- const server = http.createServer((req, res) => {- const bytes = objects.get(req.url)- res.writeHead(bytes ? 200 : 404); res.end(bytes || 'missing')- })- await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'retirement-inputs-'))- try {- const fixtureData = fixture(`http://127.0.0.1:${server.address().port}/disposable`)- objects = fixtureData.objects- const bytes = Buffer.from(JSON.stringify(fixtureData.journey))- const manifest = path.join(root, 'input.json'); await fs.writeFile(manifest, bytes)- const options = { manifest, manifestSha256: digest(bytes), platform: 'darwin', arch: 'arm64', out: path.join(root, 'staged') }- const staged = JSON.parse(await fs.readFile(await stageJourney(options)))- for (const name of ['A', 'B', 'S', 'T']) {- const downloaded = await fs.readFile(staged[name].artifactPath)- assert.equal(digest(downloaded), staged[name].package.artifact.sha256)- }- await assert.rejects(fs.access(path.join(options.out, 'receipt.json')), /ENOENT/)- await assert.rejects(stageJourney(options), /EEXIST/)- await assert.rejects(stageJourney({ ...options, manifestSha256: '0'.repeat(64) }), /Journey SHA256/)- const key = '/disposable/' + fixtureData.journey.S.head.manifestKey- objects.set(key, Buffer.from('{}'))- await assert.rejects(stageJourney({ ...options, out: path.join(root, 'tampered') }), /SHA256 mismatch/)- await assert.rejects(fs.access(path.join(root, 'tampered', 'journey-inputs.json')), /ENOENT/)- } finally {- await new Promise(resolve => server.close(resolve))- await fs.rm(root, { recursive: true, force: true })- }-})--test('journal observations require exact pinned receiver and authenticated readiness', async () => {- const { completedJournal } = await import('./channel-retirement-macos.mjs')- const root = await fs.mkdtemp(path.join(os.tmpdir(), 'retirement-journal-'))- const id = 'a'.repeat(32), token = 'b'.repeat(64), sha256 = 'c'.repeat(64)- const dir = path.join(root, id), file = path.join(dir, 'journal.json')- const request = { id, token, source: { appPath: '/preview', removalRoots: ['/preview'] },- destination: { appPath: '/stable', commit: 'd'.repeat(40) }, destinationManifestSha256: sha256 }- const requestDigest = digest(JSON.stringify(request))- const ready = { id, requestDigest, pid: 123, executable: '/stable/bin', home: '/home/fixture',- commit: request.destination.commit, connectionId: 'local', profile: 'default' }- const record = { request, requestDigest, stage: 'complete', state: { selectedHome: ready.home },- ready: { ...ready, mac: createHmac('sha256', Buffer.from(token, 'hex')).update(JSON.stringify(ready)).digest('hex') } }- try {- await fs.mkdir(dir)- await fs.mkdir(path.join(root, 'e'.repeat(32)))- await fs.writeFile(file, JSON.stringify(record))- assert.equal(completedJournal(root, '/preview', '/stable', sha256).pid, 123)- assert.throws(() => completedJournal(root, '/preview', '/stable', '0'.repeat(64)), /Assertion/)- record.ready.pid++- await fs.writeFile(file, JSON.stringify(record))- assert.throws(() => completedJournal(root, '/preview', '/stable', sha256), /Assertion/)- } finally { await fs.rm(root, { recursive: true, force: true }) }-})diff --git a/tests/install/e2e-assets/channel-retirement-window.mjs b/tests/install/e2e-assets/channel-retirement-window.mjsdeleted file mode 100644index 9637b1edc8b..00000000000--- a/tests/install/e2e-assets/channel-retirement-window.mjs+++ /dev/null@@ -1,66 +0,0 @@-// 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.ps1deleted file mode 100644index a9900b448fd..00000000000--- a/tests/install/e2e-assets/channel-retirement-windows-native.ps1+++ /dev/null@@ -1,113 +0,0 @@-# 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.mjsdeleted file mode 100644index f1824bc58d8..00000000000--- a/tests/install/e2e-assets/channel-retirement-windows-observations.mjs+++ /dev/null@@ -1,30 +0,0 @@-// 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/macos-bundled-e2e.sh b/tests/install/macos-bundled-e2e.shindex 0295aef9fe6..3d3436cea46 100644--- a/tests/install/macos-bundled-e2e.sh+++ b/tests/install/macos-bundled-e2e.sh@@ -39,7 +39,6 @@set -euo pipefailPHASE="all"-RETIREMENT_WORK=""MANIFEST_URL=""ARCH="arm64"UPDATE_WATCH_TIMEOUT_MS=900000@@ -52,9 +51,6 @@ while [ "$#" -gt 0 ]; do--manifest-url)[ "$#" -ge 2 ] || { echo 'error: --manifest-url needs a value' >&2; exit 1; }MANIFEST_URL="$2"; shift 2 ;;- --retirement-work)- [ "$#" -ge 2 ] || { echo 'error: --retirement-work needs a value' >&2; exit 1; }- RETIREMENT_WORK="$2"; shift 2 ;;--arch)[ "$#" -ge 2 ] || { echo 'error: --arch needs a value' >&2; exit 1; }ARCH="$2"; shift 2 ;;@@ -76,12 +72,6 @@ NODE_BIN="${HERMES_E2E_NODE:-$(command -v node)}"export HERMES_E2E_NODE="$NODE_BIN"# OS activation does not inherit the ordinary journey's sandbox overrides.-# Retirement uses the unused natural home of this disposable hosted account.-if [ "$PHASE" = retirement ]; then- [ -n "$RETIREMENT_WORK" ] || { echo 'error: retirement requires controller work directory' >&2; exit 1; }- exec "$NODE_BIN" "$REPO_ROOT/tests/install/channel-retirement-e2e.mjs" --work "$RETIREMENT_WORK" --arch "$ARCH"-fi-WORK_ROOT="${HERMES_E2E_WORKROOT:-${RUNNER_TEMP:-${TMPDIR:-/tmp}}/hermes-bundled-e2e}"LOG_DIR="${HERMES_E2E_LOG_DIR:-$WORK_ROOT/logs}"HOME_SANDBOX="$WORK_ROOT/home"diff --git a/tests/scripts/test_channel_retirement_controller.py b/tests/scripts/test_channel_retirement_controller.pydeleted file mode 100644index 688671550d2..00000000000--- a/tests/scripts/test_channel_retirement_controller.py+++ /dev/null@@ -1,123 +0,0 @@-"""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()