The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
teknium166619edb0e74
diff --cc apps/desktop/electron/local-gateway.test.tsindex ef09f9fc63d,00000000000..b5cd444d155mode 100644,000000..100644--- a/apps/desktop/electron/local-gateway.test.ts+++ b/apps/desktop/electron/local-gateway.test.ts@@@ -1,250 -1,0 +1,264 @@@+import { expect, test } from 'vitest'+- import { createLocalGatewayDials, ensureLocalGateway, routedGatewayEndpoint } from './local-gateway'++import { createLocalGatewayDials, ensureLocalGateway, routedGatewayEndpoint, runGatewayEnsure } from './local-gateway'++++test('the ensure client inherits the caller-scrubbed parent env, not the raw Desktop env', async () => {++ // #68367: a sibling profile's `gateway ensure` must not see the launch profile's dotenv++ // credentials. The parent env passed in IS the environment; only HERMES_HOME and the++ // backend's own entries are layered on top.++ const printEnv = ['-e', 'process.stdout.write(JSON.stringify({ leak: process.env.LEAK ?? null, home: process.env.HERMES_HOME, own: process.env.OWN }))']++ const result = await runGatewayEnsure(++ { command: process.execPath, args: printEnv, env: { OWN: '1' }, shell: false },++ process.cwd(),++ '/home/x/.hermes',++ { PATH: process.env.PATH ?? '', OWN: '0' }++ )++ expect(JSON.parse(result.stdout)).toEqual({ leak: null, home: '/home/x/.hermes', own: '1' })++})++test('canonical ensure cannot cross a rejected update or profile lifecycle gate', async () => {+ let ran = false+ await expect(ensureLocalGateway(async () => { ran = true;++ return { code: 0, stdout: '{}' } }, async () => {+ throw new Error('profile retired during update')+ })).rejects.toThrow('profile retired during update')+ expect(ran).toBe(false)+})++test.skipIf(process.platform === 'win32')('native HTTP mints fresh purpose-bound grants without browser credentials', async () => {+ const fs = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const net = await import('node:net')+ const { nativeGatewayHttpHeaders } = await import('./local-gateway')+ // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises+ // profile_id, so the endpoint must carry the realpath or identities never match.+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-http-')))+ const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }+ const requests: any[] = []++ const server = net.createServer(socket => socket.once('data', chunk => {+ const request = JSON.parse(chunk.toString())+ requests.push(request)+ socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', ticket: `grant-${requests.length}` } }) + '\n')+ }))++ await new Promise<void>(resolve => server.listen(path.join(home, 'gateway.sock'), resolve))+ await fs.chmod(path.join(home, 'gateway.sock'), 0o600)++ try {+ const descriptor = { gatewayEndpoint: endpoint, baseUrl: endpoint.api_origin }+ const a = await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + '/api/config')+ const b = await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + '/api/config')+ expect(a).toEqual({ 'X-Hermes-Gateway-Ticket': 'grant-1' })+ expect(b).toEqual({ 'X-Hermes-Gateway-Ticket': 'grant-2' })+ expect(requests.map(r => r.params)).toEqual([1, 2].map(() => ({ profile_id: home, instance_id: 'owner', purpose: 'native-http' })))+ await expect(nativeGatewayHttpHeaders(descriptor, 'http://127.0.0.1:4567/api/config')).rejects.toThrow('origin')+ expect(requests).toHaveLength(2)+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()))+ await fs.rm(home, { recursive: true, force: true })+ }+})++test.skipIf(process.platform === 'win32')('a served secondary mints its ticket through the multiplexer control socket, bound to its own profile', async () => {+ const fs = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const net = await import('node:net')+ const { mintLocalGatewayTicket } = await import('./local-gateway')+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-mux-')))+ const secondary = path.join(root, 'profiles', 'cold')+ await fs.mkdir(secondary, { recursive: true, mode: 0o700 })+ await fs.chmod(root, 0o700)+ // Only the multiplexer root has a control socket; profiles/cold has none (it is served).+ const requests: any[] = []++ const server = net.createServer(socket => socket.once('data', chunk => {+ requests.push(JSON.parse(chunk.toString()).params)+ socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: secondary, instance_id: 'mux', ticket: 'served-grant' } }) + '\n')+ }))++ await new Promise<void>(resolve => server.listen(path.join(root, 'gateway.sock'), resolve))+ await fs.chmod(path.join(root, 'gateway.sock'), 0o600)+ const endpoint = { profile_id: secondary, instance_id: 'mux', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }++ try {+ // Without control_home the secondary's own (absent) socket is probed: stale owner, not a grant.+ await expect(mintLocalGatewayTicket(endpoint, 'native-http')).rejects.toThrow('Gateway ticket control socket missing')+ expect(await mintLocalGatewayTicket({ ...endpoint, control_home: root }, 'native-http')).toBe('served-grant')+ expect(requests).toEqual([{ profile_id: secondary, instance_id: 'mux', purpose: 'native-http' }])+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()))+ await fs.rm(root, { recursive: true, force: true })+ }+})++test('ensure consumes structured readiness without acquiring a child owner', async () => {+ const endpoint = { profile_id: '/private/profile', instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }+ const connection = await ensureLocalGateway(async () => ({ code: 0, stdout: JSON.stringify({ state: 'ready', endpoint }) }))+ expect(connection.baseUrl).toBe(endpoint.api_origin)+ expect(connection.gatewayEndpoint).toEqual(endpoint)+ expect(connection).not.toHaveProperty('process')+ expect(connection.token).toBe('')+ await expect(ensureLocalGateway(async () => ({ code: 5, stdout: JSON.stringify({ state: 'starting', reason_code: 'deadline' }) }))).rejects.toThrow('starting')+})++test('an ensure child that never reached the protocol boundary is diagnosed from stderr, not as a JSON parse error', async () => {+ // `main`'s hermes has no `gateway ensure` subcommand: argparse usage on stderr, nothing on stdout.+ const legacy = { code: 2, stdout: '', stderr: "usage: hermes gateway [-h] ...\nhermes gateway: 'ensure' is not a `hermes gateway` command.\nRun `hermes gateway --help` to see all commands.\n" }+ await expect(ensureLocalGateway(async () => legacy)).rejects.toThrow(/produced no result \(exit 2\): Run `hermes gateway --help`/)+ // A missing profile: the CLI exits 1 before the ensure command runs.+ await expect(ensureLocalGateway(async () => ({ code: 1, stdout: '', stderr: "Error: Profile 'gone' does not exist.\n" }))).rejects.toThrow(/exit 1\): Error: Profile 'gone' does not exist\./)+ // A protocol outcome is never re-diagnosed: `incompatible` stays the gateway's own verdict.+ await expect(ensureLocalGateway(async () => ({ code: 3, stdout: '{"endpoint":null,"reason_code":"runtime_protocol","state":"incompatible"}', stderr: 'noise' }))).rejects.toThrow('Gateway incompatible (runtime_protocol)')+ await expect(ensureLocalGateway(async () => ({ code: 0, stdout: '', stderr: '' }))).rejects.toThrow(/produced no result \(exit 0\)\. Update Hermes/)+})++test('private dial credential is one-use and bound to the requesting native window', () => {+ const dials = createLocalGatewayDials()+ const dial = new URL(dials.prepare('http://127.0.0.1:1234', 'private-ticket', 7))+ expect(dial.searchParams.get('ticket')).toBe('private-ticket')+ dial.searchParams.delete('ticket')+ const url = dial.toString()+ expect(url).not.toContain('private-ticket')+ const details = { url, webContentsId: 8, resourceType: 'webSocket', requestHeaders: { Origin: 'http://renderer', 'Sec-WebSocket-Protocol': 'hermes-gateway-v1, hermes-gateway-ticket.private-ticket' } }+ expect(dials.headers(details)).toBeNull()+ // The dial may cross a loopback proxy that rewrites host:port but keeps the nonce.+ const proxied = url.replace('127.0.0.1:1234', '127.0.0.1:4321')+ const headers = dials.headers({ ...details, url: proxied, webContentsId: 7 })!+ expect(headers).not.toHaveProperty('Origin')+ expect(headers['Sec-WebSocket-Protocol']).toBe('hermes-gateway-v1, hermes-gateway-ticket.private-ticket')+ expect(dials.headers({ ...details, webContentsId: 7 })).toBeNull()+})++test('a dial against a replaced local gateway forgets the cached endpoint once and re-ensures', async () => {+ const { redialLocalGateway } = await import('./local-gateway')+ const endpoints = [{ instance_id: 'dead' }, { instance_id: 'alive' }]+ const forgotten: string[] = []+ let ensures = 0++ const result = await redialLocalGateway({+ ensure: async () => endpoints[Math.min(ensures++, 1)],+ forget: async () => { forgotten.push('primary') },+ use: async endpoint => {+ if (endpoint.instance_id === 'dead') {throw new Error('Gateway ticket bootstrap failed')}++ return `ticket-for-${endpoint.instance_id}`+ }+ })++ expect(result).toBe('ticket-for-alive')+ expect(forgotten).toEqual(['primary'])+ expect(ensures).toBe(2)+})++test('a dial that keeps failing after one re-ensure surfaces the error instead of looping', async () => {+ const { redialLocalGateway } = await import('./local-gateway')+ let ensures = 0+ let forgets = 0+ await expect(redialLocalGateway({+ ensure: async () => { ensures++;++ return { instance_id: 'still-dead' } },+ forget: async () => { forgets++ },+ use: async () => { throw new Error('Invalid gateway ticket response') }+ })).rejects.toThrow('Invalid gateway ticket response')+ expect(ensures).toBe(2)+ expect(forgets).toBe(1)+})++test.skipIf(process.platform === 'win32')('a stopped gateway that unlinked its control socket is a stale owner, not a raw filesystem error', async () => {+ const fs = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const net = await import('node:net')+ const { mintLocalGatewayTicket, redialLocalGateway } = await import('./local-gateway')+ // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises+ // profile_id, so the endpoint must carry the realpath or identities never match.+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-redial-')))+ const socketPath = path.join(home, 'gateway.sock')+ const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }++ const serve = async (ticket: string) => {+ const server = net.createServer(socket => socket.once('data', () => {+ socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', ticket } }) + '\n')+ }))++ await new Promise<void>(resolve => server.listen(socketPath, resolve))+ await fs.chmod(socketPath, 0o600)++ return server+ }++ const stop = async (server: ReturnType<typeof net.createServer>) => {+ await new Promise<void>(resolve => server.close(() => resolve()))+ await fs.rm(socketPath, { force: true })+ }++ let replacement: ReturnType<typeof net.createServer> | null = null+ const original = await serve('grant-original')++ try {+ expect(await mintLocalGatewayTicket(endpoint)).toBe('grant-original')+ await stop(original)++ let ensures = 0+ let forgets = 0++ const result = await redialLocalGateway({+ ensure: async () => {+ ensures += 1++ if (ensures === 2) {replacement = await serve('grant-replacement')}++ return endpoint+ },+ forget: () => { forgets += 1 },+ use: e => mintLocalGatewayTicket(e)+ })++ expect(result).toBe('grant-replacement')+ expect(forgets).toBe(1)+ expect(ensures).toBe(2)+ } finally {+ if (replacement) {await stop(replacement)}+ await fs.rm(home, { recursive: true, force: true })+ }+})++test.skipIf(process.platform === 'win32')('a group-accessible control socket is refused as unsafe, and unrelated errors are never stale', async () => {+ const fs = await import('node:fs/promises')+ const os = await import('node:os')+ const path = await import('node:path')+ const net = await import('node:net')+ const { isStaleLocalGatewayError, mintLocalGatewayTicket } = await import('./local-gateway')+ // macOS: os.tmpdir() is /var/..., a symlink to /private/var; the gateway canonicalises+ // profile_id, so the endpoint must carry the realpath or identities never match.+ const home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'desktop-unsafe-')))+ const socketPath = path.join(home, 'gateway.sock')+ const endpoint = { profile_id: home, instance_id: 'owner', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1234', capabilities: ['session-authority-v1'], supervisor: 'none' }+ const server = net.createServer(socket => socket.end())+ await new Promise<void>(resolve => server.listen(socketPath, resolve))+ await fs.chmod(socketPath, 0o660)++ try {+ const failure = await mintLocalGatewayTicket(endpoint).catch(error => error)+ expect(failure).toBeInstanceOf(Error)+ expect(failure.message).toBe('Unsafe gateway control path')+ expect(isStaleLocalGatewayError(failure)).toBe(true)+ expect(isStaleLocalGatewayError(new Error('EACCES: permission denied'))).toBe(false)+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()))+ await fs.rm(home, { recursive: true, force: true })+ }+})++test('a ?profile= request on the shared host descriptor mints for the sibling profile home', () => {+ const endpoint = { profile_id: '/h/.hermes', instance_id: 'i', authority_epoch: 1, runtime_protocol: 1, api_origin: 'http://127.0.0.1:1', capabilities: [], supervisor: 'none', control_home: null }+ expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/sessions?profile=p2', '/h/.hermes')).toMatchObject({ profile_id: '/h/.hermes/profiles/p2', control_home: '/h/.hermes' })+ expect(routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/api/sessions?profile=default', '/h/.hermes')).toBe(endpoint)+ expect(routedGatewayEndpoint({ ...endpoint, profile_id: '/h/.hermes/profiles/p2', control_home: '/h/.hermes' }, 'http://127.0.0.1:1/x?profile=default', '/h/.hermes')).toMatchObject({ profile_id: '/h/.hermes' })+ expect(() => routedGatewayEndpoint(endpoint, 'http://127.0.0.1:1/x?profile=../evil', '/h/.hermes')).toThrow('Invalid profile route')+})diff --cc apps/desktop/electron/local-gateway.tsindex 2f93c65fa68,00000000000..ba607583865mode 100644,000000..100644--- a/apps/desktop/electron/local-gateway.ts+++ b/apps/desktop/electron/local-gateway.ts@@@ -1,273 -1,0 +1,275 @@@+import { spawn } from 'node:child_process'+import crypto from 'node:crypto'++import { hiddenWindowsChildOptions } from './windows-child-options'+- export function runGatewayEnsure(backend, cwd: string, home: string): Promise<{ code: number; stdout: string; stderr: string }> {++export function runGatewayEnsure(++ backend, cwd: string, home: string, parentEnv: NodeJS.ProcessEnv = process.env++): Promise<{ code: number; stdout: string; stderr: string }> {+ return new Promise((resolve, reject) => {- const child = spawn(backend.command, backend.args, hiddenWindowsChildOptions({ cwd, env: { ...process.env, HERMES_HOME: home, ...backend.env }, shell: backend.shell, stdio: ['ignore', 'pipe', 'pipe'] }))++ const child = spawn(backend.command, backend.args, hiddenWindowsChildOptions({ cwd, env: { ...parentEnv, HERMES_HOME: home, ...backend.env }, shell: backend.shell, stdio: ['ignore', 'pipe', 'pipe'] }))+ let stdout = ''+ let stderr = ''+ // Only the bounded ensure client is ours. Never retain/kill its detached owner.+ const timer = setTimeout(() => child.kill(), 40_000)+ child.stdout.on('data', data => { stdout += data.toString();++ if (stdout.length > 65536) {child.kill()} })+ // Diagnostics only (never protocol): an older `hermes` without the subcommand, a missing+ // profile or an import crash explain themselves here while stdout stays empty.+ child.stderr.on('data', data => { stderr = (stderr + data.toString()).slice(-4096) })+ child.on('error', () => { clearTimeout(timer); reject(new Error('Could not run hermes gateway ensure')) })+ child.on('close', code => { clearTimeout(timer); resolve({ code: code ?? 7, stdout, stderr }) })+ })+}++import fs from 'node:fs/promises'+import net from 'node:net'+import path from 'node:path'++export interface GatewayEndpoint {+ profile_id: string+ instance_id: string+ authority_epoch: number+ runtime_protocol: number+ api_origin: string+ capabilities: string[]+ supervisor: string+ /** Multiplexer home whose control socket answers for a served secondary; null when the profile owns its own. */+ control_home?: string | null+}++/** The single-line JSON `hermes gateway ensure --json` prints, or a diagnosis of why there is none.+ *+ * Every protocol outcome (ready/starting/incompatible/...) is JSON on stdout. Empty or+ * non-JSON stdout means the command never reached the protocol boundary: an older `hermes`+ * on PATH that has no `ensure` subcommand, a profile that does not exist, an interpreter+ * crash. A bare JSON.parse there surfaced as "Unexpected end of JSON input" with the real+ * reason discarded on stderr. */+export function parseGatewayEnsureOutput(result: { code: number; stdout: string; stderr?: string }): Record<string, any> {+ try {+ const payload = JSON.parse(result.stdout)++ if (payload && typeof payload === 'object' && !Array.isArray(payload)) {return payload}+ } catch { /* diagnosed below */ }++ const reason = String(result.stderr ?? '').trim().split(/\r?\n/).filter(Boolean).pop()++ throw new Error(`hermes gateway ensure produced no result (exit ${result.code})${reason ? `: ${reason}` : ''}. Update Hermes or check the profile, then retry.`)+}++export async function ensureLocalGateway(run: () => Promise<{ code: number; stdout: string; stderr?: string }>, beforeEnsure?: () => Promise<void>) {+ await beforeEnsure?.()+ const result = await run()+ const payload = parseGatewayEnsureOutput(result)++ if (result.code !== 0 || payload.state !== 'ready') {+ throw new Error(`Gateway ${payload.state || 'inaccessible'} (${payload.reason_code || 'ensure_failed'}). Use hermes gateway status for recovery.`)+ }++ const endpoint: GatewayEndpoint = payload.endpoint+ const origin = new URL(endpoint.api_origin)++ if (!['http:', 'https:'].includes(origin.protocol) || !['127.0.0.1', '[::1]'].includes(origin.hostname)+ || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash+ || !origin.port || endpoint.runtime_protocol !== 1 || !endpoint.instance_id || !endpoint.profile_id+ || !endpoint.capabilities.includes('session-authority-v1')) {+ throw new Error('Invalid local gateway endpoint')+ }++ return { baseUrl: endpoint.api_origin, wsUrl: `${endpoint.api_origin.replace(/^http/, 'ws')}/api/ws?native_dial=unminted`, mode: 'local', source: 'local', authMode: 'native', token: '', gatewayEndpoint: endpoint }+}++// The cached connection descriptor pins the gateway instance that answered the+// first `gateway ensure`. When that owner is gone (crash, `gateway stop`,+// update restart) every ticket mint against the stale control socket fails and+// the renderer's reconnect backoff would loop on the dead descriptor forever.+// Forget the cached descriptor exactly once and re-run the canonical ensure;+// a second failure is a real error and surfaces to the caller.+export function isStaleLocalGatewayError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error ?? '')++ return message.startsWith('Gateway ticket') || message === 'Invalid gateway ticket response' || message === 'Unsafe gateway control path'+}++export async function redialLocalGateway<TEndpoint, TResult>(deps: {+ ensure: () => Promise<TEndpoint>+ forget: () => Promise<void> | void+ use: (endpoint: TEndpoint) => Promise<TResult>+}): Promise<TResult> {+ const first = await deps.ensure()++ try {+ return await deps.use(first)+ } catch (error) {+ if (!isStaleLocalGatewayError(error)) {throw error}+ await deps.forget()++ return deps.use(await deps.ensure())+ }+}++function dialNonce(url: string): string | null {+ try {+ const parsed = new URL(url)++ return parsed.pathname === '/api/ws' ? parsed.searchParams.get('native_dial') : null+ } catch {+ return null+ }+}++// A one-use ticket crosses private IPC, then leaves the URL before dialing.+// Public descriptors and persisted connection state never contain credentials.+export function createLocalGatewayDials() {+ const pending = new Map<string, { ticket: string; webContentsId: number; expires: number }>()++ return {+ prepare(origin: string, ticket: string, webContentsId: number) {+ for (const [key, value] of pending) {if (value.expires <= Date.now()) {pending.delete(key)}}++ if (pending.size >= 100) {throw new Error('Too many pending gateway dials')}+ // Keyed by the one-use nonce, not the full URL: a loopback proxy the app dials+ // through (tests, tunnels) rewrites host:port but carries the query through.+ const nonce = crypto.randomUUID()+ const url = `${origin.replace(/^http/, 'ws')}/api/ws?native_dial=${nonce}`+ pending.set(nonce, { ticket, webContentsId, expires: Date.now() + 25_000 })++ return `${url}&ticket=${encodeURIComponent(ticket)}`+ },+ headers(details: { url: string; webContentsId?: number; resourceType: string; requestHeaders?: Record<string, string> }) {+ const nonce = dialNonce(details.url)+ const grant = nonce ? pending.get(nonce) : undefined++ if (!nonce || !grant || grant.webContentsId !== details.webContentsId || details.resourceType !== 'webSocket') {return null}+ pending.delete(nonce)++ if (grant.expires <= Date.now()) {return null}+ const headers = { ...details.requestHeaders }++ for (const key of Object.keys(headers)) {if (key.toLowerCase() === 'origin') {delete headers[key]}}++ return headers+ }+ }+}++async function privateNode(file: string, kind: 'directory' | 'socket' | 'file') {+ const node = await fs.lstat(file)+ const valid = { directory: node.isDirectory(), socket: node.isSocket(), file: node.isFile() }[kind]++ if (!valid || node.uid !== process.getuid?.() || (node.mode & 0o077)) {throw new Error('Unsafe gateway control path')}+}++/** The endpoint a `?profile=<name>` request is scoped to on a shared host descriptor: the same+ * daemon, ticket minted for the sibling profile's home (`profiles/<name>` under the launch root).+ * The gateway refuses a ticket whose profile it does not serve, so a bad name fails closed. */+export function routedGatewayEndpoint(endpoint: GatewayEndpoint, urlOrProfile: string, launchHome: string): GatewayEndpoint {+ const profile = (/^[a-z]+:\/\//.test(urlOrProfile) ? new URL(urlOrProfile).searchParams.get('profile') : urlOrProfile)?.trim()++ if (!profile || profile === 'current') {return endpoint}+ const own = path.basename(endpoint.profile_id)+ const ownName = path.basename(path.dirname(endpoint.profile_id)) === 'profiles' ? own : 'default'++ if (profile === ownName) {return endpoint}++ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(profile)) {throw new Error('Invalid profile route')}+ const root = path.basename(path.dirname(endpoint.profile_id)) === 'profiles' ? path.dirname(path.dirname(endpoint.profile_id)) : launchHome+ const home = profile === 'default' ? root : path.join(root, 'profiles', profile)++ return { ...endpoint, profile_id: home, control_home: endpoint.control_home || endpoint.profile_id }+}++export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string, launchHome = descriptor.gatewayEndpoint.profile_id) {+ if (new URL(url).origin !== descriptor.gatewayEndpoint.api_origin || descriptor.baseUrl !== descriptor.gatewayEndpoint.api_origin) {+ throw new Error('Native gateway HTTP origin mismatch')+ }++ return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(routedGatewayEndpoint(descriptor.gatewayEndpoint, url, launchHome), 'native-http') }+}++let windowsTicketClient: ((endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http') => Promise<string>) | undefined++export function configureWindowsGatewayTicketClient(client: NonNullable<typeof windowsTicketClient>) {+ windowsTicketClient = client+}++function isMissingNodeError(error: unknown): boolean {+ const code = (error as NodeJS.ErrnoException)?.code++ return code === 'ENOENT' || code === 'ENOTDIR'+}++async function resolveControlSocket(home: string): Promise<string> {+ const socketPath = path.join(home, 'gateway.sock')++ try { await privateNode(socketPath, 'socket') } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {throw error}+ const pointer = path.join(home, 'gateway.sock.path')+ await privateNode(pointer, 'file')+ const target = (await fs.readFile(pointer, 'utf8')).trim()+ const hash = crypto.createHash('sha256').update(home).digest('hex').slice(0, 16)++ if (!path.isAbsolute(target) || path.basename(path.dirname(target)) !== `hermes-gw-${hash}` || path.basename(target) !== 'control.sock') {throw new Error('Invalid gateway control pointer')}+ await privateNode(path.dirname(target), 'directory')+ await privateNode(target, 'socket')++ return target+ }++ return socketPath+}++export async function mintLocalGatewayTicket(endpoint: GatewayEndpoint, purpose: 'interactive' | 'native-http' = 'interactive'): Promise<string> {+ if (process.platform === 'win32') {+ if (!windowsTicketClient) {throw new Error('Gateway ticket client is not configured')}++ return windowsTicketClient(endpoint, purpose)+ }++ const home = endpoint.profile_id+ // A served secondary has no socket of its own: the default multiplexer's control socket+ // mints its tickets (bound to the secondary's profile_id). Same rule as+ // hermes_cli.gateway_runtime.control_home_for.+ const controlHome = endpoint.control_home || home++ for (const dir of new Set([home, controlHome])) {+ if (await fs.realpath(dir) !== dir) {throw new Error('Noncanonical gateway profile')}+ await privateNode(dir, 'directory')+ }++ let socketPath: string++ try { socketPath = await resolveControlSocket(controlHome) } catch (error) {+ // `gateway stop` unlinks both the socket and its pointer: the owner is gone,+ // which the redial must treat as stale rather than as a raw filesystem error.+ if (isMissingNodeError(error)) {throw new Error('Gateway ticket control socket missing')}+ throw error+ }++ return new Promise((resolve, reject) => {+ const socket = net.createConnection(socketPath)+ let buffer = ''+ const deadline = setTimeout(() => socket.destroy(new Error('Gateway ticket deadline')), 5000)+ socket.on('error', () => reject(new Error('Gateway ticket bootstrap failed')))+ socket.on('close', () => { clearTimeout(deadline); reject(new Error('Gateway ticket connection closed')) })+ socket.on('connect', () => socket.write(JSON.stringify({ protocol: 1, id: 1, verb: 'session-ticket', params: { profile_id: home, instance_id: endpoint.instance_id, purpose } }) + '\n'))+ socket.on('data', chunk => {+ buffer += chunk.toString()++ if (buffer.length > 65536) {return socket.destroy(new Error('Oversized gateway ticket response'))}++ if (!buffer.includes('\n')) {return}++ try {+ const reply = JSON.parse(buffer.split('\n')[0])+ const grant = reply.result++ if (!reply.ok || reply.protocol !== 1 || reply.id !== 1 || grant?.instance_id !== endpoint.instance_id || grant?.profile_id !== home || typeof grant?.ticket !== 'string') {throw new Error('Invalid gateway ticket')}+ resolve(grant.ticket)+ } catch { reject(new Error('Invalid gateway ticket response')) }++ socket.destroy()+ })+ })+}diff --cc apps/desktop/electron/main.tsindex 0ebd91c07f7,78f4966791c..236d71b4a8e--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -74,9 -63,14 +74,14 @@@ import} from './backend-claim'import { dashboardFallbackArgs } from './backend-command'import { createBackendConnectionState } from './backend-connection-state'+import { assertDescriptorStillOwned, forgetFailedDescriptor } from './backend-descriptor-cache'import { BackendDialClaims } from './backend-dial-claim'- import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'+ import {+ buildDesktopBackendEnv,+ hermesManagedNodePathEntries,+ normalizeHermesHomeRoot,+ profileBackendParentEnv+ } from './backend-env'-import { createBackendExitRecoveryLatch } from './backend-exit-recovery'import { isReauthRequiredError, waitForHermesReady } from './backend-health'import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'@@@ -12157,40 -12576,355 +12149,46 @@@ async function dialPoolBackend(profile}}- // Everything below starts a LOCAL `hermes serve` child. Multiplex-only says- // the host has exactly one, and routing (resolveProfileBackendRoute case 6)- // keeps local profiles off this path — this is the backstop that makes the- // pool spawn path genuinely unreachable rather than merely unused.- // Same options object the router reads, so the guard cannot drift from it- // (profileRouteOptions folds the per-profile SSH override into- // profileRemoteOverride; a hand-rolled term here missed that).- const guardRoute = profileRouteOptions(profile)+ assertLocalProfileCanStart(profile, profileDeletionGate, key =>+ directoryExists(path.join(HERMES_HOME, 'profiles', key))+ )- assertNoSecondLocalBackend(poolKey, {- isolated: guardRoute.isolatedBackend,- primaryRemoteActive: guardRoute.primaryRemoteActive,- profileRemoteOverride: opts.forceLocal ? false : guardRoute.profileRemoteOverride,- unscopableRequest: opts.unscopableRequest- })-- // Bound the slot wait BELOW the renderer's backend-boot budget (45s): once- // the renderer has given up on this spawn, a ticket still queued for the- // pool-idle window (10 min) would hold the pool key hostage and every- // later click on the profile would join that stale wait. Failing here- // surfaces the "all N slots busy" reason instead of a generic boot timeout.- // The caller stamped entry.spawnPriority from its own request; a foreground- // dial that joined the claim before this entry existed left a mark instead.- if (takeForegroundSpawn(poolKey, profile)) {- entry.spawnPriority = 'foreground'- }-- const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)-- assertPoolEntryStillOwned(poolKey, entry)-- if (spawnPriority === 'background' && !backgroundSlotRetryBackoff.canAttempt(poolKey)) {- throw new BackgroundSlotRetryDeferredError(profile)- }-- // The arbiter subscribes to the actual coordinator queue, so a later- // foreground promotion receives reclamation too, not just fresh starts.- const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {- timeoutMs: POOL_SLOT_WAIT_MS,- priority: spawnPriority- })-- entry.localBackendSlotKey = poolKey- entry.localBackendSpawnRequest = spawnRequest-- if (spawnRequest.queued) {- rememberLog(- `Profile backend "${profile}" waiting for a free local slot (${localBackendSpawnCoordinator.activeCount}/${poolMaxBackends()} busy, ${localBackendSpawnCoordinator.queuedCount} queued)`+ const connection = await ensureLocalGateway(async () => {+ const backend = await ensureRuntime(+ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),+ () => assertPoolEntryStillOwned(poolKey, entry))- }-- const cancelRequest = () => spawnRequest.cancel()- localBackendLifecycle.signal.addEventListener('abort', cancelRequest, { once: true })-- try {- entry.releaseLocalBackendSlot = await spawnRequest.acquired- backgroundSlotRetryBackoff.clear(poolKey)- } catch (error) {- if (isBackgroundSlotWaitTimeout(error)) {- backgroundSlotRetryBackoff.recordFailure(poolKey)- }-- throw error- } finally {- localBackendLifecycle.signal.removeEventListener('abort', cancelRequest)- }- if (entry.localBackendSpawnRequest === spawnRequest) {- entry.localBackendSpawnRequest = null- }-- assertPoolEntryStillOwned(poolKey, entry)-- const token = crypto.randomBytes(32).toString('base64url')-- // Same update mutual exclusion as the primary window's waitForLocalStart- // (#73822): pool backends spawn from the same venv, so an ungated respawn- // during applyUpdates' critical section re-locks the venv and trips the- // venv-blocker preflight. No boot-progress UI here — pool backends boot- // silently for background profiles — so we only log while parked.- {- let poolAnnounced = false-- const clearance = await waitForUpdateClearance(updateGateDeps(), {- signal: localBackendLifecycle.signal,- isCancelled: () => backendPool.get(poolKey) !== entry,- onWaitTick: reason => {- if (!poolAnnounced) {- poolAnnounced = true- rememberLog(`[updates] update in progress (${reason}); deferring pool backend start for profile "${profile}"`)- }- },- pollMs: UPDATE_WAIT_POLL_MS,- timeoutMs: UPDATE_WAIT_TIMEOUT_MS- })-- if (clearance === 'cancelled') {- assertPoolEntryStillOwned(poolKey, entry)- }- }-- profileDeletionGate.assertCanStart(profile)- assertPoolEntryStillOwned(poolKey, entry)-- // --profile wins over the inherited HERMES_HOME env (see _apply_profile_override- // step 3 in hermes_cli/main.py), so the child re-homes to this profile.- // --port 0: the OS assigns an ephemeral port; the child announces it on stdout.- const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']-- const backend = await ensureRuntime(await resolveHermesBackend(backendArgs), () =>+ profileDeletionGate.assertCanStart(profile)assertPoolEntryStillOwned(poolKey, entry)- )-- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = await getBackendArgsForRuntime(backend)- assertPoolEntryStillOwned(poolKey, entry)- const hermesCwd = resolveHermesCwd()- const webDist = resolveWebDist()- const readyFile = backend.readyFile ? makeDashboardReadyFile() : null-- // Guard BEFORE the "Starting" line: a profile that only exists on a remote- // backend (remote-primary desktop asked for a forced-local child) rejects- // here, and logging "Starting" first left an orphaned line with no READY- // and no exit — the exact undiagnosable burst signature in remote-gateway- // user bundles (Aug 2026, Dash's report).- assertLocalProfileCanStart(profile, profileDeletionGate, key =>- directoryExists(path.join(HERMES_HOME, 'profiles', key))- )- rememberLog(`Starting Hermes backend for profile "${profile}" via ${backend.label}`)-- const parentStartMarker = await desktopParentStartMarker()- const backendNonce = crypto.randomBytes(16).toString('hex')- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)- assertPoolEntryStillOwned(poolKey, entry)-- const child = spawnOwnedBackend(- backend.command,- backend.args,- hiddenWindowsChildOptions({- cwd: hermesCwd,- env: desktopBackendSpawnEnv(- {- // Never another profile's dotenv credentials from the Desktop env (#68367).- ...profileBackendParentEnv({ hermesHome: HERMES_HOME, profile }),- HERMES_HOME,- ...backend.env,- // Pin the gateway's tool/terminal cwd to the same directory we chose for- // the child process. Inherited TERMINAL_CWD (or a stale config bridge)- // can still point at the install dir even when spawn cwd is home.- TERMINAL_CWD: hermesCwd,- HERMES_DASHBOARD_SESSION_TOKEN: token,- // Marks this dashboard backend as desktop-spawned so it runs the cron- // scheduler tick loop (the gateway isn't running under the app).- HERMES_DESKTOP: '1',- // Exact parent identity lets the backend self-exit after an unclean- // Desktop death without mistaking a reused PID for its owner. If the- // optional marker probe fails, retain legacy PID-only tracking.- ...parentIdentityEnv,- HERMES_WEB_DIST: webDist,- ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})- },- GUEST_ONBOARDING- ),- shell: backend.shell,- stdio: ['ignore', 'pipe', 'pipe']- })- )-- entry.process = child- entry.token = token- registerLocalBackendExitFinalizer(backendPool, poolKey, entry, () => releaseLocalBackendSlot(entry))- // Buffer stdout+stderr from the instant of spawn (#93608): an early crash's- // traceback must survive into the claim error and the before-ready exit- // message instead of a bare exit code. rememberLog attaches later, after- // the claim, and would miss anything printed before it.- const outputTail = createBackendOutputTail()- outputTail.attach(child)-- let ready = false- let rejectStart = null-- const startFailed = new Promise((_resolve, reject) => {- rejectStart = reject- })-- // Exit/error can now arrive while the ownership claim is still pending.- startFailed.catch(() => {})-- child.once('error', error => {- rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)- void teardownFailedLocalBackend(poolKey, entry).catch(cleanupError => {- rememberLog(- `Hermes backend for profile "${profile}" cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`- )- })- rejectStart?.(error)- })- child.once('exit', (code, signal) => {- rememberLog(formatBackendExitLine(`Hermes backend for profile "${profile}" exited`, code, signal, outputTail))- releaseBackendChild(child)-- if (!ready) {- rejectStart?.(- new Error(- `Hermes backend for profile "${profile}" exited before it became ready (${signal || code}).${outputTail.describe()}`- )- )- }- })-- // Start watching for the READY announcement BEFORE any await (#60323):- // stdout is already flowing into the tail, and Node streams never replay- // consumed chunks to late listeners — a sentinel printed while- // claimBackendChild runs would otherwise be lost forever, timing out a- // healthy backend. The tail-buffer accessor covers any residual gap.- const portAnnouncement = waitForDashboardPortAnnouncement(child, {- bufferedOutput: () => outputTail.text(),- describeOutputTail: () => outputTail.describe(),- readyFile- })- return runGatewayEnsure({ ...backend, env: desktopBackendSpawnEnv(backend.env || {}, GUEST_ONBOARDING) }, resolveHermesCwd(), HERMES_HOME)- portAnnouncement.catch(() => {})- await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- child.stdout.on('data', rememberLog)- child.stderr.on('data', rememberLog)-- const port = await Promise.race([portAnnouncement, startFailed])- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- if (readyFile) {- fs.unlink(readyFile, () => {})- }-- entry.port = port-- const baseUrl = `http://127.0.0.1:${port}`- await Promise.race([waitForHermes(baseUrl, token), startFailed])- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })- ready = true-- const childAlive = () => child.exitCode === null && !child.killed-- const authToken = await adoptServedDashboardToken(baseUrl, token, {- childAlive,- label: `Hermes backend for profile "${profile}"`,- rememberLog- })-- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- entry.token = authToken-- // Verify the WebSocket session token before declaring backend ready.- // HTTP /api/status can pass while WS auth fails (separate transport, separate guards).- const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`-- // Our own child: a cold start can stall its loop past the base budget (#96177).- const wsProbe = await probeGatewayWebSocket(wsUrl, {- WebSocketImpl: globalThis.WebSocket,- ...spawnedBackendProbeOptions(childAlive)- })-- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- if (!wsProbe.ok) {- throw new Error(- `Hermes backend for profile "${profile}" is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`++ // Never another profile's dotenv credentials from the Desktop env (#68367).++ return runGatewayEnsure(++ { ...backend, env: desktopBackendSpawnEnv(backend.env || {}, GUEST_ONBOARDING) },++ resolveHermesCwd(),++ HERMES_HOME,++ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile })+ )- }-- return {- baseUrl,- mode: 'local',- source: 'local',- authMode: 'token',- token: authToken,- profile,- wsUrl,- logs: hermesLog.slice(-80),- ...getWindowState()- }-}--// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —-// idle reaper, LRU eviction, profile delete/rename, quit — shares one-// in-flight stop per key and retains the process handle until the bounded-// SIGTERM -> SIGKILL escalation in waitForBackendExit() resolves. Previously-// SIGTERM + immediate entry delete dropped the handle and a slow child-// survived detached under PID 1.-const poolStopper = createPoolStopper({- pool: backendPool,- stopChild: child => stopBackendChild(child),- waitForExit: child => waitForBackendExit(child),- // Remote / SSH-isolated pool entries keep `process: null`. Child exit is- // immediate; hold the same in-flight fence through bootstrap drain + SSH- // teardown so a reconnect cannot publish into a dying scope (#106935).- afterStop: async key => {- try {- await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))- } catch (err) {- // The idle reaper calls stopPoolBackend un-awaited; a failed SSH teardown- // must not surface as an unhandled rejection or block the pool fence.- sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)- }- }-})--function stopPoolBackend(profile: string): Promise<void> {- const entry = backendPool.get(profile)-- const stopping = releaseLocalBackendSlotAfterExit(- () => releaseLocalBackendSlot(entry),- () => poolStopper.stop(profile)- )-- // Fire-and-forget callers still need diagnostics; awaiters receive the- // rejection, while physical ownership and the exit finalizer remain live.- void stopping.catch(error => {- rememberLog(`Profile backend "${profile}" stop failed: ${error instanceof Error ? error.message : String(error)}`)+ }, async () => {+ await waitForUpdateClearance(updateGateDeps(), { pollMs: UPDATE_WAIT_POLL_MS, timeoutMs: UPDATE_WAIT_TIMEOUT_MS })+ // Update waits yield: retirement or profile deletion may win in that gap.+ assertPoolEntryStillOwned(poolKey, entry)+ assertLocalProfileCanStart(profile, profileDeletionGate, key => directoryExists(path.join(HERMES_HOME, 'profiles', key)))})- return stopping-}--// Tell every window the pooled backend under `poolKey` is being retired so the-// renderer parks that scope (wantOpen=false) instead of redialing into the-// slot it just vacated. Fired BEFORE the SIGTERM (pool-retire.ts contract).-function broadcastPoolBackendRetiring(poolKey: string) {- for (const win of BrowserWindow.getAllWindows()) {- const { webContents } = win+ assertPoolEntryStillOwned(poolKey, entry)- if (webContents && !webContents.isDestroyed()) {- webContents.send('hermes:pool:retiring', { poolKey })- }- }+ return { ...connection, profile, logs: hermesLog.slice(-80), ...getWindowState() }}-const poolRetirer = createPoolRetirer({- pool: backendPool,- coordinator: localBackendSpawnCoordinator,- ...createPoolRetirementClient(fetchJson),- stopBackend: stopPoolBackend,- onRetiring: broadcastPoolBackendRetiring,- log: rememberLog-})--localBackendLifecycle.signal.addEventListener('abort', poolRetirer.dispose, { once: true })+// Forget a cached descriptor. Nothing is killed: the gateway behind it owns its+// own lifetime (`hermes gateway ensure` attach semantics), so the next+// ensure*() for this key simply re-dials. Every retire path — dispatch probe+// failure, resume revalidation, registry removal, profile delete/rename, quit —+// funnels through here so the verb stays in one place.+async function stopPoolBackend(profile: string) {+ backendPool.delete(profile)+}async function teardownPoolBackendAndWait(profile) {await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))@@@ -12469,20 -13476,259 +12467,25 @@@ async function startHermes(requestedPro// Local WSL backend — paths are bridgeable.setWslBridgeProfileState(primaryProfile, true)- const connection = await ensureLocalGateway(() => runGatewayEnsure({ ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}, GUEST_ONBOARDING) }, resolveHermesCwd(), HERMES_HOME))- stopAttachedBackendMonitor()-- const backend = setup.backend- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = await getBackendArgsForRuntime(backend)- backendConnectionState.assertCurrentAttempt(connectionAttempt)- const hermesCwd = resolveHermesCwd()- const webDist = resolveWebDist()- const readyFile = backend.readyFile ? makeDashboardReadyFile() : null-- await advanceBootProgress('backend.spawn', `Starting Hermes backend via ${backend.label}`, 84)- rememberLog(`Starting Hermes backend via ${backend.label}`)-- const profile = primaryProfileKey()- const parentStartMarker = await desktopParentStartMarker()- const backendNonce = crypto.randomBytes(16).toString('hex')- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)-- backendConnectionState.assertCurrentAttempt(connectionAttempt)-- const hermesProcess = spawnOwnedBackend(- backend.command,- backend.args,- hiddenWindowsChildOptions({- cwd: hermesCwd,- env: desktopBackendSpawnEnv(- {- // Never another profile's dotenv credentials from the Desktop env (#68367).- ...profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: activeProfile }),- // Explicitly pin HERMES_HOME for the child so Python's get_hermes_home()- // resolves to the SAME location our resolveHermesHome() picked. Without- // this pin, Python falls back to ~/.hermes on every platform — fine on- // mac/linux (where our default matches), but on Windows our default is- // %LOCALAPPDATA%\hermes, which differs from C:\Users\<u>\.hermes.- // Mismatch would split config / sessions / .env / logs across two- // directories. install.ps1 sets HERMES_HOME via setx; the desktop- // can't reliably do that, so we set it inline for every spawn.- HERMES_HOME,- ...backend.env,- TERMINAL_CWD: hermesCwd,- HERMES_DASHBOARD_SESSION_TOKEN: token,- // Marks this dashboard backend as desktop-spawned so it runs the cron- // scheduler tick loop (the gateway isn't running under the app).- HERMES_DESKTOP: '1',- // Exact parent identity lets the backend self-exit after an unclean- // Desktop death without mistaking a reused PID for its owner. If the- // optional marker probe fails, retain legacy PID-only tracking.- ...parentIdentityEnv,- HERMES_WEB_DIST: webDist,- ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})- },- GUEST_ONBOARDING- ),- shell: backend.shell,- stdio: ['ignore', 'pipe', 'pipe']- })- )-- // Buffer stdout+stderr from the instant of spawn (#93608): an early- // crash's traceback must survive into the claim error and the- // before-ready exit message shown by the boot UI. rememberLog attaches- // later, after the claim, and would miss anything printed before it.- const primaryOutputTail = createBackendOutputTail()- primaryOutputTail.attach(hermesProcess)-- // Start watching for the READY announcement BEFORE any await (#60323):- // claimBackendChild can take seconds (its Windows Get-Process probe cold- // start alone runs 2-8s) and advanceBootProgress awaits renderer IPC.- // stdout is already flowing into the tail, and Node streams never replay- // consumed chunks to late listeners, so a sentinel printed during that- // window was lost forever — the wait then hit its 90s timeout and a- // healthy backend was killed (deterministic on Windows, racy on- // macOS/Linux). The tail-buffer accessor covers any residual gap.- const portAnnouncement = waitForDashboardPortAnnouncement(hermesProcess, {- bufferedOutput: () => primaryOutputTail.text(),- describeOutputTail: () => primaryOutputTail.describe(),- readyFile- })-- // Mark handled so an early rejection (child dies during the claim) can't- // surface as an unhandled rejection before the Promise.race below attaches.- portAnnouncement.catch(() => {})- await claimBackendChild(- hermesProcess,- `${backend.command} ${backend.args.join(' ')}`,- profile,- backendNonce,- primaryOutputTail- )- const processOwner = backendConnectionState.attachProcess(connectionAttempt, hermesProcess)-- if (!processOwner) {- stopBackendChild(hermesProcess)- await waitForBackendExit(hermesProcess)- releaseBackendChild(hermesProcess)- throw new Error('Hermes backend start was superseded by a newer connection attempt.')- }-- hermesProcess.stdout.on('data', rememberLog)- hermesProcess.stderr.on('data', rememberLog)- let backendReady = false- let rejectBackendStart = null-- const backendStartFailed = new Promise((_resolve, reject) => {- rejectBackendStart = reject- })-- hermesProcess.once('error', error => {- releaseBackendChild(hermesProcess)-- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {- rememberLog(`Ignoring stale Hermes backend error: ${error.message}`)- scheduleUnexpectedPrimaryRecovery({ error: error.message, ready: backendReady })- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))-- return- }-- rememberLog(`Hermes backend failed to start: ${error.message}`)- updateBootProgress(- {- error: error.message,- message: `Hermes backend failed to start: ${error.message}`,- phase: 'backend.error',- running: false- },- { allowDecrease: true }- )- sendBackendExit({ code: null, signal: null, error: error.message })- rejectBackendStart?.(error)- })- hermesProcess.once('exit', (code, signal) => {- releaseBackendChild(hermesProcess)-- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {- rememberLog(formatBackendExitLine('Ignoring stale Hermes backend exit', code, signal, primaryOutputTail))-- scheduleUnexpectedPrimaryRecovery({ code, signal, ready: backendReady })-- if (!backendReady) {- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))- }-- return- }-- rememberLog(formatBackendExitLine('Hermes backend exited', code, signal, primaryOutputTail))-- if (!scheduleUnexpectedPrimaryRecovery({ code, signal, ready: backendReady })) {- sendBackendExit({ code, signal })- }-- if (!backendReady) {- const message = `Hermes backend exited before it became ready (${signal || code}).${primaryOutputTail.describe()}`- updateBootProgress(- {- error: message,- message,- phase: 'backend.error',- running: false- },- { allowDecrease: true }- )- rejectBackendStart?.(- new Error(- `Hermes backend exited before it became ready (${signal || code}). Log: ${DESKTOP_LOG_PATH}\n${recentHermesLog()}`- )- )- }- })-- await advanceBootProgress('backend.port', 'Waiting for Hermes backend to launch', 86)- backendConnectionState.assertCurrentAttempt(connectionAttempt)++ const connection = await ensureLocalGateway(() => runGatewayEnsure(++ { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}, GUEST_ONBOARDING) },++ resolveHermesCwd(),++ HERMES_HOME,++ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })++ ))+ void showPluginCompatNoticeOnce()- // Discover the ephemeral port the child bound to- const port = await Promise.race([portAnnouncement, backendStartFailed])backendConnectionState.assertCurrentAttempt(connectionAttempt)- if (readyFile) {- fs.unlink(readyFile, () => {})- }-- const baseUrl = `http://127.0.0.1:${port}`- await advanceBootProgress('backend.wait', 'Waiting for Hermes backend to become ready', 90)- backendConnectionState.assertCurrentAttempt(connectionAttempt)- await Promise.race([waitForHermes(baseUrl, token), backendStartFailed])- backendConnectionState.assertCurrentAttempt(connectionAttempt)- backendReady = true- // The host now has a bound, registered backend: the next launcher will- // discover and attach to it, so the spawn gate is done.- releaseHostSpawnReservation()- primaryExitRecovery.reset()backendStartFailure = null-- const childAlive = () => hermesProcess.exitCode === null && !hermesProcess.killed-- const authToken = await adoptServedDashboardToken(baseUrl, token, {- childAlive,- rememberLog- })-- backendConnectionState.assertCurrentAttempt(connectionAttempt)-- // Verify the WebSocket session token before declaring backend ready.- const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`-- // Same policy as the pool path: our own child may still be cold-starting (#96177).- const wsProbe = await probeGatewayWebSocket(wsUrl, {- WebSocketImpl: globalThis.WebSocket,- ...spawnedBackendProbeOptions(childAlive)- })-- backendConnectionState.assertCurrentAttempt(connectionAttempt)-- if (!wsProbe.ok) {- throw new Error(- `Local Hermes backend is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`- )- }-- updateBootProgress({- phase: 'backend.ready',- message: 'Hermes backend is ready. Finalizing desktop startup',- progress: 94,- running: true,- error: null- })-- // A successful boot (including a soft restart that the repair-guard- // chose over a hard reinstall, see #74874) means any in-flight repair- // attempt counter has been honoured — reset it so the next genuine- // failure starts fresh from attempt 1 instead of inheriting the- // accumulated count of the resolved episode.+ updateBootProgress({ phase: 'backend.ready', message: 'Hermes gateway is ready', progress: 94, running: true, error: null })bootstrapRepairAttempt = 0- // The backend's plugin discovery just ran and refreshed HERMES_HOME/.plugin-compat-report.json.- // Surface it once (per distinct set of affected plugins) after the window is up; never block boot.- setTimeout(() => void showPluginCompatNoticeOnce(), 1500)-- return {- baseUrl,- mode: 'local',- source: 'local',- authMode: 'token',- token: authToken,- profile,- wsUrl,- logs: hermesLog.slice(-80),- ...getWindowState()- }+ // The primary descriptor names its own profile: a profile-less descriptor+ // reads as "default" downstream and breaks per-source profile memory when+ // the primary actually booted as another profile (#825324fd).+ return { ...connection, profile: primaryProfileKey(), logs: hermesLog.slice(-80), ...getWindowState() }})().catch(async error => {- releaseHostSpawnReservation()-if (!backendConnectionState.clearPromiseForAttempt(connectionAttempt)) {throw error}diff --cc cron/jobs.pyindex fff0e7c0eb2,31c7f2dae31..95221ff4c2c--- a/cron/jobs.py+++ b/cron/jobs.py@@@ -2395,9 -2376,9 +2395,10 @@@ def mark_job_runstatus: Optional[str] = None,*,expected_fire_owner: Optional[str] = None,+ execution_id: Optional[str] = None,model_unreachable: bool = False,quota_hold_seconds: Optional[float] = None,+ recover_consumed_fire: bool = False,) -> bool:"""Mark a job as run: update last_run_at/last_status, bump completed, recompute next_run_at,and retire the record as a terminal completion when the repeat limit is reached.@@@ -2413,12 -2394,12 +2414,14 @@@(Cowork-style; see cron/unreachable_retry.py).``quota_hold_seconds``: the provider said it stays closed for this long (a quota 429 with- ``retry after <N>s``). Recurring jobs are parked at their first occurrence after the window- instead of re-firing into it on every tick (cron/quota_hold.py, #89376).+ ``retry after <N>s``). Recurring jobs are parked through the window instead of re-firing into+ it on every tick. ``recover_consumed_fire`` lets a scheduled sparse cron recover its+ consumed fire when the provider reopens; manual runs retain the natural schedule+ (cron/quota_hold.py, #89376)."""def apply(jobs, _i, job):+ if execution_id is not None and execution_id in job.get("canonical_completions", []):+ return Trueif expected_fire_owner is not None:claim = job.get("fire_claim")if not isinstance(claim, dict) or claim.get("by") != expected_fire_owner:diff --cc hermes_cli/backup.pyindex 697dc23863f,51406332486..b3e8c3585fa--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@@ -1114,15 -1082,11 +1178,16 @@@ def run_import(args) -> Optional[int]print(f"\nImporting {file_count} files ...")hermes_root.mkdir(parents=True, exist_ok=True)t0 = time.monotonic()- restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(- zf, members, prefix, hermes_root, file_count)+ from gateway.runtime_ownership import OwnershipConflict+ try:+ restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(+ zf, members, prefix, hermes_root, file_count)+ except OwnershipConflict as exc:+ print(f"\nImport refused; no files restored: {exc}")+ sys.exit(1)elapsed = time.monotonic() - t0- print(f"\nImport complete: {restored} files restored in {elapsed:.1f}s\n Target: {display_hermes_home()}")+ print(f"\nImport {'incomplete' if errors else 'complete'}: {restored} files restored in {elapsed:.1f}s\n"+ f" Target: {display_hermes_home()}")if restored_external:print(f"\n Restored {restored_external} memory-provider file(s) to "f"their original location(s) outside {display_hermes_home()}.")diff --cc hermes_cli/config_migrations.pyindex 78a2f936df3,94e94b80426..fae59ce578c--- a/hermes_cli/config_migrations.py+++ b/hermes_cli/config_migrations.py@@@ -753,23 -754,24 +754,36 @@@ MIGRATIONS: Tuple[Tuple[int, Callable[[(45, _migrate_to_45),# 45 → 46: legacy editor `disabled: true` on MCP servers becomes `enabled: false` (see _migrate_to_46).(46, _migrate_to_46),+ # 46 → 47: cron.bot_chat_delivery_timeout_seconds is gone with the local `hermes chat`+ # fallback lane it bounded. Bot Chat deliveries are admitted to the running gateway and+ # settle on its durable receipt; there is no cron-side turn left to time out.+ (47, functools.partial(+ _rewrite_key, section="cron", key="bot_chat_delivery_timeout_seconds", new=None,+ match=lambda _cur: True,+ added="removed cron.bot_chat_delivery_timeout_seconds",+ message=(+ " ✓ Removed cron.bot_chat_delivery_timeout_seconds — bot-chat deliveries are now "+ "admitted to the target profile's running gateway and tracked by receipt, so cron no "+ "longer runs (or times out) a Bot Chat turn of its own."),+ extra_guard=lambda raw: "bot_chat_delivery_timeout_seconds" in raw)),)+ #: Steps triggered by a legacy key or identifier (a renamed or retired key, a removed plugin or+ #: toolset, the plugin-era SOUL.md section): they carry its setting to where the runtime reads it+ #: or drop what nothing reads, which is right however old the file is. A config.yaml with no+ #: ``_config_version`` is current-schema content that was never stamped (installers seed it from+ #: cli-config.yaml.example; targeted writers never stamp), so it gets only these: every other step+ #: decides by a value or an absence that, in such a file, is the user's own choice. v13 is left+ #: out: it clears OPENAI_MODEL from .env, a generic name Hermes never reads but the user's tools may.+ #: v41 is left out too: it rewrites profile SOUL.md on a heading match, an artifact whose+ #: provenance the config stamp says nothing about.+ LEGACY_KEY_STEPS = frozenset({12, 14, 16, 17, 29, 33, 38, 39, 42, 43, 46})- def run_migrations(current_ver: int, results: Dict[str, Any], quiet: bool) -> None:- """Apply every registered migration whose target version exceeds *current_ver*.++ def run_migrations(+ current_ver: int, results: Dict[str, Any], quiet: bool, *, unversioned: bool = False) -> None:+ """Apply every registered migration whose target version exceeds *current_ver*; a config+ with no ``_config_version`` (*unversioned*) gets only :data:`LEGACY_KEY_STEPS`.*current_ver* is the on-disk schema version captured ONCE before any step runs and does notadvance between steps — each step is gated on the same initial value.diff --cc hermes_cli/web_routers/_common.pyindex 4ca1321c1fb,e80f977ef86..f18020eacb1--- a/hermes_cli/web_routers/_common.py+++ b/hermes_cli/web_routers/_common.py@@@ -129,32 -160,44 +160,51 @@@ CORRUPT_STORE_DETAIL ="error": "state_db_corrupt","message": "state.db corrupt — run `hermes doctor` (then `hermes doctor --fix` or `hermes sessions repair`).",}+ # One payload per persistence-cause bucket (``classify_persistence_error``); ``error`` codes+ # all follow the ``state_db_*`` scheme of the pre-existing ``state_db_corrupt``.+ # Same guidance as the deleted_wal / replaced turn explainers: `doctor --fix` while a holder+ # lives would repair the wrong generation in place, so it is deliberately NOT suggested here.+ DELETED_WAL_DETAIL = {+ "error": "state_db_deleted_wal",+ "message": "another Hermes process still holds an old copy of the session database's write-ahead log — "+ "quit every Hermes process on this profile, run `hermes doctor` (it names the holders), "+ "then start Hermes again. Do not run `hermes doctor --fix` while they run.",+ }+ STATE_DB_REPLACED_DETAIL = {+ "error": "state_db_replaced",+ "message": "state.db was replaced while Hermes was running — stop Hermes, run `hermes doctor`, "+ "then start it again. Do not run `hermes doctor --fix`, which would repair the wrong file in place.",+ }+ # Every other bucket a malformed image can classify as ("corrupt", "fts_index") is the corrupt payload.+ _STORE_STATUS_DETAIL_BY_CAUSE = {"deleted_wal": DELETED_WAL_DETAIL, "replaced": STATE_DB_REPLACED_DETAIL}+def corrupt_store_status(db_path, exc) -> HTTPException:+ """The structured ``state_db_corrupt`` 503 for a malformed store, warning once per store per+ :data:`_CORRUPT_STORE_WARN_INTERVAL_S` (debug afterwards). Callers ``raise ... from exc``."""++ from hermes_state_errors import classify_persistence_error+ key, now = str(db_path), time.monotonic()+ last = _corrupt_store_warned_at.get(key)++ detail = _STORE_STATUS_DETAIL_BY_CAUSE.get(classify_persistence_error(exc), CORRUPT_STORE_DETAIL)+ if last is None or now - last >= _CORRUPT_STORE_WARN_INTERVAL_S:+ _corrupt_store_warned_at[key] = now- log.warning("state.db at %s is corrupt (%s); dashboard reads return a status payload until it is "++ log.warning("state.db at %s is unreadable (%s); dashboard reads return a status payload until it is "+ "repaired — run `hermes doctor`", db_path, exc)+ else:- log.debug("state.db at %s still corrupt: %s", db_path, exc)- return HTTPException(status_code=503, detail={**CORRUPT_STORE_DETAIL, "path": key})++ log.debug("state.db at %s still has error: %s", db_path, exc)++ return HTTPException(status_code=503, detail={**detail, "path": key})++@contextlib.contextmanagerdef corrupt_store_as_status(db_path):- """Map a corrupt-image ``sqlite3.DatabaseError`` from a state.db read to a 503 status+ """Map a corrupt-image ``sqlite3.DatabaseError`` or ``StateDbReplacedError`` from a state.db read to a 503 statuspayload, warning once per store per :data:`_CORRUPT_STORE_WARN_INTERVAL_S`.Busy/locked and every other error propagate unchanged."""- from hermes_state_errors import is_malformed_db_error+ from hermes_state_errors import StateDbReplacedError, classify_persistence_error, is_malformed_db_errortry:yield- except sqlite3.DatabaseError as exc:- if not is_malformed_db_error(exc):+ except (sqlite3.DatabaseError, StateDbReplacedError) as exc:+ if not isinstance(exc, StateDbReplacedError) and not is_malformed_db_error(exc):raise- key, now = str(db_path), time.monotonic()- last = _corrupt_store_warned_at.get(key)- detail = _STORE_STATUS_DETAIL_BY_CAUSE.get(classify_persistence_error(exc), CORRUPT_STORE_DETAIL)- if last is None or now - last >= _CORRUPT_STORE_WARN_INTERVAL_S:- _corrupt_store_warned_at[key] = now- log.warning("state.db at %s is unreadable (%s); dashboard reads return a status payload until it is "- "repaired — run `hermes doctor`", db_path, exc)- else:- log.debug("state.db at %s still has error: %s", db_path, exc)- raise HTTPException(status_code=503, detail={**detail, "path": key}) from exc+ raise corrupt_store_status(db_path, exc) from excdiff --cc hermes_cli/web_routers/sessions.pyindex 9fbc7da1081,6e7147e5b50..b3df1f5bec0--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@@ -19,12 -19,14 +19,14 @@@ from fastapi.responses import Streamingfrom hermes_cli.web_deps import latefrom hermes_cli.web_server_gateway import _strip_session_list_rows-from hermes_cli.web_server_sessions import _maybe_auto_archive_for_profile, _session_latest_descendant+from hermes_cli.web_server_sessions import _session_latest_descendantfrom hermes_cli.web_models import (BulkDeleteSessions, SessionImport, SessionOwnerBackfill, SessionPrune, SessionRename)- from hermes_cli.web_routers._common import CORRUPT_STORE_DETAIL, log as _log, destructive_profile, http_failure+ from hermes_cli.web_routers._common import (+ CORRUPT_STORE_DETAIL, corrupt_store_as_status, log as _log, destructive_profile, http_failure,+ )from hermes_state import is_malformed_db_error- from hermes_state_errors import is_transient_sqlite_error+ from hermes_state_errors import StateDbReplacedError, is_transient_sqlite_errorfrom hermes_state_health import STORAGE_CORRUPT, note_storage_error, storage_statelist_router = APIRouter()diff --cc tests/tools/test_bot_mode_dm.pyindex 492320bace3,564aef8ede8..a8ef4a16eae--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@@ -420,12 -371,40 +420,42 @@@ def test_friendly_names_and_desktop_sluassert result["status"] == "queued", resultassert result["to"] == f"@{expected}"- _mode, _dm_file, argv = _runner_parts(calls[0]["command"])+ _mode, _dm_file, argv, profile_home = _runner_parts(calls[0]["command"])assert argv[1:3] == ["-p", expected]+ assert Path(profile_home) == (home / "profiles" / expected).resolve()+ assert authority.calls[0][1]["profile"] == expected+ @pytest.mark.parametrize(("target", "local_name", "relayed"), [+ ("hermes@mini", "Hermes Mini", True),+ ("@hermes@mini", "HermesMini", True),+ ("Ops@Home", "Ops@Home", False), # an '@' friendly name no connection answers to stays local (#100671)+ ])+ def test_connection_qualified_target_reaches_the_relay_not_a_look_alike_local_bot(+ tmp_path, monkeypatch, target, local_name, relayed):+ """'hermes@mini' is the form the relay hands out, and stamps on replies, for a remote row whose bare forms+ collide. Resolved locally first, a local bot whose friendly name slugs to 'hermes-mini' captured it: the DM+ and its reply thread landed in the wrong bot's transcript and memory."""+ calls = _capture_spawn(monkeypatch)+ monkeypatch.setattr(bot_relay, "_hermes_cli", lambda: "hermes")+ home = _managed_home(tmp_path, teammates=("ops",))+ _rename(home, "ops", display_name=local_name)+ bot_relay.write_remote_roster(home, [+ {"profile": "default", "handle": "hermes", "connection_id": "mini", "connection_label": "Mini"},+ ])++ result = json.loads(bot_mode_dm.message_agent_tool(target=target, message="status?", agent=_FakeAgent(home)))++ local = [_runner_parts(c["command"])[2][1:3] for c in calls if "--run-delivery" in c["command"]]+ envelopes = bot_relay.claim_pending_envelopes(home)+ if relayed:+ assert [e["target_connection"] for e in envelopes] == ["mini"], result+ assert local == []+ else:+ assert envelopes == [] and result["to"] == "@ops"+ assert local == [["-p", "ops"]]++def test_ambiguous_friendly_name_fails_closed(tmp_path, monkeypatch):"""Two bots titled the same must not let a DM land on whichever sorts first; thereserved @hermes alias can never be hijacked by a rename."""