The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into ethie/pm-clean
etherneta6ae6ace518f
diff --cc .github/workflows/js-tests.ymlindex fb753d29922,89da9e8c60f..be298107bd4--- a/.github/workflows/js-tests.yml+++ b/.github/workflows/js-tests.yml@@@ -18,19 -18,33 +18,22 @@@ jobstimeout-minutes: 30steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ - name: Set up the locked JS build toolchain+ id: node+ uses: ./.github/actions/setup-pmwith:- node-version: 26- cache: npm+ # Desktop checks also run Python payload and icon build helpers.+ toolchain: all- - name: Install zsh- # The desktop SSH watchdog tests run their probe through a real zsh- # login shell (#111949). The ubuntu image ships no zsh and the tests- # skip without it, so install it here or those legs never run on CI.- #- # The desktop portal-session live test drives real Electron windows- # (electron/portal-session-live.test.ts) and skips without a display,- # so give the runner a virtual one the same way the Playwright lane does.+ - name: Install zsh and a virtual display for Electronif: runner.os == 'Linux'- run: sudo apt-get install -y zsh+ run: |+ sudo apt-get install -y zsh xvfb \+ libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 \+ xdg-utils libatspi2.0-0 libdrm2 libgbm1 libasound2t64- - name: grab npm 12- run: |- # No-op once the bundled npm is already 12.x — saves ~5-15s/job and- # keeps the installed major aligned with the npm12 cache-key tag.- npm --version | grep -q '^12\.' || npm i -g npm@12-- # The ``cache: npm`` option of ``setup-node`` caches only the ~/.npm- # tarball cache. The job then extracts the full workspace node_modules+ # setup-pm caches npm downloads, not the installed workspace tree.+ # The job then extracts the full workspace node_modules# again and runs the postinstalls again, which includes the Electron# binary fetch. This caches the installed tree itself, keyed on the# lockfile, and skips ``npm ci`` on an exact hit. There are nodiff --cc agent/model_metadata.pyindex 165a2d15da6,26419717ad7..39c21258c98--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@@ -1044,9 -1103,14 +1054,15 @@@ def _load_context_cache_document() -> dif not path.exists():return {}try:- with open(path, encoding="utf-8") as f:+ with open(path, encoding="utf-8-sig") as f:- data = yaml.safe_load(f) or {}+ data = yaml.safe_load(f)+ if not isinstance(data, dict):+ return {}+ for section in ("context_lengths", "bedrock_confirmed_v1"):+ if not isinstance(data.get(section), dict):+ data[section] = {}+ return data+ return data.get("context_lengths") or {}except Exception as e:logger.debug("Failed to load context length cache: %s", e)return {}diff --cc apps/desktop/electron/backend-env.tsindex 3baf3af4e94,f3fd8c81975..0c0bec9a069--- a/apps/desktop/electron/backend-env.ts+++ b/apps/desktop/electron/backend-env.ts@@@ -1,9 -1,9 +1,10 @@@+ import os from 'node:os'import path from 'node:path'-// Match the POSIX fallback surface used by the Python terminal environment.-// macOS apps launched from Finder/Dock often inherit only /usr/bin:/bin:/usr/sbin:/sbin,-// which misses Apple Silicon Homebrew and user-installed CLI tools such as codex.+// macOS apps launched from Finder/Dock inherit only /usr/bin:/bin:/usr/sbin:/sbin,+// which misses Homebrew and user-installed CLI tools (codex, git credential+// helpers). Hermes' own managed tools need no PATH help — the backend composes+// their environment in-process via pm — but user tools on PATH do.const POSIX_SANE_PATH_ENTRIES = Object.freeze(['/opt/homebrew/bin','/opt/homebrew/sbin',@@@ -55,7 -61,53 +56,10 @@@ function appendUniquePathEntries(entriereturn ordered.join(delimiter)}- function normalizeHermesHomeRoot(hermesHome, { pathModule = pathModuleForPlatform(process.platform) }: any = {}) {-/**- * Hermes-managed Node.js directories, in preferred lookup order.- *- * There are two on-disk layouts. `scripts/install.ps1` unpacks portable Node- * straight into `%LOCALAPPDATA%\hermes\node` (node.exe at the root, no `bin\`);- * `scripts/install.sh` and the node-bootstrap helper use the POSIX- * `$HERMES_HOME/node/bin`. Emit BOTH on every platform so mixed and migrated- * installs resolve, leading with the layout native to the current platform.- *- * This is the single source of truth for the ordering rule on the Node side —- * `main.ts` imports it rather than keeping its own copy. Mirrors- * `iter_hermes_node_dirs()` in hermes_constants.py, which the Electron main- * process cannot import.- */-function hermesManagedNodePathEntries(- hermesHome,- { platform = process.platform, pathModule = pathModuleForPlatform(platform) }: any = {}-) {- if (!hermesHome) {- return []- }-- const root = pathModule.join(hermesHome, 'node')- const bin = pathModule.join(root, 'bin')-- return platform === 'win32' ? [root, bin] : [bin, root]-}--function buildDesktopBackendPath({- hermesHome,- venvRoot,- currentPath = '',- platform = process.platform,- pathModule = pathModuleForPlatform(platform)-}: any = {}) {- const delimiter = delimiterForPlatform(platform)- const hermesNodeDirs = hermesManagedNodePathEntries(hermesHome, { platform, pathModule })- const venvBin = venvRoot ? pathModule.join(venvRoot, platform === 'win32' ? 'Scripts' : 'bin') : null- const saneEntries = platform === 'win32' ? [] : POSIX_SANE_PATH_ENTRIES-- return appendUniquePathEntries([hermesNodeDirs, venvBin, currentPath, saneEntries], { delimiter })-}-+ function normalizeHermesHomeRoot(+ hermesHome,+ { pathModule = pathModuleForPlatform(process.platform), homedir = os.homedir() }: any = {}+ ) {if (!hermesHome) {return hermesHome}diff --cc apps/desktop/electron/main.tsindex f677193ad37,d6ff99058cb..700cb591473--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -30,15 -28,24 +30,24 @@@ importshell,systemPreferences} from 'electron'+import type { Session } from 'electron'-import { classifyActiveRuntime } from './active-runtime-state'+import { type ActiveRuntimeState, classifyActiveRuntime } from './active-runtime-state'- import { destroyKeepaliveAgents, htmlResponseError, jsonAgentFor, withRetry } from './api-transport'+ import {+ destroyKeepaliveAgents,+ downloadAgentFor,+ htmlResponseError,+ httpStatusError,+ jsonAgentFor,+ readJsonErrorBody,+ readStatusCode,+ withRetry+ } from './api-transport'import { appIconCandidates, resolveAppIcon } from './app-icon'-import {- stopBackendChild as stopBackendChildImpl,- stopBackendTreesForUpdate,- waitForBackendExit as waitForBackendExitImpl-} from './backend-child'+import { stageAppInstallerFile } from './app-installer-file'+import { appVersionInfo, type AppVersionInfo, assertSourceUpdateChannel, packagedReleaseChannel } from './app-version'+import { runAppInstallerChecker } from './appinstaller-checker'+import { stopBackendChild as stopBackendChildImpl, waitForBackendExit } from './backend-child'import {type BackendOutputTail,claimDecision,@@@ -98,9 -95,9 +107,10 @@@ importbuildBrowserWindowUrl} from './browser-windows'import { detectBundleSkew } from './bundle-skew'-import { detectBundleSwap } from './bundle-swap'+import { detectBundleSwap, readBundleSwapStamp } from './bundle-swap'import { registerChatOnboardingWindow } from './chat-onboarding-window'+ import { discoverWithTeamFallback } from './cloud-discovery'+import { provisionCliLinks } from './cli-provision'import { installCommandScreenshot } from './command-screenshot'import { writeComposerPaste } from './composer-paste'import { applyConnectionChange, teardownSshState } from './connection-apply'@@@ -111,12 -108,10 +121,10 @@@ importbuildGatewayWsUrlWithTicket,connectionScopeKey,cookiesHaveLiveSession,- cookiesHavePrivyAccessToken,- cookiesHavePrivySession,cookiesHaveSession,+ gatewayTicketFailure,gatewayWsUrlIpcResult,hostLabelFromBaseUrl,- isGatewayAuthRejection,localProfileEntry,modeIsRemoteLike,normalizeRemoteBaseUrl,@@@ -216,25 -203,27 +224,31 @@@ import} from './find-in-page'import { createFirstRunSetupGate } from './first-run-setup-gate'import { registerFsIpc } from './fs-ipc'+import type {+ GatewayFileSaveContext,+ GatewayFileSaveDeps,+ GatewayFileSaveResult,+ GatewaySaveDialogOptions,+ GatewaySaveDialogResult+} from './gateway-file-download'import {- filenameFromContentDisposition,- fsPumpDeps,gatewayFilePath,gatewayFileRequestPaths,- isNotFoundError,- parseDataUrlToBuffer,- pumpStreamToFile,resolveGatewayFileBackend,- writeBufferToFile+ saveGatewayDownload} from './gateway-file-download'-import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'+import { downloadViaOauthSessionToFile, downloadViaTokenToFile } from './gateway-file-download-transport'+import { stopGatewayBeforeUpdate } from './gateway-stop-before-update'+import { resolveGatewayVersion } from './gateway-version'import { probeGatewayWebSocket } from './gateway-ws-probe'import { registerGitIpc } from './git-ipc'- import { envTokenRejected, githubApiHeaders, githubTokenFromEnv } from './github-api-auth'+ import {+ describeGitHubCredentialSource,+ forgetGhCliToken,+ githubApiHeaders,+ githubTokenRejected,+ resolveGitHubCredential+ } from './github-api-auth'import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'import { readAndConsumeHandoffResult } from './handoff-result'import {@@@ -2758,10 -2945,48 +2765,48 @@@ function makeDashboardReadyFile()// resolveGitBinary — locate git.exe on Windows. A fresh installer-driven// install only has PortableGit under %LOCALAPPDATA%\hermes\git (never on// PATH), so a bare spawn('git') ENOENTs and self-update checks fail with-// "Couldn't check for updates". Mirror findGitBash: PortableGit first, then-// standard Git-for-Windows locations, then PATH. Cached after first probe.+// "Couldn't check for updates". PortableGit first, then standard+// Git-for-Windows locations, then PATH. Cached after first probe.let _gitBinaryCache = null+ // A binary can exist on disk and still be unlaunchable — on macOS an+ // Intel-only build ahead on PATH (e.g. a pre-Rosetta-removal Homebrew)+ // fails at spawn time with errno -86 (EBADARCH), which callers then report+ // as an update-server/network problem. Probing `git --version` before+ // committing to a candidate skips such entries; the existence-only+ // fallback keeps behaviour unchanged where the probe itself cannot run.+ function binaryRuns(candidate) {+ try {+ execFileSync(candidate, ['--version'], {+ stdio: 'ignore',+ timeout: 5000,+ windowsHide: true+ })++ return true+ } catch {+ return false+ }+ }++ function findPathCandidates(command) {+ const pathEntries = String(process.env.PATH || '')+ .split(path.delimiter)+ .filter(Boolean)++ const candidates = []++ for (const entry of pathEntries) {+ const candidate = path.join(entry, command)++ if (fileExists(candidate)) {+ candidates.push(candidate)+ }+ }++ return candidates+ }+function resolveGitBinary() {if (_gitBinaryCache) {return _gitBinaryCache@@@ -2949,8 -3197,17 +3017,17 @@@ function runGit(args, options: any = {}stderr += textoptions.onLine?.('stderr', text)})- child.once('error', reject)+ // A spawn-level failure means git itself never ran (missing, not+ // executable, wrong CPU architecture) — a local problem, not a network one.+ child.once('error', error => {+ const local = describeGitSpawnFailure(error, gitBinary)++ reject(local ? Object.assign(new Error(local), { kind: GIT_UNUSABLE, cause: error }) : error)+ })+ // 'close', not 'exit': exit can fire before the stdio pipes drain, and a+ // resolved-early `remote get-url` came back as "" often enough to route+ // passive checks down the wrong remote path.- child.once('close', code => resolve({ code, stdout, stderr }))+ child.once('close', (code: number): void => resolve({ code, stdout, stderr }))})}@@@ -16842,11 -17565,11 +16617,11 @@@ const terminalIpc = registerTerminalIpcconst disposeTerminalSession = terminalIpc.disposeTerminalSession-ipcMain.handle('hermes:updates:check', async (_event, opts) =>- checkUpdates({ force: Boolean(opts?.force) }).catch(error => ({+ipcMain.handle('hermes:updates:check', async (_event: Electron.IpcMainInvokeEvent, opts?: { force?: boolean }): Promise<UpdaterStatusWire> =>- checkUpdates({ force: Boolean(opts?.force) }).catch((error: Error): UpdaterStatusWire => ({++ checkUpdates({ force: Boolean(opts?.force) }).catch((error: Error & { kind?: string }): UpdaterStatusWire => ({supported: true,branch: readDesktopUpdateConfig().branch,- error: 'check-failed',+ error: error?.kind === GIT_UNUSABLE ? GIT_UNUSABLE : 'check-failed',message: error?.message || String(error),fetchedAt: Date.now()}))diff --cc apps/desktop/scripts/bundle-electron-main.mjsindex 04735abb963,23f23d261c5..b72b11b9e8e--- a/apps/desktop/scripts/bundle-electron-main.mjs+++ b/apps/desktop/scripts/bundle-electron-main.mjs@@@ -1,82 -1,87 +1,90 @@@#!/usr/bin/env node-// bundle-electron-main.mjs — bundles electron/main.ts and electron/preload.ts-// into self-contained js files in dist/ so the packaged app doesn't need-// node_modules/ or tsx at runtime.-//-// Output:-// dist/electron-main.mjs (MJS bundle — entry point for packaged app)-// dist/electron-preload.js (CJS bundle — loaded via BrowserWindow preload)-// dist/preview-guest-preload.js (CJS bundle — preview <webview> guest preload)-//-// `electron` and `node-pty` are external (provided by the runtime / staged-// separately via stage-native-deps).-import { build } from 'esbuild'-import { resolve, dirname } from 'node:path'-import { fileURLToPath } from 'node:url'-import { mkdirSync } from 'node:fs'-import { buildCommandScreenshotMonitor } from './build-command-screenshot-monitor.mjs'+import { execFileSync } from 'node:child_process'+import { mkdirSync, readFileSync } from 'node:fs'+import { join, resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { parseArgs } from 'node:util'+import { isMain, workspaceTool } from '../../../scripts/build/frontend-common.mjs'+import { environmentDefaultsBanner } from './bundle-env.mjs'-const here = dirname(fileURLToPath(import.meta.url))-const root = resolve(here, '..')-const distDir = resolve(root, 'dist')-mkdirSync(distDir, { recursive: true })-// Stage for both --dev and release bundles; non-mac hosts skip this helper.-buildCommandScreenshotMonitor({ distDir })+const repoRoot = resolve(import.meta.dirname, '../../..')-const mainEntry = resolve(root, 'electron/entry.ts')-const mainOut = resolve(distDir, 'electron-main.mjs')-const preloadEntry = resolve(root, 'electron/preload.ts')-const preloadOut = resolve(distDir, 'electron-preload.js')+// Evaluate the one identity module in a fresh process. Its CJS cache and the+// caller's environment must not carry a previous variant into this artifact.+function productIdentity(source, stamp) {+ const variant = stamp.updateMechanism === 'microsoft-store' ? 'store'+ : stamp.payload === 'bootstrap' ? '' : stamp.payload+ if (!['', 'bundled', 'light', 'store'].includes(variant)) {+ throw new Error(`Invalid desktop stamp payload: ${stamp.payload}`)+ }+ return execFileSync(process.execPath, ['-e', 'console.log(JSON.stringify(require(process.argv[1])))',+ join(source, 'apps/desktop/product-identity.cjs')], {+ env: { ...process.env, HERMES_DESKTOP_VARIANT: variant, HERMES_PAYLOAD_TAG: stamp.tag || '',+ // Commit builds stamp source='commit-build'; the display name carries+ // the short SHA (see product-identity.cjs). Tagged builds pass ''.+ HERMES_BUILD_COMMIT: stamp.source === 'commit-build' ? (stamp.commit || '') : '' },+ encoding: 'utf8',+ }).trim()+}-const external = ['electron', 'node-pty', 'get-windows', 'fs']-// Production bundles bake packaged=true so unpackaged `electron .` still-// behaves like a packaged build. Dev bundles (`--dev`) leave the env alone-// so HERMES_DESKTOP_DEV_SERVER / source-tree resolution keep working.-const isDev = process.argv.includes('--dev')-const define = isDev- ? {}- : { 'process.env.HERMES_DESKTOP_IS_PACKAGED': JSON.stringify(true) }+/** Bundle main/preload using only the prepared workspace's compiler. */+export async function bundleElectronMain({ source, out, stamp, dev = false }) {+ source = resolve(source)+ out = resolve(out)+ const { build } = await import(pathToFileURL(workspaceTool(source, 'apps/desktop', 'esbuild')).href)+ // Defaults must run before bundled modules resolve paths or onboarding flags.+ // Dev bundles leave the environment alone so source-tree resolution keeps working.+ const envBanner = dev ? '' : environmentDefaultsBanner(process.env.HERMES_BUNDLE_ENV_JSON || '{}')+ const define = {}+ if (!dev) {+ if (!stamp) throw new Error('A prepared install stamp is required')+ const raw = readFileSync(stamp, 'utf8')+ const metadata = JSON.parse(raw)+ define['process.env.HERMES_DESKTOP_IS_PACKAGED'] = JSON.stringify(true)+ define.__HERMES_INSTALL_STAMP__ = raw+ define.__HERMES_PRODUCT_IDENTITY__ = productIdentity(source, metadata)+ }+ mkdirSync(out, { recursive: true })+ const common = {+ absWorkingDir: join(source, 'apps/desktop'),+ bundle: true,+ platform: 'node',+ target: 'node20',+ external: ['electron', 'node-pty', 'get-windows', 'fs'],+ define,+ logLevel: 'info',+ }+ await build({+ ...common,+ entryPoints: [join(source, 'apps/desktop/electron/main.ts')],+ format: 'esm',+ outfile: join(out, 'electron-main.mjs'),+ banner: { js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);" + envBanner },+ })+ await build({+ ...common,+ entryPoints: [join(source, 'apps/desktop/electron/preload.ts')],+ format: 'cjs',+ outfile: join(out, 'electron-preload.js'),+ })++ // Preview-pane <webview> guest preload; main.ts hands this path to the++ // preview webview via will-attach-webview.++ await build({++ ...common,++ entryPoints: [join(source, 'apps/desktop/electron/preview-guest-preload-entry.ts')],++ format: 'cjs',++ outfile: join(out, 'preview-guest-preload.js'),++ })+}-// Bundle main.ts → dist/electron-main.mjs-await build({- entryPoints: [mainEntry],- bundle: true,- platform: 'node',- format: 'esm',- target: 'node20',- outfile: mainOut,- external,- banner: {- js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",- },- define,- logLevel: 'info',-})-console.log(`bundled ${mainOut}${isDev ? ' (dev)' : ''}`)--// Bundle preload.ts → dist/electron-preload.js-await build({- entryPoints: [preloadEntry],- bundle: true,- platform: 'node',- format: 'cjs',- target: 'node20',- outfile: preloadOut,- external,- define,- logLevel: 'info',-})-console.log(`bundled ${preloadOut}${isDev ? ' (dev)' : ''}`)--// Bundle preview-guest-preload-entry.ts → dist/preview-guest-preload.js-// (main.ts hands this path to the preview webview via will-attach-webview)-const guestPreloadEntry = resolve(root, 'electron/preview-guest-preload-entry.ts')-const guestPreloadOut = resolve(distDir, 'preview-guest-preload.js')--await build({- entryPoints: [guestPreloadEntry],- bundle: true,- platform: 'node',- format: 'cjs',- target: 'node20',- outfile: guestPreloadOut,- external,- define,- logLevel: 'info',-})-console.log(`bundled ${guestPreloadOut}${isDev ? ' (dev)' : ''}`)+if (isMain(import.meta.url)) {+ const { values } = parseArgs({ options: {+ source: { type: 'string', default: repoRoot },+ out: { type: 'string' }, stamp: { type: 'string' }, dev: { type: 'boolean' },+ } })+ await bundleElectronMain({+ ...values,+ out: values.out || join(values.source, 'apps/desktop/dist'),+ stamp: values.stamp || join(values.source, 'apps/desktop/build/install-stamp.json'),+ })+}diff --cc apps/desktop/src/api/client.tsindex e8c356a3fce,e82d3274fca..3c55f20fcd9--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@@ -45,22 -50,26 +51,32 @@@ export class HermesGateway extends Json// REST handlers accept profile reuse the primary dashboard via ?profile=;// unscoped handlers retain a profile backend. Remote overrides still route to// their owning backend. Null → primary, so single-profile users are unaffected.-let _apiProfile: null | string = null+interface ApiRequestScope {+ profile: string | null+ connectionId: string | null+}++// This is the request authority, not a second copy in a presentation store.+export const $apiRequestScope: MapStore<ApiRequestScope> = map<ApiRequestScope>({ profile: null, connectionId: null })export function setApiRequestProfile(profile: null | string): void {- _apiProfile = profile || null+ $apiRequestScope.setKey('profile', profile || null)}- export function profileScoped(profile?: null | string): { profile?: string } {+ // An explicit scope (string or object, not `undefined`/`null`) is a user+ // pointing a scope selector (Settings "Applies to", Capabilities, Messaging)+ // at another profile — a visible action whose cold dial may take the pool's+ // reserved foreground slot (#111651). The ambient path and the deliberate+ // `null` → primary path stay untagged (main's background default) so+ // hydration cannot consume that slot. The tag rides on the scope helper itself+ // so no api/ helper can carry a scope without it.+ export function profileScoped(profile?: null | string): { priority?: 'foreground'; profile?: string } {- const selected = profile === undefined ? _apiProfile : profile+ const selected = profile === undefined ? $apiRequestScope.get().profile : profile- return selected ? { profile: selected } : {}+ return {+ ...(selected ? { profile: selected } : {}),+ ...(profile == null ? {} : { priority: 'foreground' as const })+ }}/** Profile that profile-scoped REST/WS calls should target (null → primary).diff --cc apps/desktop/src/app/chat/index.tsxindex 41ec93a6720,ca116f23c35..34fa97724c1--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@@ -761,36 -759,22 +763,24 @@@ const ChatViewContent = memo(function Cdata-slot="composer-bounds"{...dropHandlers}>- <Thread- clampToComposer={showChatBar}- cwd={currentCwd}- gateway={gateway}- intro={showIntro ? { personality: introPersonality, seed: introSeed } : undefined}- loading={threadLoading}- onBranchInNewChat={onBranchInNewChat}- onCancel={haltRun}- onDismissError={onDismissError}- onRestoreToMessage={onRestoreToMessage}- scrollProfile={modelOptionsProfile || activeGatewayProfile}- sessionId={activeSessionId}- sessionKey={threadKey}- />+ {!guideOpening && (+ <Thread+ clampToComposer={showChatBar}+ cwd={currentCwd}+ gateway={gateway}+ intro={showIntro ? { personality: introPersonality, seed: introSeed } : undefined}+ loading={threadLoading}+ onBranchInNewChat={onBranchInNewChat}+ onCancel={haltRun}+ onDismissError={onDismissError}+ onRestoreToMessage={onRestoreToMessage}+ scrollProfile={modelOptionsProfile || activeGatewayProfile}+ sessionId={activeSessionId}+ sessionKey={threadKey}+ />+ )}{resumeExhausted && routedSessionId && (- <div className="absolute inset-0 z-10 grid place-items-center bg-(--ui-chat-surface-background) px-8 py-10">- <ErrorState- className="max-w-sm"- description={t.desktop.resumeStrandedBody}- title={t.desktop.resumeStrandedTitle}- >- <div className="grid justify-items-center">- <Button onClick={() => onRetryResume(routedSessionId)} size="sm" variant="outline">- {t.desktop.resumeRetry}- </Button>- </div>- </ErrorState>- </div>+ <ResumeExhaustedOverlay onRetryResume={onRetryResume} sessionId={routedSessionId} />)}{showChatBar && <ScrollToBottomButton sessionId={activeSessionId} />}{/* Vibe hearts rise from the composer only when no pet is out (elsediff --cc apps/desktop/src/app/settings/gateway-settings.test.tsxindex 3a4d0a10fd4,87811b30cc3..00806265209--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx@@@ -59,182 -57,86 +59,234 @@@ afterEach(() =>})describe('GatewaySettings', () => {+ it('releases a pending save after a late probe invalidates its response', async () => {+ const saved = { ...localConnection, mode: 'remote', remoteUrl: 'https://a.example', remoteTokenSet: true }+ getConnectionConfig.mockResolvedValue(saved)+ const pendingSave = deferred<typeof saved>()+ const pendingProbe = deferred<{ reachable: boolean; authMode: string; providers: never[] }>()+ saveConnectionConfig.mockReturnValueOnce(pendingSave.promise)+ const probeConnectionConfig = vi.fn().mockReturnValue(pendingProbe.promise)++ Object.assign(window.hermesDesktop, { probeConnectionConfig })+ render(<GatewaySettings />)+ const saveButton = (await screen.findByRole('button', { name: 'Save for next restart' })) as HTMLButtonElement+ await waitFor(() => expect(probeConnectionConfig).toHaveBeenCalledWith('https://a.example'))+ fireEvent.click(saveButton)+ expect(saveConnectionConfig).toHaveBeenCalledExactlyOnceWith({+ mode: 'remote',+ remoteUrl: 'https://a.example',+ remoteAuthMode: 'token',+ remoteToken: undefined+ })+ expect(saveButton.disabled).toBe(true)+ await act(async (): Promise<void> => pendingProbe.resolve({ reachable: true, authMode: 'oauth', providers: [] }))+ await act(async (): Promise<void> => pendingSave.resolve(saved))+ expect(saveButton.disabled).toBe(false)+ expect(screen.getByRole('button', { name: /Sign in with/ })).toBeTruthy()+ expect(screen.queryByPlaceholderText('Existing token saved')).toBeNull()+ })++ it('pre-saves OAuth before login and applies the resolved auth mode without requiring a test', async () => {+ getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'remote', remoteUrl: 'https://login.example' })+ const pendingSave = deferred<void>()+ saveConnectionConfig.mockReturnValueOnce(pendingSave.promise)+ const oauthLoginConnectionConfig = vi.fn().mockResolvedValue({ connected: true })+ const applyConnectionConfig = vi.fn().mockResolvedValue(localConnection)+ const testConnectionConfig = vi.fn()+ Object.assign(window.hermesDesktop, {+ oauthLoginConnectionConfig,+ applyConnectionConfig,+ testConnectionConfig,+ probeConnectionConfig: vi.fn().mockResolvedValue({+ reachable: true,+ authMode: 'oauth',+ providers: [{ name: 'password', displayName: 'Username & Password', supportsPassword: true }]+ })+ })+ render(<GatewaySettings />)+ fireEvent.click(await screen.findByRole('button', { name: 'Sign in' }))+ expect(saveConnectionConfig).toHaveBeenCalledExactlyOnceWith({+ mode: 'remote',+ remoteAuthMode: 'oauth',+ remoteUrl: 'https://login.example'+ })+ expect(oauthLoginConnectionConfig).not.toHaveBeenCalled()+ await act(async (): Promise<void> => pendingSave.resolve())+ await screen.findByText('Signed in')+ expect(oauthLoginConnectionConfig).toHaveBeenCalledExactlyOnceWith('https://login.example')+ fireEvent.click(screen.getByRole('button', { name: 'Save and reconnect' }))+ await waitFor(() =>+ expect(applyConnectionConfig).toHaveBeenCalledExactlyOnceWith({+ mode: 'remote',+ remoteAuthMode: 'oauth',+ remoteUrl: 'https://login.example',+ remoteToken: undefined+ })+ )+ expect(testConnectionConfig).not.toHaveBeenCalled()+ })++ it('keeps a saved token when blank and requires consent before replacing it in plaintext', async () => {+ const saved = {+ ...localConnection,+ mode: 'remote',+ remoteUrl: 'https://a.example',+ remoteTokenSet: true,+ remoteTokenPreview: 'saved-preview',+ secureTokenStorage: false,+ remoteTokenPlainText: true+ }++ getConnectionConfig.mockResolvedValue(saved)+ saveConnectionConfig.mockResolvedValue(saved)+ const pendingSave = deferred<typeof saved>()+ saveConnectionConfig.mockReturnValueOnce(pendingSave.promise)+ Object.assign(window.hermesDesktop, {+ probeConnectionConfig: vi.fn().mockResolvedValue({ reachable: true, authMode: 'token', providers: [] })+ })+ render(<GatewaySettings />)+ await screen.findByPlaceholderText('Existing token saved-preview')+ fireEvent.click(screen.getByRole('button', { name: 'Save for next restart' }))+ await waitFor(() =>+ expect(saveConnectionConfig).toHaveBeenCalledExactlyOnceWith({+ mode: 'remote',+ remoteUrl: 'https://a.example',+ remoteAuthMode: 'token',+ remoteToken: undefined+ })+ )+ // Flush the save's reset and probe effects before acquiring the replacement field.+ await act(async (): Promise<void> => pendingSave.resolve(saved))+ const tokenInput = await screen.findByPlaceholderText('Existing token saved-preview')+ expect(tokenInput.isConnected, 'saved credential control must survive the refresh probe').toBe(true)+ fireEvent.change(tokenInput, { target: { value: 'replacement' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save for next restart' }))+ await screen.findByText('Store the gateway token in plain text?')+ expect(saveConnectionConfig).toHaveBeenCalledTimes(1)+ fireEvent.click(screen.getByRole('button', { name: 'Save as plain text' }))+ await waitFor(() =>+ expect(saveConnectionConfig).toHaveBeenLastCalledWith({+ mode: 'remote',+ remoteUrl: 'https://a.example',+ remoteAuthMode: 'token',+ remoteToken: 'replacement',+ allowPlainTextToken: true+ })+ )+ })++ it('discards an old token test while saving the current credential-ready payload', async () => {+ getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'remote', remoteUrl: 'https://a.example' })+ const probeConnectionConfig = vi.fn().mockResolvedValue({ reachable: true, authMode: 'token', providers: [] })+ const pendingTest = deferred<{ ok: boolean; baseUrl: string }>()+ const testConnectionConfig = vi.fn().mockReturnValue(pendingTest.promise)++ Object.assign(window.hermesDesktop, { probeConnectionConfig, testConnectionConfig })+ render(<GatewaySettings />)+ const token = await screen.findByPlaceholderText('Paste session token')+ fireEvent.change(token, { target: { value: 'old-token' } })+ fireEvent.click(screen.getByRole('button', { name: 'Test remote' }))+ expect(testConnectionConfig).toHaveBeenCalledWith({+ mode: 'remote',+ remoteUrl: 'https://a.example',+ remoteAuthMode: 'token',+ remoteToken: 'old-token'+ })+ fireEvent.change(token, { target: { value: 'new-token' } })+ await act(async (): Promise<void> => pendingTest.resolve({ ok: true, baseUrl: 'https://a.example' }))+ expect(screen.queryByText('Connected to https://a.example')).toBeNull()+ fireEvent.click(screen.getByRole('button', { name: 'Save for next restart' }))+ await waitFor(() =>+ expect(saveConnectionConfig).toHaveBeenCalledWith(+ expect.objectContaining({+ mode: 'remote',+ remoteUrl: 'https://a.example',+ remoteAuthMode: 'token',+ remoteToken: 'new-token'+ })+ )+ )+ })-- it('keeps saved Cloud instances usable without discovery and marks the live source, not the default', async () => {- getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud', remoteUrl: 'https://a.example' })- registry.value = {- connections: [- { id: 'saved-a', kind: 'cloud', label: 'Research', url: 'https://a.example', authMode: 'oauth' },- { id: 'saved-b', kind: 'cloud', label: 'Writing', url: 'https://b.example', authMode: 'oauth' }- ]+ it('reconnects a moved agent under its new team without replacing its saved identity or changing another default', async () => {+ const saved = {+ id: 'saved-b',+ kind: 'cloud',+ label: 'My agent',+ url: 'https://moved.example',+ authMode: 'oauth',+ org: 'old-team'}- const agentSignIn = vi.fn()- const applyConnectionConfig = vi.fn()+ registry.value = { connections: [saved] }+ getConnectionConfig.mockResolvedValue({+ ...localConnection,+ mode: 'cloud',+ cloudOrg: 'old-team',+ remoteUrl: 'https://other.example'+ })+ const calls: string[] = []+ const oauthLogoutConnectionConfig = vi.fn(async () => {+ calls.push('logout')+ })+ const agentSignIn = vi.fn(async () => {+ calls.push('login')+ return { connected: true }+ })+ const save = vi.fn(async () => {+ calls.push('save')+ })+ const discover = vi.fn().mockResolvedValue({+ needsOrgSelection: true,+ orgs: [{ id: 'new-team', name: 'New team', role: 'OWNER' }]+ })Object.assign(window.hermesDesktop, {- applyConnectionConfig,- cloud: {- status: vi.fn().mockResolvedValue({ signedIn: false }),- agentSignIn- }+ oauthLogoutConnectionConfig,+ connections: { save },+ cloud: { status: vi.fn().mockResolvedValue({ signedIn: true }), discover, agentSignIn }})render(<GatewaySettings embedded />)- const research = await screen.findByText('Research')- const row = research.closest('[data-slot]') ?? research.parentElement!.parentElement!- fireEvent.click(within(row as HTMLElement).getByRole('button', { name: 'Use gateway' }))- await waitFor(() => expect(selectConnection).toHaveBeenCalledWith('saved-a'))- expect(screen.getByText('Active in this window')).toBeTruthy()- expect(agentSignIn).not.toHaveBeenCalled()- expect(applyConnectionConfig).not.toHaveBeenCalled()+ await screen.findByText('New team')+ discover.mockResolvedValue({+ agents: [{ id: 'moved', name: 'Moved agent', dashboardUrl: saved.url }],+ org: { id: 'new-team' }+ })+ fireEvent.click(screen.getByRole('button', { name: 'Select', exact: true }))+ await screen.findByRole('button', { name: 'Use gateway' })+ expect(save).not.toHaveBeenCalled()+ fireEvent.click(screen.getByRole('button', { name: 'Use gateway' }))+ await waitFor(() => expect(selectConnection).toHaveBeenCalledWith(saved.id))+ expect(calls).toEqual(['logout', 'login', 'save'])+ expect(agentSignIn).toHaveBeenCalledWith(saved.url)+ expect(save).toHaveBeenCalledWith({ ...saved, org: 'new-team' })+ expect(saveConnectionConfig).not.toHaveBeenCalled()registry.value = null})+ it('keeps saved Cloud instances usable without discovery and marks the live source, not the default', async () => {- getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud', remoteUrl: 'https://a.example' })- registry.value = {- connections: [- { id: 'saved-a', kind: 'cloud', label: 'Research', url: 'https://a.example', authMode: 'oauth' },- { id: 'saved-b', kind: 'cloud', label: 'Writing', url: 'https://b.example', authMode: 'oauth' }- ]++ getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud', remoteUrl: 'https://a.example' })++ registry.value = {++ connections: [++ { id: 'saved-a', kind: 'cloud', label: 'Research', url: 'https://a.example', authMode: 'oauth' },++ { id: 'saved-b', kind: 'cloud', label: 'Writing', url: 'https://b.example', authMode: 'oauth' }++ ]++ }++ const agentSignIn = vi.fn()++ const applyConnectionConfig = vi.fn()++ Object.assign(window.hermesDesktop, {++ applyConnectionConfig,++ cloud: {++ status: vi.fn().mockResolvedValue({ signedIn: false }),++ agentSignIn+ }- const agentSignIn = vi.fn()- const applyConnectionConfig = vi.fn()- Object.assign(window.hermesDesktop, {- applyConnectionConfig,- cloud: {- status: vi.fn().mockResolvedValue({ signedIn: false }),- agentSignIn- }- })- render(<GatewaySettings embedded />)- const research = await screen.findByText('Research')- const row = research.closest('[data-slot]') ?? research.parentElement!.parentElement!- fireEvent.click(within(row as HTMLElement).getByRole('button', { name: 'Use gateway' }))- await waitFor(() => expect(selectConnection).toHaveBeenCalledWith('saved-a'))- expect(screen.getByText('Active in this window')).toBeTruthy()- expect(agentSignIn).not.toHaveBeenCalled()- expect(applyConnectionConfig).not.toHaveBeenCalled()- registry.value = null+ })++ render(<GatewaySettings embedded />)++ const research = await screen.findByText('Research')++ const row = research.closest('[data-slot]') ?? research.parentElement!.parentElement!++ fireEvent.click(within(row as HTMLElement).getByRole('button', { name: 'Use gateway' }))++ await waitFor(() => expect(selectConnection).toHaveBeenCalledWith('saved-a'))++ expect(screen.getByText('Active in this window')).toBeTruthy()++ expect(agentSignIn).not.toHaveBeenCalled()++ expect(applyConnectionConfig).not.toHaveBeenCalled()++ registry.value = null++})it('authenticates and saves only the chosen discovered instance with its friendly name', async () => {registry.value = nullgetConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud' })diff --cc apps/desktop/src/app/settings/gateway-settings.tsxindex 5409a87c41a,90155bd6596..ab6ce8ca050--- a/apps/desktop/src/app/settings/gateway-settings.tsx+++ b/apps/desktop/src/app/settings/gateway-settings.tsx@@@ -8,7 -6,13 +8,13 @@@ import { ConfirmDialog } from '@/componimport { Input } from '@/components/ui/input'import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'import { Tip } from '@/components/ui/tooltip'- import type { DesktopCloudAgent, DesktopCloudOrg, DesktopConnectionConfigInput } from '@/global'+ import type {- DesktopAuthProvider,+ DesktopCloudAgent,+ DesktopCloudOrg,++ DesktopConnectionConfigInput,+ DesktopConnectionProbeResult,+ DesktopRegistryConnection+ } from '@/global'import { useI18n } from '@/i18n'import { ExternalLink } from '@/lib/external-link'import {diff --cc apps/desktop/src/app/settings/local-models-settings.test.tsxindex a8fe29c86a4,328ba8f891d..87b4a397097--- a/apps/desktop/src/app/settings/local-models-settings.test.tsx+++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx@@@ -34,12 -21,14 +34,16 @@@ vi.mock('@/hermes', () => (getLocalModelsJobs: vi.fn(),getLocalModelsStatus: vi.fn(),getLocalRuntimeJob: vi.fn(),+ // The page imports the profile store (settings-scope chip), whose module+ // body subscribes $activeGatewayProfile → setApiRequestProfile at load.+ getProfiles: vi.fn(async () => ({ profiles: [] })),installLocalRuntime: vi.fn(),listHFRepoFiles: vi.fn(),+ pauseLocalDownload: vi.fn(),quickstartLocalModels: vi.fn(),+ resumeLocalDownload: vi.fn(),searchHFModels: vi.fn(),+ setApiRequestProfile: vi.fn(),sideloadLocalModel: vi.fn()}))diff --cc apps/desktop/src/app/settings/local-models-settings.tsxindex 75034f2d98a,b5ac9ffa005..64ac398bc5e--- a/apps/desktop/src/app/settings/local-models-settings.tsx+++ b/apps/desktop/src/app/settings/local-models-settings.tsx@@@ -55,17 -48,30 +55,18 @@@ importwatchLocalRuntimeJobs} from '@/store/local-runtime-jobs'import { notify, notifyError } from '@/store/notifications'-import type { LocalCatalogModel, LocalHardware, LocalModelsStatus } from '@/types/hermes'+import type { LocalCatalogModel, LocalRuntimeJob } from '@/types/hermes'+import {+ downloadStatusText,+ gbLabel,+ LocalModelDownloadActions,+ LocalModelDownloadProgress,+ ProgressBar+} from './local-model-download-progress'import { ListRow, Pill, SettingsContent, SettingsSection, SettingsSkeleton } from './primitives'+ import { ActiveProfileNote } from './profile-scope'-function ProgressBar({ percent }: { percent: number | undefined }) {- return (- <div className="h-1.5 w-full overflow-hidden rounded-full bg-(--ui-bg-tertiary)">- <div- className="h-full rounded-full bg-primary transition-[width] duration-300"- style={{ width: `${Math.max(2, Math.min(100, percent ?? 2))}%` }}- />- </div>- )-}--function gbLabel(bytes: number | null | undefined): string {- if (!bytes) {- return '—'- }-- return `${(bytes / (1 << 30)).toFixed(1)} GB`-}-// Catalog display order: what runs well leads. Resident (all on GPU)// first, then spilled (works, slower), then doesn't-fit; catalog order// (recommended first) holds within each band.diff --cc apps/desktop/src/app/shell/hooks/use-status-snapshot.tsindex 65aae4b0822,f21df6f7cfc..92082982d85--- a/apps/desktop/src/app/shell/hooks/use-status-snapshot.ts+++ b/apps/desktop/src/app/shell/hooks/use-status-snapshot.ts@@@ -112,18 -106,11 +112,22 @@@ export function useStatusSnapshot}if (statusResult.status === 'fulfilled') {- setStatusSnapshot(statusResult.value)+ const next = statusResult.value+ // Preserve reference identity on a no-op: the 60s tick re-reads a+ // usually-unchanged snapshot, and a fresh object for the same content+ // re-renders every consumer for nothing.+ setStatusSnapshot(previous => (JSON.stringify(previous) === JSON.stringify(next) ? previous : next))+ const warning: boolean = Boolean(statusResult.value.shared_profile_warning)++ // Keep dismissal until the conflict clears. A new overlap can warn again.+ if (warning !== sharedProfileWarning) {+ if (sharedProfileNoticeId) {+ dismissNotification(sharedProfileNoticeId)+ }++ sharedProfileWarning = warning+ sharedProfileNoticeId = warning ? notify({ kind: 'warning', message: warningMessage }) : undefined+ }}} finally {scheduleRefresh()diff --cc apps/desktop/src/components/update-status.test.tsxindex 48fbae31d40,00000000000..09a15ad160fmode 100644,000000..100644--- a/apps/desktop/src/components/update-status.test.tsx+++ b/apps/desktop/src/components/update-status.test.tsx@@@ -1,208 -1,0 +1,208 @@@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import type { DesktopUpdateStatus, DesktopVersionInfo } from '@/global'+import { I18nProvider, type Locale, TRANSLATIONS, type Translations } from '@/i18n'+import { en } from '@/i18n/en'+import type { UpdateApplyState } from '@/store/updates'++import { deriveUpdateStatus, VersionHero } from './update-status'++// VersionHero is the shared About/overlay hero. Its module imports the real+// updates store graph; mock it shallowly — these tests exercise the hero's+// own rendering, not the store.+vi.mock('@/store/updates', async () => {+ const { atom } = await import('nanostores')++ return {+ $backendUpdateApply: atom<UpdateApplyState | null>(null),+ $backendUpdateChecking: atom<boolean>(false),+ $backendUpdateStatus: atom<DesktopUpdateStatus | null>(null),+ $updateApply: atom<UpdateApplyState | null>(null),+ $updateChecking: atom<boolean>(false),+ $updateStatus: atom<DesktopUpdateStatus | null>(null),+ checkBackendUpdates: vi.fn(),+ checkUpdates: vi.fn(),+ openUpdateOverlayFor: vi.fn(),+ startActiveUpdate: vi.fn()+ }+})++const IDLE_APPLY: UpdateApplyState = {+ applying: false,+ stage: 'idle',+ message: '',+ percent: null,+ error: null,+ command: null,+ log: []+}++function derive(status: DesktopUpdateStatus | null, apply: UpdateApplyState = IDLE_APPLY, checking = false) {+ return deriveUpdateStatus({ apply, checking, status, target: 'client', u: en.updates })+}++describe('deriveUpdateStatus', () => {+ it('never-checked: idle tone, invites a check', () => {+ const view = derive(null)++ expect(view.tone).toBe('idle')+ expect(view.updateAvailable).toBe(false)+ expect(view.line).toBe(en.updates.tapCheck)+ })++ it('unsupported wins over everything else and keeps the backend message', () => {+ const view = derive({ supported: false, message: 'managed install', behind: 5, updateAvailable: true })++ expect(view.tone).toBe('unsupported')+ expect(view.line).toBe('managed install')+ expect(view.supported).toBe(false)+ })++ it('check error includes both the transport message and the underlying error', () => {+ const view = derive({ supported: true, error: 'check-failed', message: 'ECONNREFUSED' })++ expect(view.tone).toBe('error')- expect(view.line).toBe(en.updates.cantReach)++ expect(view.line).toBe(`${en.updates.cantReach} ECONNREFUSED`)+ expect(view.error).toBe('ECONNREFUSED\ncheck-failed')+ })++ it.each([undefined, ''])('keeps the error when the transport message is %s', message => {+ const view = derive({ supported: true, error: 'check-failed', message })++ expect(view.error).toBe('check-failed')+ })++ it('applying beats available so the card cannot offer a second install', () => {+ const view = derive({ supported: true, behind: 3 }, { ...IDLE_APPLY, applying: true, stage: 'update' })++ expect(view.applying).toBe(true)+ expect(view.tone).toBe('available')+ expect(view.line).toBe(en.updates.installing)+ })++ it('restart stage counts as applying even when the applying flag already dropped', () => {+ const view = derive({ supported: true }, { ...IDLE_APPLY, applying: false, stage: 'restart' })++ expect(view.applying).toBe(true)+ })++ it('behind count renders counted copy; count-free updateAvailable falls back', () => {+ expect(derive({ supported: true, behind: 4 }).line).toBe(en.updates.updateReady(4))++ // Shallow clone: exact count unknowable, flagged via updateAvailable.+ const unknown = derive({ supported: true, behind: 0, updateAvailable: true })++ expect(unknown.line).toBe(en.updates.updateReadyUnknown)+ expect(unknown.updateAvailable).toBe(true)+ })++ it('up to date: idle tone with the latest-version line', () => {+ const view = derive({ supported: true, behind: 0 })++ expect(view.tone).toBe('idle')+ expect(view.updateAvailable).toBe(false)+ expect(view.line).toBe(en.updates.latestBody)+ })++ it('backend target says the backend is current, not "you"', () => {+ const view = deriveUpdateStatus({+ apply: IDLE_APPLY,+ checking: false,+ status: { supported: true, behind: 0 },+ target: 'backend',+ u: en.updates+ })++ expect(view.line).toBe(en.updates.latestBodyBackend)+ })+})++describe('VersionHero bundle banners', () => {+ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ })++ const version = (over: Partial<DesktopVersionInfo>): DesktopVersionInfo =>+ ({ appVersion: '0.19.0', ...over }) as DesktopVersionInfo++ const stubRelaunch = () => {+ const relaunchApp = vi.fn().mockResolvedValue(undefined)+ const original = window.hermesDesktop+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { ...original, openExternal: vi.fn(), relaunchApp }+ })++ return relaunchApp+ }++ it('shows an R2 channel name that is not a built-in translated label', (): void => {+ render(<VersionHero version={version({ channel: 'pm-preview' })} />)++ expect(screen.getByText(`${en.updates.version('0.19.0')} · pm-preview`)).toBeTruthy()+ })++ it.each(Object.entries(TRANSLATIONS) as [Locale, Translations][])(+ 'localizes version channels in %s',+ (locale: Locale, copy: Translations): void => {+ for (const channel of ['stable', 'canary'] as const) {+ const label: string = copy.updates.channels[channel]++ expect(label).toBeTypeOf('string')++ const { unmount }: { unmount: () => void } = render(+ <I18nProvider configClient={null} initialLocale={locale}>+ <VersionHero version={version({ channel })} />+ </I18nProvider>+ )++ expect(screen.getByText(`${copy.updates.version('0.19.0')} · ${label}`)).toBeTruthy()+ unmount()+ }+ }+ )++ // FAIL-BEFORE (C19): the shared About extraction dropped the swap-pending+ // restart affordance even though main still produces bundleSwapPending and+ // exposes the relaunchApp IPC — users could no longer finish an applied+ // update from the UI.+ it('swap-pending: restart banner wired to relaunchApp, not the installer link', () => {+ const relaunchApp = stubRelaunch()++ render(<VersionHero version={version({ bundleSwapPending: true })} />)++ expect(screen.getByText(en.updates.bundleSwapPending)).toBeTruthy()+ expect(screen.queryByText(en.updates.bundleOutOfSync)).toBeNull()++ fireEvent.click(screen.getByRole('button', { name: en.updates.bundleSwapPendingAction }))+ expect(relaunchApp).toHaveBeenCalledTimes(1)+ })++ it('out-of-sync without a pending swap: keeps the get-installer banner', () => {+ stubRelaunch()++ render(<VersionHero version={version({ bundleOutOfSync: true })} />)++ expect(screen.getByText(en.updates.bundleOutOfSync)).toBeTruthy()+ expect(screen.queryByText(en.updates.bundleSwapPending)).toBeNull()+ expect(screen.queryByRole('button', { name: en.updates.bundleSwapPendingAction })).toBeNull()+ })++ it('a pending swap wins over the out-of-sync banner — restart, not reinstall', () => {+ stubRelaunch()++ render(<VersionHero version={version({ bundleOutOfSync: true, bundleSwapPending: true })} />)++ expect(screen.getByText(en.updates.bundleSwapPending)).toBeTruthy()+ expect(screen.queryByText(en.updates.bundleOutOfSync)).toBeNull()+ })++ it('no flags: no banner at all', () => {+ render(<VersionHero version={version({})} />)++ expect(screen.queryByText(en.updates.bundleOutOfSync)).toBeNull()+ expect(screen.queryByText(en.updates.bundleSwapPending)).toBeNull()+ })+})diff --cc apps/desktop/src/components/update-status.tsxindex 76a7f1e65ba,00000000000..5ffe381cb7fmode 100644,000000..100644--- a/apps/desktop/src/components/update-status.tsx+++ b/apps/desktop/src/components/update-status.tsx@@@ -1,337 -1,0 +1,340 @@@+import { useStore } from '@nanostores/react'+import { type ReactElement, type ReactNode, useState } from 'react'++import { BrandMark } from '@/components/brand-mark'+import { Button } from '@/components/ui/button'+import { Codicon } from '@/components/ui/codicon'+import type { DesktopUpdateStatus, DesktopVersionInfo } from '@/global'+import { type Translations, useI18n } from '@/i18n'+import { AlertTriangle, CheckCircle2, ExternalLink, Loader2, RefreshCw } from '@/lib/icons'+import { cn } from '@/lib/utils'+import {+ $backendUpdateApply,+ $backendUpdateChecking,+ $backendUpdateStatus,+ $updateApply,+ $updateChecking,+ $updateStatus,+ checkBackendUpdates,+ checkUpdates,+ openUpdateOverlayFor,+ startActiveUpdate,+ type UpdateApplyState,+ type UpdateTarget+} from '@/store/updates'++const RELEASE_NOTES_URL = 'https://github.com/NousResearch/hermes-agent/releases'+const INSTALLER_URL = 'https://hermes-agent.nousresearch.com/'++export type UpdateStatusTone = 'idle' | 'available' | 'error' | 'unsupported'++export interface UpdateStatusView {+ line: string+ tone: UpdateStatusTone+ error?: string+ updateAvailable: boolean+ applying: boolean+ supported: boolean+}++function retirementStatus(+ retirement: NonNullable<DesktopUpdateStatus['retirement']>,+ applying: boolean,+ supported: boolean,+ u: Translations['updates']+): UpdateStatusView {+ // Suffixed-identity build: nothing to download or migrate — just the notice.+ return { applying, supported, updateAvailable: false, tone: 'error', line: u.discontinuedTitle, error: u.discontinuedBody }+}++/**+ * One status derivation for every "am I up to date?" surface (About page,+ * updates overlay). Pure so the tone/copy contract is unit-testable.+ */+interface UpdateStatusInput {+ apply: UpdateApplyState+ checking: boolean+ status: DesktopUpdateStatus | null+ target: UpdateTarget+ u: Translations['updates']+}++export function deriveUpdateStatus(input: UpdateStatusInput): UpdateStatusView {+ const { apply, status, target, u } = input++ if (target === 'client' && status?.retirement) {+ return retirementStatus(status.retirement, apply.applying || apply.stage === 'restart', status.supported !== false, u)+ }++ return ordinaryUpdateStatus(input)+}++function ordinaryUpdateStatus({+ apply,+ checking,+ status,+ target,+ u+}: UpdateStatusInput): UpdateStatusView {+ const behind = status?.behind ?? 0+ // behind is null when the exact count is unknowable (shallow clone): the+ // backend flags that case via updateAvailable instead of a number.+ const updateAvailable = behind > 0 || Boolean(status?.updateAvailable)+ const supported = status?.supported !== false+ const applying = apply.applying || apply.stage === 'restart'++ if (!supported) {+ return { applying, line: status?.message ?? u.unsupportedMessage, supported, tone: 'unsupported', updateAvailable }+ }++ if (status?.error) {++ // A git that never ran is a local problem; leading with "couldn't reach++ // the update server" would misdiagnose it as a network failure.++ const prefix = status.error === 'git-unusable' ? '' : u.cantReach+ return {+ applying,+ error: [status.message, status.error].filter(l => !!l).join('\n'),- line: u.cantReach,++ line: [prefix, status.message].filter(Boolean).join(' '),+ supported,+ tone: 'error',+ updateAvailable+ }+ }++ if (applying) {+ return { applying, line: u.installing, supported, tone: 'available', updateAvailable }+ }++ if (updateAvailable) {+ return {+ applying,+ line: behind > 0 ? u.updateReady(behind) : u.updateReadyUnknown,+ supported,+ tone: 'available',+ updateAvailable+ }+ }++ if (status) {+ return {+ applying,+ line: target === 'backend' ? u.latestBodyBackend : u.latestBody,+ supported,+ tone: 'idle',+ updateAvailable+ }+ }++ return { applying, line: checking ? u.checking : u.tapCheck, supported, tone: 'idle', updateAvailable }+}++function relativeTime(ms: number | undefined, u: Translations['updates']): string {+ if (!ms) {+ return u.never+ }++ const diff = Date.now() - ms++ if (diff < 60_000) {+ return u.justNow+ }++ if (diff < 3_600_000) {+ return u.minAgo(Math.round(diff / 60_000))+ }++ if (diff < 86_400_000) {+ return u.hoursAgo(Math.round(diff / 3_600_000))+ }++ return u.daysAgo(Math.round(diff / 86_400_000))+}++/**+ * The "Hermes Desktop / version / brand mark" hero shared by the About page+ * and the updates overlay, including the bundle-out-of-sync warning. The+ * heading render is injectable so a dialog surface can emit a DialogTitle+ * for its accessible name while About keeps a plain h2.+ */+export function VersionHero({+ renderHeading,+ version+}: {+ renderHeading?: (heading: string) => ReactNode+ version: DesktopVersionInfo | null+}): ReactElement {+ const { t } = useI18n()+ const u = t.updates++ return (+ <div className="flex flex-col items-center gap-3 pt-6 pb-2 text-center">+ <BrandMark className="size-16" />+ <div>+ {renderHeading ? (+ renderHeading(u.appName)+ ) : (+ <h2 className="text-lg font-semibold tracking-tight">{u.appName}</h2>+ )}+ <p className="mt-1 text-xs text-muted-foreground">+ {version?.appVersion ? u.version(version.appVersion) : u.versionUnavailable}+ {version?.channel ? ` · ${Object.entries(u.channels).find(([name]: [string, string]): boolean => name === version.channel)?.[1] ?? version.channel}` : ''}+ </p>+ </div>+ {(version?.bundleSwapPending || version?.bundleOutOfSync) && (+ <div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm">+ <div className="flex items-start gap-2">+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />+ <div className="min-w-0">+ <p className="font-medium">{version.bundleSwapPending ? u.bundleSwapPending : u.bundleOutOfSync}</p>+ <p className="mt-1 text-xs text-muted-foreground">+ {version.bundleSwapPending ? u.bundleSwapPendingDesc : u.bundleOutOfSyncDesc}+ </p>+ {version.bundleSwapPending ? (+ <Button+ className="mt-2"+ onClick={() => void window.hermesDesktop?.relaunchApp?.()}+ size="sm"+ variant="textStrong"+ >+ <RefreshCw className="size-3" />+ {u.bundleSwapPendingAction}+ </Button>+ ) : (+ <Button asChild className="mt-2" size="sm" variant="textStrong">+ <a+ href={INSTALLER_URL}+ onClick={event => {+ event.preventDefault()+ void window.hermesDesktop?.openExternal?.(INSTALLER_URL)+ }}+ rel="noreferrer"+ target="_blank"+ >+ <ExternalLink className="size-3" />+ {u.bundleOutOfSyncAction}+ </a>+ </Button>+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ )+}++interface UpdateActionsProps {+ target: UpdateTarget+ u: Translations['updates']+ view: UpdateStatusView+}++function UpdateActions({ target, u, view }: UpdateActionsProps): ReactElement | null {+ if (view.applying) { return null }++ if (!view.updateAvailable || !view.supported) { return null }++ return (+ <>+ <Button onClick={() => startActiveUpdate(target)} size="sm">{u.updateNow}</Button>+ <Button onClick={() => openUpdateOverlayFor(target)} size="sm" variant="textStrong">{u.seeWhatsNew}</Button>+ </>+ )+}++/**+ * The bordered update-state card (status line, last-checked age, check /+ * update / release-notes actions) in the About page's visual language.+ * Target-aware: 'client' reads the desktop self-update atoms, 'backend' the+ * remote backend's. The actual apply flow stays in the updates overlay —+ * "Update now" opens it and starts the install there.+ */+export function UpdateStatusCard({+ showReleaseNotes = true,+ target+}: {+ showReleaseNotes?: boolean+ target: UpdateTarget+}): ReactElement {+ const { t } = useI18n()+ const u = t.updates+ const isBackend = target === 'backend'+ const status = useStore(isBackend ? $backendUpdateStatus : $updateStatus)+ const checking = useStore(isBackend ? $backendUpdateChecking : $updateChecking)+ const apply = useStore(isBackend ? $backendUpdateApply : $updateApply)+ const [justChecked, setJustChecked] = useState<boolean>(false)++ const view = deriveUpdateStatus({ apply, checking, status, target, u })++ const handleCheck = async (): Promise<void> => {+ setJustChecked(false)+ const next = await (isBackend ? checkBackendUpdates({ force: true }) : checkUpdates({ force: true }))+ setJustChecked(Boolean(next))+ }++ return (+ <div+ className={cn(+ 'rounded-xl border px-4 py-3 text-sm',+ view.tone === 'available' && 'border-primary/30 bg-primary/5 text-foreground',+ view.tone === 'error' && 'border-destructive/35 bg-destructive/5 text-destructive',+ (view.tone === 'idle' || view.tone === 'unsupported') && 'border-border/70 bg-muted/20 text-foreground'+ )}+ >+ <div className="flex items-start gap-2">+ {view.tone === 'available' ? (+ <Codicon className="mt-0.5 size-4 shrink-0 text-primary" name="cloud-download" size="1rem" />+ ) : view.tone === 'error' || view.tone === 'unsupported' ? null : (+ <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />+ )}+ <div className="min-w-0">+ <p className="font-medium">{view.line}</p>+ {view.error && <p className="mt-1 text-xs text-muted-foreground">{view.error}</p>}+ {view.tone !== 'unsupported' && (+ <p className="mt-1 text-xs text-muted-foreground">+ {u.lastChecked(relativeTime(status?.fetchedAt, u))}+ {justChecked && !checking ? u.justNowSuffix : ''}+ </p>+ )}+ </div>+ </div>++ {view.tone !== 'unsupported' && (+ <div className="mt-3 flex flex-wrap items-center gap-4">+ <Button+ disabled={checking || view.applying}+ onClick={() => void handleCheck()}+ size="sm"+ variant="textStrong"+ >+ {checking ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}+ {checking ? u.checkingShort : u.checkNow}+ </Button>++ <UpdateActions+ target={target}+ u={u}+ view={view}+ />++ {showReleaseNotes && (+ <Button asChild className="ml-auto" size="sm" variant="text">+ <a+ href={RELEASE_NOTES_URL}+ onClick={event => {+ event.preventDefault()+ void window.hermesDesktop?.openExternal?.(RELEASE_NOTES_URL)+ }}+ rel="noreferrer"+ target="_blank"+ >+ <ExternalLink className="size-3" />+ {u.releaseNotes}+ </a>+ </Button>+ )}+ </div>+ )}+ </div>+ )+}diff --cc apps/desktop/src/i18n/ar.tsindex 70ef0881041,84273e59bb6..0f956724ee2--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@@ -2353,47 -2378,8 +2355,48 @@@ export const ar = defineLocale(tryAgain: 'إعادة المحاولة',notAvailableTitle: 'التحديث غير متاح',unsupportedMessage: 'لا يمكن لهذا الإصدار من Hermes تحديث نفسه من داخل التطبيق.',+ appName: 'Hermes Desktop',+ version: value => `الإصدار ${value}`,+ versionUnavailable: 'الإصدار غير متاح',+ bundleOutOfSync: 'إصدار التطبيق قديم',+ bundleOutOfSyncDesc:+ 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',+ bundleOutOfSyncAction: 'الحصول على المثبّت',+ checkNow: 'التحقق الآن',+ checkingShort: 'جار التحقق...',+ seeWhatsNew: 'عرض الجديد',+ releaseNotes: 'ملاحظات الإصدار',+ installing: 'جار التثبيت...',+ cantReach: 'تعذر الوصول لخدمة التحديث',+ tapCheck: 'اضغط للتحقق من التحديثات.',+ updateReady: count => `${count} تحديث متاح`,+ updateReadyUnknown: 'تحديث جديد جاهز.',+ lastChecked: age => `آخر تحقق ${age}`,+ justNowSuffix: 'الآن',+ never: 'أبدا',+ justNow: 'الآن',+ minAgo: count => `قبل ${count} دقيقة`,+ hoursAgo: count => `قبل ${count} ساعة`,+ daysAgo: count => `قبل ${count} يوم`,+ versionDetailsTitle: 'تفاصيل الإصدار',+ versionDetailsBody: 'هذا التثبيت مُدار خارج التطبيق. حدّثه بالطريقة نفسها التي استخدمتها لتثبيته.',+ versionDetailsVersion: 'الإصدار',+ versionDetailsCommit: 'الالتزام',+ versionDetailsBuildOrigin: 'مصدر البناء',+ versionDetailsDistribution: 'التوزيع',+ versionDetailsDistributionDesktop: 'تطبيق سطح المكتب',+ versionDetailsDistributionDesktopMsix: 'تطبيق سطح المكتب (MSIX)',+ versionDetailsDistributionDesktopInstaller: 'تطبيق سطح المكتب (المُثبِّت)',+ versionDetailsDistributionSourceInstaller: 'المصدر (سكربت التثبيت)',+ versionDetailsDistributionSource: 'المصدر',+ versionDetailsDistributionStore: 'Microsoft Store',+ versionDetailsRuntimeEmbedded: 'وقت تشغيل مضمّن',+ versionDetailsRuntimeExternal: 'خارجي (يستخدم وقت تشغيل الجهاز)',+ versionDetailsRuntime: 'وقت التشغيل',+ versionDetailsInstallId: 'معرّف التثبيت',+ versionDetailsUncommittedChanges: '(+ تغييرات غير ملتزمة)',connectionRetry: 'تحقق من اتصالك وأعد المحاولة.',+ gitUnusable: 'لم يتمكن Hermes من تشغيل Git على هذا الجهاز، لذا لم يتمكن من التحقق من التحديثات.',latestBody: 'أنت تستخدم أحدث إصدار.',latestBodyBackend: 'الواجهة الخلفية تعمل بأحدث إصدار.',allSetTitle: 'كل شيء جاهز',diff --cc apps/desktop/src/i18n/ja.tsindex 092d5c99774,2d6f25a159d..532acf74ee0--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@@ -2720,8 -2745,8 +2729,9 @@@ export const ja = defineLocale(notAvailableTitle: '更新は利用できません',unsupportedMessage: 'このバージョンの Hermes はアプリ内から自分を更新できません。',connectionRetry: '接続を確認してもう一度試してください。',+ gitUnusable: 'このコンピューターで Git を実行できなかったため、更新を確認できませんでした。',latestBody: '最新バージョンを実行しています。',+ versionDetailsDistributionStore: 'Microsoft Store',latestBodyBackend: 'バックエンドは最新バージョンを実行しています。',allSetTitle: '準備完了',availableTitle: '新しい更新が利用可能',diff --cc apps/desktop/src/i18n/ru.tsindex 8c7ec62a228,66104c48cbf..028202725e5--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@@ -3021,8 -3056,8 +3030,9 @@@ export const ru = defineLocale(notAvailableTitle: 'Обновление недоступно',unsupportedMessage: 'Эта версия Hermes не может обновлять себя из приложения.',connectionRetry: 'Проверьте соединение и попробуйте снова.',+ gitUnusable: 'Hermes не удалось запустить Git на этом компьютере, поэтому проверить обновления не получилось.',latestBody: 'У вас последняя версия.',+ versionDetailsDistributionStore: 'Microsoft Store',latestBodyBackend: 'Бэкенд работает на последней версии.',allSetTitle: 'Всё готово',availableTitle: 'Доступно новое обновление',diff --cc apps/desktop/src/i18n/zh-hant.tsindex 49e93922313,421362188a9..4518b02ae24--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@@ -2704,8 -2726,8 +2710,9 @@@ export const zhHant = defineLocale(notAvailableTitle: '更新不可用',unsupportedMessage: '此版本的 Hermes 無法在應用程式內自行更新。',connectionRetry: '請檢查網路連線後重試。',+ gitUnusable: 'Hermes 無法在這台電腦上執行 Git,因此無法檢查更新。',latestBody: '您正在執行最新版本。',+ versionDetailsDistributionStore: 'Microsoft Store',latestBodyBackend: '後端正在執行最新版本。',allSetTitle: '已是最新版本',availableTitle: '有可用更新',diff --cc cron/scheduler.pyindex a024936991c,a38c17bc93a..dcb9b3609ef--- a/cron/scheduler.py+++ b/cron/scheduler.py@@@ -1115,12 -1148,10 +1148,14 @@@ _DEFAULT_SCRIPT_TIMEOUT = 3600 # secon_SCRIPT_TIMEOUT = _DEFAULT_SCRIPT_TIMEOUT_RUN_CLAIM_HEARTBEAT_SECONDS = 60.0_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS = _RUN_CLAIM_HEARTBEAT_SECONDS * 3+ # Pause before re-sampling a fire-claim heartbeat miss; a genuinely re-owned claim misses twice.+ _FIRE_CLAIM_MISS_CONFIRM_SECONDS = 1.0+# MERGE-CHECK: our pm-aware cron-script helpers (_pm_runtime_venv_dir, _pm_store_python_exe, the+# pm-aware _windows_cron_python_invocation/_windows_cron_bootstrap_argv) lived in this upstream-deleted+# block. Upstream moved the script helpers to cron/scheduler_script.py WITHOUT pm awareness (pyvenv.cfg+# probing instead); that file is outside this merge's file list, so porting the pm logic is left to the parent.def _cron_cleanup_timeout_seconds() -> float:"""Return the wall-clock bound for cron post-run cleanup."""default = 10.0diff --cc gateway/platforms/whatsapp_cloud.pyindex a98899d6ce6,a409f009bf9..48dfdbfcd60--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@@ -943,11 -945,12 +945,12 @@@ class WhatsAppCloudAdapter(WhatsAppBehaif file_size > _MAX_TEXT_INJECT_BYTES:logger.info("[whatsapp_cloud] skipping text injection for %s (%d bytes > %d)", doc, file_size, _MAX_TEXT_INJECT_BYTES)continue- injection = f"[Content of {doc.name}]:\n{doc.read_text(encoding='utf-8', errors='replace')}"+ injection = f"[Content of {doc.name}]:\n{doc.read_text(encoding='utf-8-sig', errors='replace')}"body = f"{injection}\n\n{body}" if body else injection+ inlined[i] = Trueexcept OSError:logger.exception("[whatsapp_cloud] failed to read document text: %s", doc)- return body+ return body, inlinedasync def _build_message_event_from_cloud(self, raw_message: Dict[str, Any], contacts_by_waid: Dict[str, str], metadata: Dict[str, Any],diff --cc gateway/shutdown_flush.pyindex ca1cc282a8e,405ac2c3696..74af44744f5--- a/gateway/shutdown_flush.py+++ b/gateway/shutdown_flush.py@@@ -146,10 -148,13 +148,13 @@@ def drain_transcript_spool(session_id:entries = []for path in candidates:try:- payload = json.loads(path.read_text(encoding="utf-8"))+ payload = json.loads(path.read_text(encoding="utf-8-sig"))except Exception:continue- if (payload.get("reason") != TRANSCRIPT_CAP_DROP_REASON+ # A parseable non-object file (scalar/list) cannot be attributed to any session: skip it+ # like unparseable JSON instead of letting ``.get`` abort the whole drain.+ if (not isinstance(payload, dict)+ or payload.get("reason") != TRANSCRIPT_CAP_DROP_REASONor payload.get("session_key") != session_id):continuemessage = (payload.get("data") or {}).get("message")@@@ -216,16 -226,20 +226,22 @@@ def recover_pending_to_db(session_db=Norecovered = 0try:for path in flush_files:+ # One unparseable payload or rejected append must only skip THIS file: the file is+ # never unlinked, so aborting the pass would re-poison every later boot.+ # utf-8-sig: our BOM-tolerant read fix for flush files.- payload = json.loads(path.read_text(encoding="utf-8-sig"))- # Agent-history snapshots use a different schema (reason +- # messages list) and are meant for manual operator recovery,- # not automatic DB insertion. Skip them silently.- if payload.get("reason") == "shutdown-with-unpersisted-agent-history":- continue- if _recover_one_payload(session_db, path, payload):- recovered += 1- path.unlink(missing_ok=True)+ try:- payload = json.loads(path.read_text(encoding="utf-8"))- # Agent-history snapshots are for manual operator recovery, not automatic DB- # insertion.++ payload = json.loads(path.read_text(encoding="utf-8-sig"))++ # Agent-history snapshots use a different schema (reason +++ # messages list) and are meant for manual operator recovery,++ # not automatic DB insertion. Skip them silently.+ if payload.get("reason") == "shutdown-with-unpersisted-agent-history":+ continue+ if _recover_one_payload(session_db, path, payload,+ session_resolver=session_resolver):+ recovered += 1+ path.unlink(missing_ok=True)+ except Exception as exc:+ logger.warning("Failed to recover pending message from %s: %s", path, exc)finally:if own_db: # shutdown cancellation/interrupt must not strand an owned DBwith contextlib.suppress(Exception):diff --cc hermes_bootstrap.pyindex ad09bd4a0cc,313e08a6ac7..73c7a688b87--- a/hermes_bootstrap.py+++ b/hermes_bootstrap.py@@@ -96,46 -302,25 +302,48 @@@ def harden_import_path(src_root: str |sys.path.insert(0, root)-def activate_durable_lazy_target() -> None:- """Put the durable lazy-install dir (``HERMES_LAZY_INSTALL_TARGET``) on ``sys.path``.+# Apply on import — entry points just need ``import hermes_bootstrap``+# (or ``from hermes_bootstrap import apply_windows_utf8_bootstrap``) at+# the very top of their module, before importing anything else. The+# import side effect does the right thing.+apply_windows_utf8_bootstrap()+suppress_platform_ver_console()- Immutable Docker images seal the venv and redirect lazy installs to the data volume;- packages installed there on a previous run must be importable before any backend- imports its SDK. Appends to the END of ``sys.path`` so the core venv always wins name- collisions (see ``tools.lazy_deps``). Never raises; unset target is a no-op.- """- if not os.environ.get("HERMES_LAZY_INSTALL_TARGET", "").strip():- return- try:- from tools import lazy_deps- lazy_deps.activate_durable_lazy_target()- except Exception:- pass # a failed activation just leaves the backend reporting itself unavailable+# Every entry point imports this module before its dependency graph.+from pathlib import Path+from hermes_cli.runtime_paths import activate_dependencies+from hermes_cli._early_recovery import recover_if_needed+from hermes_cli._parser import command_argv-# Apply on import — entry points only need ``import hermes_bootstrap`` first.-apply_windows_utf8_bootstrap()-suppress_platform_ver_console()-activate_durable_lazy_target()+_root = Path(__file__).resolve().parent+# Repair needs only stdlib. Do not activate the damaged tree to reach it.+_pm_repair = command_argv(sys.argv[1:])[:2] == ["pm", "repair"]+if not _pm_repair:+ from hermes_cli.venv_sync import prepare_launch, relaunch_command++ try:+ _launch_python = prepare_launch(_root, sys.argv[1:])+ if _launch_python is not None:+ _main_spec = getattr(sys.modules.get("__main__"), "__spec__", None)+ _command = relaunch_command(+ _launch_python, _root, sys.argv, sys.orig_argv,+ getattr(_main_spec, "name", None),+ )+ if os.name == "nt":+ import subprocess++ raise SystemExit(subprocess.call(_command))+ os.execv(str(_launch_python), _command)+ except Exception as exc:+ print(f"hermes: source-update completion failed: {exc}", file=sys.stderr)+ raise SystemExit(1) from None+ recover_if_needed(_root)+ try:+ activate_dependencies(_root)+ except (RuntimeError, OSError) as exc:+ if command_argv(sys.argv[1:])[:1] != ["pm"]:+ print(f"hermes: {exc}; run `hermes pm repair`", file=sys.stderr)+ raise SystemExit(1) from None+ install_happy_eyeballs_socket_connect()++diff --cc hermes_cli/_startup_fast.pyindex 6c905730057,e72c5672292..228395f23d9--- a/hermes_cli/_startup_fast.py+++ b/hermes_cli/_startup_fast.py@@@ -28,16 -12,11 +28,16 @@@ import oimport sys__all__ = [- "project_root_str",- "project_root_str", "normalize_hermes_home_env", "ensure_project_root_on_path", "is_termux_env",- "is_termux_fast_version_argv", "is_global_fast_version_argv",- "is_container_startup_environment", "active_profile_may_override_home",- "container_mode_may_be_active", "read_openai_version", "read_install_method",- "print_fast_version_info", "try_fast_version",++ "project_root_str", "normalize_hermes_home_env",+ "ensure_project_root_on_path",+ "is_global_fast_version_argv",+ "is_container_startup_environment",+ "active_profile_may_override_home",+ "container_mode_may_be_active",+ "read_openai_version",+ "read_install_method",+ "print_fast_version_info",+ "try_fast_version",]diff --cc hermes_cli/doctor_connectivity.pyindex 32b9b3fd20c,bdd0ace0170..b5c7a562b9f--- a/hermes_cli/doctor_connectivity.py+++ b/hermes_cli/doctor_connectivity.py@@@ -7,9 -7,13 +7,12 @@@ print and issue strings to append. No pfrom __future__ import annotationsimport concurrent.futures+ import errnoimport functoolsimport os+ import socket-import sysfrom typing import NamedTuple+ from urllib.parse import urlsplitfrom hermes_cli.colors import Colors, colorfrom hermes_cli.models import _HERMES_USER_AGENTdiff --cc hermes_cli/doctor_tools.pyindex 75f75a949b6,661fb8bf003..1a9a663aa71--- a/hermes_cli/doctor_tools.py+++ b/hermes_cli/doctor_tools.py@@@ -12,7 -11,8 +12,8 @@@ from pathlib import Patfrom hermes_cli.doctor_platform import _system_package_install_cmdfrom hermes_cli.doctor_report import Finding, _fail_and_issue, check_bool, check_info, check_ok, check_warn, doctor_checkfrom hermes_cli.vercel_auth import describe_vercel_auth-from hermes_constants import agent_browser_runnable, is_termux as _is_termux+from hermes_constants import is_termux as _is_termux+ from tools.environments.docker import docker_runtime_name, docker_runtime_start_hint, find_dockerdef _safe_which(cmd: str) -> str | None:diff --cc hermes_cli/local_runtime/binaries.pyindex db0a1c9d123,11844a6dabf..4b948b7aa6a--- a/hermes_cli/local_runtime/binaries.py+++ b/hermes_cli/local_runtime/binaries.py@@@ -37,11 -63,44 +37,49 @@@ def runtimes_root() -> Pathreturn get_default_hermes_root() / "runtimes" / "llamacpp"+def pinned_tag(backend: str) -> str:+ version = pm.Lockfile(pm.paths.lockfile_path()).version(BACKEND_PACKAGES[backend])+ if version is None:+ raise BinaryResolutionError(f"llama.cpp {backend} has no PM version pin")+ return f"b{version}"+ def manifest_verified(manifest: Path) -> bool:+ """True when an install manifest records a verified_version (missing/damaged -> False)."""+ try:+ data = json.loads(manifest.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError):+ return False+ return isinstance(data, dict) and bool(data.get("verified_version"))+++ def _release_number(tag: str) -> int:+ digits = "".join(ch for ch in tag if ch.isdigit())+ return int(digits) if digits else 0+++ def installed_tags() -> list[str]:+ """Tags with a verified install, newest first by release number. The boot ladder and the+ update check both read installed-ness from here — one resolver, every caller."""+ root = runtimes_root()+ if not root.exists():+ return []+ found = {entry.name for entry in root.iterdir()+ if entry.is_dir() and entry.name != "downloads"+ and any(manifest_verified(m) for m in entry.glob("*/manifest.json"))}+ return sorted(found, key=_release_number, reverse=True)+++ def _host_os_arch() -> tuple[str, str]:+ """(os, arch) normalized to release-asset vocabulary. PITFALL: PROCESSOR_ARCHITECTURE lies+ under x64 emulation on ARM64 Windows, and platform.machine() reads the same env on some+ Pythons — so on Windows prefer PROCESSOR_IDENTIFIER's text when present."""+ system = platform.system().lower()+ os_name = {"windows": "win", "darwin": "macos", "linux": "ubuntu"}.get(system, system)+ arch = "arm64" if platform.machine().lower() in ("arm64", "aarch64") else "x64"+ if os_name == "win":+ ident = os.environ.get("PROCESSOR_IDENTIFIER", "").lower()+ if "armv8" in ident or "arm " in ident:+ arch = "arm64"+ return os_name, archdef select_backend(gpu_vendor: str | None, os_name: str | None = None) -> str:diff --cc hermes_cli/main.pyindex 0b487adf07b,36d83e206f0..efbeeef7c8b--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@@ -35,6 -35,28 +35,10 @@@ if _bootstrap_root not in sys.pathsys.path.insert(0, _bootstrap_root)from hermes_cli import _startup_fast # noqa: E402+ # A literal ``~``/``$VAR`` in HERMES_HOME (fish, or any quoted value) must become absolute+ # before the first reader — otherwise it resolves against cwd and scaffolds <cwd>/~/.hermes.+ _startup_fast.normalize_hermes_home_env()+-# Early venv self-heal — MUST run before any third-party import below. A prior-# ``hermes update`` may have left a recovery marker with a core package wiped;-# the hermes_cli.config/env_loader imports further down would then crash before-# main() reaches _recover_from_interrupted_install(). ``_early_recovery`` is-# stdlib-only (safe on a corrupted venv) and repairs just enough to finish this-# import; the marker lifecycle stays with the full recovery path. Its own-# import is unguarded on purpose: same package dir, so if IT can't import-# nothing in hermes_cli can.-# It is also the canonical home of the probe/repair tables reused by the full recovery path below. See-# #57828.-from hermes_cli import _early_recovery as _early_recovery_mod--try:- _early_recovery_mod.recover_if_needed()-except Exception:- pass--# Startup-liveness watchdog: for gateway runs, arm BEFORE the heavy import# graph below — an import-time deadlock (native-extension init, contended# import lock) is exactly the "wedged before the event loop, no logs, livediff --cc hermes_cli/managed_scope.pyindex 8832e1f2c09,888080075d7..f8f742ff3ef--- a/hermes_cli/managed_scope.py+++ b/hermes_cli/managed_scope.py@@@ -15,8 -15,15 +15,15 @@@ import threadinfrom pathlib import Pathfrom typing import Dict, Optional-import yaml+import hermes_yaml as yaml+ # Stale-module bridge: this module binds ``utils.file_signature`` at import time, so a fresh+ # import in a post-pull updater process (pre-handoff purge keeps root modules cached) dies+ # unless the stale ``utils`` is dropped first. See hermes_cli.stale_modules.+ from hermes_cli.stale_modules import drop_stale_root_modules++ drop_stale_root_modules()+from utils import file_signaturelogger = logging.getLogger(__name__)diff --cc hermes_cli/plugin_catalog.pyindex f9504caa13c,c9861506dd3..b12148b77b3--- a/hermes_cli/plugin_catalog.py+++ b/hermes_cli/plugin_catalog.py@@@ -250,6 -272,20 +272,20 @@@ def _live_cache_path() -> Pathreturn get_hermes_home() / "cache" / "plugin-catalog.json"+ # Wall-clock deadline of the last failed live fetch. Without it a dead catalog host costs one+ # full request timeout PER CALL (the plugins hub and ``plugins list`` used to ask once per+ # installed plugin), so the dashboard event loop stalled for minutes.+ _live_fetch_failed_until = 0.0+++ def _stale_live_cache(cache: Path) -> Optional[Dict[str, Any]]:+ """A previously fetched copy still beats the in-tree one when the network is down."""+ try:- return json.loads(cache.read_text(encoding="utf-8")) if cache.is_file() else None++ return json.loads(cache.read_text(encoding="utf-8-sig")) if cache.is_file() else None+ except Exception:+ return None++def fetch_live_catalog(*, force: bool = False) -> Optional[Dict[str, Any]]:"""The published ``plugin-catalog.json`` (``{"entries": [...], "removed": [...]}``), cached under``HERMES_HOME/cache`` for :data:`LIVE_CATALOG_TTL_SECONDS`. ``None`` on ANY failure — callers fall@@@ -257,9 -296,11 +296,11 @@@cache = _live_cache_path()try:if not force and cache.is_file() and time.time() - cache.stat().st_mtime < LIVE_CATALOG_TTL_SECONDS:- return json.loads(cache.read_text(encoding="utf-8"))+ return json.loads(cache.read_text(encoding="utf-8-sig"))except Exception as exc:logger.debug("Plugin catalog: unreadable live cache %s: %s", cache, exc)+ if not force and time.time() < _live_fetch_failed_until:+ return _stale_live_cache(cache)try:import httpxfrom hermes_constants import mkdir_under_hermes_homediff --cc hermes_cli/plugins_cmd.pyindex c4bcdcbfeac,b09b20f303a..2830db5ddec--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@@ -2481,12 -2178,9 +2484,13 @@@ _PLUGIN_ACTIONS ="search": lambda args: _catalog().cmd_search(getattr(args, "term", "") or "", json_output=getattr(args, "json", False)),"browse": lambda args: _catalog().cmd_search(""),- "validate": lambda args: _catalog().cmd_validate(args.path, as_json=getattr(args, "json", False)),+ "validate": lambda args: _catalog().cmd_validate(+ args.path, as_json=getattr(args, "json", False), install_deps=getattr(args, "install_deps", False)),"update": lambda args: cmd_update(args.name),+ "adopt": lambda args: cmd_adopt(args.name),+ "trust-update-url": lambda args: cmd_trust_update_url(args.name),+ "check-updates": lambda args: cmd_check_updates(args),+ "check": lambda args: cmd_check_updates(args),"remove": lambda args: cmd_remove(args.name),"rm": lambda args: cmd_remove(args.name),"uninstall": lambda args: cmd_remove(args.name),diff --cc hermes_cli/plugins_cmd_catalog.pyindex 47fabb4a427,44324150d25..ed0cf150757--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@@ -78,11 -94,16 +79,16 @@@ def catalog_annotation(dir_path) -> Optreturn f"catalog:{sidecar.get('tier') or 'community'}@{str(sidecar.get('sha') or '')[:8]}"- def removed_annotation(name: str, dir_path) -> Optional[str]:- """Kill-list reason when an INSTALLED plugin matches by name, catalog name or repo, else ``None``."""+ def removed_annotation(name: str, dir_path, removed_entries: List[RemovedEntry]) -> Optional[str]:+ """Kill-list reason when an INSTALLED plugin matches by name, catalog name or repo, else ``None``.++ ``removed_entries`` is required: callers annotating many rows (``plugins list``, the dashboard hub)+ resolve the kill list once with :func:`plugin_catalog.resolved_removed_entries` and pass it in.+ Resolving per row cost one live-catalog fetch — one network timeout, offline — per plugin.+ """- sidecar = read_catalog_sidecar(dir_path) or {}+ sidecar = catalog_install_record(dir_path) or {}for candidate in (name, sidecar.get("catalog_name"), sidecar.get("repo")):- removed = find_removed(str(candidate)) if candidate else None+ removed = match_removed(str(candidate), removed_entries) if candidate else Noneif removed is not None:return removed.reason or "no reason recorded"return Nonediff --cc hermes_cli/profiles.pyindex 25d481937da,9169885f3b9..9618eaba62d--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@@ -15,9 -16,7 +16,8 @@@ from dataclasses import dataclasfrom pathlib import Pathfrom typing import Dict, List, Optional, Tuple- from agent.skill_utils import is_excluded_skill_pathfrom hermes_cli.archive_safe import archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targz+from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRSfrom hermes_constants import (LOCAL_RUNTIME_ROOT_DIRS, clear_named_profile_deleted, mark_named_profile_deleted, named_profile_has_identity,named_profile_is_deleted, named_profile_is_live,@@@ -1617,15 -1653,12 +1699,15 @@@ def _stop_gateway_process(profile_dir:# Active profile (sticky default)- def get_active_profile() -> str:- """Read the sticky active profile name."""- path = _get_active_profile_path()+ def get_active_profile(root: Path | None = None) -> str:+ """Read the sticky active profile name (of *root*, default: this process's Hermes root)."""+ path = root / "active_profile" if root is not None else _get_active_profile_path()try:- return path.read_text(encoding="utf-8").strip() or "default"- except (UnicodeDecodeError, OSError):+ name = path.read_text(encoding="utf-8-sig").strip()+ if not name:+ return "default"+ return name+ except (FileNotFoundError, UnicodeDecodeError, OSError):return "default"diff --cc hermes_cli/setup_terminal.pyindex 9d7b37ad80f,5453c5419fb..f7381270fcf--- a/hermes_cli/setup_terminal.py+++ b/hermes_cli/setup_terminal.py@@@ -6,8 -6,10 +6,9 @@@ import jsoimport loggingimport osimport shutil-import sysfrom pathlib import Pathfrom tools import tool_backend_helpers+ from tools.environments.docker import docker_runtime_name, find_dockerfrom hermes_cli import nous_subscriptionlogger = logging.getLogger("hermes_cli.setup")diff --cc hermes_cli/source_build.pyindex d3b64459305,00000000000..d80eac1f0a4mode 100644,000000..100644--- a/hermes_cli/source_build.py+++ b/hermes_cli/source_build.py@@@ -1,116 -1,0 +1,132 @@@+"""Source launch/update composition over the shared JavaScript builders."""++import os+from pathlib import Path+import shutil+import subprocess+import sys+++def source_product_current(project_root: Path, product: str, out: Path) -> bool:+ """Read the compiler's receipt without acquiring tools or dependencies."""+ from pm import env_for++ env = env_for("node")+ node = shutil.which("node", path=env.get("PATH", ""))+ if not node:+ return False+ try:+ result = subprocess.run(+ [node, str(project_root / "scripts/build/freshness.mjs"),+ "--source", str(project_root), "--product", product, "--out", str(out)],+ cwd=project_root, env=env, capture_output=True, text=True, check=True,+ )+ return result.stdout.strip() == "true"+ except (OSError, subprocess.SubprocessError):+ return False+++def source_build_env(base_env: dict | None = None, *, explicit: bool = False) -> dict[str, str]:+ from pm import ensure+ from hermes_constants import get_hermes_home++ env = {**os.environ, **(base_env or {}), "CI": "1", "HERMES_PYTHON": sys.executable,+ "PYTHON": sys.executable}+ env.pop("ESBUILD_BINARY_PATH", None)+ npmrc = get_hermes_home() / "npmrc"+ if npmrc.is_file():+ env.setdefault("NPM_CONFIG_USERCONFIG", str(npmrc))+ return ensure("npm", base_env=env, explicit=explicit).env+++def run_source_script(project_root: Path, script: str, *args: str, env: dict) -> None:+ subprocess.run(+ [shutil.which("node", path=env["PATH"]), str(project_root / script), *args],+ cwd=project_root, env=env, check=True,+ )+++def prepare_source_dependencies(project_root: Path, workspaces: tuple[str, ...], *, env: dict,+ explicit: bool = False) -> None:+ from pm import lazy_installs_allowed++ run_source_script(+ project_root, "scripts/build/node-deps.mjs", "--source", str(project_root), "--reuse",+ *(() if explicit or lazy_installs_allowed() else ("--no-install",)),+ *(arg for workspace in workspaces for arg in ("--workspace", workspace)), env=env,+ )+++def prepare_launch_dependencies(project_root: Path, *, env: dict) -> None:+ """A launch rebuild must not prune another installed source frontend."""+ from hermes_cli.main_desktop import _desktop_dist_exists, _desktop_packaged_executable++ desktop_dir = project_root / "apps/desktop"+ desktop = _desktop_dist_exists(desktop_dir) or _desktop_packaged_executable(desktop_dir) is not None+ workspaces = ("ui-tui", "web") + (("apps/desktop",) if desktop else ())+ prepare_source_dependencies(project_root, workspaces, env=env)+++def build_source_tui(project_root: Path, *, env: dict) -> None:+ run_source_script(project_root, "scripts/build/tui.mjs", env=env)+++def build_source_web(project_root: Path, *, env: dict, icons: Path | None = None,+ explicit: bool = False) -> None:+ if icons is None:+ icons = project_root+ run_source_script(project_root, "scripts/generate-icons.mjs", *(() if explicit else ("--on-demand",)), env=env)+ run_source_script(project_root, "scripts/build/web.mjs", "--source", str(project_root),+ "--icons", str(icons), "--out", str(project_root / "hermes_cli/web_dist"), env=env)+++def build_update_products(project_root: Path, *, desktop: bool) -> None:+ """Prepare the selected union once; a failed product aborts the update."""+ # Both current updates and historical takeover reach this in a fresh target+ # interpreter, never in the updater's pre-sync import graph.+ from hermes_cli.main_install_repair import _warn_configured_features_missing_deps+ from hermes_cli.update_stage import publish_stage++ _warn_configured_features_missing_deps()+ env = source_build_env(explicit=True)+ workspaces = ("ui-tui", "web") + (("apps/desktop",) if desktop else ())+ publish_stage("Updating Node dependencies")+ prepare_source_dependencies(project_root, workspaces, env=env, explicit=True)+ publish_stage("Building the TUI")+ build_source_tui(project_root, env=env)+ publish_stage("Building the web UI")+ build_source_web(project_root, env=env, explicit=True)+ if desktop:- from hermes_cli.main_desktop import build_prepared_desktop++ from hermes_cli.main_desktop import _install_rebuilt_desktop_app, build_prepared_desktop++ publish_stage("Building the desktop app")+ build_prepared_desktop(+ project_root / "apps/desktop", source_mode=False,+ npm=shutil.which("npm", path=env["PATH"]), env=env, icons=project_root, explicit=True,+ )++ # A current release/ can still sit beside a stale installed copy (an earlier++ # update rebuilt but never installed); healing must not wait for the next build.++ installed, problems = _install_rebuilt_desktop_app(project_root / "apps/desktop")++ for app in installed:++ print(f" ✓ Installed the rebuilt Desktop app at {app}")++ for problem in problems:++ print(f" ⚠ {problem}")++ # A configured memory provider that no longer ships in core is installed from the++ # catalog for every profile home sharing this venv (config, data and tool names++ # unchanged). The update must finish even if the migration blows up.++ try:++ from hermes_cli.memory_provider_migration import migrate_all_homes++++ migrate_all_homes()++ except Exception as exc:++ print(f" ⚠ Memory provider migration skipped: {exc}")+++if __name__ == "__main__":+ import argparse++ parser = argparse.ArgumentParser(description="Build source-install frontends")+ parser.add_argument("--source", type=Path, required=True)+ parser.add_argument("--desktop", action="store_true")+ args = parser.parse_args()+ build_update_products(args.source.resolve(), desktop=args.desktop)diff --cc hermes_cli/update_cmd_maint.pyindex 2ac1d830b48,8780903cc8a..92d23a5305e--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@@ -277,11 -245,31 +277,13 @@@ def _refresh_dashboard_after_update(*,See #83595."""- from hermes_cli.update_cmd import _m, _record_update_step- if node_failures:- print()- print(" ℹ Leaving running dashboard process(es) untouched because the")- print(" Node.js dependency refresh did not complete.")- return+ from hermes_cli.update_cmd import _m++ from hermes_constants import get_hermes_home- try:- from hermes_constants import get_hermes_home- stop_result = _m()._kill_stale_dashboard_processes(- restart_managed=True, already_restarted_units=already_restarted_units,- scope_home=str(get_hermes_home()),- )- except Exception as exc:- # Isolated like every sibling post-update step: a failure here (#112604) used to abort- # the fleet matrix, reconciliation and the inner receipt finalize that follow it. A- # dashboard/serve left on pre-update code is still caught by the survivor probe →- # reconciliation (exit 1).- logger.warning("Post-update dashboard cleanup failed: %s", exc)- _record_update_step("dashboard_cleanup", False, f"{type(exc).__name__}: {exc}")- print()- print(f"⚠ Could not refresh running dashboard/serve process(es): {exc}")- print(" If one is still running, restart it so it serves the updated code:")- print(" hermes dashboard --port <port> (or: systemctl --user restart hermes-dashboard)")- return+ stop_result = _m()._kill_stale_dashboard_processes(- restart_managed=True, already_restarted_units=already_restarted_units++ restart_managed=True, already_restarted_units=already_restarted_units,++ scope_home=str(get_hermes_home()),+ )if not stop_result.get("unrecovered"):returndiff --cc hermes_constants.pyindex 61b8529d6ab,df35569ac1d..7ab7b372ff2--- a/hermes_constants.py+++ b/hermes_constants.py@@@ -42,9 -42,13 +42,14 @@@ def get_hermes_home_override() -> strreturn str(override) if override is not _UNSET and override else None+ def _expand_hermes_home(path: str) -> Path:+ """Expand environment and user-home syntax in a Hermes home path."""+ return Path(os.path.expanduser(os.path.expandvars(path)))++def _get_platform_default_hermes_home() -> Path:- """Return the platform-native default Hermes home path."""+ """Return the platform default with the literal data-directory suffix."""+ suffix = os.environ.get("HERMES_DATA_DIR_SUFFIX", "")if sys.platform == "win32":local_appdata = os.environ.get("LOCALAPPDATA", "").strip()base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"@@@ -169,17 -173,18 +174,18 @@@ LOCAL_RUNTIME_ROOT_DIRS: frozenset[str_default_hermes_root_memo: "tuple[str, str, Path] | None" = None-def get_default_hermes_root() -> Path:- """Root Hermes dir for profile-level ops: ``<root>`` when ``HERMES_HOME=<root>/profiles/<name>``."""+def get_default_hermes_root(*, home: str | Path | None = None) -> Path:+ """Root of an explicit home, or the process home when none is supplied."""global _default_hermes_root_memonative_home = _get_platform_default_hermes_home()- env_home = str(home) if home is not None else os.environ.get("HERMES_HOME", "")- env_home = os.environ.get("HERMES_HOME", "").strip()++ env_home = str(home).strip() if home is not None else os.environ.get("HERMES_HOME", "").strip()+ env_path = _expand_hermes_home(env_home) if env_home else None+ memo_key = (str(native_home), str(env_path) if env_path is not None else "")memo = _default_hermes_root_memo- if memo is not None and memo[:2] == (str(native_home), env_home):+ if memo is not None and memo[:2] == memo_key:return memo[2]result = native_home- if env_home:- env_path = Path(env_home)+ if env_path is not None:try:env_path.resolve().relative_to(native_home.resolve()) # under ~/.hermes (normal or profile mode)except ValueError: # Docker/custom root: <root>/profiles/<name> -> <root>, else HERMES_HOME itselfdiff --cc scripts/run_tests_parallel.pyindex 602e4ea23f1,9c461f88820..b78e7466f91mode 100644,100755..100644--- a/scripts/run_tests_parallel.py+++ b/scripts/run_tests_parallel.pydiff --cc tests/agent/test_save_url_image.pyindex e01834be1b8,00669062a8e..bdaa0e79de9--- a/tests/agent/test_save_url_image.py+++ b/tests/agent/test_save_url_image.py@@@ -105,12 -114,9 +115,9 @@@ class TestSaveUrlImageassert path.read_bytes() == PNG_1PX# The cache directory must be under HERMES_HOME — gateway cleanup# relies on this being the canonical location.- assert "cache/images" in str(path)+ assert os.path.join("cache", "images") in str(path)assert path.suffix == ".png"---def test_404_raises(self, http_server):"""HTTP errors must propagate — caller decides whether to fall back."""base, _ = http_serverdiff --cc tests/gateway/test_feishu.pyindex bf60e469fe0,490e9fff003..e128c8b30d7--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@@ -782,9 -776,10 +789,10 @@@ class TestAdapterBehavior(unittest.Testself.assertEqual(msg_type.value, "voice")self.assertEqual(media_urls, ["/tmp/feishu-audio.ogg"])self.assertEqual(media_types, ["audio/ogg"])+ self.assertEqual(media_text_inlined, [False])- @patch.dict(os.environ, {}, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_extract_text_message_starting_with_slash_becomes_command(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@@ -1035,7 -1029,58 +1043,58 @@@self.assertEqual(first.message_id, "om_2")self.assertEqual(first.source.message_id, first.message_id)+ @patch.dict(+ os.environ,+ {+ "HERMES_FEISHU_TEXT_BATCH_MAX_MESSAGES": "8",+ "HERMES_FEISHU_TEXT_BATCH_MAX_CHARS": "4000",+ },+ clear=False,+ )+ def test_text_batch_preserves_later_message_attachments(self):+ from gateway.config import PlatformConfig+ from gateway.platforms.event import MessageEvent, MessageType+ from gateway.session import SessionSource+ from plugins.platforms.feishu.adapter import FeishuAdapter++ adapter = FeishuAdapter(PlatformConfig())+ adapter.handle_message = AsyncMock()+ source = SessionSource(+ platform=adapter.platform,+ chat_id="oc_chat",+ chat_name="Feishu DM",+ chat_type="dm",+ user_id="ou_user",+ user_name="张三",+ )++ async def _run() -> None:+ await adapter._enqueue_text_event(+ MessageEvent(text="first", message_type=MessageType.TEXT, source=source)+ )+ await adapter._enqueue_text_event(+ MessageEvent(+ text="second",+ message_type=MessageType.TEXT,+ source=source,+ media_urls=["/cache/second.md"],+ media_types=["text/markdown"],+ media_text_inlined=[True],+ )+ )+ await adapter._flush_text_batch_now(adapter._text_batch_key(source_event))++ source_event = MessageEvent(text="", message_type=MessageType.TEXT, source=source)+ asyncio.run(_run())++ adapter.handle_message.assert_awaited_once()+ event = adapter.handle_message.await_args.args[0]+ self.assertEqual(event.text, "first\nsecond")+ self.assertEqual(event.media_urls, ["/cache/second.md"])+ self.assertEqual(event.media_types, ["text/markdown"])+ self.assertEqual(event.media_text_inlined, [True])+- @patch.dict(os.environ, {}, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_media_batch_merges_rapid_photo_messages(self):from gateway.config import PlatformConfigfrom gateway.platforms.event import MessageEvent, MessageTypediff --cc tests/hermes_cli/conftest.pyindex 822c06a2010,7f88065f335..0d11ab58c40--- a/tests/hermes_cli/conftest.py+++ b/tests/hermes_cli/conftest.py@@@ -56,6 -56,32 +56,22 @@@ def _suppress_concurrent_hermes_gate(re)[email protected](autouse=True)-def _inline_post_swap_handoff(request, monkeypatch):- """Run the post-swap tail in-process instead of re-executing ``hermes update --post-swap``.-- ``_apply_pulled_update`` / ``_update_via_zip`` hand the rest of the run to a child- interpreter on the pulled tree. A mocked updater flow must not spawn that child (it would- run a real dependency sync against the worktree), so the tail runs here through the same- payload round-trip — every step stays patchable and the payload shape is still exercised.- Tests of the hand-off itself opt out with ``@pytest.mark.real_post_swap_handoff``.- """- if request.node.get_closest_marker("real_post_swap_handoff"):- return- try:- from hermes_cli import update_cmd, update_receipt- except Exception:- return++def isolated_source_completion(monkeypatch):++ """Unit-test the completion tail in-process; real transport is tested separately."""++ from hermes_cli import update_cmd, update_completion++++ monkeypatch.setattr("hermes_cli.source_build.build_update_products", lambda *a, **kw: None)++ monkeypatch.setattr("hermes_cli.venv_sync.publish_launchers", lambda *a: None)+- def _inline(args, **payload_kwargs):- payload = update_cmd._post_swap_payload(**payload_kwargs)- if payload["receipt"]:- update_receipt.resume_update_receipt(payload["receipt"])- update_cmd._execute_post_swap(payload, args, payload_kwargs["gateway_mode"])++ def complete(request):++ update_completion._complete_selected(request)++ return {"exit_code": 0, "receipt": update_completion._read_terminal_receipt(request),++ "windows_resume": request["windows_resume"]}+- monkeypatch.setattr(update_cmd, "_hand_off_post_swap", _inline, raising=False)++ monkeypatch.setattr(update_cmd, "run_completion", complete)++@pytest.fixturedef isolated_update_runtime(monkeypatch, tmp_path, request):"""Keep mocked updater flows off the host checkout and runtime fleet."""diff --cc tests/hermes_cli/test_doctor.pyindex e81aede8de7,fddb011581f..007d059dad8--- a/tests/hermes_cli/test_doctor.py+++ b/tests/hermes_cli/test_doctor.py@@@ -474,6 -413,42 +474,42 @@@ class TestDoctorMemoryProviderSectionassert ("Built-in memory files disabled by config" in out) is not memory_enabled+ def test_run_doctor_termux_treats_docker_and_browser_warnings_as_expected(monkeypatch, tmp_path):+ helper = TestDoctorMemoryProviderSection()+ monkeypatch.setenv("TERMUX_VERSION", "0.118.3")+ monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")++ real_which = shutil.which++ def fake_which(cmd):+ if cmd in {"docker", "node", "npm"}:+ return None+ return real_which(cmd)++ monkeypatch.setattr(shutil, "which", fake_which)+ # The docker check resolves through find_docker() (which also knows the macOS Docker+ # Desktop paths), so pin it off the host instead of relying on PATH alone.+ from hermes_cli import doctor_tools++ monkeypatch.setattr(doctor_tools, "find_docker", lambda: None)++ out = helper._run_doctor_and_capture(monkeypatch, tmp_path, provider="")++ assert "Docker backend is not available inside Termux" in out+ assert "Node.js not found (browser tools are optional in the tested Termux path)" in out+ assert "Install Node.js on Termux with: pkg install nodejs" in out+ assert "Termux browser setup:" in out+ assert "1) pkg install nodejs" in out+ assert "2) npm install -g agent-browser" in out+ assert "3) agent-browser install" in out+ assert "Termux compatibility fallbacks:" in out- assert "use .[termux-all] for broad compatibility" in out++ assert "Termux uses the Hermes APT package: pkg install hermes-agent." in out+ assert "Matrix E2EE extra is excluded on Termux" in out+ assert "Local faster-whisper extra is excluded on Termux" in out+ assert "STT fallback: use Groq Whisper (set GROQ_API_KEY) or OpenAI Whisper (set VOICE_TOOLS_OPENAI_KEY)." in out+ assert "docker not found (optional)" not in out++def test_run_doctor_accepts_named_provider_from_providers_section(monkeypatch, tmp_path):home = tmp_path / ".hermes"home.mkdir(parents=True, exist_ok=True)diff --cc tests/hermes_cli/test_kanban_gateway_restart_handoff.pyindex d7e3c316638,e6088ea2ecb..7f201c694a8--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py@@@ -141,7 -143,52 +143,52 @@@ def test_standalone_dispatcher_keeps_diassert captured_cmd[:3] == ["hermes", "-p", "coder"]+ @pytest.mark.linux_only+ def test_oneshot_unit_dispatcher_scope_wraps_or_warns_never_dooms_silently(+ worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+ ) -> None:+ """A dispatcher under any systemd unit that is NOT the supervised gateway (a+ ``Type=oneshot`` dispatch timer, #113612) loses its cgroup at unit exit. With a+ user bus the worker gets its own ``hermes-worker-*`` scope; without one the+ spawn still happens (the unit's ``KillMode``/lifetime is unknowable, a+ long-lived sequencer keeps working) but the operator is told exactly why the+ workers may die. A cron caller under the same unit is unchanged."""+ from tools import process_registry++ workspace, task = worker_setup+ spawned: list[list[str]] = []++ class FakeProc:+ pid = 4243++ monkeypatch.setattr(subprocess, "Popen", lambda cmd, **kwargs: spawned.append(list(cmd)) or FakeProc())+ monkeypatch.setenv("INVOCATION_ID", "oneshot-dispatch-timer")+ monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: False)+ monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: True)+ monkeypatch.setattr(+ process_registry, "_build_systemd_scope_argv",+ lambda cmd, unit_suffix: ["systemd-run", "--user", "--scope", "--unit", f"hermes-worker-{unit_suffix}", *cmd],+ )++ kbd._default_spawn(task, str(workspace))+ assert spawned[-1][:3] == ["systemd-run", "--user", "--scope"]+ assert f"hermes-worker-kanban-{task.id}-run-{task.current_run_id}" in spawned[-1]++ monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: False)+ monkeypatch.setattr(process_registry, "_scope_degraded_warned", False)+ with caplog.at_level("WARNING", logger=process_registry.logger.name):+ kbd._default_spawn(task, str(workspace))+ assert spawned[-1][:3] == ["hermes", "-p", "coder"]+ warned = [r.getMessage() for r in caplog.records if "KILLED when the unit exits" in r.getMessage()]+ assert len(warned) == 1 and "KillMode=process" in warned[0]++ cron = process_registry.restart_safe_gateway_child_argv(+ ["hermes", "cron"], unit_suffix="cron-job-1", require_restart_safe_scope=True,+ )+ assert cron.mode == "in_process"++[email protected]_only[email protected]("linux")def test_real_user_systemd_scope_preserves_worker_context(worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch) -> None:diff --cc tests/hermes_cli/test_local_runtime.pyindex 0694d11db43,50fb9753f4b..88dcfcdd8be--- a/tests/hermes_cli/test_local_runtime.py+++ b/tests/hermes_cli/test_local_runtime.py@@@ -795,6 -867,19 +795,19 @@@ def test_bootstrap_failure_never_raisesraise RuntimeError("no network")monkeypatch.setattr(- "hermes_cli.local_runtime.binaries.ensure_runtime_installed", boom)+ "hermes_cli.local_runtime.binaries.installed_engine", boom)result = bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}})assert result is None # no exception escaped+++ def test_manifest_verified_tolerates_non_dict_manifest(tmp_path):+ """A parseable-but-non-object manifest used to raise AttributeError out of+ manifest_verified (the .get ran inside a try that only caught decode/OSError),+ breaking any() scans over install dirs."""+ from hermes_cli.local_runtime.binaries import manifest_verified++ m = tmp_path / "manifest.json"+ m.write_text('"oops"', encoding="utf-8")+ assert manifest_verified(m) is False+ m.write_text(json.dumps({"verified_version": "5015 (abc)"}), encoding="utf-8")+ assert manifest_verified(m) is Truediff --cc tests/hermes_cli/test_mcp_catalog.pyindex b81b0990f6a,2939172ecc6..59164027142--- a/tests/hermes_cli/test_mcp_catalog.py+++ b/tests/hermes_cli/test_mcp_catalog.py@@@ -555,7 -588,50 +555,48 @@@ class TestInstallassert "${MCP_DEMO_API_KEY}" in rawassert "secret-val" not in raw+ def test_install_oauth_preregistered_client_writes_oauth_block(self, catalog_dir, monkeypatch):+ """Vendors without DCR: ``auth.oauth`` lands verbatim in ``mcp_servers.<name>.oauth`` while+ the credentials it references are prompted into .env — config.yaml stays secret-free."""+ auth = {+ "type": "oauth",+ "env": [+ {"name": "DEMO_CLIENT_ID", "prompt": "id", "secret": False},+ {"name": "DEMO_CLIENT_SECRET", "prompt": "secret"},+ ],+ "oauth": {+ "client_id": "${DEMO_CLIENT_ID}", "client_secret": "${DEMO_CLIENT_SECRET}",+ "redirect_host": "localhost", "redirect_port": 27890,+ },+ }+ _write_manifest(catalog_dir, "demo", _basic_manifest(+ transport={"type": "http", "url": "https://mcp.example.com/v2/mcp"}, auth=auth))++ from hermes_cli import mcp_catalog+ from hermes_cli.config import get_config_path, get_env_value, load_config++ monkeypatch.setattr(mcp_catalog, "_prompt_input", lambda prompt, **kw: f"val-for-{prompt}")+ mcp_catalog.install_entry(_entry("demo"), enable=True)++ server = load_config()["mcp_servers"]["demo"]+ assert server["auth"] == "oauth"+ assert server["oauth"] == {+ "client_id": "val-for-id", "client_secret": "val-for-secret",+ "redirect_host": "localhost", "redirect_port": 27890,+ }+ assert get_env_value("DEMO_CLIENT_SECRET") == "val-for-secret"+ raw = get_config_path().read_text(encoding="utf-8")+ assert "${DEMO_CLIENT_SECRET}" in raw and "val-for-secret" not in raw++ # A ``${VAR}`` the manifest never declares would reach the token endpoint as a literal+ # placeholder (invalid_client): rejected at parse time, like the api_key header contract.+ auth["oauth"]["client_id"] = "${UNDECLARED_ID}"+ path = _write_manifest(catalog_dir, "demo2", _basic_manifest(+ "demo2", transport={"type": "http", "url": "https://mcp.example.com/v2/mcp"}, auth=auth))+ with pytest.raises(mcp_catalog.CatalogError, match="UNDECLARED_ID"):+ mcp_catalog._parse_manifest(path)+--# ---------------------------------------------------------------------------# Uninstall# ---------------------------------------------------------------------------diff --cc tests/hermes_cli/test_pending_supervisor_recovery.pyindex a0a29618d75,b886e606bfb..78b5ac9d7d3--- a/tests/hermes_cli/test_pending_supervisor_recovery.py+++ b/tests/hermes_cli/test_pending_supervisor_recovery.py@@@ -4,10 -4,61 +4,10 @@@ from types import SimpleNamespacimport pytest- from hermes_cli import gateway, main, update_cmd_fleet as fleet+ from hermes_cli import gateway, main, update_cmd_fleet as fleet, update_receipt[email protected]_only[email protected]("failure", ["listing", "timeout", "missing", "restart", "inactive", "running", "missing-owned", None])-def test_pending_marker_requires_complete_systemd_recovery(monkeypatch, tmp_path, failure):- stopped = []- monkeypatch.setattr(gateway, "find_gateway_pids", lambda **kw: [123] if failure == "running" and not stopped else [])- monkeypatch.setattr(gateway, "kill_gateway_processes", lambda **kw: stopped.append(True))- monkeypatch.setattr(gateway, "_wait_for_gateway_exit", lambda **kw: None)- monkeypatch.setattr(gateway, "supports_systemd_services", lambda: True)- monkeypatch.setattr(fleet, "_SYSTEMD_SCOPES", (("user", ["systemctl", "--user"]),))- monkeypatch.setattr(fleet._time, "sleep", lambda _: None)- ticks = iter(range(1000))- monkeypatch.setattr(fleet._time, "monotonic", lambda: next(ticks))- recovered = []- def systemctl(cmd, **kw):- if "list-units" in cmd:- if stopped:- return SimpleNamespace(returncode=0, stdout="", stderr="")- if failure == "timeout":- raise subprocess.TimeoutExpired(cmd, 10)- if failure == "missing":- raise FileNotFoundError("systemctl")- return SimpleNamespace(returncode=int(failure == "listing"), stdout=(- "hermes-gateway-one.service loaded active running\n"- + ("" if failure == "missing-owned" else "hermes-gateway-two.service loaded failed failed\n")), stderr="")- bad = cmd[-1] == "hermes-gateway-two"- if "restart" in cmd:- recovered.append(cmd[-1])- return SimpleNamespace(returncode=int(bad and failure == "restart"), stdout="")- if "is-active" in cmd:- active = not (bad and failure == "inactive")- return SimpleNamespace(returncode=0 if active else 3, stdout="active" if active else "inactive")- return SimpleNamespace(returncode=0, stdout="0s")-- monkeypatch.setattr(fleet, "_systemctl", systemctl)- monkeypatch.setattr(fleet, "_current_checkout_sha", lambda: "pending")- monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **kw: [- {"profile": name.removeprefix("hermes-gateway-"), "state": "current", "code_sha": "pending"}- for name in recovered- ])- fleet._write_fleet_restart_pending_marker(expected_sha="pending", runtimes=[- {"kind": "gateway", "profile": profile} for profile in ("one", "two")- ])- marker = fleet._fleet_restart_pending_marker_path()- if failure not in (None, "running"):- with pytest.raises(SystemExit, match="1"):- fleet._apply_pending_fleet_restart_catchup()- assert marker.exists()- else:- fleet._apply_pending_fleet_restart_catchup()- assert not marker.exists()- assert set(recovered) == {"hermes-gateway-one", "hermes-gateway-two"}@pytest.mark.parametrize("failure", ["listing", "restart", "inactive", "unloaded", None])diff --cc tests/hermes_cli/test_plugins_cmd_catalog.pyindex 6bc214a0c30,c7c99c02363..9dbd109a056--- a/tests/hermes_cli/test_plugins_cmd_catalog.py+++ b/tests/hermes_cli/test_plugins_cmd_catalog.py@@@ -97,5 -95,19 +97,19 @@@ def test_kill_list_blocks_cli_dashboardwith pytest.raises(SystemExit):pc.cmd_install("cat-plugin", enable=False)pc.cmd_install("cat-plugin", enable=False, allow_removed=True)- assert (world["plugins_dir"] / "cat-plugin" / cat.CATALOG_SIDECAR).exists()+ assert cat.catalog_install_record(world["plugins_dir"] / "cat-plugin") is not None- assert cat.removed_annotation("cat-plugin", world["plugins_dir"] / "cat-plugin") == "malware"+ assert cat.removed_annotation("cat-plugin", world["plugins_dir"] / "cat-plugin",+ cat.resolved_removed_entries()) == "malware"+++ def test_removed_annotation_requires_a_pre_resolved_kill_list(world):+ """No on-demand fallback: callers must resolve the kill list once, never per row."""+ with pytest.raises(TypeError):+ cat.removed_annotation("cat-plugin", world["plugins_dir"] / "cat-plugin")+++ def test_owner_repo_hash_subdir_shorthand_resolves_like_the_catalog_spelling():+ from hermes_cli.plugins_cmd import _resolve_git_url+ assert _resolve_git_url("plastic-labs/honcho#hermes-plugin-honcho") == (+ "https://github.com/plastic-labs/honcho.git", "hermes-plugin-honcho")+ assert _resolve_git_url("owner/repo") == ("https://github.com/owner/repo.git", None)diff --cc tests/hermes_cli/test_setup_tts_xai_oauth.pyindex 4baa4ca6dd9,e814c6c3dfd..fc916739462--- a/tests/hermes_cli/test_setup_tts_xai_oauth.py+++ b/tests/hermes_cli/test_setup_tts_xai_oauth.py@@@ -2,7 -2,9 +2,9 @@@import json+ import pytest+-import yaml+import hermes_yaml as yamldef test_run_xai_oauth_login_from_setup_does_not_hijack_active_provider(diff --cc tests/hermes_cli/test_startup_fast_guards.pyindex 688968cd5ca,27aed5712f3..3835872ff75--- a/tests/hermes_cli/test_startup_fast_guards.py+++ b/tests/hermes_cli/test_startup_fast_guards.py@@@ -98,11 -106,52 +98,60 @@@ def test_fast_version_reports_install_massert "Install method: git" in result.stdout[email protected]("argv", [["update"], ["pm", "doctor"], ["gateway", "status"]])+def test_termux_chat_shortcut_leaves_subcommands_to_dispatch(monkeypatch, argv):+ from hermes_cli import main++ monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")+ monkeypatch.delenv("HERMES_TERMUX_DISABLE_FAST_CLI", raising=False)+ monkeypatch.setattr(sys, "argv", ["hermes", *argv])+ assert main._try_termux_fast_cli_launch() is False+ def test_literal_tilde_hermes_home_expands_before_any_reader(tmp_path):+ """A literal ``~`` in HERMES_HOME (fish, or any quoted value) is expanded at process entry.++ Before the fix ``Path("~/.x")`` was relative, so the real CLI resolved it against cwd and+ scaffolded a full home under ``<cwd>/~/.x``. The negative assertion on cwd is the+ reporter's own acceptance criterion.+ """+ fake_home = tmp_path / "home"+ cwd = tmp_path / "project"+ fake_home.mkdir()+ cwd.mkdir()+ env = {**os.environ, "HOME": str(fake_home), "USERPROFILE": str(fake_home), "HERMES_HOME": "~/.x"}+ env.pop("HERMES_DEV", None)+ env["PYTHONPATH"] = str(REPO_ROOT)+ result = subprocess.run(+ [sys.executable, "-m", "hermes_cli.main", "config", "path"],+ capture_output=True, text=True, timeout=120, cwd=cwd, env=env,+ )+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == str(fake_home / ".x" / "config.yaml")+ assert not (cwd / "~").exists(), sorted(p.name for p in cwd.iterdir())++ # Raw-reader observable: the ~30 ``os.environ["HERMES_HOME"]`` readers in hermes_cli/ never+ # call the resolver, so the entry-point hunk in main.py (not hermes_constants) must have+ # rewritten the env var by the time the module import finishes.+ probe = subprocess.run(+ [sys.executable, "-c", "import hermes_cli.main, os; print(os.environ['HERMES_HOME'])"],+ capture_output=True, text=True, timeout=120, cwd=cwd, env=env,+ )+ assert probe.returncode == 0, probe.stderr+ assert probe.stdout.strip() == str(fake_home / ".x")+++ def test_normalize_hermes_home_env_rewrites_tilde_and_leaves_absolute_alone(tmp_path, monkeypatch):+ from hermes_cli import _startup_fast++ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ monkeypatch.setenv("HERMES_HOME", "~/.x")+ _startup_fast.normalize_hermes_home_env()+ assert os.environ["HERMES_HOME"] == str(tmp_path / ".x")++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "abs"))+ _startup_fast.normalize_hermes_home_env()+ assert os.environ["HERMES_HOME"] == str(tmp_path / "abs")++ monkeypatch.delenv("HERMES_HOME")+ _startup_fast.normalize_hermes_home_env()+ assert "HERMES_HOME" not in os.environdiff --cc tests/hermes_cli/test_update_scoped_reconciliation.pyindex 00000000000,237b1b081c2..cd6aab320aemode 000000,100644..100644--- a/tests/hermes_cli/test_update_scoped_reconciliation.py+++ b/tests/hermes_cli/test_update_scoped_reconciliation.py@@@ -1,0 -1,290 +1,87 @@@+ """Marker settlement uses its own inventory, never a historical receipt's ownership."""++ import json++ import pytest++ from hermes_cli import process_identity, update_cmd_fleet as fleet, update_receipt+ from hermes_constants import get_hermes_home++ MANUAL = {"kind": "serve", "profile": "work", "pid": 900, "supervisor": "manual-serve", "restart_via": "respawn-argv", "code_sha": "old", "detail": {"create_time": 1000.0}}+ CURRENT = {"profile": "alpha", "state": "current", "code_sha": "new"}+ GATEWAY = {"kind": "gateway", "profile": "alpha", "code_sha": "old"}++ CASES = [+ ("receipt-successor", {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}, None, [CURRENT], False),+ ("marker-external-restart", {}, "new", [CURRENT], False),+ ("missing-sibling", {"outcome": "failed", "plan": {"runtimes": [GATEWAY, dict(GATEWAY, profile="beta")]}}, "new", [CURRENT], True),+ ("stale-successor", {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}, None, [dict(CURRENT, state="stale", code_sha="old")], True),+ ("unknown-successor", {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}, None, [dict(CURRENT, state="unknown")], True),+ ("marker-no-sha", {}, "", [CURRENT], True),+ ("checkout-moved", {}, "old", [CURRENT], True),+ ("marker-empty-no-receipt", {}, "new", [], True),+ ("markerless-stamped-manual", {"outcome": "partial", "plan": {"runtimes": [MANUAL]}}, None, [], False),+ ("old-manual-new-marker", {"outcome": "success", "post_update": {"sha": "old"}, "plan": {"runtimes": [MANUAL]}, "fleet": []}, "new", [], True),+ ("same-sha-not-ownership", {"outcome": "success", "post_update": {"sha": "new"}, "plan": {"runtimes": [MANUAL]}, "fleet": []}, "new", [], True),+ ("mixed-receipt-successors", {"outcome": "partial", "plan": {"runtimes": [GATEWAY, MANUAL]}, "fleet": [dict(CURRENT, state="stale", code_sha="old")]}, None, [CURRENT], False),+ ]+++ def seed(monkeypatch, old, marker, live, alive=True):+ root = get_hermes_home() / "logs" / "update_receipts"+ root.mkdir(parents=True, exist_ok=True)+ target = root / "latest.json"+ target.write_text(json.dumps(old))+ monkeypatch.setattr(process_identity, "_pid_alive_matches", lambda *a: alive)+ monkeypatch.setattr(fleet, "_current_checkout_sha", lambda: "new")+ monkeypatch.setattr("hermes_cli.update_cmd._current_checkout_sha", lambda: "new")+ monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **k: live)+ if marker is not None:+ fleet._write_fleet_restart_pending_marker(expected_sha=marker)+ return target+++ @pytest.mark.parametrize("name,old,marker,live,pending", CASES, ids=[case[0] for case in CASES])+ def test_scoped_reconciliation_matrix(monkeypatch, capsys, name, old, marker, live, pending):+ live = list(live)+ target = seed(monkeypatch, old, marker, live)+ if name in ("marker-external-restart", "missing-sibling", "checkout-moved"):+ runtimes = [GATEWAY, dict(GATEWAY, profile="beta")] if name == "missing-sibling" else [GATEWAY]+ fleet._write_fleet_restart_pending_marker(expected_sha=marker, runtimes=runtimes)+ before = target.read_bytes()+ assert fleet._pending_fleet_restart_needed() is pending+ fleet._warn_pending_fleet_restart_on_startup()+ assert ("hermes gateway restart" in capsys.readouterr().err) is pending- # These unfinished receipts require the same evidence for startup and deferred catch-up.- fleet._apply_pending_fleet_restart_catchup(defer=True)- assert ("fleet restart deferred" in capsys.readouterr().out) is pending++ # Deferred catch-up rides the ordinary completion owner under PM; the marker++ # lifecycle is what the startup warning reflects here.+ assert target.read_bytes() == before+ assert fleet._fleet_restart_pending_marker_path().exists() is (marker is not None and pending)+ if name == "missing-sibling":+ live.append(dict(CURRENT, profile="beta"))+ assert not fleet._pending_fleet_restart_needed()+ assert not fleet._fleet_restart_pending_marker_path().exists()+ assert target.read_bytes() == before++[email protected]("alive", [True, False, None], ids=["alive", "dead", "unknown"])[email protected]("sha", ["old", "new", None], ids=["different-sha", "same-sha", "no-sha"])-def test_empty_marker_never_inherits_receipt_ownership(monkeypatch, capsys, alive, sha):- old = {"outcome": "success", "plan": {"runtimes": [MANUAL]}, "post_update": {"sha": sha}}- target = seed(monkeypatch, old, "new", [], alive)- before = target.read_bytes()- fleet._warn_pending_fleet_restart_on_startup()- warning = capsys.readouterr().err- assert "hermes gateway restart" in warning- assert ("serve [work] pid 900" in warning) is (alive is not False)- assert fleet._fleet_restart_pending_marker_path().exists()- assert target.read_bytes() == before--[email protected]("consumer", ["predicate", "startup"])-def test_reconciliation_uses_one_receipt_snapshot(monkeypatch, capsys, consumer):- old = {"outcome": "partial", "plan": {"runtimes": [MANUAL]}, "fleet": []}- seed(monkeypatch, old, None, [])- reads = []-- def read_rotating_receipt():- reads.append(True)- return old if len(reads) == 1 else {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}-- monkeypatch.setattr(update_receipt, "read_latest_receipt", read_rotating_receipt)- if consumer == "predicate":- assert not fleet._pending_fleet_restart_needed()- else:- fleet._warn_pending_fleet_restart_on_startup()- warning = capsys.readouterr().err- assert "hermes gateway restart" not in warning- assert "serve [work] pid 900" in warning- assert len(reads) == 1- assert list((get_hermes_home() / "serve_restart_pending").glob("*.json"))--[email protected]("marker", [None, "new"])[email protected]("blocked_storage", [False, True])-def test_probe_exception_does_not_hide_manual_warning(monkeypatch, capsys, marker, blocked_storage):- old = {"outcome": "partial", "plan": {"runtimes": [GATEWAY, MANUAL]}}- target = seed(monkeypatch, old, marker, [])- if marker is not None:- fleet._write_fleet_restart_pending_marker(expected_sha=marker, runtimes=[GATEWAY])- before = target.read_bytes()- if blocked_storage:- (get_hermes_home() / "serve_restart_pending").write_text("not a directory")-- def unavailable(**kwargs):- raise OSError("gateway probe unavailable")-- monkeypatch.setattr(update_receipt, "collect_fleet_versions", unavailable)- fleet._warn_pending_fleet_restart_on_startup()- warning = capsys.readouterr().err- assert "hermes gateway restart" in warning- assert "serve [work] pid 900" in warning- assert ("could not be saved" in warning) is blocked_storage- assert target.read_bytes() == before--[email protected]("completed_restart", [False, True])[email protected]("legacy", [False, True], ids=["owned-inventory", "legacy-marker"])-def test_new_marker_cannot_borrow_old_alpha_receipt(monkeypatch, capsys, legacy, completed_restart):- """N owns alpha; N+1 owns alpha and beta but dies before writing its receipt."""- old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}- if completed_restart:- old.update(post_update={"sha": "new"}, gateway_restart={"incomplete": False})- live = [CURRENT]- target = seed(monkeypatch, old, "new", live)- marker = fleet._fleet_restart_pending_marker_path()- if not legacy:- with marker.open("a") as stream:- stream.write("inventory=" + json.dumps({"version": 1, "runtimes": [GATEWAY, dict(GATEWAY, profile="beta")]}) + "\n")- receipt_before, marker_before = target.read_bytes(), marker.read_bytes()- fleet._warn_pending_fleet_restart_on_startup()- assert "hermes gateway restart" in capsys.readouterr().err- assert fleet._pending_fleet_restart_needed()- fleet._apply_pending_fleet_restart_catchup(defer=True)- assert "fleet restart deferred" in capsys.readouterr().out- assert marker.read_bytes() == marker_before- assert target.read_bytes() == receipt_before- live.append(dict(CURRENT, profile="beta"))- assert fleet._pending_fleet_restart_needed() is legacy- assert marker.exists() is legacy- assert target.read_bytes() == receipt_before--[email protected]("inventory", [None, {}, [], {"version": 2, "runtimes": [GATEWAY]}, {"version": 1, "runtimes": []}, {"version": 1, "runtimes": [GATEWAY, dict(MANUAL, detail={})]}, {"version": 1, "runtimes": [None]}, {"version": 1, "runtimes": [{"kind": "gateway", "profile": "unknown"}]}, {"version": 1, "runtimes": [{"kind": "gateway", "profile": []}]}])-def test_unverified_marker_inventory_stays_pending(monkeypatch, inventory):- seed(monkeypatch, {"outcome": "success", "plan": {"runtimes": [GATEWAY]}}, "new", [CURRENT])- marker = fleet._fleet_restart_pending_marker_path()- with marker.open("a") as stream:- stream.write("inventory=" + json.dumps(inventory) + "\n")- before = marker.read_bytes()- assert fleet._pending_fleet_restart_needed()- monkeypatch.setattr("hermes_cli.update_cmd._run_pending_fleet_restart", lambda: True)- with pytest.raises(SystemExit) as exc:- fleet._apply_pending_fleet_restart_catchup()- assert exc.value.code == 1- assert marker.read_bytes() == before--[email protected]("suffix", ['inventory={', 'inventory=null\ninventory={"version":1,"runtimes":[]}', 'broken-line'])[email protected]("suffix", ["inventory=not-json", "expected_sha=", "inventory={}", "stray=1"])+ def test_malformed_marker_stays_pending(monkeypatch, suffix):+ seed(monkeypatch, {}, "new", [CURRENT])+ marker = fleet._fleet_restart_pending_marker_path()+ with marker.open("a") as stream:+ stream.write(suffix + "\n")+ assert fleet._pending_fleet_restart_needed()+ assert marker.exists()++-def test_pulled_update_marker_owns_pre_update_inventory(monkeypatch):- from types import SimpleNamespace- from hermes_cli import update_cmd- from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan-- old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}- target = seed(monkeypatch, old, None, [CURRENT])- before = target.read_bytes()- plan = UpdatePlan(runtimes=[RuntimeRecord(kind="gateway", profile=p) for p in ("alpha", "beta")])- monkeypatch.setattr(update_cmd, "_invalidate_update_cache", lambda: None)- monkeypatch.setattr(update_cmd, "_verify_head_after_pull", lambda *a, **k: "new")-- def interrupt(*args):- raise KeyboardInterrupt-- monkeypatch.setattr(update_cmd, "_sweep_bytecode_after_update", interrupt)- with pytest.raises(KeyboardInterrupt):- update_cmd._apply_pulled_update([], "main", "old", SimpleNamespace(in_place_update=True), None, gateway_mode=False, is_fork=False, desktop_dir=None, had_desktop_app_before_update=False, pre_update_snapshot_id=None, _pre_update_plan=plan, _windows_gateway_resume=None, args=SimpleNamespace())- marker = fleet._fleet_restart_pending_marker_path()- fields = dict(line.split("=", 1) for line in marker.read_text().splitlines())- assert fields["expected_sha"] == "new"- assert json.loads(fields["inventory"]) == {"version": 1, "runtimes": plan.to_dict()["runtimes"]}- assert fleet._pending_fleet_restart_needed()- assert target.read_bytes() == before--[email protected]("successor", ["missing", "stale", "unknown", "probe-error", "current"])-def test_catchup_verifies_owned_fleet_after_restart(monkeypatch, successor):- from hermes_cli import update_cmd-- old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}- live = [CURRENT]- target = seed(monkeypatch, old, "new", live)- fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY, dict(GATEWAY, profile="beta")])- marker = fleet._fleet_restart_pending_marker_path()- receipt_before, marker_before = target.read_bytes(), marker.read_bytes()- restarted = []-- def restart():- restarted.append("alpha")- live[:] = [CURRENT]- if successor not in ("missing", "probe-error"):- live.append(dict(CURRENT, profile="beta", state=successor, code_sha="old" if successor == "stale" else "new"))- return True-- def collect(**kwargs):- if restarted and successor == "probe-error":- raise OSError("fleet unavailable")- return live-- monkeypatch.setattr(update_cmd, "_run_pending_fleet_restart", restart)- monkeypatch.setattr(update_receipt, "collect_fleet_versions", collect)- if successor == "current":- fleet._apply_pending_fleet_restart_catchup()- assert not marker.exists()- else:- with pytest.raises(SystemExit) as exc:- fleet._apply_pending_fleet_restart_catchup()- assert exc.value.code == 1- assert marker.read_bytes() == marker_before- live[:] = [CURRENT, dict(CURRENT, profile="beta")]- monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **k: live)- fleet._apply_pending_fleet_restart_catchup()- assert not marker.exists()- assert restarted == ["alpha"]- assert target.read_bytes() == receipt_before--[email protected]("blocked_storage", [False, True])-def test_verified_restart_surviving_marker_preserves_manual_debt(monkeypatch, capsys, blocked_storage):- from hermes_cli import update_cmd-- manual = [MANUAL, dict(MANUAL, pid=901)]- old = {"outcome": "partial", "post_update": {"sha": "new"}, "gateway_restart": {"incomplete": False, "phase_error": ""}, "plan": {"runtimes": [GATEWAY, *manual]}, "fleet": [CURRENT]}- target = seed(monkeypatch, old, "new", [CURRENT])- fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY, *manual])- marker = fleet._fleet_restart_pending_marker_path()- receipt_before, marker_before = target.read_bytes(), marker.read_bytes()- directory = get_hermes_home() / "serve_restart_pending"- if blocked_storage:- directory.write_text("not a directory")- restarted = []- monkeypatch.setattr(update_cmd, "_run_pending_fleet_restart", lambda: restarted.append(True) or True)- if blocked_storage:- with pytest.raises(SystemExit) as exc:- fleet._apply_pending_fleet_restart_catchup()- assert exc.value.code == 1- assert marker.read_bytes() == marker_before- directory.unlink()- restarted.clear()- fleet._apply_pending_fleet_restart_catchup()- assert not restarted- assert not marker.exists()- assert {json.loads(path.read_text())["pid"] for path in directory.glob("*.json")} == {900, 901}- fleet._warn_pending_fleet_restart_on_startup()- warning = capsys.readouterr().err- assert "hermes gateway restart" not in warning- assert "pid 900" in warning and "pid 901" in warning- assert target.read_bytes() == receipt_before--+ def test_marker_reconciliation_collects_one_live_snapshot(monkeypatch):+ seed(monkeypatch, {}, "new", [CURRENT])+ fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY])+ probes = []++ def collect(**kwargs):+ probes.append(True)+ return [CURRENT] if len(probes) == 1 else []++ monkeypatch.setattr(update_receipt, "collect_fleet_versions", collect)+ assert not fleet._pending_fleet_restart_needed()+ assert len(probes) == 1diff --cc tests/hermes_cli/test_update_stale_dashboard.pyindex bfacbd8785f,902c9452609..fc788f3fa52--- a/tests/hermes_cli/test_update_stale_dashboard.py+++ b/tests/hermes_cli/test_update_stale_dashboard.py@@@ -323,9 -327,11 +325,11 @@@ class TestDashboardUpdateCleanup"hermes_cli.main._kill_stale_dashboard_processes",return_value={"matched": [12345], "killed": [], "failed": [(12345, "denied")],"unrecovered": []},- ):+ ) as kill:- _finish_dashboard_update_cleanup([])+ update_cmd_maint._refresh_dashboard_after_update()+ # The sweep only touches this home's backends (#113978).+ assert kill.call_args.kwargs["scope_home"] == str(own_home)assert "stopped during update" not in capsys.readouterr().outdiff --cc tests/scripts/test_run_tests_parallel.pyindex e80e56ae9e8,14450ecfbec..edde659c5c0--- a/tests/scripts/test_run_tests_parallel.py+++ b/tests/scripts/test_run_tests_parallel.py@@@ -273,11 -270,107 +273,67 @@@ def _run_runner(probe_dir: Path, *extra)+ @pytest.mark.parametrize("help_flag", ["-h", "--help"])+ def test_help_prints_usage_without_discovering_or_running_tests(+ tmp_path: Path, help_flag: str+ ) -> None:+ """Runner help stays in argparse instead of becoming a pytest sweep."""+ repo_root = Path(__file__).resolve().parent.parent.parent+ runner = repo_root / "scripts" / "run_tests_parallel.py"++ proc = subprocess.run(+ [sys.executable, str(runner), "--paths", str(tmp_path / "no-tests"), help_flag],+ cwd=repo_root,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ encoding="utf-8",+ errors="replace",+ timeout=10,+ )++ assert proc.returncode == 0, proc.stdout+ assert "usage:" in proc.stdout+ assert "Discovered" not in proc.stdout+++ def test_unknown_bare_flag_errors_with_usage_instead_of_sweeping(tmp_path: Path) -> None:+ """A typo'd flag fails once, up front, and never reaches a per-file pytest.++ Bare tokens are checked against pytest's own option set, so real pytest+ forms (attached short value ``-rA``, bare ``-x``) still pass through and+ run, while ``--jbs`` is rejected with this runner's usage before discovery.+ """+ probe_dir = _make_probe_dir(tmp_path)++ proc = _run_runner(probe_dir, "--jbs")+ assert proc.returncode == 2, proc.stdout+ assert "usage:" in proc.stdout and "unrecognized arguments: --jbs" in proc.stdout+ assert "Discovered" not in proc.stdout++ proc = _run_runner(probe_dir, "-rA", "-x")+ assert proc.returncode == 0, proc.stdout+ assert "2✓" in proc.stdout or "2 passed" in proc.stdout, proc.stdout+++ def test_known_flag_missing_value_errors_with_usage_instead_of_sweeping(+ tmp_path: Path,+ ) -> None:+ """``--tb`` with no value is a pytest UsageError, not a per-file sweep.++ The flag itself is known, so an unknown-token check alone lets it through;+ pytest's own parser must be allowed to reject it up front.+ """+ probe_dir = _make_probe_dir(tmp_path)++ proc = _run_runner(probe_dir, "--tb")+ assert proc.returncode == 2, proc.stdout+ assert "usage:" in proc.stdout and "--tb: expected one argument" in proc.stdout+ assert "Discovered" not in proc.stdout-def test_bare_value_flag_keeps_its_value(tmp_path: Path) -> None:- """``-k test_alpha`` reaches pytest as a selector, not as a path.-- The value token (``test_alpha``) must NOT be swallowed by the runner's- positional-path discovery — if it were, discovery would look for a path- named ``test_alpha``, find nothing, and the run would degrade. We assert- the run succeeds AND only one of the two tests was selected (proving the- ``-k`` filter actually applied inside pytest).- """- probe_dir = _make_probe_dir(tmp_path)- proc = _run_runner(probe_dir, "-k", "test_alpha")- assert proc.returncode == 0, proc.stdout- # Exactly one test selected: the per-file summary shows "1✓" (1 passed).- # test_beta is deselected by the -k filter.- assert "1✓" in proc.stdout or "1 passed" in proc.stdout, proc.stdout- assert "2✓" not in proc.stdout, (- f"both tests ran — -k filter did not apply:\n{proc.stdout}"- )-----def test_positional_path_not_treated_as_flag(tmp_path: Path) -> None:- """A positional path arg still overrides discovery (not routed to pytest)."""- probe_dir = _make_probe_dir(tmp_path)- repo_root = Path(__file__).resolve().parent.parent.parent- runner = repo_root / "scripts" / "run_tests_parallel.py"- # Pass the probe dir positionally (no --paths), plus a bare -q.- proc = subprocess.run(- [sys.executable, str(runner), str(probe_dir), "-j", "1",- "--file-timeout", "30", "-q"],- cwd=repo_root, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- encoding="utf-8", errors="replace", timeout=60,- )- assert proc.returncode == 0, proc.stdout- # Discovery found the probe file (2 tests), proving the positional path- # was consumed as a root, not forwarded to pytest as a bad flag.- assert "test_flagprobe.py" in proc.stdout, proc.stdout--def test_file_retry_self_heals_and_prints_both_attempts(tmp_path: Path) -> None:"""A pass-on-retry is green, loud, and retains the failing traceback."""- repo_root = Path(__file__).resolve().parent.parent.parent+ repo_root = _probe_root(tmp_path)runner = repo_root / "scripts" / "run_tests_parallel.py"marker = tmp_path / "ran-once"probe = tmp_path / "test_flaky_probe.py"diff --cc tests/test_hermes_constants.pyindex 52beb5a620c,97b86b24baf..6ef5fd2052c--- a/tests/test_hermes_constants.py+++ b/tests/test_hermes_constants.py@@@ -48,7 -55,18 +48,18 @@@ class TestGetDefaultHermesRootmonkeypatch.setenv("HERMES_HOME", str(profile))assert get_default_hermes_root() == docker_root+ def test_expanded_custom_profile_returns_custom_root(self, tmp_path, monkeypatch):+ custom_root = tmp_path / "deployment"+ home_token = "$" + "HOME"+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv(+ "HERMES_HOME", f"{home_token}/deployment/profiles/research"+ )+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "native-home")++ assert get_default_hermes_root() == custom_root+- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_no_hermes_home_returns_localappdata_root_on_windows(self, tmp_path, monkeypatch):"""Native Windows falls back to %LOCALAPPDATA%\\hermes, not ~/.hermes."""local_appdata = tmp_path / "LocalAppData"diff --cc tests/tools/test_file_ops_cwd_tracking.pyindex 4436a15c183,759ce92f0ed..e2672582dfb--- a/tests/tools/test_file_ops_cwd_tracking.py+++ b/tests/tools/test_file_ops_cwd_tracking.py@@@ -18,7 -19,6 +18,8 @@@ from __future__ import annotationimport pytest++import pytest+from tools.file_operations import ShellFileOperations@@@ -107,25 -125,67 +126,68 @@@ class TestShellFileOpsCwdTrackingassert result.exit_code == 0assert "fixed-content" in result.stdout+ @pytest.mark.platforms("linux")+ def test_patch_returns_success_only_when_file_actually_written(self, tmp_path):+ """Safety rail: patch_replace success must reflect the real file state.++ This test doesn't trigger the bug directly (it would require manual+ corruption of the write), but it pins the invariant: when+ patch_replace returns success=True, the file on disk matches the+ intended content. If a future write_file change ever regresses,+ this test catches it.+ """+ target = tmp_path / "file.txt"- target.write_text("old content\n")++ target.write_text("old content\n", encoding="utf-8")++ env = _FakeEnv(start_cwd=str(tmp_path))+ ops = ShellFileOperations(env, cwd=str(tmp_path))++ result = ops.patch_replace(str(target), "old content\n", "new content\n")+ assert result.success is True+ assert result.error is None- assert target.read_text() == "new content\n", (++ assert target.read_text(encoding="utf-8") == "new content\n", (+ "patch_replace claimed success but file wasn't written correctly"+ )+++ def test_wrapper_cd_failure_names_the_invalid_working_directory(self, tmp_path):+ """When the backend's own ``builtin cd -- <cwd> || exit 126`` fails (a+ host ``terminal.cwd`` inside a container, #113894) the surfaced error+ must name the working directory / ``terminal.cwd`` problem, not just+ the raw ``cd:`` line that reads like a fault at the requested path."""+ host_cwd = r"C:\Users\rashi\OneDrive\Documents\ai_workspace"+ ops = ShellFileOperations(_WrapperEnv(host_cwd))+ result = ops.write_file(str(tmp_path / "probe.py"), "print('hi')\n")++ assert result.error is not None+ assert "terminal.cwd" in result.error and host_cwd in result.error+ assert "No such file or directory" in result.error # the shell's own line is kept+ assert not (tmp_path / "probe.py").exists()++ @pytest.mark.parametrize("op", ["read_file", "read_file_raw", "read_file_bytes", "patch", "search"])+ def test_wrapper_cd_failure_is_reported_as_such_on_every_read_path(self, tmp_path, op):+ """#98723: a wrapper-level failure must be reported as what it is on the+ paths that do NOT embed stdout (stat-probe reads, patch pre-image, search),+ never as 'environment unavailable' / 'file not found' / 'rg or find missing';+ and no ``_has_command`` verdict may be cached from a probe that never ran."""+ target = tmp_path / "t.txt"+ target.write_text("hello\n", encoding="utf-8")+ ops = ShellFileOperations(_WrapperEnv("/Users/nobody/ws"))+ result = {+ "read_file": lambda: ops.read_file(str(target)),+ "read_file_raw": lambda: ops.read_file_raw(str(target)),+ "read_file_bytes": lambda: ops.read_file_bytes(str(target)),+ "patch": lambda: ops.patch_replace(str(target), "hello", "bye"),+ "search": lambda: ops.search("t*", str(tmp_path), target="files"),+ }[op]()+ assert "/Users/nobody/ws" in result.error and "No such file or directory" in result.error+ assert "unavailable" not in result.error and "requires" not in result.error+ assert ops._has_command("find") is False+ assert ops._command_cache == {} # a later valid cwd must re-probe++ def test_container_hint_only_for_container_backends(self, tmp_path):+ """The in-container path hint misdirects on local/ssh backends (the cwd may+ be an explicit arg, a session ``cd`` or a deleted directory)."""+ local = ShellFileOperations(_WrapperEnv("/nope/local", env_type="local")).read_file_raw("/x")+ docker = ShellFileOperations(_WrapperEnv("/nope/docker", env_type="docker")).read_file_raw("/x")+ assert "/workspace" not in local.error+ assert "/workspace" in docker.error-- def test_patch_returns_success_only_when_file_actually_written(self, tmp_path):- """Safety rail: patch_replace success must reflect the real file state.-- This test doesn't trigger the bug directly (it would require manual- corruption of the write), but it pins the invariant: when- patch_replace returns success=True, the file on disk matches the- intended content. If a future write_file change ever regresses,- this test catches it.- """- target = tmp_path / "file.txt"- target.write_text("old content\n", encoding="utf-8")-- env = _FakeEnv(start_cwd=str(tmp_path))- ops = ShellFileOperations(env, cwd=str(tmp_path))-- result = ops.patch_replace(str(target), "old content\n", "new content\n")- assert result.success is True- assert result.error is None- assert target.read_text(encoding="utf-8") == "new content\n", (- "patch_replace claimed success but file wasn't written correctly"- )diff --cc tests/tools/test_process_registry.pyindex 304ab36848a,4b7f7c2c5a0..e1255072f71--- a/tests/tools/test_process_registry.py+++ b/tests/tools/test_process_registry.py@@@ -1689,10 -1684,9 +1689,10 @@@ class TestTerminateHostPidWindowsassert "/F" in captured["args"], "Force flag required for headless Chromium"class TestTerminateHostPidPosix:- """POSIX branch walks the tree via psutil and SIGTERMs children first."""+ """POSIX branch gives a managed parent its shutdown window first."""+ @pytest.mark.platforms("linux")- def test_posix_walks_tree_and_terminates_children_then_parent(self, monkeypatch):+ def test_posix_terminates_parent_before_snapshot_descendants(self, monkeypatch):from tools import process_registry as primport psutil@@@ -1725,11 -1718,51 +1724,52 @@@pr.ProcessRegistry._terminate_host_pid(12345)- assert terminate_order == [101, 102, 103, 12345], (- "Children must be terminated before the parent"+ assert terminate_order == [12345, 101, 102, 103], (+ "Parent must receive SIGTERM before any snapshot descendant")+ @pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal ordering; Windows uses taskkill")+ @pytest.mark.live_system_guard_bypass+ def test_posix_self_reaping_supervisor_child_is_never_signalled_by_registry(self, monkeypatch, tmp_path):+ """A parent that tears down its own children on SIGTERM keeps that job.++ #111598: Chromium/Electron reap their zygotes during an async SIGTERM+ shutdown; SIGTERMing the descendants first left the browser without a+ zygote and it crash-dumped (SIGTRAP). Invariant: the registry signals the+ parent first and a child the parent reaps inside the grace window is+ never signalled by the registry, so the parent exits 0.+ """+ monkeypatch.setattr(ProcessRegistry, "_daemon_term_grace_seconds",+ staticmethod(lambda: 2.0))+ log = tmp_path / "order.log"+ child_sh = tmp_path / "child.sh"+ parent_sh = tmp_path / "parent.sh"+ # Child logs a registry-delivered TERM; the parent kills it with KILL+ # (logs nothing) and reaps it, then exits 0 — like a browser reaping its zygote.+ child_sh.write_text(+ "#!/bin/bash\n"+ f"trap 'echo child-TERM >> {log}; exit 0' TERM\n"+ f"echo up >> {log}\nwhile :; do sleep 0.1; done\n")+ parent_sh.write_text(+ "#!/bin/bash\n"+ f"bash {child_sh} & kid=$!\n"+ f"trap 'echo parent-TERM >> {log}; kill -KILL $kid; wait $kid; exit 0' TERM\n"+ "while :; do sleep 0.1; done\n")+ parent = subprocess.Popen(["bash", str(parent_sh)], stdin=subprocess.DEVNULL)+ try:+ assert _wait_until(lambda: log.exists() and "up" in log.read_text(), timeout=5.0)+ ProcessRegistry._terminate_host_pid(parent.pid)+ assert _wait_until(lambda: parent.poll() is not None, timeout=5.0)+ lines = log.read_text().split()+ assert parent.returncode == 0, f"supervisor must exit cleanly, got {parent.returncode}"+ assert "parent-TERM" in lines and "child-TERM" not in lines, (+ f"registry must SIGTERM only the parent, which reaps its own child: {lines}")+ finally:+ if parent.poll() is None:+ parent.kill()+ parent.wait()++ @pytest.mark.platforms("linux")def test_posix_oserror_falls_back_to_os_kill(self, monkeypatch):from tools import process_registry as primport psutildiff --cc tools/bot_live_delivery.pyindex fd7bdef097f,1668f2925d6..36931646f8b--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@@ -103,10 -103,14 +103,14 @@@ def _locked(home: Path | str)def _read(path: Path) -> dict[str, Any] | None:+ """Exact-id read: absent → None; unreadable or not a JSON object → raises (callers fail closed)."""try:- return json.loads(path.read_text(encoding="utf-8-sig"))- record = json.loads(path.read_text(encoding="utf-8"))++ record = json.loads(path.read_text(encoding="utf-8-sig"))except FileNotFoundError:return None+ if not isinstance(record, dict):+ raise ValueError(f"ticket {path.name} is not a JSON object ({type(record).__name__})")+ return record# Tickets already reported unreadable by this process. The live poller rescans thediff --cc tools/bot_mode_dm.pyindex 18b42157304,8f88da09ed5..516f5024a4f--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@@ -468,8 -475,8 +475,8 @@@ def _admit_live_dm(profile_home: Pathowner = find_canonical_live_owner(profile_home)if owner is None:return None- intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"),+ intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8-sig"),- delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest(),+ delivery_id=_dm_delivery_id(dm_file),**({"author": author} if author else {}))try:fd = os.open(intent_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)diff --cc tools/bot_relay.pyindex 2e913e09150,fc706877305..7153cdc19a3--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@@ -241,7 -240,9 +241,9 @@@ def _expire_if_stale(root: Path | str,"""True when the outbox envelope is older than ``ttl``; writes the 'queued_expired'reply so the sender's waiter resolves (best effort). Unreadable envelopes are left for the claim."""try:- env = json.loads(path.read_text(encoding="utf-8-sig")) # MERGE-CHECK: utf-8-sig kept (pm-era BOM-tolerant read fix)- env = json.loads(path.read_text(encoding="utf-8"))++ env = json.loads(path.read_text(encoding="utf-8-sig")) # BOM-tolerant (pm-era read fix)+ if not isinstance(env, dict):+ raise ValueError(f"expected a JSON object, got {type(env).__name__}")created = float(env.get("created_at") or path.stat().st_mtime)except (OSError, ValueError):return False@@@ -288,7 -289,10 +290,10 @@@ def claim_pending_envelopes(root: Pathclaimed = base / CLAIMED_DIR / path.namewith contextlib.suppress(OSError, ValueError):os.replace(path, claimed) # atomic claim- out.append(json.loads(claimed.read_text(encoding="utf-8-sig")))- envelope = json.loads(claimed.read_text(encoding="utf-8"))++ envelope = json.loads(claimed.read_text(encoding="utf-8-sig"))+ if not isinstance(envelope, dict):+ raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")+ out.append(envelope)return outdiff --cc tools/browser_lightpanda.pyindex 3ea4dfc0cfd,8fe03531e7f..67cb9e585e6--- a/tools/browser_lightpanda.py+++ b/tools/browser_lightpanda.py@@@ -315,7 -315,9 +315,9 @@@ def reap_orphaned_lightpanda() -> intfor record_path in sorted(state_dir.glob("*.json")):session_name = record_path.stemtry:- record = json.loads(record_path.read_text(encoding="utf-8"))+ record = json.loads(record_path.read_text(encoding="utf-8-sig"))+ if not isinstance(record, dict):+ raise ValueError(f"expected a JSON object, got {type(record).__name__}")except (OSError, ValueError):record_path.unlink(missing_ok=True)continuediff --cc tools/checkpoint_manager.pyindex 7b15054ba09,576ac9bc001..11033d35cbb--- a/tools/checkpoint_manager.py+++ b/tools/checkpoint_manager.py@@@ -756,20 -608,25 +756,34 @@@ class CheckpointManager"""Reset per-turn dedup. Call at the start of each agent iteration."""self._checkpointed_dirs.clear()+ def unsupported_backend_reason(self, task_id: str = "default") -> Optional[str]:+ """Explain why host checkpoints are off limits for a container-backed session.++ Classifies the task's backend at call time (nothing is remembered), so /rollback is+ refused before the first mutation and follows a backend change within the session."""+ from tools.file_tools_paths import container_backend_for_task+ backend = container_backend_for_task(task_id)+ if backend is None:+ return None+ return (+ f"Checkpoints are not taken for terminal.backend={backend}: "+ "file paths belong to the container, not this host."+ )+- # --- public API ---+ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------def record_agent_write(self, file_path: str) -> None:- """Record the content hash of a file Hermes just wrote (agent-write ledger), so safe-mode- :meth:`restore` can skip files the user hand-edited afterwards. Never raises."""+ """Record the content hash of a file Hermes just successfully wrote.++ Feeds the agent-write ledger used by :meth:`restore` in safe mode:+ at restore time, a file whose current content no longer matches the+ recorded hash was hand-edited by the user after Hermes last touched+ it, and is skipped instead of clobbered.++ Never raises — the ledger is best-effort bookkeeping.+ """if not self.enabled:returntry:diff --cc tools/read_extract.pyindex 0debd64a2c8,079ea7917d4..8a762d3f2b0--- a/tools/read_extract.py+++ b/tools/read_extract.py@@@ -408,9 -406,9 +411,9 @@@ def _notebook_outputs(cell: dict, jq_po_CELL_LABELS = {"markdown": "Markdown", "code": "Code", "raw": "Raw"}- def _extract_notebook(path: str) -> str:+ def _extract_notebook(path: str, *, display_path: Optional[str] = None) -> str:try:- with open(path, encoding="utf-8", errors="replace") as fh:+ with open(path, encoding="utf-8-sig", errors="replace") as fh:nb = json.load(fh)except (OSError, ValueError, json.JSONDecodeError) as exc:raise ExtractionError(f"Not a valid notebook: {exc}") from excdiff --cc tools/skills_hub.pyindex 62ab6defda2,10e72a876e6..03665784964--- a/tools/skills_hub.py+++ b/tools/skills_hub.py@@@ -76,6 -76,6 +76,17 @@@ def __getattr__(name: str)raise AttributeError(f"module {__name__!r} has no attribute {name!r}")++def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__++ target = _PLUGIN_COMPAT_LAZY.get(name)++ if target is None:++ return _plugin_compat_prev_getattr(name)++ import importlib++ from hermes_cli.plugin_compat import warn_once++ warn_once(__name__, name, *target)++ return getattr(importlib.import_module(target[0]), target[1])++# ---- END PLUGIN-COMPAT ----++++# ---------------------------------------------------------------------------# Install-path safety + guarded HTTP# ---------------------------------------------------------------------------@@@ -442,14 -445,14 +457,3 @@@ _PLUGIN_COMPAT_LAZY =}_plugin_compat_prev_getattr = __getattr__------def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__-- target = _PLUGIN_COMPAT_LAZY.get(name)-- if target is None:-- return _plugin_compat_prev_getattr(name)-- import importlib-- from hermes_cli.plugin_compat import warn_once-- warn_once(__name__, name, *target)-- return getattr(importlib.import_module(target[0]), target[1])--# ---- END PLUGIN-COMPAT ----diff --cc tools/tirith_security.pyindex 2d6a0ebfeda,9dad3d80ed8..6a6a80f5c06--- a/tools/tirith_security.py+++ b/tools/tirith_security.py@@@ -45,32 -56,51 +45,35 @@@ def _load_security_config() -> dict"tirith_fail_open": _env_bool("TIRITH_FAIL_OPEN", cfg.get("tirith_fail_open", True))}- # Circuit breaker: after _CRASH_LIMIT consecutive spawn/execution failures tirith is disabled- # for the rest of the process so a broken binary can't turn every tool call into a fail-open- # retry loop. Reset on success. Lock-free on purpose: a racing double-increment only opens the- # breaker one call early; no corruption or security bypass is possible.-# --- Module state ----# Cached path after first resolution. _INSTALL_FAILED means "tried and failed" (distinct-# from None = "not yet tried") so a failed install is not retried per command.-_resolved_path: str | None | bool = None-_INSTALL_FAILED = False-_install_failure_reason: str = "" # reason tag when _resolved_path is _INSTALL_FAILED-# Routed profiles (multiplexed gateway) resolve their own binary: ``security.tirith_path`` and-# ``<home>/bin/tirith`` are per profile, so the launch profile's slot above must not answer for them.-_resolved_path_by_home: dict[str, str] = {}-+ # Circuit breaker: after _CRASH_LIMIT consecutive spawn/execution failures tirith is disabled so a broken+ # binary can't turn every tool call into a fail-open retry loop (#41400). The breaker HALF-OPENS after+ # _CIRCUIT_RETRY_S: one caller re-probes tirith for real, and any completed scan (exit 0/1/2 — allow/block/warn+ # all prove the binary is healthy) closes it, while a failed probe re-arms the timer. Without the TTL this was+ # a one-way latch: once open, the reset branch below was unreachable for the rest of the process.+ # Thread safety: crash counting stays lock-free — a racing double-increment only opens the breaker one call+ # early, which is harmless, and matches the mcp_tool.py error counters rather than the locked _warn_once+ # pattern. _breaker_lock guards ONLY the half-open claim (TTL check + timestamp re-arm, nanoseconds); it is+ # never held across the subprocess probe, so it cannot reintroduce the #41400 hang. Claiming re-arms+ # _circuit_open_at first, so concurrent callers see a fresh TTL and stay fail-open: one probe per TTL window._CRASH_LIMIT = 3- # Reset on successful execution (see _record_tirith_crash / check_command_security). Thread safety:- # _crash_count and _circuit_open are module-level globals mutated without a lock. check_command_security can- # be called from concurrent agent threads (gateway multi-session). The race is benign — at worst two threads- # both increment past _CRASH_LIMIT and both set _circuit_open = True, opening the breaker one call early.- # This intentionally matches the lock-free style of error counters in mcp_tool.py rather than the locked- # _warn_once pattern, because the worst case is harmless. See #41400.+ _CIRCUIT_RETRY_S = 300 # half-open probe interval (seconds)_crash_count: int = 0_circuit_open: bool = False+ _circuit_open_at: float = 0.0+ _breaker_lock = threading.Lock()-_install_lock = threading.Lock()-_install_thread: threading.Thread | None = None-# Warn-once: spawn/path warnings sit in the hot path and would otherwise repeat once per# terminal command while tirith is unavailable (e.g. install thread still running)._warned_messages: set[str] = set()_warned_lock = threading.Lock()-_MARKER_TTL = 86400 # disk failure marker validity (24h) -- avoids retry across restarts--def _record_tirith_crash() -> None:- global _crash_count, _circuit_open+ global _crash_count, _circuit_open, _circuit_open_at_crash_count += 1if _crash_count >= _CRASH_LIMIT:- _circuit_open = True+ _circuit_open, _circuit_open_at = True, time.monotonic()logger.warning("tirith circuit breaker opened after %d consecutive failures; "- "disabling for the rest of the process", _crash_count)+ "disabling for %ds", _crash_count, _CIRCUIT_RETRY_S)def _warn_once(key: str, message: str, *args) -> None:@@@ -256,13 -516,19 +272,19 @@@ def check_command_security(command: strcfg = _load_security_config()if not cfg["tirith_enabled"]:return _verdict("allow")- # Circuit breaker: if tirith has crashed _CRASH_LIMIT times in a row, stop trying for the rest of the- # process. Without this, a corrupted or missing binary causes every tool call to hit the same spawn- # failure → fail-open → agent retry loop, hanging the user for 20+ minutes (issue #41400).+ # Circuit breaker: if tirith has crashed _CRASH_LIMIT times in a row, stop trying and fail open (issue+ # #41400). After _CIRCUIT_RETRY_S the breaker half-opens: exactly one caller claims the probe slot —+ # claiming re-arms _circuit_open_at under _breaker_lock, so concurrent callers see a fresh TTL and stay+ # fail-open — and falls through to a real scan below.if _circuit_open:- return _verdict("allow", "tirith disabled (circuit breaker)")+ with _breaker_lock:+ if _circuit_open and time.monotonic() - _circuit_open_at < _CIRCUIT_RETRY_S:+ return _verdict("allow", "tirith disabled (circuit breaker)")+ if _circuit_open: # TTL expired: claim the single-flight probe slot for this window+ _circuit_open_at = time.monotonic()+ logger.info("tirith circuit breaker half-open: probing after %ds", _CIRCUIT_RETRY_S)# No binary for this platform, ever: skip the resolver so we never spawn.- if not is_platform_supported():+ if cfg["tirith_path"] == "tirith" and not is_platform_supported():return _verdict("allow")tirith_path = _resolve_tirith_path(cfg["tirith_path"])timeout, fail_open = cfg["tirith_timeout"], cfg["tirith_fail_open"]diff --cc tools/write_approval.pyindex d607e7c9dc9,d767256187a..30ca642f257--- a/tools/write_approval.py+++ b/tools/write_approval.py@@@ -93,7 -93,10 +93,10 @@@ def list_pending(subsystem: str) -> Lisrecords: List[Dict[str, Any]] = []for p in _pending_files(subsystem):try:- records.append(json.loads(p.read_text(encoding="utf-8-sig")))- record = json.loads(p.read_text(encoding="utf-8"))++ record = json.loads(p.read_text(encoding="utf-8-sig"))+ if not isinstance(record, dict):+ raise ValueError(f"expected a JSON object, got {type(record).__name__}")+ records.append(record)except Exception:logger.warning("Skipping unreadable pending record: %s", p)records.sort(key=lambda r: r.get("created_at", 0))@@@ -105,10 -108,10 +108,11 @@@ def get_pending(subsystem: str, pendingpath = _pending_path(subsystem, pending_id)if not path.exists():return None- with suppress(Exception):- data = json.loads(path.read_text(encoding="utf-8"))+ try:- return json.loads(path.read_text(encoding="utf-8-sig"))++ data = json.loads(path.read_text(encoding="utf-8-sig"))+ return data if isinstance(data, dict) else None- return None+ except Exception:+ return Nonedef discard_pending(subsystem: str, pending_id: str) -> bool:diff --cc website/docs/getting-started/updating.mdindex 974f7916bcb,57fea5acc05..0acf24d78b5--- a/website/docs/getting-started/updating.md+++ b/website/docs/getting-started/updating.md@@@ -131,15 -32,16 +131,15 @@@ This suppresses both cached update noti### What happens during an update-When you run `hermes update`, the following steps occur:+For an admitted source checkout, `hermes update` runs these phases:- 1. **Pre-update snapshot** — Hermes saves selected state files for every profile in that profile's `state-snapshots/` directory. These include pairing data, cron jobs, `config.yaml`, `.env`, and `auth.json`. Automatic quick snapshots skip individual files larger than 1 GiB. `updates.pre_update_backup` selects `quick`, `full`, or `off`. Full archives use the [backup exclusions](/reference/faq#hermes-backup-vs-hermes-profile-export). Recovery uses [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots recover state files, not application code.-1. **Pre-update snapshot** — a lightweight state snapshot is saved by default (covers pairing data, cron jobs, `config.yaml`, `.env`, `auth.json`, and other state files that get modified at runtime; individual files over 1 GiB are skipped so a large sessions DB never slows the update down). Because the code swap and gateway restarts touch every profile, the same snapshot is taken for **every profile** on the install — each into its own `state-snapshots/` directory — and the post-update cron-jobs safety net checks each profile against its own snapshot. Controlled by `updates.pre_update_backup` (`quick` by default, `full` for a zip of all of `HERMES_HOME`, `off` to disable). Recoverable via the snapshot restore flow described under [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots are file-loss recovery, not code-rollback insurance — for a coherent point-in-time rollback use `--backup` (full mode). The snapshot is best-effort: if it fails, the update prints a `⚠ Pre-update snapshot FAILED` warning and continues, and the receipt records `pre_update_backup` as a failed step (a deliberate `off`/`--no-backup` lands in the receipt's skips with its reason instead).-2. **Git pull** — pulls the latest code from the `main` branch and updates submodules++1. **Pre-update snapshot** — Hermes saves selected state files for every profile in that profile's `state-snapshots/` directory. These include pairing data, cron jobs, `config.yaml`, `.env`, and `auth.json`. Automatic quick snapshots skip individual files larger than 1 GiB. `updates.pre_update_backup` selects `quick`, `full`, or `off`. Full archives use the [backup exclusions](/reference/faq#hermes-backup-vs-hermes-profile-export). Recovery uses [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots recover state files, not application code. The snapshot is best-effort: if it fails, the update prints a `⚠ Pre-update snapshot FAILED` warning and continues, and the receipt records `pre_update_backup` as a failed step (a deliberate `off`/`--no-backup` lands in the receipt's skips with its reason instead).+2. **Code update** — applies the configured source branch or stable release tag and updates submodules.3. **Post-pull syntax validation + auto-rollback** — after the pull, Hermes compiles the nine critical files every `hermes` invocation imports at startup. If any fails to parse (e.g. an orphan merge-conflict marker, an accidentally truncated file), Hermes runs `git reset --hard <pre-pull-sha>` to roll the install back so your shell stays bootable. Re-run `hermes update` once the upstream fix lands.- After this point the updater re-executes itself on the freshly pulled code (`update.log` shows `=== hermes update continued on the pulled code ===`), so the remaining steps never mix old and new modules in one process. If you see two `hermes update` processes for a moment, that is the hand-off.-4. **Dependency install** — runs `uv pip install -e ".[all]"` to pick up new or changed dependencies+4. **Dependency preparation** — PM provisions required tools and prepares a complete Python environment from the new lock, existing extras, and enabled plugin requirements. It validates that environment before publishing its selection.5. **Config migration** — detects new config options added since your version and prompts you to set them- 6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build. A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update reports `⚠ Update partially complete` and `hermes desktop` retries the rebuild.- 7. **Gateway auto-restart** — running gateways are refreshed after the update completes so the new code takes effect immediately. Service-managed gateways (systemd on Linux, launchd on macOS) are restarted through the service manager. Manual gateways are relaunched automatically when Hermes can map the running PID back to a profile. Manually-launched `hermes serve` / `hermes dashboard` backends (for example a network-bound serve powering a remote Desktop) are handled the same way: each backend records its bind address in the install's spawn ledger at startup, so the update stops it before the code swap and relaunches it afterward on the **same host and port** — a remote Desktop pointed at that endpoint reconnects instead of stranding. Backends owned by a running Desktop app are left to the app's own respawn.+ 6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build (on Windows a real-time scanner briefly holding `release/win-unpacked` is ridden out with a few short retries). A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update reports `⚠ Update partially complete` and `hermes desktop` retries the rebuild. On macOS the rebuilt bundle is then copied (with `ditto`, signature intact) over a stale `/Applications/Hermes.app` or `~/Applications/Hermes.app`, so the copy Finder and the Dock launch matches the backend; an installed copy that is currently running is left alone and the update tells you to quit it and run `hermes update` again.+ 7. **Gateway auto-restart**: running gateways are refreshed after the update completes. Service-managed gateways (systemd on Linux, launchd on macOS) restart through the service manager. Manual gateways are relaunched when Hermes can map their PID to a profile. Manually launched `hermes serve` / `hermes dashboard` backends are different: the updater leaves them running and asks their owner to restart them. See [Manual backend restart reminders](#manual-backend-restart-reminders). Backends owned by a running Desktop app remain the app's responsibility.8. **Multiplex migration (multi-profile installs)** — once the fleet is verified on the new code, an install with two or more profiles that still run **one gateway per profile** is folded into a single multiplexed default gateway when nothing blocks it (same as `hermes gateway migrate --multiplex --yes`); if a blocker exists (a bot token shared by two profiles, a secondary profile binding a port with no `/p/<profile>/` ingress) the update prints the blockers with their fixes and changes nothing. Single-profile installs are never touched. See [Migrating from per-profile gateways](../user-guide/multi-profile-gateways.md#migrating-from-per-profile-gateways).### Why the gateway restart can take a whilediff --cc website/docs/reference/environment-variables.mdindex e63046ad04a,33a1b95648f..b3033bd7eb6--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@@ -123,8 -123,8 +123,8 @@@ Hermes reads environment variables fro| `VOICE_TOOLS_OPENAI_KEY` | Preferred OpenAI key for OpenAI speech-to-text and text-to-speech providers || `HERMES_LOCAL_STT_COMMAND` | Optional local speech-to-text command template. Supports `{input_path}`, `{output_dir}`, `{language}`, and `{model}` placeholders || `HERMES_LOCAL_STT_LANGUAGE` | Default language hint for STT. Used by the `local` (faster-whisper) provider, `HERMES_LOCAL_STT_COMMAND`, the local `whisper` CLI fallback (default: `en`), Groq, and xAI when no per-provider `language` is set in `config.yaml` |- | `HERMES_HOME` | Select the configuration and user-data home. Defaults to `~/.hermes` on POSIX and `%LOCALAPPDATA%\hermes` on Windows; the official Docker image uses `/opt/data`. Profile/runtime context can select a more specific home. |-| `HERMES_HOME` | Override Hermes config directory (default: `~/.hermes`). A literal `~` or `$VAR` in the value is expanded (fish does not expand `~` inside `VAR=~/…`), so it never resolves relative to the current directory. Also scopes the gateway PID file and systemd service name, so multiple installations can run concurrently |-| `HERMES_GIT_BASH_PATH` | **Windows only.** Override `bash.exe` discovery for the terminal tool. Points at any bash — full Git-for-Windows install, WSL bash via symlink, MSYS2, Cygwin. The installer sets this automatically to the PortableGit it provisioned. See the [Windows (Native) Guide](../user-guide/windows-native.md#how-hermes-runs-shell-commands-on-windows) |++| `HERMES_HOME` | Select the configuration and user-data home. A literal `~` or `$VAR` in the value is expanded (fish does not expand `~` inside `VAR=~/…`), so it never resolves relative to the current directory. Defaults to `~/.hermes` on POSIX and `%LOCALAPPDATA%\hermes` on Windows; the official Docker image uses `/opt/data`. Profile/runtime context can select a more specific home. |+| `HERMES_DATA_DIR_SUFFIX` | Append this value literally to the default Hermes home and default Electron `userData` directory. For example, `-asdfasdf` selects `~/.hermes-asdfasdf`, while `magic-test` selects `~/.hermesmagic-test` on POSIX. No separator is added. Named profiles and shared root data stay under the suffixed home. Explicit `HERMES_HOME` and `HERMES_DESKTOP_USER_DATA_DIR` keep their existing precedence and are not suffixed. Set this in the launch environment, before startup, not in `.env` or `config.yaml` inside the home being selected. An unset or empty value keeps the ordinary defaults. || `HERMES_DISABLE_WINDOWS_UTF8` | **Windows only.** Set to `1` to disable the UTF-8 stdio shim (`configure_windows_stdio()`) and fall back to the console's locale code page. Useful for bisecting encoding bugs; rarely the right setting in normal operation || `HERMES_KANBAN_HOME` | Override the shared Hermes root that anchors the kanban board (db + workspaces + worker logs). Falls back to `get_default_hermes_root()` (the parent of any active profile). Useful for tests and unusual deployments || `HERMES_KANBAN_BOARD` | Pin the active kanban board for this process. Takes precedence over `~/.hermes/kanban/current`; the dispatcher injects this into worker subprocess env so workers physically cannot see tasks on other boards. Defaults to `default`. Slug validation: lowercase alphanumerics + hyphens + underscores, 1-64 chars |diff --cc website/docs/user-guide/security.mdindex 40a73343f72,766befd5191..054cbd5252f--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@@ -800,10 -799,9 +808,12 @@@ securityWhen `tirith_fail_open` is `true` (default), commands proceed if tirith is not installed or times out. Set to `false` in high-security environments to block commands when tirith is unavailable.+ Three consecutive operational failures (spawn error, timeout, crash) suspend scanning for five minutes so a broken binary cannot stall every command; after that window one command re-probes tirith, and any completed scan (allow, warn or block) resumes normal scanning. A probe that fails again re-arms the five-minute window.+-Tirith ships prebuilt binaries for Linux (x86_64 / aarch64) and macOS (x86_64 / arm64). On platforms with no prebuilt binary (Windows, etc.), tirith is silently skipped — pattern-matching guards still run, and the CLI does not surface an "unavailable" banner. To use tirith on Windows, run Hermes under WSL.+PM supports Tirith on Linux (x86_64 / aarch64) and macOS (x86_64 / arm64).+With the default path, unsupported targets, including native Windows and+Android/Termux, skip Tirith. Pattern-matching guards still run. To use the managed+Tirith package on Windows, run Hermes under WSL.Tirith's verdict integrates with the approval flow: safe commands pass through, while both suspicious and blocked commands trigger user approval with the full tirith findings (severity, title, description, safer alternatives). Users can approve or deny — the default choice is deny to keep unattended scenarios secure.