The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into feat/unified-gateway-runtime
teknium1c6dc7ab120ca
diff --cc .github/workflows/ci.yamlindex 692a897230c,a9a641b0a34..aec32e5870a--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@@ -36,21 -62,21 +62,21 @@@ jobsdetect:name: Detect affected areasruns-on: ubuntu-latest- timeout-minutes: 1+ timeout-minutes: 3outputs:- python: ${{ steps.classify.outputs.python }}- python_prod: ${{ steps.classify.outputs.python_prod }}- frontend: ${{ steps.classify.outputs.frontend }}- site: ${{ steps.classify.outputs.site }}- scan: ${{ steps.classify.outputs.scan }}- deps: ${{ steps.classify.outputs.deps }}- uv_lock: ${{ steps.classify.outputs.uv_lock }}- npm_lock: ${{ steps.classify.outputs.npm_lock }}- installer: ${{ steps.classify.outputs.installer }}- desktop_updater: ${{ steps.classify.outputs.desktop_updater }}- rust: ${{ steps.classify.outputs.rust }}- docker_meta: ${{ steps.classify.outputs.docker_meta }}- mcp_catalog: ${{ steps.classify.outputs.mcp_catalog }}+ python: ${{ steps.gate-lanes.outputs.python }}+ python_prod: ${{ steps.gate-lanes.outputs.python_prod }}+ frontend: ${{ steps.gate-lanes.outputs.frontend }}+ site: ${{ steps.gate-lanes.outputs.site }}+ scan: ${{ steps.gate-lanes.outputs.scan }}+ deps: ${{ steps.gate-lanes.outputs.deps }}+ uv_lock: ${{ steps.gate-lanes.outputs.uv_lock }}+ npm_lock: ${{ steps.gate-lanes.outputs.npm_lock }}+ bootstrap: ${{ steps.gate-lanes.outputs.bootstrap }}+ desktop_updater: ${{ steps.gate-lanes.outputs.desktop_updater }}+ rust: ${{ steps.gate-lanes.outputs.rust }}+ docker_meta: ${{ steps.gate-lanes.outputs.docker_meta }}+ mcp_catalog: ${{ steps.gate-lanes.outputs.mcp_catalog }}ci_review: ${{ steps.classify.outputs.ci_review }}ci_review_files: ${{ steps.classify.outputs.ci_review_files }}event_name: ${{ github.event_name }}diff --cc apps/desktop/electron/gateway-file-download.tsindex 7dc5657f458,b83d0d6fcad..cfffa4dd89d--- a/apps/desktop/electron/gateway-file-download.ts+++ b/apps/desktop/electron/gateway-file-download.ts@@@ -2,9 -2,8 +2,10 @@@// main process. Extracted from main.ts so the streaming, data-URL decoding, and// filename derivation are unit-testable without spinning up Electron.//- // The native/token transport lives in gateway-download-transport.ts; OAuth- // remains in main.ts for the Electron session partition. Both transports- // delegate the byte-moving to `pumpStreamToFile` here, which streams the-// The token / OAuth transports delegate to the shared finalizer here. It-// waits for the save dialog before `pumpStreamToFile` streams the++// The token / OAuth transports (gateway-file-download-transport.ts) and the++// native gateway-descriptor transport (gateway-download-transport.ts) delegate++// to the shared finalizer here. It waits for the save dialog before++// `pumpStreamToFile` streams the// response into a sibling temp file with backpressure and renames it onto the// user-selected destination only once the body has landed in full — so a large// download never has to be buffered whole in the native process, and a faileddiff --cc apps/desktop/electron/main.tsindex f546a046923,f77cfe2df27..65a967b35ff--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -1,18 -1,4 +1,18 @@@- import { execFileSync, spawn } from 'node:child_process'+ import { type ChildProcess, execFileSync, spawn } from 'node:child_process'++import type { GatewayEndpoint } from './local-gateway'+import { configureWindowsGatewayTicketClient, createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, routedGatewayEndpoint, runGatewayEnsure } from './local-gateway'+import { mintGatewayTicketWithPython } from './local-gateway-python'+const localGatewayDials = createLocalGatewayDials()+configureWindowsGatewayTicketClient(async (endpoint, purpose) => {+ const backend = await ensureRuntime(await resolveHermesBackend([]), () => undefined)++ if (backend.kind !== 'python' || backend.shell) {+ throw new Error('Gateway ticket bootstrap requires the installed Hermes Python runtime')+ }++ return mintGatewayTicketWithPython(backend, resolveHermesCwd(), endpoint, purpose)+})import crypto from 'node:crypto'import fs from 'node:fs'import http from 'node:http'@@@ -72,21 -62,24 +74,22 @@@ importprocessStartMarker,REAP_PROBE_TIMEOUT_MS} from './backend-claim'-import { dashboardFallbackArgs, serveBackendArgs } from './backend-command'+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,- profileBackendParentEnv- } from './backend-env'-import type { HostBackendRecord } from './backend-discovery'+ import { buildDesktopBackendEnv, profileBackendParentEnv } from './backend-env'-import { createBackendExitRecoveryLatch } from './backend-exit-recovery'import { isReauthRequiredError, waitForHermesReady } from './backend-health'- import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'+ import {+ backendCommandMatches,+ type BackendOwnershipEntry,+ createBackendOwnership,+ createBackendShutdownCoordinator+ } from './backend-ownership'import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'-import { waitForDashboardPortAnnouncement } from './backend-ready'import { recycleOwnedBackend } from './backend-recycle'import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'+ import { createInstalledRuntimeGate } from './backend-resolution'import { createBackendServeSupportResolver } from './backend-serve-support'import {isHostKeyChangedBootFailure,@@@ -186,8 -193,10 +202,10 @@@ importupsertConnection} from './connection-registry'import type { RosterProfileMetadata } from './connection-registry'+ import { liveWindowState, overlayWindowState } from './connection-window-state'import { describeCrashReason, installCrashForensics } from './crash-forensics'-import { adoptServedDashboardToken, resolveServedDashboardToken } from './dashboard-token'+import { adoptServedDashboardToken } from './dashboard-token'+ import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'import { formatDesktopLogLine } from './desktop-log-line'import {@@@ -228,28 -242,25 +251,27 @@@ import} from './find-in-page'import { createFirstRunSetupGate } from './first-run-setup-gate'import { registerFsIpc } from './fs-ipc'- import { downloadViaTokenToFile } from './gateway-download-transport'++import { downloadViaTokenToFile as downloadViaNativeGatewayToFile } from './gateway-download-transport'+ import type {+ GatewayFileSaveContext,+ GatewayFileSaveDeps,+ GatewayFileSaveResult,+ GatewaySaveDialogOptions,+ GatewaySaveDialogResult+ } from './gateway-file-download'import {- filenameFromContentDisposition,- fsPumpDeps,++ finalizeGatewayDownload,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, spawnedBackendProbeOptions } from './gateway-ws-probe'+import { probeGatewayWebSocket } from './gateway-ws-probe'+ import { windowsGitCandidates } from './git-binary-candidates'import { registerGitIpc } from './git-ipc'- import {- describeGitHubCredentialSource,- forgetGhCliToken,- githubApiHeaders,- githubTokenRejected,- resolveGitHubCredential- } from './github-api-auth'import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'import { readAndConsumeHandoffResult } from './handoff-result'import {@@@ -314,8 -341,12 +345,12 @@@ import { registerMcpOauthCallbackIpc }import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'import { fetchLocalMedia } from './media-range'import { createMinimizeToTray } from './minimize-to-tray'- import { createNativeAccessTokenCoordinator, NativeAuthChangedError } from './native-access-token'+ import {+ createNativeAccessTokenCoordinator,+ type NativeAccessTokenOptions,+ NativeAuthChangedError+ } from './native-access-token'-import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions'+import { oauthSessionIsLive, resolveJsonBody, resolveOauthRestAuth, resolveReadinessProbeAuth } from './native-auth-decisions'import {nativeRefreshUrl,type NativeTokenSet,@@@ -325,12 -356,20 +360,20 @@@} from './native-oauth'import { runNativeLogin } from './native-oauth-login'import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'+ import { planNoConsoleGitSpawn, setNoConsoleGitRoots, windowsGitHost } from './no-console-git'import { registerNativeNotifications } from './notification-ipc'+ import { isExpectedOauthNavigationAbort } from './oauth-navigation'import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'- import { mintGatewayWsTicket as mintOauthGatewayWsTicket, requestWithOauthFallback } from './oauth-rest-request'+ import {+ mintGatewayWsTicket as mintOauthGatewayWsTicket,+ requestWithOauthFallback,+ shouldReplayAfterCookie401+ } from './oauth-rest-request'import { wireOauthSessionResponse } from './oauth-session-response'+ import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'-import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'+import { createParentStartMarkerResolver } from './parent-process-identity'+ import { bundledPayload, installIdForRoot, type PayloadInfo } from './payload-backend'import { petOverlayClickThrough } from './pet-overlay'import { placePetOverlay, registerPetOverlayIpc } from './pet-overlay-ipc'import {@@@ -346,8 -385,25 +389,9 @@@ importimport { createPortalSession } from './portal-session'import { createKeepAwake } from './power-save'import { readPreUpdateBackupEnabled } from './pre-update-backup-config'+import { registerPreparedSubmissions } from './prepared-submissions'import { capturePreviewContents } from './preview-capture'+ import { onPreviewWatchOwnerDestroyed, sendPreviewFileChangedToOwner } from './preview-file-watch'import { PreviewReachRegistry } from './preview-reach'import {createPrimaryRemoteConnection,@@@ -394,8 -454,8 +442,9 @@@ importrevalidateSuspectPooledRemoteBackends} from './remote-liveness'import { resolveRemoteOauthTicket, rosterSourceEnumerationTimeoutMs } from './remote-oauth-ticket'+ import { remoteSessionCookies } from './remote-session-cookies'import {+ applyRemoteRequestHeaders,attachRemoteRequestHeaderListener,collectRemoteHeaderSources,createRegistryGatewayWsUrlHandler,@@@ -3890,23 -4259,16 +4047,10 @@@ async function releaseBackendLock(updatinitialPids.push(hermesProcess.pid)}- stopBackendTreesForUpdate(hermesProcess, {- forceKillProcessTree,- stopAllPoolBackends- })- for (const entry of backendPool.values()) {- if (entry.process && Number.isInteger(entry.process.pid)) {- initialPids.push(entry.process.pid)- }- }-+ await Promise.all([teardownPrimaryBackendAndWait(), stopAllPoolBackends()])- // Stop separately-running messaging gateways (all profiles) BEFORE the- // release gate. The gateway is launched by the gateway-launcher desktop- // plugin via /api/gateway/start and is NOT in backendConnectionState or- // backendPool, so the tree-kills above never see it — on Windows its- // launcher (venv\Scripts\python.exe) keeps the venv mandatory-locked and- // the 15s gate aborts the hand-off before the venv-blocker scan's- // pausable-gateway exemption ever gets a chance (#70337). Delegate to- // `hermes gateway stop --all`: the CLI discovers every profile's gateway- // (launcher + worker — gateway.pid records only the uv WORKER, and- // taskkill /T from the worker never reaches its parent), drains in-flight- // agents, and force-kills survivors. Best-effort; abort paths restore via- // startGatewaysAfterUpdateAbort. No-op off Windows.+ // Uninstall deletes the whole runtime. Drain separately-running gateways+ // through the CLI, rather than targeting a gateway worker by PID.stopGatewayBeforeUpdate(venvHermesShimPath(updateRoot), HERMES_HOME)// Reap Hermes-OWNED venv daemons the tree-kill above cannot reach: the@@@ -3932,9 -4303,21 +4085,15 @@@stragglers.push(currentHermesProcess.pid)}- for (const entry of backendPool.values()) {- if (entry.process && Number.isInteger(entry.process.pid)) {- stragglers.push(entry.process.pid)- }- }-return stragglers},- killProcessTree: forceKillProcessTree,+ killProcessTree: pid => {+ try {+ forceKillProcessTree(pid)+ } catch (error) {+ rememberLog(`[${tag}] taskkill PID ${pid} failed: ${error instanceof Error ? error.message : String(error)}`)+ }+ },sleep: (ms: number) => new Promise(r => setTimeout(r, ms)),now: () => Date.now(),log: rememberLog@@@ -8055,175 -7939,38 +7721,39 @@@ function postJsonNoAuth(url: string, bo}// All explicit mutations go through the coordinator; only its refresh/store- // dependencies may call the raw persistence helpers above.- const nativeAccessTokenCoordinator = createNativeAccessTokenCoordinator({- clearTokens: _clearNativeTokens,- isRefreshAuthRejection: error => readStatusCode(error) === 401,- loadTokens: _loadNativeTokens,- normalizeBaseUrl: normalizeRemoteBaseUrl,- refreshTokens: async (baseUrl, tokens) =>- parseTokenResponse(- await postJsonNoAuth(- nativeRefreshUrl(baseUrl),- { refresh_token: tokens.refreshToken, provider: tokens.provider },- { timeoutMs: 10_000 }- )- ),- storeTokens: _storeNativeTokens,- tokenNeedsRefresh- })-- const ensureNativeAccessToken = nativeAccessTokenCoordinator.ensure-- // OAuth-session download that streams the response body straight to a- // user-selected destination (via finalizeGatewayDownload). The connect timeout- // is cleared once the response headers arrive.- function downloadViaOauthSessionToFile(url, ctx, options: any = {}) {- return new Promise((resolve, reject) => {- const sess = getOauthSessionForUrl(url)-- if (!sess) {- reject(new Error('OAuth session partition is unavailable.'))-- return- }-- let parsed-- try {- parsed = new URL(url)- } catch (error) {- reject(new Error(`Invalid URL: ${error.message}`))-- return- }-- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {- reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`))-- return- }-- const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)-- const request = electronNet.request({- method: 'GET',- url,- session: sess,- useSessionCookies: true,- redirect: 'follow'- } as any)-- let settled = false-- const timer = setTimeout(() => {- if (settled) {- return- }-- settled = true-- try {- request.abort()- } catch {- // already finished- }-- reject(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))- }, timeoutMs)-- request.on('response', res => {- if (settled) {- return- }-- // Response headers arrived — cancel the connect timeout so it can't abort- // the stream while the save dialog is open or bytes are still flowing.- settled = true- clearTimeout(timer)- finalizeGatewayDownload(res, res.statusCode || 500, res.headers || {}, {- ...ctx,- abort: () => {- try {- request.abort()- } catch {- // already finished- }- }- }).then(resolve, reject)- })- request.on('error', error => {- if (settled) {- return- }-- settled = true- clearTimeout(timer)- reject(error)- })- request.end()- })- }-- // Shared tail for both transports: validate status, pick a filename, prompt the- // save dialog, then stream the (still-unconsumed) response body to the chosen- // destination. On an HTTP error the status code is attached so saveGatewayFile- // can trigger the 404-only compatibility fallback.- async function finalizeGatewayDownload(res, statusCode, headers, ctx: any = {}) {- if (statusCode >= 400) {- throw httpStatusError(statusCode, await readGatewayErrorText(res))- }-- const disposition = headers['content-disposition'] || headers['Content-Disposition']- const filename = filenameFromContentDisposition(disposition) || ctx.suggested || ctx.fallbackName-- const result = await dialog.showSaveDialog(mainWindow, {- defaultPath: filename,- title: 'Save File'+ // dependencies may call the raw persistence helpers above. It single-flights+ // the /auth/native/refresh rotation per host (concurrent callers share one+ // flight instead of racing rotations and losing the winner) and fences a+ // refresh that lands after a login/logout changed the identity underneath it+ // (22751c8fd9b9). A 401 on refresh means the RT is dead — tokens are dropped+ // so the UI prompts a fresh native login; a 503/transient keeps them.+ const nativeAccessTokenCoordinator: ReturnType<typeof createNativeAccessTokenCoordinator> =+ createNativeAccessTokenCoordinator({+ clearTokens: _clearNativeTokens,+ isRefreshAuthRejection: (error: unknown): boolean => readStatusCode(error) === 401,+ loadTokens: _loadNativeTokens,+ normalizeBaseUrl: normalizeRemoteBaseUrl,+ refreshTokens: async (baseUrl: string, tokens: NativeTokenSet): Promise<NativeTokenSet> =>+ parseTokenResponse(+ await postJsonNoAuth(+ nativeRefreshUrl(baseUrl),+ { refresh_token: tokens.refreshToken, provider: tokens.provider },+ { timeoutMs: 10_000 }+ )+ ),+ storeTokens: _storeNativeTokens,+ tokenNeedsRefresh})- if (result.canceled || !result.filePath) {- ctx.abort?.()-- return { canceled: true, saved: false }- }-- try {- // Failure-atomic: exclusive temp create beside the destination, rename into- // place only once the body is complete (#96597).- await pumpStreamToFile(res, result.filePath, fsPumpDeps())- } catch (error) {- ctx.abort?.()- throw error- }-- return { path: result.filePath, saved: true }- }-- // Read a bounded amount of an error response body for the thrown message.- function readGatewayErrorText(res): Promise<string> {- return new Promise(resolve => {- const chunks = []- let total = 0-- res.on('data', chunk => {- if (total >= 500) {- return- }-- const buffer = Buffer.from(chunk)-- total += buffer.length- chunks.push(buffer)- })- res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8').slice(0, 500)))- res.on('error', () => resolve(Buffer.concat(chunks).toString('utf8').slice(0, 500)))- })- }+ // Return a valid native access token for baseUrl, refreshing via+ // /auth/native/refresh if the stored one is at/near expiry. Returns null when+ // there are no tokens or the refresh is terminally rejected (caller re-logins).+ const ensureNativeAccessToken: (baseUrl: string, options?: NativeAccessTokenOptions) => Promise<string | null> =+ nativeAccessTokenCoordinator.ensureinterface GatewayFileConnection extends RegistryBackendRequestScope {- authMode?: 'oauth' | 'token'+ gatewayEndpoint?: GatewayEndpoint+ authMode?: 'oauth' | 'token' | 'native'baseUrl: stringtoken?: null | string}@@@ -8274,42 -8016,38 +7799,56 @@@ async function saveGatewayFile(payloadpayload.sessionId)- const url = `${connection.baseUrl}${requestPaths.download}`+ const deps: GatewayFileSaveDeps = {+ showSaveDialog: (options: GatewaySaveDialogOptions): Promise<GatewaySaveDialogResult> =>+ dialog.showSaveDialog(mainWindow, options)+ }- try {- if (connection.authMode === 'oauth') {- return await requestWithOauthFallback(connection.baseUrl, {- ensureNativeAccessToken,- requestWithBearer: bearer => downloadViaTokenToFile(url, null, ctx, finalizeGatewayDownload, { bearer }),- requestWithCookie: () => downloadViaOauthSessionToFile(url, ctx)- })- }+ return saveGatewayDownload(requestPaths, ctx, {+ ...deps,+ download: async (requestPath: string, context: GatewayFileSaveContext): Promise<GatewayFileSaveResult> => {+ const url: string = `${connection.baseUrl}${requestPath}`- return await downloadViaTokenToFile(url, connection.token, ctx, finalizeGatewayDownload, {- gatewayDescriptor: connection.gatewayEndpoint ? connection : undefined- })- } catch (error) {- // Desktop and the remote gateway update independently. A gateway predating- // /api/fs/download 404s here; fall back (ONLY on 404) to the older capped- // data-URL route so downloads keep working against older backends.- if (isNotFoundError(error)) {- return await saveGatewayFileViaDataUrl(connection, requestPaths.dataUrl, ctx)- }+ if (connection.authMode === 'oauth') {+ return requestWithOauthFallback(connection.baseUrl, {+ ensureNativeAccessToken,+ requestWithBearer: (bearer: string): Promise<GatewayFileSaveResult> =>+ downloadViaTokenToFile(url, null, context, deps, { bearer }),+ requestWithCookie: (): Promise<GatewayFileSaveResult> =>+ downloadViaOauthSessionToFile<Session>(url, context, {+ ...deps,+ getSession: getOauthSessionForUrl,+ request: electronNet.request+ })+ })+ }- throw error- }++ // A canonical local gateway authenticates with its native descriptor++ // headers; that transport also retries the connection phase and refuses++ // redirects so a one-use grant never reaches a new target.++ if (connection.gatewayEndpoint) {++ return downloadViaNativeGatewayToFile(++ url,++ connection.token ?? null,++ context,++ (++ response: http.IncomingMessage,++ _statusCode: number,++ _headers: http.IncomingHttpHeaders,++ transport: { abort: () => void }++ ): Promise<GatewayFileSaveResult> => finalizeGatewayDownload(response, context, transport.abort, deps),++ { gatewayDescriptor: connection }++ )++ }+++ return downloadViaTokenToFile(url, connection.token ?? null, context, deps)+ },+ readDataUrl: (requestPath: string): Promise<string> => readGatewayFileDataUrl(connection, requestPath)+ })}- // Compatibility fallback: fetch the file through the capped- // `/api/fs/read-data-url` route, decode it, and save. Bounded by the gateway's- // data-URL cap, so it only serves smaller files — enough to keep older gateways- // working until they gain the streaming route.- async function saveGatewayFileViaDataUrl(- connection: GatewayFileConnection,- requestPath: string,- ctx: GatewayFileSaveContext- ) {- const json = await fetchJsonForBackend(connection, requestPath)+ async function readGatewayFileDataUrl(connection: GatewayFileConnection, requestPath: string): Promise<string> {+ const json: unknown = await fetchJsonForBackend(connection, requestPath)const dataUrl =json && typeof json === 'object' && 'dataUrl' in json && typeof json.dataUrl === 'string' ? json.dataUrl : ''@@@ -11318,11 -11002,12 +10838,11 @@@ async function ensureRegistryBackendconnectionId,profile,managedUpdateCorrelation = '',- opts: { passive?: boolean; spawnPriority?: LocalBackendSpawnPriority } = {}+ opts: { passive?: boolean } = {}) {- const spawnPriority = spawnPriorityFrom(opts.spawnPriority)const passive = Boolean(opts.passive)const registry = readDesktopConnectionsRegistry()- const id = String(connectionId || '').trim() || registry.primary+ const id = registryDialConnectionId(connectionId, registry.primary)const source = registry.connections.find(c => c.id === id)if (!source) {@@@ -11422,13 -11101,32 +10936,26 @@@// can't collide with the v1 remote descriptor cached at the bare key.profileDeletionGate.assertCanStart(profileKey)- const localRoute = resolveRegistryLocalRoute(profileKey, {+ const rawProfile = String(profile ?? '').trim()++ const localProfileExists = rawProfile+ ? directoryExists(path.join(HERMES_HOME, 'profiles', rawProfile.toLowerCase()))+ : undefined++ // Pass the raw profile, not profileKey: profileKey collapses null to+ // 'default' and would refuse an unprofiled enumeration as a concrete dial.+ const localRoute = resolveRegistryLocalRoute(rawProfile || null, {globalRemote: globalRemoteActive(),- profileRemoteOverride: Boolean(profileHasRemoteOverride(profileKey))+ profileRemoteOverride: Boolean(profileHasRemoteOverride(profileKey)),+ ...(rawProfile ? { localProfileExists } : {})})+ if (localRoute.refuse) {+ throw new Error(localRoute.refuse)+ }+if (localRoute.delegate) {- return ensureBackend(profile, { passive, spawnPriority })- }-- const stoppingLocal = poolStopper.inFlight(localRoute.poolKey)-- if (stoppingLocal) {- await stoppingLocal+ return ensureBackend(profile, { passive })}const existingLocal = backendPool.get(localRoute.poolKey)@@@ -12150,62 -12021,432 +11677,117 @@@ 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- })+ const connection = await ensureLocalGateway(async () => {+ const backend = await ensureRuntime(+ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),+ () => assertPoolEntryStillOwned(poolKey, entry)+ )- // 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'- }+ profileDeletionGate.assertCanStart(profile)+ assertPoolEntryStillOwned(poolKey, entry)- const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)+ // 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 })+ )+ }, 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)))+ })- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)+ assertPoolEntryStillOwned(poolKey, entry)- if (spawnPriority === 'background' && !backgroundSlotRetryBackoff.canAttempt(poolKey)) {- throw new BackgroundSlotRetryDeferredError(profile)- }+ return { ...connection, profile, logs: hermesLog.slice(-80), ...getWindowState() }+}- // 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- })+// 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)+}- entry.localBackendSlotKey = poolKey- entry.localBackendSpawnRequest = spawnRequest+async function teardownPoolBackendAndWait(profile) {+ await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))+}- if (spawnRequest.queued) {- rememberLog(- `Profile backend "${profile}" waiting for a free local slot (${localBackendSpawnCoordinator.activeCount}/${poolMaxBackends()} busy, ${localBackendSpawnCoordinator.queuedCount} queued)`- )- }+async function stopAllPoolBackends() {+ backendPool.clear()+}- const backendShutdown = createBackendShutdownCoordinator(async () => {- const cancelRequest = (): void => {- spawnRequest.cancel()++/**++ * Last teardown act on Windows: kill orphaned tools still running out of++ * THIS install's artifact root, so no straggler pins the package silo++ * (0x80070020 on the next activation). The managed tool store is NOT a quit++ * root — it is machine-scoped and shared with the surviving gateway and++ * other installs; image locks there are the updater's pause/resume job.++ * Runs after the graceful backend teardown, skips the pids it owned and++ * every live Hermes runtime process, so it is only the net for what++ * detached. Best effort throughout; see package-process-reap.ts.++ */++function reapInstallRootedStragglers(excludePids: number[]): void {++ if (!IS_WINDOWS) {++ return+ }+- 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, backendPool, localBackendLifecycle.signal)-- 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 starts a backend on the runtime- // being replaced. No boot-progress UI here — pool backends boot- // silently for background profiles — so we only log while parked.- {- let poolAnnounced = false-- await waitForUpdateClearance(updateGateDeps(), {- signal: localBackendLifecycle.signal,- isCancelled: (): boolean => 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- })- }-- profileDeletionGate.assertCanStart(profile)-- // --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), () =>- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)- )-- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = await getBackendArgsForRuntime(backend)- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)- 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, backendPool, localBackendLifecycle.signal)-- 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- })-- portAnnouncement.catch(() => {})- await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)-- child.stdout.on('data', rememberLog)- child.stderr.on('data', rememberLog)-- const port = await Promise.race([portAnnouncement, startFailed])- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)-- 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, backendPool, localBackendLifecycle.signal)- 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, backendPool, localBackendLifecycle.signal)-- 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, backendPool, localBackendLifecycle.signal)-- 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}`- )- }-- 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-// physical shutdown promise resolves. Previously-// SIGTERM + immediate entry delete dropped the handle and a slow child-// survived detached under PID 1.-const poolStopper = createPoolStopper({- pool: backendPool,- // localBackendLifecycle is the single owner of local child stop semantics:- // stopChild triggers its stop (stop + bounded exit wait + slot release);- // waitForExit resolves when that same stop promise settles. Remote /- // SSH-isolated pool entries keep `process: null` — child exit is immediate- // there, so the same in-flight fence carries only the bootstrap drain +- // SSH teardown below (#106935).- stopChild: child => {- void localBackendLifecycle.stop(child as ChildProcess | null | undefined)- },- waitForExit: child => localBackendLifecycle.stop(child as ChildProcess | null | undefined),- 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)}`)- })-- 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-- if (webContents && !webContents.isDestroyed()) {- webContents.send('hermes:pool:retiring', { poolKey })- }- }-}--const poolRetirer = createPoolRetirer({- pool: backendPool,- coordinator: localBackendSpawnCoordinator,- ...createPoolRetirementClient(fetchJson),- stopBackend: stopPoolBackend,- onRetiring: broadcastPoolBackendRetiring,- log: rememberLog-})--localBackendLifecycle.signal.addEventListener('abort', poolRetirer.dispose, { once: true })--async function teardownPoolBackendAndWait(profile) {- await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))-}--async function stopAllPoolBackends() {- const entries = [...backendPool.values()]- await poolStopper.stopAll()- entries.forEach(releaseLocalBackendSlot)-}--/**- * Last teardown act on Windows: kill orphaned tools still running out of- * THIS install's artifact root, so no straggler pins the package silo- * (0x80070020 on the next activation). The managed tool store is NOT a quit- * root — it is machine-scoped and shared with the surviving gateway and- * other installs; image locks there are the updater's pause/resume job.- * Runs after the graceful backend teardown, skips the pids it owned and- * every live Hermes runtime process, so it is only the net for what- * detached. Best effort throughout; see package-process-reap.ts.- */-function reapInstallRootedStragglers(excludePids: number[]): void {- if (!IS_WINDOWS) {- return- }-- const payloadRoot = installShape() === 'bundled' ? process.resourcesPath : null++ const payloadRoot = installShape() === 'bundled' ? process.resourcesPath : null++ try {+ reapPackageRootedProcesses({+ installRoots: [payloadRoot],+ listProcesses: () =>+ listWindowsProcesses(+ (file, args, options) =>+ execFileSync(file, args, {+ ...hiddenWindowsChildOptions({ encoding: 'utf8', timeout: options.timeout }),+ windowsHide: options.windowsHide+ }) as unknown as string+ ),+ killProcess: pid => process.kill(pid, 'SIGKILL'),+ selfPid: process.pid,+ excludePids,+ isWindows: true,+ log: message => rememberLog(message)+ })+ } catch (err) {+ rememberLog(`[package-reap] skipped: ${(err as Error).message}`)+ }+ }+++// Closing Desktop never stops the detached gateway: only processes this app++// still owns are torn down, and the straggler reap protects every live Hermes++// runtime tree (package-process-reap.ts).+ const backendShutdown = createBackendShutdownCoordinator(async (): Promise<void> => {+ const ownedChildren = IS_WINDOWS ? collectOwnedBackendChildren() : []const localShutdown = localBackendLifecycle.shutdown()- const primary = backendConnectionState.invalidate()+ const primary = backendConnectionState.getProcess()+ const primaryStop = teardownPrimaryBackendAndWait()+ const pooledStops = stopAllPoolBackends()- stopBackendChild(primary)- if (poolIdleReaper) {- clearInterval(poolIdleReaper)- poolIdleReaper = null- }-+ // Bounded: a backend that ignores SIGTERM must not wedge app quit (main's 7 s teardown budget).- await waitForTeardown([localShutdown, waitForBackendExit(primary), stopAllPoolBackends()], 7_000)+ await waitForTeardown([localShutdown, primaryStop, pooledStops], 7_000)++ reapInstallRootedStragglers(Number.isInteger(primary?.pid) ? [primary.pid] : [])++ // Verify last, so a surviving child cannot skip the teardown above.+ const closeStopFailure = windowsCloseStopOwnedBackends(ownedChildren)++ if (closeStopFailure) {+ rememberLog(`[close-stop] ${closeStopFailure.message}`)++ throw closeStopFailure+ }})const quitTeardown = createQuitTeardownCoordinator(() => app.quit())@@@ -12285,6 -12533,269 +11874,12 @@@ async function prepareProfileRenameRequ})}-// ── Attach-first: one backend per HOST (multiplex-only) ───────────────────-// Escape hatch: a dedicated, private backend for this app instead of the host's.-const ISOLATED_BACKEND = process.env.HERMES_DESKTOP_ISOLATED_BACKEND === '1'-const ATTACHED_LIVENESS_POLL_MS = 15_000-let attachedBackendMonitor: NodeJS.Timeout | null = null-let hostSpawnReservation: SpawnReservation | null = null--function stopAttachedBackendMonitor() {- if (attachedBackendMonitor) {- clearInterval(attachedBackendMonitor)- attachedBackendMonitor = null- }-}--/**- * An attached backend has no child process, so `child.exit` can never drive- * recovery. Poll its readiness instead; a backend that dies under us- * invalidates the connection and hands the respawn to the same supervisor path- * a dead child would (which re-runs discovery and spawns, since the host now- * has no backend).- */-function startAttachedBackendMonitor(attached: AttachedBackend) {- stopAttachedBackendMonitor()-- attachedBackendMonitor = setInterval(() => {- void waitForHermes(attached.baseUrl, attached.token, undefined, 'token', {}, { alreadyBound: true }).catch(() => {- stopAttachedBackendMonitor()- rememberLog(`[attach] attached backend on ${attached.baseUrl} (pid ${attached.pid}) is gone; recovering`)- invalidatePrimaryConnection()- scheduleUnexpectedPrimaryRecovery({ error: 'The Hermes backend this app attached to exited.', ready: true })- })- }, ATTACHED_LIVENESS_POLL_MS)-- attachedBackendMonitor.unref?.()-}--/** Discover and attach to the host's running backend; null means "spawn one". */-function attachToRunningHostBackend(): Promise<AttachedBackend | null> {- const options = { isolated: ISOLATED_BACKEND, ledgerPath: spawnLedgerPath(HERMES_HOME, path.join) }-- return attachOrReserveSpawn(options, hostBackendAttachDeps(), hostSpawnGateDeps())- .then(outcome => {- if ('attached' in outcome) {- releaseHostSpawnReservation()-- return outcome.attached- }-- hostSpawnReservation = outcome.reservation-- return null- })- .catch(error => {- // Discovery must never be able to block boot: fall through to spawning.- rememberLog(`[attach] host backend discovery failed (${error.message}); spawning our own`)-- return null- })-}--function hostBackendAttachDeps() {- return {- log: rememberLog,- readLedger: (target: string) => {- try {- return fs.readFileSync(target, 'utf8')- } catch {- return null- }- },- probeWebSocket: (wsUrl: string) => probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket }),- publishedTokenFor: (record: HostBackendRecord) =>- lookupPublishedSessionToken(- record,- {- home: os.homedir(),- lockDir: process.env.HERMES_GATEWAY_LOCK_DIR,- platform: process.platform,- stateHome: process.env.XDG_STATE_HOME- },- {- lstat: target => fs.lstatSync(target),- readFile: target => fs.readFileSync(target, 'utf8'),- uid: typeof process.getuid === 'function' ? process.getuid() : null- }- ),- resolveServedToken: (baseUrl: string) => resolveServedDashboardToken(baseUrl, ''),- // A ledger record is written only after its backend binds, so a refused- // port is a dead record (a hard-killed backend leaves both the record and- // its published token behind), not one still starting.- waitForReady: (baseUrl: string, token: string) =>- waitForHermes(baseUrl, token, undefined, 'token', {}, { alreadyBound: true })- }-}--function hostSpawnGatePath() {- return path.join(HERMES_HOME, 'desktop-backend-spawn.json')-}--function hostSpawnGateDeps() {- return {- now: () => Date.now(),- read: () => {- try {- const record = JSON.parse(fs.readFileSync(hostSpawnGatePath(), 'utf8'))- const owner = Number(record?.pid)-- if (!Number.isInteger(owner) || owner <= 0) {- return null- }-- // A gate whose owner is gone is no gate at all.- try {- process.kill(owner, 0)- } catch {- return null- }-- return { ownerAlive: true, startedAt: Number(record?.startedAt) || 0 }- } catch {- return null- }- },- take: () => {- const gatePath = hostSpawnGatePath()-- try {- fs.writeFileSync(gatePath, JSON.stringify({ pid: process.pid, startedAt: Date.now() }), { mode: 0o600 })- } catch {- // A gate we cannot write is a race we cannot win; spawning anyway is- // exactly today's behaviour, so never fail boot over it.- }-- return () => {- try {- fs.unlinkSync(gatePath)- } catch {- // Already gone / never written.- }- }- },- sleep: (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))- }-}--function releaseHostSpawnReservation() {- hostSpawnReservation?.release()- hostSpawnReservation = null-}--function startHermes({ supervisorRecovery = false }: { supervisorRecovery?: boolean } = {}): Promise<- Awaited<ReturnType<typeof backendConnectionState.getPromise>>-> {- primaryRecoverySuppressed = false- primaryStartsInFlight += 1-- const start: Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> = localBackendLifecycle.start(- () => runHermesStart({ supervisorRecovery })- )-- const releaseStart = (): void => {- primaryStartsInFlight -= 1- }-- // Ordering contract: this reaction is registered on the SAME promise the- // caller receives, before any caller `.catch`, so releaseStart has already- // run (primaryStartsInFlight back to 0) when runPrimaryRecoverySpawn's- // `.catch` evaluates primaryRecoveryState(). Returning a derived promise- // (start.then(...)) or wrapping `start` would invert that order: every- // pre-ready retry would see hasPendingStart:true, be refused, and leave the- // recovery claim stuck with no retry and no UI.- void start.then(releaseStart, releaseStart)-- return start-}-+ // A quit or update handoff kills renderers while their windows can still report+ // live; the renderer lifecycle must treat that as teardown, not a crash to reload.+ function rendererTeardownInProgress(): boolean {+ return isQuittingForHandoff || backendShutdown.hasStarted()+ }+-function primaryRecoveryState() {- return {- hasCurrentOwner: backendConnectionState.getProcess() !== null || backendConnectionState.getPromise() !== null,- hasPendingStart: primaryStartsInFlight > 0,- intentionalTeardown: primaryRecoverySuppressed || isQuittingForHandoff || backendShutdown.hasStarted()- }-}--function reportPrimaryRecoveryCrashLoop(code: number | null, signal: string | null): boolean {- if (!primaryExitRecovery.isCrashLooping()) {- return false- }-- const message =- 'Hermes backend keeps crashing right after it restarts; not restarting it again. Relaunch Hermes Desktop.'-- rememberLog(`[supervisor] ${message}`)- sendBackendExit({ code, signal, error: message })-- return true-}--const firstLine = (text: string): string => (text || '').split('\n').find(Boolean) || ''--function runPrimaryRecoverySpawn(code: number | null, signal: string | null) {- startHermes({ supervisorRecovery: true }).catch(respawnError => {- rememberLog(`[supervisor] backend respawn failed: ${firstLine(respawnError.message)}`)-- // Terminal boot failures still own their existing recovery UI. Only a- // supervisor-owned respawn that failed transiently before ready may spend- // another bounded recovery slot.- const latched = latchedBootFailure()-- if (latched) {- rememberLog(`[supervisor] respawn refused: boot failure latched: ${firstLine(latched.message)}`)-- return- }-- // releaseStart (startHermes) already ran: same-promise reaction order, so- // hasPendingStart is false here. See the ordering contract in startHermes.- if (primaryExitRecovery.retryAfterFailedStart(primaryRecoveryState())) {- rememberLog('[supervisor] backend respawn failed before ready; retrying within crash-loop budget')- runPrimaryRecoverySpawn(code, signal)-- return- }-- reportPrimaryRecoveryCrashLoop(code, signal)- })-}--// A ready primary child died. When its exit leaves the primary slot with no-// owner and no start in flight (outside an intentional teardown), the-// supervisor owns the respawn (#112344): the stale-classified exit used to-// "log and return", and recovery then hinged on the renderer noticing its-// socket drop — a 9 h engine-less window when it did not. Pool children are-// deliberately not consulted: they never own the window backend.-function scheduleUnexpectedPrimaryRecovery({- code = null,- signal = null,- error = null,- ready = false-}: { code?: number | null; error?: string | null; ready?: boolean; signal?: string | null } = {}) {- if (!ready) {- return false- }-- const claimed = primaryExitRecovery.claim(primaryRecoveryState())-- if (!claimed) {- return reportPrimaryRecoveryCrashLoop(code, signal)- }-- rememberLog('[supervisor] backend exit left no primary owner and no start in flight; respawning')- sendBackendExit({ code, signal, ...(error ? { error } : {}) })- runPrimaryRecoverySpawn(code, signal)-- return true-}-/*** The terminal boot failure currently latched in this process, if any. These* latches are cleared only by an explicit recovery path (reset, repair,@@@ -12356,7 -12869,18 +11949,15 @@@ async function startHermes(requestedPromigrateActiveProfileIfMissing()const connectionAttempt = backendConnectionState.startAttempt()- const primaryProfile = requestedProfile || primaryProfileKey()+- // ONE launch-profile decision for this attempt (#108417): routing pin,- // --profile argv, and the child env all derive from the same read, so a++ // ONE launch-profile decision for this attempt (#108417): routing identity,++ // the --profile argv and the child env all derive from the same read, so a+ // hermes:profile:remember landing mid-startup becomes the NEXT boot's+ // preference instead of splitting routing identity from the launch- // argument. (The pin below still honors a live primary — but a primary- // being live means startHermes never got here.)- const { argvProfile: activeProfile, routingProfile: primaryProfile } = resolveLaunchProfile(readActiveDesktopProfile)-- // Pin the routing table to the profile this primary actually boots as; a- // later hermes:profile:remember must not retarget requests mid-life.- primaryProfilePin.pin(primaryProfile)++ // argument. An explicit profile-scoped caller names both.++ const { argvProfile: activeProfile, routingProfile: primaryProfile } = requestedProfile++ ? { argvProfile: requestedProfile, routingProfile: requestedProfile }++ : resolveLaunchProfile(readActiveDesktopProfile)// Legacy path callers without an explicit profile belong to the primary// window backend. Profile-scoped callers still pass their key directly.@@@ -12411,17 -12935,16 +12012,19 @@@rememberLog(`[env] login-shell PATH resolution unavailable (${loginShellPath.reason}); keeping inherited PATH`)}- const token = crypto.randomBytes(32).toString('base64url')- // Pin the desktop's chosen profile via the global --profile flag. A launch- // override is persisted into active-profile.json before startHermes, so- // Hermes.exe --profile <name> and hermes -p <name> desktop both land here.- // Null (no stored preference, no launch flag) keeps the legacy bare serve- // so the child still follows the sticky active_profile file.- // `activeProfile` is the SAME decision that pinned routing above — never- // re-read here (#108417). (--port 0: the OS assigns an ephemeral port; the- // child announces it on stdout.)- const backendArgs = serveBackendArgs(activeProfile || undefined)+ const backendArgs = ['gateway', 'ensure', '--json']+++ // Pin the desktop's chosen profile via the global --profile flag. This is+ // deterministic (it wins over the sticky ~/.hermes/active_profile file) and- // resolves HERMES_HOME the same way `hermes -p <name>` does on the CLI. An- // unset preference keeps the legacy launch so existing installs are- // unaffected.- const activeProfile = requestedProfile || readActiveDesktopProfile()-++ // resolves HERMES_HOME the same way `hermes -p <name>` does on the CLI. A++ // launch override is persisted into active-profile.json before startHermes,++ // so Hermes.exe --profile <name> and hermes -p <name> desktop both land++ // here. `activeProfile` is the SAME decision that named routing above —++ // never re-read here (#108417). An unset preference keeps the legacy++ // launch so existing installs are unaffected.+ if (activeProfile) {+ backendArgs.unshift('--profile', activeProfile)+ }const setup = await runPrimaryBackendStartup({signal: localBackendLifecycle.signal,@@@ -12468,25 -13027,275 +12081,26 @@@// Local WSL backend — paths are bridgeable.setWslBridgeProfileState(primaryProfile, true)- 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 = primaryProfile- 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(() => {})-- const processOwner = await backendConnectionState.claimProcess(- connectionAttempt,- hermesProcess,- (child: ChildProcess): ReturnType<typeof claimBackendChild> =>- claimBackendChild(- child,- `${backend.command} ${backend.args.join(' ')}`,- profile,- backendNonce,- primaryOutputTail- )- )-- if (!processOwner) {- await localBackendLifecycle.stop(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- }-- // The CURRENT owner failed to start: its routing identity must not- // outlive it. A newer attempt already re-pins on its own decision- // (#108417), and the stale branch above never reaches this clear.- primaryProfilePin.clear()-- 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))-- // The current primary child is gone; release its routing pin so the- // next startHermes() re-reads active-profile.json instead of re-pinning- // the dead child's profile (#108417). Supervisor respawns go through- // startHermes, which makes a fresh decision — a respawn cannot inherit- // a pin from a process that no longer exists.- primaryProfilePin.clear()-- 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()}`- )- )- }- })+ const connection = await ensureLocalGateway(() => runGatewayEnsure(+ { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}, GUEST_ONBOARDING) },+ resolveHermesCwd(),+ HERMES_HOME,+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })+ ))+- await advanceBootProgress('backend.port', 'Waiting for Hermes backend to launch', 86)- backendConnectionState.assertCurrentAttempt(connectionAttempt)+ 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() }++ return { ...connection, profile: primaryProfile, logs: hermesLog.slice(-80), ...getWindowState() }})().catch(async error => {- releaseHostSpawnReservation()-if (!backendConnectionState.clearPromiseForAttempt(connectionAttempt)) {throw error}@@@ -14280,22 -15176,48 +13981,35 @@@ ipcMain.handle('hermes:connection', asyprimaryProfileKey())- return connectDesktopProfileRoute(route)- return connectDesktopProfileRoute(route, spawnPriorityFrom(extra?.priority), event.sender)++ return connectDesktopProfileRoute(route, event.sender)})- async function connectDesktopProfileRoute(route: DesktopProfileRoute) {-async function connectDesktopProfileRoute(- route: DesktopProfileRoute,- spawnPriority: LocalBackendSpawnPriority = 'foreground',- sender?: Electron.WebContents-) {++async function connectDesktopProfileRoute(route: DesktopProfileRoute, sender?: Electron.WebContents) {// Coalesce concurrent renderer dials for one profile scope (#90812): the// renderer-side reconnect lock is per-window, so two windows waking at once// both land here. The claim key mirrors ensureBackend()'s own profile// normalization so every spelling of the primary coalesces onto one dial.const scopeKey = backendScopeKey(route.connectionId, route.profile)- const clearSpawnPriority = applySpawnPriority(scopeKey, spawnPriority)- let connection-- try {- connection = await backendDialClaims.run(scopeKey, () =>- route.connectionId- ? ensureRegistryBackend(route.connectionId, route.profile, '', { spawnPriority })- : ensureBackend(route.profile, { spawnPriority })- )- } finally {- clearSpawnPriority()- }+ const connection = await backendDialClaims.run(scopeKey, () =>+ route.connectionId ? ensureRegistryBackend(route.connectionId, route.profile) : ensureBackend(route.profile)+ )+ // Every republish carries LIVE window state (#102451): the backend pool entry+ // (and the getWindowState() snapshot startHermes baked into it) outlives+ // reloads, reconnects and sleep/wake, so a reply built only from the cached+ // descriptor overwrites the renderer's live fullscreen flag with the+ // mint-time snapshot. Reading the caller's state HERE keeps registry-scoped,+ // primary-resolved and bare replies consistent with the+ // hermes:window-state-changed live-push path.+ const windowState = liveWindowState(sender, {+ fromWebContents: BrowserWindow.fromWebContents,+ getWindowState,+ fallback: mainWindow+ })+if (route.connectionId) {- return { ...connection, connectionId: route.connectionId, registryScoped: true }+ return overlayWindowState({ ...connection, connectionId: route.connectionId, registryScoped: true }, windowState)}const connectionId = resolvedConnectionId(readDesktopConnectionsRegistry(), connection)@@@ -14304,16 -15228,23 +14020,18 @@@}// Registry-scoped variant: resolve a backend for (connectionId, profile).- // connectionId '' / 'local' / the registry primary all behave sensibly; the- // local kind delegates to ensureBackend when the v1 route is local, and- // forces a genuinely-local child when the v1 global mode is remote (the- // registry 'local' entry always means this machine).- ipcMain.handle('hermes:connection:for', async (_event, payload) => {+ // An empty connection id is not registry.primary — that substitution dials+ // another SSH host when a scoped caller drops the id. 'local' and an explicit+ // primary id still resolve to those sources. The local kind delegates to-// ensureBackend when the v1 route is local, and forces a genuinely-local-// child when the v1 global mode is remote (the registry 'local' entry always-// means this machine) unless the profile is remote-only.++// ensureBackend when the v1 route is local, and attaches to this machine's++// canonical gateway when the v1 global mode is remote (the registry 'local'++// entry always means this machine) unless the profile is remote-only.+ ipcMain.handle('hermes:connection:for', async (event, payload) => {- const { connectionId, profile, priority } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)+ const { connectionId, profile } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)const registry = readDesktopConnectionsRegistry()- const id = String(connectionId || '').trim() || registry.primary+ const id = registryDialConnectionId(connectionId, registry.primary)- const spawnPriority = spawnPriorityFrom(priority)- return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' })- return connectDesktopProfileRoute(- { connectionId: id, profile: String(profile ?? '').trim() || 'default' },- spawnPriority,- event.sender- )++ return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' }, event.sender)})const windowConnectionRoutes = new WindowConnectionRouteRegistry()diff --cc apps/desktop/src/api/client.tsindex bbc0044e590,b4fdc848f7e..b6ef46d635b--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@@ -1,4 -1,5 +1,11 @@@- import { type GatewayEvent, type GatewayEventName, JsonRpcGatewayClient, type ServerRequest, type ServerRequestHandler } from '@hermes/shared'-import { JsonRpcGatewayClient } from '@hermes/shared'++import {++ type GatewayEvent,++ type GatewayEventName,++ JsonRpcGatewayClient,++ type ServerRequest,++ type ServerRequestHandler++} from '@hermes/shared'+ import { map, type MapStore } from 'nanostores'import type { HermesApiRequest } from '@/global'diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.tsindex 3af6857ef17,95d802ee27c..97be14fde1f--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts@@@ -4,9 -4,10 +4,11 @@@ import { afterEach, beforeEach, describimport { reasoningEffortPending } from '@/app/chat/session-view'import type { ClientSessionState } from '@/app/types'import type * as HermesModule from '@/hermes'+ import { textPart } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'+import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'+ import { $notifications } from '@/store/notifications'-import { setSessionOwnerHint, setSessions } from '@/store/session'+import { $activeSessionId, setSessionOwnerHint, setSessions } from '@/store/session'import { $sessionTiles, sessionTileDelegate } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex 154dbe82aef,4a619493fef..c57ed34e099--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@@ -321,17 -319,24 +324,31 @@@ export function useSessionTileDelegate(? { connectionId: owner.connectionId, profile: owner.targetProfile || owner.profile }: owner- const prefetchPromise = getLatestSessionMessages(storedSessionId, restScope).catch(() => null)+ const prefetchPromise = authoritativeSnapshot+ ? Promise.resolve(null)+ : getLatestSessionMessages(storedSessionId, restScope).catch(() => null)- if (existing && cached?.storedSessionId === storedSessionId && (cached.busy || cached.messages.length > 0)) {+ if (+ !authoritativeSnapshot &&+ existing &&+ cached?.storedSessionId === storedSessionId &&+ (cached.busy || cached.messages.length > 0)+ ) {const prefetch = await prefetchPromise++ // A long turn can push every rendered row off the newest page; read+ // older pages until they overlap so the graft keeps earlier history.+ const prefetched = await extendRefreshPageToOverlap(+ toChatMessages(prefetch?.messages ?? []),+ cached.messages,+ olderPageReader(storedSessionId, restScope, prefetch)+ )++ // The overlap reads await; drop the page if the tile was rebound.+ if (sessionStateByRuntimeIdRef.current.get(existing)?.storedSessionId !== storedSessionId) {+ return existing+ }+// Deltas and completion may land while REST is in flight.updateSessionState(existing,@@@ -429,51 -418,24 +446,51 @@@updateSessionState(runtimeId,- state => ({- // The deferred build reports the session's own effort later (#79807).- ...markReasoningEffortPending(state),- busy: Boolean(info?.running),- // Persist the session's own model/provider from resume so the tile- // pill does not wait on a chrome-scoped catalog read (#93892).- ...(typeof info?.model === 'string' ? { model: info.model } : {}),- ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),- ...(typeof info?.reasoning_effort === 'string'- ? { reasoningEffort: info.reasoning_effort, reasoningEffortPending: false }- : {}),- ...(typeof info?.reasoning_effort_wire === 'string'- ? { reasoningEffortWire: info.reasoning_effort_wire }- : {}),- ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),- messages:- state.messages.length > 0 ? state.messages : toChatMessages(prefetch?.messages ?? resumed?.messages ?? [])- }),+ state => {+ const previousMessages = state.messages.length > 0 ? state.messages : resumeRequestBaselineMessages++ const messages = authoritativeSnapshot+ ? resumed.messages.length > 0+ ? overlayConcurrentMessageChanges(+ mergeTileTranscript(+ resumeRequestBaselineMessages,- resumed.messages,++ toChatMessages(resumed.messages),+ cached?.streamId+ ),+ resumeRequestBaselineMessages,+ previousMessages+ )+ : previousMessages+ : previousMessages.length > 0+ ? previousMessages+ : toChatMessages(prefetch?.messages ?? resumed.messages ?? [])++ const busyChangedWhileResuming = cached+ ? Boolean(+ state.busy &&+ (state.turnStartedAt !== cached.turnStartedAt || (state.turnLive && !cached.turnLive))+ )+ : state.busy++ const running = resolveResumedBusy(resumed.running ?? info?.running, busyChangedWhileResuming)++ return {+ // The deferred build reports the session's own effort later (#79807).+ ...markReasoningEffortPending(state),+ ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),+ ...(typeof info?.model === 'string' ? { model: info.model } : {}),+ ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),+ ...(typeof info?.reasoning_effort === 'string'+ ? { reasoningEffort: info.reasoning_effort, reasoningEffortPending: false }+ : {}),+ ...(typeof info?.reasoning_effort_wire === 'string'+ ? { reasoningEffortWire: info.reasoning_effort_wire }+ : {}),+ awaitingResponse: running && !resumed.inflight?.assistant,+ busy: running,+ messages+ }+ },storedSessionId)diff --cc apps/desktop/src/app/session/hooks/use-background-queue-drain.tsindex ecebd861952,7c609043734..e40b4da45d7--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts@@@ -185,9 -239,9 +241,9 @@@ export function useBackgroundQueueDraincontinue}- const entry = entries[0]+ const entry = entries.find(candidate => !candidate.serverStatus)- if (!entry || (drainFailuresRef.current.get(entry.id) ?? 0) >= MAX_AUTO_DRAIN_ATTEMPTS) {+ if (!entry || (drainFailuresRef.current.get(entry.id) ?? entry.drainFailures ?? 0) >= MAX_AUTO_DRAIN_ATTEMPTS) {continue}diff --cc apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.tsindex 77e6cc611f7,5e956645774..a1778852e45--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts@@@ -92,10 -92,11 +93,12 @@@ const HANDLERS: GatewayEventHandler[]/** The gateway-event dispatcher, extracted from useMessageStream. */export function useGatewayEventHandler(deps: GatewayEventDeps) {+ const executionAuthorities = useRef(new Map())const { activeSessionIdRef, compactedTurnRef, refreshHermesConfig, sessionStateByRuntimeIdRef } = deps- const unscopedStreamSessionIdRef = useRef<string | null>(null)+ // One pin per concurrent unscoped stream, not a single shared slot: two chats+ // streaming at once used to clobber each other's pin (#46194 / #62823).+ const unscopedStreamSessionIdsRef = useRef<readonly string[]>([])// session.info arrives in bursts (agent build ready + turn end + title /// MCP / compress edges within the same second). Each used to fire its owndiff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 98175f2fd12,1a82102dcfb..57b03ae703d--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@@ -6,10 -4,10 +6,11 @@@ import type { MutableRefObject } from 'import { useEffect, useRef } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ClientSessionState } from '@/app/types'- import { getSession } from '@/hermes'- import { textPart } from '@/lib/chat-messages'+ import { getLatestSessionMessages, getSession } from '@/hermes'+ import { textPart, toChatMessages } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'+ import { $compactingSessions, setSessionCompacting } from '@/store/compaction'import { $composerAttachments, $composerDraft, type ComposerAttachment, setComposerDraft } from '@/store/composer'import { $queuedPromptsBySession, getQueuedPrompts } from '@/store/composer-queue'import { requestGatewayForAgent } from '@/store/gateway'@@@ -46,7 -42,8 +47,9 @@@ import { uploadComposerAttachment, useP// never-settling in-flight promise from one test into the next.beforeEach(() => {clearSingleFlightSessionResumeState()+ window.localStorage.removeItem('hermes.desktop.preparedSubmissions.v1')+ vi.mocked(getLatestSessionMessages).mockReset()+ vi.mocked(getLatestSessionMessages).mockImplementation(async () => ({ messages: [], session_id: 'session' }))})vi.mock('@/hermes', () => ({@@@ -6220,3 -6022,156 +6390,156 @@@ describe('usePromptActions live-owner rexpect(requestGateway.mock.calls.map(c => c[0])).toEqual(['prompt.submit'])})})++ describe('usePromptActions stale multi-window guard (#65047)', () => {+ afterEach(() => {+ cleanup()+ $notifications.set([])+ setSessions(() => [])+ })++ it('refuses prompt.submit when the local transcript is behind and refreshes it', async () => {+ const storedId = 'stored-stale-submit'+ setSessions(() => [sessionInfo({ id: storedId, profile: 'work-vps', title: 'Remote chat' })])+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: storedId,+ messages: [+ { content: 'a', role: 'user', timestamp: 1 },+ { content: 'b', role: 'assistant', timestamp: 2 },+ { content: 'c', role: 'user', timestamp: 3 },+ { content: 'd', role: 'assistant', timestamp: 4 }+ ]+ })++ const requestGateway = vi.fn(async () => ({}) as never)+ const seeds: Record<string, unknown>[] = []+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={state => seeds.push(state)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[+ { id: 'u1', role: 'user', parts: [textPart('a')] },+ { id: 'a1', role: 'assistant', parts: [textPart('b')] }+ ]}+ storedSessionId={storedId}+ />+ )++ expect(await handle!.submitText('stale send from secondary window')).toBe(false)+ expect(getLatestSessionMessages).toHaveBeenCalledWith(storedId, 'work-vps')+ expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())++ const last = seeds.at(-1) as { awaitingResponse?: boolean; busy?: boolean; messages?: unknown[] } | undefined+ expect(last?.busy).toBe(false)+ expect(last?.awaitingResponse).toBe(false)+ expect(last?.messages).toHaveLength(4)+ expect($notifications.get().some(note => note.kind === 'warning')).toBe(true)+ })++ it('allows prompt.submit when the authoritative transcript is not ahead', async () => {+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: RUNTIME_SESSION_ID,+ messages: [+ { content: 'a', role: 'user', timestamp: 1 },+ { content: 'b', role: 'assistant', timestamp: 2 }+ ]+ })++ const requestGateway = vi.fn(async () => ({}) as never)+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[+ { id: 'u1', role: 'user', parts: [textPart('a')] },+ { id: 'a1', role: 'assistant', parts: [textPart('b')] }+ ]}+ />+ )++ expect(await handle!.submitText('fresh enough')).toBe(true)+ expect(requestGateway).toHaveBeenCalledWith(+ 'prompt.submit',- { session_id: RUNTIME_SESSION_ID, text: 'fresh enough' },++ { session_id: RUNTIME_SESSION_ID, submission_id: expect.any(String), text: 'fresh enough' },+ 1_800_000+ )+ expect($notifications.get().some(note => note.kind === 'warning')).toBe(false)+ })++ it('does not refuse when raw session rows are longer only because tools fold into chat messages', async () => {+ const remoteSessionMessages = [+ { content: 'check the repo', role: 'user' as const, timestamp: 1 },+ {+ content: 'Looking.',+ role: 'assistant' as const,+ timestamp: 2,+ tool_calls: [{ id: 'tc-1', function: { name: 'terminal', arguments: '{"command":"ls"}' } }]+ },+ {+ content: '{"output":"ok"}',+ role: 'tool' as const,+ tool_call_id: 'tc-1',+ tool_name: 'terminal',+ timestamp: 3+ },+ { content: 'Done.', role: 'assistant' as const, timestamp: 4 }+ ]++ const localChat = toChatMessages(remoteSessionMessages)++ expect(remoteSessionMessages.length).toBeGreaterThan(localChat.length)+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: RUNTIME_SESSION_ID,+ messages: remoteSessionMessages+ })++ const requestGateway = vi.fn(async () => ({}) as never)+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={localChat}+ />+ )++ expect(await handle!.submitText('follow-up after tools')).toBe(true)+ expect(requestGateway).toHaveBeenCalledWith(+ 'prompt.submit',- { session_id: RUNTIME_SESSION_ID, text: 'follow-up after tools' },++ { session_id: RUNTIME_SESSION_ID, submission_id: expect.any(String), text: 'follow-up after tools' },+ 1_800_000+ )+ })++ it('does not refuse when the authoritative transcript read fails', async () => {+ vi.mocked(getLatestSessionMessages).mockRejectedValue(new Error('wrong backend'))++ const requestGateway = vi.fn(async () => ({}) as never)+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[{ id: 'u1', role: 'user', parts: [textPart('a')] }]}+ />+ )++ expect(await handle!.submitText('send anyway')).toBe(true)+ expect(requestGateway).toHaveBeenCalledWith(+ 'prompt.submit',- { session_id: RUNTIME_SESSION_ID, text: 'send anyway' },++ { session_id: RUNTIME_SESSION_ID, submission_id: expect.any(String), text: 'send anyway' },+ 1_800_000+ )+ })+ })diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex e443d20a242,6a991ac1113..c33833d8aba--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@@ -17,9 -18,9 +18,10 @@@ import$composerAttachments,type ComposerAttachment,mainComposerScope,+ revokeDiscardedAttachmentPreviews,terminalContextBlocksFromDraft} from '@/store/composer'+import { serverOwnsComposerQueue } from '@/store/composer-queue'import { $hudMode } from '@/store/hud'import { clearNotifications, notify, notifyError } from '@/store/notifications'import { consumePendingCredentialWarning, requestDesktopOnboarding } from '@/store/onboarding'@@@ -35,8 -35,13 +37,13 @@@ importsetMessages,touchSessionActivity} from '@/store/session'-import { $sessionStates } from '@/store/session-states'+import { $sessionStates, knownOwnerForSession } from '@/store/session-states'+ import type { SessionInfo } from '@/types/hermes'+ import {+ profileScopeForTranscriptSession,+ resolveActiveTranscriptSession+ } from '../../../contrib/hooks/use-background-sync'import type { ClientSessionState } from '../../../types'import { sessionContextDrift } from '../session-context-drift'import { resolveSessionProfile } from '../use-session-actions/utils'@@@ -110,23 -108,43 +117,59 @@@ const MAIN_SUBMIT_SCOPE: NonNullable<SusetMessages}+ export interface ResumedRuntimeBindingDeps {+ activeSessionIdRef: MutableRefObject<string | null>+ paneState?: ClientSessionState+ resumedRuntimeId: string+ sessions: SessionInfo[]+ storedSessionId: string+ updateSessionState: SubmitPromptDeps['updateSessionState']+ }++ export function rebindPaneToResumedRuntime({+ activeSessionIdRef,+ paneState,+ resumedRuntimeId,+ sessions,+ storedSessionId,+ updateSessionState+ }: ResumedRuntimeBindingDeps): void {+ if (+ paneState?.messages.length &&+ paneState.storedSessionId &&+ resolveComposerSessionKey(paneState.storedSessionId, sessions) ===+ resolveComposerSessionKey(storedSessionId, sessions)+ ) {+ const carried: ChatMessage[] = paneState.messages++ updateSessionState(+ resumedRuntimeId,+ state => (state.messages.length ? state : { ...state, messages: carried }),+ storedSessionId+ )+ }++ activeSessionIdRef.current = resumedRuntimeId+ setActiveSessionId(resumedRuntimeId)+ }+/** The prompt submit pipeline, extracted from usePromptActions. */+/** Canonical admission receipt; `user_row_id` binds the optimistic bubble to its durable row. */+type SubmitReceipt = Pick<PromptSubmitResult, 'user_row_id'> & {+ admission_id?: string+ submission_id?: string+ session_id?: string+ status?: string+}++/** A refusal the backend issued before admitting anything, so an identityless retry cannot duplicate a turn. */+function isPreAdmissionRefusal(error: unknown): boolean {+ if (!error || typeof error !== 'object' || !('code' in error)) { return false }+ const { code, message } = error as { code?: unknown; message?: unknown }++ return code === 4094 || (code === 4000 && typeof message === 'string' && /submission_id/.test(message))+}+export function useSubmitPrompt(deps: SubmitPromptDeps) {const {activeSessionIdRef,@@@ -544,10 -503,14 +561,16 @@@}),targetStoredSessionId)+ }const dropOptimistic = (sid: null | string) => {+ if (queueAdmission) { return }++ // The optimistic bubble is gone, so its blob: previews die with it —+ // unless a rejected-submit restore already re-loaded the attachments+ // into the composer, which re-owns those URLs (#63682 handoff).+ revokeDiscardedAttachmentPreviews(attachments, usingComposerAttachments ? $composerAttachments.get() : [])+if (!sid) {if (targetIsCurrentView()) {scope.setMessages(current => current.filter(m => m.id !== optimisticId))@@@ -851,18 -824,54 +887,65 @@@// the gateway receives @file: paths that resolve in its workspace.// Images keep their inline bounded thumbnail — see optimisticAttachmentRef.attachmentRefs = syncedAttachments.map(optimisticAttachmentRef).filter((r): r is string => Boolean(r))- rewriteOptimistic(liveSessionId)+ rewriteOptimistic(liveSessionId, syncedAttachments)- const text = buildContextText(syncedAttachments)+ const text = retained?.text ?? buildContextText(syncedAttachments)+ // Another Desktop window may own a newer transcript while this one+ // still shows an open-time snapshot. Refuse the send and refresh- // rather than forking the session (#65047).++ // rather than forking the session (#65047). A server-owned++ // (canonical gateway) route has one writer and one FIFO, so a send++ // from a stale view only queues behind the peer's turn — no fork.+ const guardStoredId = targetStoredSessionId ?? selectedStoredSessionIdRef.current+- if (guardStoredId && liveSessionId) {++ if (!serverQueue && guardStoredId && liveSessionId) {+ const localSnapshot = updateSessionState(liveSessionId, state => state, targetStoredSessionId)++ const refreshed = await refreshIfTranscriptStale(guardStoredId, localSnapshot.messages, {+ excludeMessageId: optimisticId,+ profile: profileScopeForTranscriptSession(resolveActiveTranscriptSession(guardStoredId, liveSessionId))+ })++ if (sessionDriftReason()) {+ return abortForSessionSwitch(liveSessionId)+ }++ if (refreshed) {+ updateSessionState(+ liveSessionId,+ state => ({+ ...state,+ awaitingResponse: false,+ busy: false,+ messages: refreshed,+ pendingBranchGroup: null+ }),+ targetStoredSessionId+ )++ if (targetIsCurrentView()) {+ scope.setMessages(() => refreshed)+ notify({+ kind: 'warning',+ message: copy.staleSessionBody,+ title: copy.staleSessionTitle+ })+ }++ releaseBusy()++ return false+ }+ }++ trackPendingSubmission(targetStoredSessionId ?? liveSessionId, {+ id: submissionId,+ text,+ displayText: options?.displayText+ })++ const imageAttachments = syncedAttachments.filter(attachment => attachment.kind === 'image' && attachment.mime)+ .map(attachment => ({ path: attachment.path!, mime: attachment.mime! }))+const submitParams = (targetId: string) => ({session_id: targetId,text,diff --cc apps/desktop/src/components/assistant-ui/clarify-tool.tsxindex 522bdfe2f66,e056a232395..a232190d926--- a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.tsx@@@ -398,20 -472,23 +472,28 @@@ function ClarifyToolPending(props: Tool// request — but the question TEXT is already in the tool args, so paint a// disabled preview immediately instead of a spinner (the single-question// card does the same while request_id races the tool block).- if (request?.questions?.length || fromArgs.questions) {+ // The shared gateway answers a batch one card at a time (`_clarify_batch_sync`):+ // its requests are single-question even when the tool args are a batch, so a+ // live single-question request always drives the single card.+ const singleLive = Boolean(request?.requestId) && !request?.questions?.length++ if (!singleLive && (request?.questions?.length || fromArgs.questions)) {- return <ClarifyToolBatchPending fromArgs={fromArgs} onAnswered={() => setAnswered(true)} request={request} />+ return (+ <ClarifyToolBatchPending+ fromArgs={fromArgs}+ onAnswered={() => setAnswered(true)}+ request={request}+ undelivered={undelivered}+ />+ )}return (<ClarifyToolSinglePending- fromArgs={fromArgs}+ fromArgs={singleLive && fromArgs.questions ? {} : fromArgs}onAnswered={() => setAnswered(true)}request={request}+ undelivered={undelivered}/>)}diff --cc apps/desktop/src/global.d.tsindex 1df72d28e4e,7011da7f357..60a8f8c631d--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@@ -4,7 -4,10 +4,9 @@@ import type { TranslucencyState } fromimport type { ScreenshotApi } from '../electron/command-screenshot-types'import type { HudModifierApi } from '../electron/hud-modifier-types'+ import type { MachineProfile } from '../electron/machine-profile'import type { HermesNotification } from '../electron/notification-types'-import type { PoolLimits } from '../electron/pool-limits'+ import type { GrowRequest } from '../electron/window-growth'import type { WakeIndicatorState } from './lib/wake-indicator'import type {diff --cc apps/desktop/src/i18n/ar.tsindex 35d60b63974,4e82e3345e2..c399a7987ae--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@@ -2328,12 -2382,11 +2383,15 @@@ export const ar = defineLocale(queueSteer: 'توجيه — تصحيح الدور الجاري فورا',queueSend: 'إرسالها الآن',queueDelete: 'حذف من الطابور',+ queueLostNote: 'فُقد الدور أثناء إعادة التشغيل',+ restoreImageDraft: 'استعادة مسودة الصورة',+ queueLostDiscard: 'تجاهل',+ queueLostDiscardTip: 'أعادت البوابة التشغيل أثناء هذا الدور ولا يمكن إكماله. تجاهله لتستمر الأدوار المنتظرة خلفه.',queueStuckTitle: 'لم تُرسل الرسالة في قائمة الانتظار',queueStuckBody: 'ظل دور في قائمة الانتظار يفشل في الإرسال. ما زال في قائمة الانتظار — حاول إرساله مرة أخرى.',+ queueDroppedTitle: 'تم إسقاط عنصر قائمة الانتظار',+ queueDroppedBody:+ 'أُسقط هذا العنصر في الخلفية لأن جلسته تعذّر استئنافها بعد محاولات متكررة. بقية قائمة الانتظار لم تتأثر.',previewUnavailable: 'المعاينة غير متاحة',previewLabel: label => `معاينة ${label}`,couldNotPreview: label => `تعذرت معاينة ${label}`,diff --cc apps/desktop/src/plugins/hermes-bots/relay.tsindex ad9e428e5c1,bce85927edb..124d111d757--- a/apps/desktop/src/plugins/hermes-bots/relay.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts@@@ -105,18 -108,40 +108,51 @@@ const relay: RelayLifecycle =// leases. Local routes get a no-op release inside the host (idle-reaper// exemption). stopBotRelay releases everything.const relayRouteRetentions = new Map<string, () => void>()+// Claimed envelopes remain pinned to their sender until terminal reply ACK.+// The sender's durable claimed directory restores these after renderer restart.+const pendingRelays = new Map<string, Map<string, RelayEnvelope>>()++function pendingRelaysFor(sender: RelayConnection): Map<string, RelayEnvelope> {+ const senderKey = JSON.stringify(sender.route)+ const pending = pendingRelays.get(senderKey) || new Map<string, RelayEnvelope>()+ pendingRelays.set(senderKey, pending)++ return pending+}+ // Routes whose gateway has signaled `bot_relay.outbox.pending` since the last+ // drain pass. `*` means the event carried no connection id (local/legacy+ // primary, or an older payload) — every route may hold that envelope, so the+ // pass still visits them. A route absent from this set has no outbox work;+ // opening a socket to drain it is the idle dial.+ const RELAY_OUTBOX_ANY = '*'+ const routesWithOutboxWork = new Set<string>()++ function relayBotModeOn(): boolean {+ const decisions = host.pluginDecisions?.get() ?? {}++ return ID in decisions ? Boolean(decisions[ID]) : true+ }++ function noteRelayOutboxWork(event?: { connectionId?: string }) {+ const id = String(event?.connectionId || '').trim()++ routesWithOutboxWork.add(id || RELAY_OUTBOX_ANY)+ }++ function takeRelayOutboxWork(): { any: boolean; ids: Set<string> } {+ const any = routesWithOutboxWork.has(RELAY_OUTBOX_ANY)+ const ids = new Set(routesWithOutboxWork)++ routesWithOutboxWork.clear()++ return { any, ids }+ }++ function routeSignaledOutboxWork(connectionId: string, work: { any: boolean; ids: Set<string> }): boolean {+ return work.any || work.ids.has(connectionId)+ }+/** One reachable gateway plus a representative route onto it. The route carries* identity only, so the human label comes from the registry (connectionLabels). */interface RelayConnection {diff --cc apps/desktop/src/store/composer-queue.tsindex b4b6f8fc577,d0a036a9cec..59c7c108806--- a/apps/desktop/src/store/composer-queue.ts+++ b/apps/desktop/src/store/composer-queue.ts@@@ -1,22 -1,15 +1,30 @@@import { SLASH_COMMAND_RE } from '@hermes/shared'import { atom } from 'nanostores'+import { $connection } from './session'+import { knownOwnerForSession } from './session-states'++/** Local owner routes use canonical admission; remote legacy queues stay local. */+export function serverOwnsComposerQueue(sessionId: string | null | undefined): boolean {+ const owner = knownOwnerForSession(sessionId)++ if (owner && typeof owner === 'object' && owner.mode) { return owner.mode === 'local' }+ const connection = $connection.get()++ if (owner && typeof owner === 'object' && owner.connectionId !== connection?.connectionId) { return false }++ return Boolean(connection?.wsUrl && new URL(connection.wsUrl).searchParams.has('native_dial'))+}+- import type { ComposerAttachment } from './composer'+ import { type ComposerAttachment, revokeAttachmentPreviewUrls, revokeDiscardedAttachmentPreviews } from './composer'++ export interface RemoveQueuedPromptOptions {+ /**+ * When true, leave blob: preview URLs alive because submit/optimistic now+ * owns the snapshot (drain handoff). Default false = entry discarded.+ */+ retainPreviewUrls?: boolean+ }export interface QueuedPromptEntry {id: string@@@ -106,9 -104,12 +120,12 @@@ const setParked = (sid: string, parked$parkedQueueSessions.set(next)}-const writeSession = (sid: string, queue: QueuedPromptEntry[]) => {+export const writeSessionQueue = (sid: string, queue: QueuedPromptEntry[]) => {- const current = $queuedPromptsBySession.get()- const next = { ...current }+ // Merge over the LIVE persisted map, not the in-memory atom: another window+ // may have written its own sessions' queues between our last sync and now,+ // and writing our whole snapshot back would clobber those entries (#46732).+ const live = load()+ const next: QueueState = { ...live }if (queue.length === 0) {delete next[sid]@@@ -160,7 -180,13 +196,13 @@@ export const enqueueQueuedPrompt =queuedAt: Date.now()}- writeSessionQueue(sid, [...queueFor(sid), entry])- writeSession(++ writeSessionQueue(+ sid,+ // Queueing a fresh prompt is fresh intent to keep the conversation+ // moving — lift the persisted drain-failure budget off the entries+ // already waiting there, exactly like the park (#98015).+ [...queueFor(sid).map(e => (e.drainFailures ? { ...e, drainFailures: undefined } : e)), entry]+ )// Queueing a new prompt is fresh intent to keep the conversation moving —// a park from an earlier Stop must not hold this (or the entries ahead of// it) back.@@@ -182,7 -208,8 +224,8 @@@ export const dequeueQueuedPrompt = (keyreturn null}+ // Caller takes ownership of head.attachments (including any blob: previews).- writeSession(sid, rest)+ writeSessionQueue(sid, rest)return head}@@@ -195,17 -226,68 +242,69 @@@ export const removeQueuedPrompt =}const queue = queueFor(sid)+ const removed = queue.find(e => e.id === id)- const next = queue.filter(e => e.id !== id)++ // Server-owned (admitted) rows retire through the gateway, never locally.+ const next = queue.filter(e => e.id !== id || e.serverStatus)- if (next.length === queue.length) {+ if (!removed || next.length === queue.length) {return false}- writeSession(sid, next)+ writeSessionQueue(sid, next)+ if (!options?.retainPreviewUrls) {+ revokeAttachmentPreviewUrls(removed.attachments)+ }+return true}+ /** Count one more rejected auto-drain attempt against a queued entry and+ * persist it with the queue (#98015). The in-process retry ladder stays+ * identical; only its budget survives restarts, so a session that is dead in+ * this process is not retried four more times on every future launch. */+ export const noteQueuedPromptDrainFailure = (key: string | null | undefined, id: string): void => {+ const sid = sidOf(key)++ if (!sid) {+ return+ }++ const queue = queueFor(sid)++ if (!queue.some(e => e.id === id)) {+ return+ }+- writeSession(++ writeSessionQueue(+ sid,+ queue.map(e => (e.id === id ? { ...e, drainFailures: (e.drainFailures ?? 0) + 1 } : e))+ )+ }++ /** Clear a queued entry's persisted drain-failure budget — the queue-panel+ * sibling of the composer's in-process counter reset. Called on the user+ * gestures that express fresh intent to send (manual send, redirect, and+ * implicitly by removal on success). */+ export const clearQueuedPromptDrainFailures = (key: string | null | undefined, id: string): void => {+ const sid = sidOf(key)++ if (!sid) {+ return+ }++ const queue = queueFor(sid)++ if (!queue.some(e => e.id === id && e.drainFailures)) {+ return+ }+- writeSession(++ writeSessionQueue(+ sid,+ queue.map(e => (e.id === id ? { ...e, drainFailures: undefined } : e))+ )+ }+export const promoteQueuedPrompt = (key: string | null | undefined, id: string): boolean => {const sid = sidOf(key)@@@ -280,7 -366,11 +383,11 @@@ export const clearQueuedPrompts = (keyreturn}+ for (const entry of queueFor(sid)) {+ revokeAttachmentPreviewUrls(entry.attachments)+ }+- writeSession(sid, [])+ writeSessionQueue(sid, [])}/**@@@ -304,9 -394,12 +411,12 @@@ export const migrateQueuedPrompts = (frreturn false}- const next = { ...$queuedPromptsBySession.get() }- // Merge over the live persisted map (see writeSession) so the migration can't++ // Merge over the live persisted map (see writeSessionQueue) so the migration can't+ // clobber entries another window queued meanwhile — including into `to`.+ const live = load()+ const next: QueueState = { ...live }delete next[from]- next[to] = [...queueFor(to), ...pending]+ next[to] = [...(live[to] ?? queueFor(to)), ...pending]$queuedPromptsBySession.set(next)save(next)diff --cc apps/desktop/src/store/notifications.tsindex 79f8921dbe2,ddccd7faac3..bc84bcf3983--- a/apps/desktop/src/store/notifications.ts+++ b/apps/desktop/src/store/notifications.ts@@@ -262,9 -277,16 +276,10 @@@ export function notifyErroroptions: { action?: NotificationAction; id?: string } = {}): string {const readable = readableError(error, fallback)- const poolSlotTimeout = isLocalBackendSlotWaitTimeout(error)+ logErrorToDesktopLog(error, fallback)return notify({- action: poolSlotTimeout- ? {- label: translateNow('desktop.poolSlotTimeoutOpenSettings'),- onClick: requestPoolLimitsSettings- }- : (options.action ?? readable.action),+ action: options.action ?? readable.action,// A caller that can fire again for the same cause names its toast, so the repeat replaces it.id: options.id,kind: 'error',diff --cc apps/desktop/src/store/profile.test.tsindex e1de84852bd,003e680967a..013b9afe6d2--- a/apps/desktop/src/store/profile.test.ts+++ b/apps/desktop/src/store/profile.test.ts@@@ -37,10 -45,16 +38,15 @@@ const$profiles,ensureGatewayProfile,invalidateProfileListFetches,+ newSessionInProfile,prewarmProfileBackend,- refreshProfiles+ refreshProfiles,+ selectProfile} = await import('./profile')+ const { $projectScope, ALL_PROJECTS } = await import('./project-scope')+ const { $projectTree, resolveNewSessionCwd } = await import('./projects')+-const { $poolLimits } = await import('@/store/pool-limits')const { $connectionsRegistry } = await import('@/store/connection-registry-state')const { $connection } = await import('./session')diff --cc apps/desktop/src/store/profile.tsindex 51750c61e92,7ee23633982..042fc725d6d--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@@ -23,10 -23,13 +23,11 @@@ importensureGatewayForAgent,ensureGatewayForProfile,openGatewayForAgent,- openGatewayForProfile,- openSecondaryCount+ openGatewayForProfile} from '@/store/gateway'import { notifyError } from '@/store/notifications'-import { $poolLimits } from '@/store/pool-limits'import { notifyRemoteOverrideAuthFailure } from '@/store/profile-remote-override'+ import { exitProjectScope } from '@/store/project-scope'import { $connection, clearComposerSelectionOwner, setComposerSelectionOwner, setConnection } from '@/store/session'import type { SessionOwnerRoute } from '@/store/session-request-router'import { resetStarmapGraph } from '@/store/starmap'diff --cc apps/desktop/src/store/updates.tsindex ce4ee2ea924,0b53c0cb3b3..ea0daf3127f--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@@ -5,7 -5,7 +5,8 @@@import { atom } from 'nanostores'+import { CANONICAL_GATEWAY_PROTOCOL } from '@/api/canonical-protocol'+ import { connectionScoped, profileScoped } from '@/api/client'import type {DesktopUpdateApplyOptions,DesktopUpdateApplyResult,@@@ -95,10 -98,12 +99,14 @@@ function isUpdateToastSnoozed(): boolea}// Must match tui_gateway's DESKTOP_BACKEND_CONTRACT that this build was written-// against. The backend reports its own value in session runtime info; a lower-// value (or none — a pre-GUI checkout) means the backend is older than this-// GUI, a higher value means this GUI is older than the backend. Both+// against. Legacy backends report their own value in session runtime info; a- // lower value (or none — a pre-GUI checkout) means GUI<->backend skew.- // Canonical gateways identify their distinct wire protocol instead. That value- // does not claim the legacy API features listed below.++// lower value (or none — a pre-GUI checkout) means the backend is older than++// this GUI, a higher value means this GUI is older than the backend. Both+ // directions are GUI<->backend skew and both warn — an old GUI silently+ // driving a newer backend is just as broken as the reverse, it only fails-// further from the cause.++// further from the cause. Canonical gateways identify their distinct wire++// protocol instead. That value does not claim the legacy API features listed++// below.// v2: requires the file.attach RPC (remote-gateway non-image file upload).// v3: requires approvals.mode config RPCs and session.info reconciliation.// v4: requires explicit Fast-off session creation and session-scoped Fast edits.@@@ -147,21 -164,22 +167,26 @@@ function isInstallMethodToastSnoozed()}/**- * Guard against a desktop GUI talking to a backend that predates its contract- * (e.g. a bb/gui-built app pointed at a `main` checkout). Rather than failing- * cryptically downstream, surface a warning with a one-click align that runs- * the normal update flow (which self-heals to the right branch).+ * Guard against GUI<->backend contract skew in either direction. A backend+ * that predates this GUI's contract (e.g. a bb/gui-built app pointed at a+ * `main` checkout) gets a "backend out of date" warning with a one-click+ * align that runs the normal backend update flow. A backend *ahead* of this+ * GUI's contract (typically a long-running app that survived a backend+ * update without relaunching) gets the reverse "app out of date" warning+ * pointing at the client update flow. Without the reverse check an old GUI+ * silently drives a newer backend and fails cryptically downstream.*- * Runs on every session open; closing the toast snoozes it for a cooldown so it+ * Runs on every session open; closing a toast snoozes it for a cooldown so it* doesn't nag on every thread switch.*/-export function reportBackendContract(contract: number | undefined): void {- const reported = contract ?? 0+export function reportBackendContract(contract: number | undefined, protocol?: string): void {- // An unknown explicit protocol must not fall back to a legacy version claim.- const compatible = protocol === undefined- ? (contract ?? 0) >= REQUIRED_BACKEND_CONTRACT- : protocol === CANONICAL_GATEWAY_PROTOCOL++ // A canonical gateway speaks exactly the protocol this build targets. An++ // unknown explicit protocol must not fall back to a legacy version claim, so++ // it reads as an out-of-date backend.++ const reported =++ protocol === undefined ? (contract ?? 0) : protocol === CANONICAL_GATEWAY_PROTOCOL ? REQUIRED_BACKEND_CONTRACT : 0- if (compatible) {+ if (reported >= REQUIRED_BACKEND_CONTRACT) {dismissNotification(SKEW_TOAST_ID)// Backend caught up — forget any prior snooze so a future regression warns// immediately rather than staying silent for the rest of the window.diff --cc gateway/platforms/api_server_runs.pyindex 1322cad4300,8b662cacbdf..b12186777d1--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@@ -965,46 -957,18 +999,48 @@@ async def _execute_run(self, run: _RunLif run_id in self._stopping_run_ids:_finish("cancelled")return- with self._profile_scope(run.request_profile):- agent = self._create_agent(- stream_delta_callback=_text_cb, tool_progress_callback=self._make_run_event_callback(run_id, loop),- interim_assistant_callback=_interim_cb, **run.agent_kwargs)- self._active_run_agents[run_id] = agent- approval_notify = _make_approval_notify(self, run, _api_server=_api_server)- result, usage, served_runtime = await _submit_api_worker(- loop, lambda: _run_agent_sync(self, run, agent, approval_notify, _api_server=_api_server))+ if run.admission is not None:+ from gateway.session_api_turn import observe_api_controls, observe_api_turn+ tool_cb = self._make_run_event_callback(run_id, loop)++ def _control_cb(event_type, prompt):+ # Same authority prompt the WS viewer and GET pending_controls expose, on the+ # run's own stream so a streaming-only client learns it must respond.+ with suppress(Exception):+ loop.call_soon_threadsafe(run.put_event, _run_event(run_id, event_type, **prompt))++ def _tool_start(call_id, name, args):+ from agent.display import build_tool_preview+ tool_cb("tool.started", name, build_tool_preview(name, args or {}) or "", args, tool_call_id=call_id)++ def _tool_complete(call_id, name, args, result):+ from agent.display import _detect_tool_failure+ is_error, _ = _detect_tool_failure(name, result)+ tool_cb("tool.completed", name, None, args, tool_call_id=call_id, is_error=bool(is_error))++ with observe_api_controls(run.admission, _control_cb):+ result, usage = await observe_api_turn(+ run.admission, stream_delta_callback=_text_cb,+ tool_start_callback=_tool_start, tool_complete_callback=_tool_complete)+ # The canonical turn has no agent object here; the served pair rides on the+ # committed usage/result runtime metadata when the turn recorded one.+ served_runtime = ((usage or {}).get("runtime") if isinstance(usage, dict) else None) or (+ result.get("runtime") if isinstance(result, dict) else None) or {}+ else:+ with self._profile_scope(run.request_profile):+ agent = self._create_agent(+ stream_delta_callback=_text_cb, tool_progress_callback=self._make_run_event_callback(run_id, loop),+ interim_assistant_callback=_interim_cb, **run.agent_kwargs)+ self._active_run_agents[run_id] = agent+ approval_notify = _make_approval_notify(self, run, _api_server=_api_server)+ result, usage, served_runtime = await _submit_api_worker(+ loop, lambda: _run_agent_sync(self, run, agent, approval_notify, _api_server=_api_server))+ # Publish request metrics (daily counters + latency) with each completed run (#52323).+ self._record_api_metrics(usage, time.perf_counter() - _run_started_at)if not isinstance(result, dict):result = {}+ # The committed outcome decides: a stop issued over WS by another viewer interrupts+ # this run just as much as one issued through this adapter's own /stop.status, fields = terminal_run_status(result)if status == "cancelled":_finish("cancelled", fields)diff --cc gateway/run_notifications.pyindex 751f1eef7e0,21d50135be9..637c5e6e158--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@@ -1331,11 -1354,23 +1354,25 @@@ class GatewayNotificationsMixinparent_session_id = str(evt.get("parent_session_id") or "").strip()if parent_session_id:metadata["gateway_session_id"] = parent_session_id+ if evt.get('_automation_identities'):+ metadata['automation_identities'] = evt['_automation_identities']+ # The queued event's ``message_id`` is the message that STARTED the process, and the+ # persisted origin carries the same stale id. A synthetic completion is not a reply to+ # it: by delivery time the user has often continued elsewhere, and an event anchored+ # there makes the finished job's reply quote that old message on every reply-anchoring+ # platform (#52694: a background completion visibly replying to a stale Discord DM+ # message). Routing is unaffected — topic lanes carry thread_id and the anchor-less+ # synthetic-send branches are covered (#87051); the original id rides metadata for+ # debugging only.+ trigger_message_id = str(evt.get("message_id") or "").strip() or None+ if trigger_message_id:+ metadata["original_trigger_message_id"] = trigger_message_id+ if getattr(source, "message_id", None):+ from gateway.session_identity import replace_source+ source = replace_source(source, message_id=None)synth_event = MessageEvent(text=synth_text, message_type=MessageType.TEXT, source=source, internal=True,- message_id=str(evt.get("message_id") or "").strip() or None, metadata=metadata,+ metadata=metadata,)logger.info("Watch pattern notification — injecting for %s chat=%s thread=%s",diff --cc gateway/run_runtime_init.pyindex 03c86c864f6,00000000000..1fd69d66e52mode 100644,000000..100644--- a/gateway/run_runtime_init.py+++ b/gateway/run_runtime_init.py@@@ -1,260 -1,0 +1,266 @@@+"""Writable runner initialization, separate from process ownership."""+from __future__ import annotations++class GatewayRuntimeInitMixin:+ def _init_runtime_settings(self) -> None:+ """Load ephemeral per-call config (prefill, reasoning, busy modes, timeouts, routing)."""+ from gateway.run import (Dict, Optional, _load_gateway_config)+ self._prefill_messages = self._load_prefill_messages()+ self._reasoning_config = self._load_reasoning_config()+ self._service_tier = self._load_service_tier()+ self._show_reasoning = self._load_show_reasoning()+ self._busy_input_mode = self._load_busy_input_mode()+ self._busy_text_mode = self._load_busy_text_mode()+ # Secondary-profile busy modes snapshotted at multiplex startup; handlers never reread config.+ self._busy_input_modes_by_profile: Dict[str, str] = {}+ self._busy_text_modes_by_profile: Dict[str, str] = {}+ self._busy_text_timing = self._busy_text_timing_from_config(_load_gateway_config())+ self._busy_text_timing_by_profile: Dict[str, tuple[float, float]] = {}+ self._human_delay = self._human_delay_from_config(_load_gateway_config())+ self._human_delay_by_profile: Dict[str, Optional[tuple[int, int]]] = {}+ self._restart_drain_timeout = self._load_restart_drain_timeout()+ # Live launchd ``ExitTimeOut`` for this job (None when not launchd-owned). Read once at+ # boot — launchd fixes it at load — and applied only to signal-driven stops, which are the+ # only stops launchd times. See _load_launchd_exit_timeout().+ self._stop_requested_by_signal = False+ self._launchd_exit_timeout_s = self._load_launchd_exit_timeout(self._restart_drain_timeout)+ self._restart_after_turn_timeout = self._load_restart_after_turn_timeout()+ self._cron_drain_timeout = self._load_cron_drain_timeout()+ self._signal_interrupt_grace_timeout = self._load_signal_interrupt_grace_timeout()+ self._provider_routing = self._load_provider_routing()+ self._fallback_model = self._load_fallback_model()++ def _init_session_store(self) -> None:+ """Build the SessionStore (with process-registry reset guard), its async facade and the router."""+ from gateway.run import (AsyncSessionStore, DeliveryRouter, SessionStore)+ from tools.process_registry import process_registry+ self.session_store = SessionStore(+ self.config.sessions_dir, self.config,+ has_active_processes_fn=lambda key: process_registry.has_active_for_session(+ key))+ # Loop-side boundary: sync helpers use ``session_store`` directly; async handlers await this facade.+ self._async_session_store = AsyncSessionStore(self.session_store)+ self.delivery_router = DeliveryRouter(self.config)++ def _init_lifecycle_state(self) -> None:+ """Initialise run/exit/restart flags, per-session state, and completion-delivery bookkeeping."""+ from gateway.run import (Dict, List, MessageEvent, Optional, OrderedDict, Platform, SessionSource, SessionState, SessionTurnLeaseRegistry, asyncio, concurrent, threading, time)+ self._running = self._exit_cleanly = self._exit_with_failure = self._draining = False+ self._gateway_loop: Optional[asyncio.AbstractEventLoop] = None+ self._shutdown_event = asyncio.Event()+ self._exit_reason: Optional[str] = None+ self._exit_code: Optional[int] = None+ self._profile_failed_platforms: Dict[str, Dict[Platform, asyncio.Task]] = {}+ self._systemd_watchdog = None+ # External (NAS-driven) drain, distinct from one-way ``_draining``: set while ``.drain_request.json``+ # exists — NEW turns refused, process stays up, removing the marker reverts to ``running``.+ self._external_drain_active = False+ # ``_signal_initiated_shutdown``: SIGTERM/SIGINT with no planned-stop/takeover marker (container,+ # OOM, bare kill); _stop_impl must NOT persist gateway_state=stopped or container_boot won't restart.+ self._restart_requested = self._signal_initiated_shutdown = self._restart_task_started = False+ self._restart_detached = self._restart_via_service = self._detached_restart_helper_started = False+ self._restart_command_source: Optional[SessionSource] = None+ # Construction clock: bounds the /restart redelivery guard's window (missing dedup marker = stale).+ self._startup_time: float = time.time()+ # True when booted from a chat /restart (.restart_notify.json existed). One-shot signal so the+ # marker-missing fallback suppresses a /restart only when we KNOW we just restarted.+ self._booted_from_restart: bool = False+ self._stop_task: Optional[asyncio.Task] = None+ self._restart_task: Optional[asyncio.Task] = None+ self._executor_lock = threading.Lock()+ self._executor: Optional[concurrent.futures.ThreadPoolExecutor] = None+ # Best-effort session housekeeping runs on its OWN pool; see _run_housekeeping_in_executor.+ self._housekeeping_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None+ # Set on gateway stop so the recreate-on-shutdown path can't resurrect the pool.+ self._executor_closing = False+ # ALL per-session state lives here (gateway/session_state.py); use _session_state / _peek_session_state.+ self._sessions: Dict[str, SessionState] = {}+ # Per-SESSION_ID turn lease: serializes [load history → run → flush] when two ROUTING KEYS resolve+ # to one session_id (switch_session's many-to-one mapping), which routing-key guards cannot see.+ self._turn_leases = SessionTurnLeaseRegistry()+ # Stall-notified keys clear when pending clears / activity resumes / conversation boundary.+ # Held turn-lease tokens live on SessionState.turn.lease_tokens keyed by run generation, so a+ # stale unwind can never free a newer turn's lease (#28686). Runner-level queued interrupt text lives on+ # SessionState.persistent.pending_command_text (NOTE: distinct from the adapter-level+ # _pending_messages Dict[str, MessageEvent] in gateway/platforms/base.py, which shares the legacy+ # name). Last successfully-resolved (non-empty) model, keyed by session. Used as a fallback when a+ # fresh config read transiently returns an empty model (e.g. an mtime-keyed config-cache miss during+ # a post-interrupt recovery turn). Without this, the agent is built with model="" and every API call+ # fails HTTP 400 "No models provided" — the session goes silent until the user manually re-sends.+ # See #35314. The ``"*"`` session entry holds a process-wide last-known-good for sessions seen for+ # the first time. Lives on SessionState.conversation.last_resolved_model. Overflow buffer for+ # explicit /queue commands. The adapter-level _pending_messages dict is a single slot per session+ # (designed for "next-turn" follow-ups where repeated sends collapse into one event). /queue has+ # different semantics: each invocation must produce its own full agent turn, in FIFO order, with no+ # merging. When the slot is occupied, additional /queue items land here and are promoted+ # one-at-a-time after each run's drain. Cleared on /new and /reset. /model and other mid-session+ # operations preserve the queue. Lives on SessionState.conversation.queued_events; native image+ # paths, busy-ack debounce timestamps and the monotonic run-generation counter (#28686, NEVER reset)+ # live on SessionState too. See gateway.session_stall.+ self._session_stall_notified: Dict[str, bool] = {}+ # Consecutive "persisted transcript lagged live cached history" turns per session key; see+ # run_turn_runner._load_turn_history (#114266). Cleared on /new.+ self._transcript_lag_streaks: Dict[str, int] = {}+ # Startup restore gate: while restart-interrupted sessions auto-resume, real inbound messages+ # queue instead of competing with the synthetic resume turns; drained after all resume tasks end.+ self._startup_restore_in_progress = False+ self._startup_restore_queue: List[MessageEvent] = []+ self._startup_restore_tasks: List[asyncio.Task] = []+ # Set by start_gateway() only for an explicit ``--replace`` launch; scoped to each adapter's+ # cold-start connect and removed before any reconnect can run.+ self._platform_lock_takeover_on_start = False+ # Capped LRU of live SessionSources for fallback routing (shutdown notices, synthetic events) when+ # the persisted origin is missing and _parse_session_key can't recover thread_id.+ self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict()+ self._session_sources_max = 512+ # Lifecycle-scoped completion dedup: closes queue/watcher races inside one gateway without claiming+ # exactly-once across a crash; durable replay state stays owned by tools.async_delegation.+ self._completion_delivery_lock = threading.Lock()+ self._completion_deliveries_inflight: set[tuple[str, str, object]] = set()+ self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict()+ self._completion_delivery_retention = 2048+ # Agent-triggered terminal completions from one conversation often land in the same scheduler+ # tick; hold them briefly so the agent gets one synthetic turn instead of one per process.+ # See #70300.+ self._completion_notification_batches: dict[tuple[str, ...], list[tuple[str, dict, asyncio.Future]]] = {}+ self._completion_notification_batch_tasks: dict[tuple[str, ...], asyncio.Task] = {}+ self._completion_notification_batch_flush_tasks: set[asyncio.Task] = set()+ self._completion_notification_batch_window = 0.1+ self._completion_notification_batches_stopping = False++ def _init_runtime_caches(self) -> None:+ """Agent cache, profile identity, Teams runtime, failed-platform tracking, slash-confirm counter."""+ from gateway.run import (Any, Dict, Optional, OrderedDict, Platform, threading)+ # AIAgent per session preserves prompt caching (fresh agent per message ~10x cost on Anthropic).+ # Value: (AIAgent, config_signature); LRU cap in _enforce_agent_cache_cap, TTL in expiry watcher.+ self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()+ self._agent_cache_lock = threading.Lock()+ # Launch-time identity of the profile that owns ``self.adapters``; ``_authorization_adapter``- # compares against this rather than the per-turn ``_active_profile_name()``.- self._primary_profile_name = self._kanban_notifier_profile = self._active_profile_name()++ # compares against this rather than the per-turn ``_active_profile_name()``. A multiplex++ # host's primary map is always the default profile, even when a named profile launched++ # the process (that launcher is a secondary adapter owner).++ launch = self._active_profile_name()++ self._kanban_notifier_profile = launch++ self._primary_profile_name = (++ "default" if getattr(self.config, "multiplex_profiles", False) else launch++ )+ # Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).+ self._teams_pipeline_runtime = None+ self._teams_pipeline_runtime_error: Optional[str] = None+ # Failed-to-connect platforms for background reconnection: Platform -> {config, attempts, next_retry}+ self._failed_platforms: Dict[Platform, Dict[str, Any]] = {}+ # Strong refs to detached fatal-error handler tasks so the loop can't GC them mid-run.+ self._fatal_handler_tasks: set = set()+ # Slash-confirm state lives in tools.slash_confirm (module-level) so adapters resolve callbacks+ # without a runner backref; local counter keeps confirm_ids compact (64-byte callback_data caps).+ import itertools+ self._slash_confirm_counter = itertools.count(1)++ def _init_startup_checks(self) -> None:+ """Ensure tirith is installed and warn when manual approvals have no automated assessor."""+ from gateway.run import (_best_effort, cfg_get, logger)+ def _ensure_tirith() -> None:+ from tools.tirith_security import ensure_installed+ ensure_installed(log_failures=False) # downloads if needed; fail-open at scan time++ _best_effort(_ensure_tirith)++ # Manual approvals with no automated assessor (tirith off AND no auxiliary.approval) fail closed+ # on unattended gateways — surface it so operators knowingly enable one.+ try:+ from hermes_cli.config import load_config as _load_full_config+ # Startup heads-up (#30882): a gateway in manual approval mode with no automated risk assessor+ # (tirith disabled AND no auxiliary.approval model) can only gate dangerous commands /+ # execute_code scripts via live in-chat approval.+ _appr_cfg = _load_full_config()+ _appr_mode = str(+ cfg_get(_appr_cfg, "approvals", "mode", default="manual") or "manual"+ ).strip().lower()+ _tirith_on = bool(cfg_get(_appr_cfg, "security", "tirith_enabled", default=True))+ _aux_approval = cfg_get(_appr_cfg, "auxiliary", "approval", default=None)+ if _appr_mode == "manual" and not _tirith_on and not _aux_approval:+ logger.warning(+ "Gateway approvals.mode=manual with no automated risk "+ "assessor (security.tirith_enabled is false and "+ "auxiliary.approval is unset): dangerous commands and "+ "execute_code scripts will BLOCK until a human approves "+ "them in chat. Enable security.tirith_enabled or configure "+ "auxiliary.approval for unattended operation.")+ except Exception:+ logger.debug("approvals.mode startup check skipped", exc_info=True)++ def _init_session_db(self) -> None:+ """Open the session DB for the active scope and run opportunistic state.db / checkpoint maintenance."""+ from gateway.run import (Any, Dict, Path, _SESSION_DB_UNPINNED, _housekeeping_chore, _housekeeping_state_db_maintenance, _launch_sessions_dir, logger, threading)+ # Session DB is a property caching one AsyncSessionDB per path (a handle bound here would pin the+ # root home under multiplex); priming here keeps startup diagnostics at init.+ # Initialize session database for session_search tool support. Same frozen-handle class of bug as+ # SessionStore._db (#88532): a handle bound here is pinned to the process's root home, but /resume,+ # /title, /history and session search all run inside _profile_runtime_scope on a multiplexed gateway+ # and must see that profile's own state.db.+ self._session_db_pinned: Any = _SESSION_DB_UNPINNED+ self._session_db_handles: Dict[Path, Any] = {}+ self._session_db_handles_lock = threading.Lock()+ from gateway.session_db_recovery import RecoverableHandleCache+ self._session_db_handle_cache = RecoverableHandleCache(+ handles=self._session_db_handles, lock=self._session_db_handles_lock)+ try:+ self._open_session_db_for_active_scope(raise_on_error=True)+ except Exception as e:+ # WARNING (not DEBUG) so it lands in errors.log; else an NFS HERMES_HOME silently loses /resume etc.+ logger.warning("SQLite session store not available: %s", e)+ self._session_db_init_error = str(e) # surfaced on the home channel(s) once connected++ # Opportunistic state.db maintenance (prune + optional VACUUM), at most once per min_interval_hours.+ # A few blocking seconds per day is fine for a long-lived gateway; failures log, never raise.+ # Surface the failure to the user via their home channel(s) once the gateway connects. Without this,+ # state.db corruption or NFS/SMB lock failures silently degrade the entire gateway — messages may+ # flow but nothing is persisted, and the user has no indication until they try /resume and find+ # nothing (#88235).+ # Once per SERVED profile, each under its own scope: both the store and the ``sessions:``+ # config that governs it must be the profile's own. Bound to ``self._session_db`` this ran+ # against the construction-time launch home only, so a multiplexed secondary profile's+ # state.db was never pruned or vacuumed by anybody, and the launch profile's+ # retention_days/auto_prune decided whether it happened at all.+ from gateway.run_profile_reconcile import _for_each_served_profile+ _launch_sessions = _launch_sessions_dir(self.config) # resolved OUTSIDE any profile scope+ _housekeeping_chore(+ "state.db startup maintenance",+ lambda: _for_each_served_profile(+ self, lambda _label: _housekeeping_state_db_maintenance(_launch_sessions)))+ # Checkpoint store pruning is a housekeeping chore (``_housekeeping_checkpoint_prune``), not a+ # constructor step: its ``git gc`` repacks the whole store (tens of seconds on a GB store) and+ # here it ran before the control socket, adapters and the code_sha stamp — so the first+ # restart of the day (the ``hermes update`` one) looked hung and failed fleet verification.++ def _init_registries_and_clocks(self) -> None:+ """Pairing stores, hook registry, voice modes, background-task set, liveness and idle clocks."""+ from gateway.run import (Dict, List, Optional, asyncio, time)+ # ``pairing_store``: global/default store (CLI, callers without profile context); ``pairing_stores``:+ # per-profile map ``authz_mixin._is_user_authorized`` routes through (one whitelist per profile).+ from gateway.pairing import PairingStore+ from gateway.hooks import ProfileHookRegistries+ self.pairing_store = PairingStore()+ self.pairing_stores: Dict[str, "PairingStore"] = {}+ # One HookRegistry per served profile home, resolved from the active scope at emit time.+ self.hooks = ProfileHookRegistries()+ # Per-chat voice reply mode: "off" | "voice_only" | "all"+ self._voice_mode: Dict[str, str] = self._load_voice_modes()+ # Per-(guild,user) transcript dedup: the voice/STT pipeline can emit one utterance twice.+ self._recent_voice_transcripts: Dict[tuple[int, int], List[tuple[float, str]]] = {}+ # Background tasks kept referenced so they are not garbage-collected mid-execution.+ self._background_tasks: set = set()+ # Event-loop liveness heartbeat: rewritten every 30s while the loop dispatches; supervisors use+ # the file mtime / updated_at to tell "process alive" from "loop frozen".+ # See #66892.+ self._gateway_started_at: float = time.time()+ self._loop_heartbeat_task: Optional[asyncio.Task] = None+ self._loop_floor_timer_handle = self._loop_liveness_watchdog = None+ # scale-to-zero: gateway-scoped "last inbound seen" clock, stamped in _handle_message (the single+ # inbound chokepoint) and seeded to "now" so a fresh gateway isn't idle from epoch.+ self._last_inbound_at: float = time.time()+ # Re-arm cooldown after a wake so we don't go dormant again before the drained backlog updates+ # the clock; and a one-shot latch so the "platform owns the suspend" notice logs once.+ self._scale_to_zero_cooldown_until: float = 0.0+ self._scale_to_zero_no_suspend_logged: bool = False+ self._scale_to_zero_direct_platform_logged: bool = Falsediff --cc gateway/run_turn_hygiene.pyindex 079ae807da5,00000000000..0f15161f952mode 100644,000000..100644--- a/gateway/run_turn_hygiene.py+++ b/gateway/run_turn_hygiene.py@@@ -1,827 -1,0 +1,833 @@@+"""Gateway turn hygiene phases; inherited by GatewayTurnMixin."""+from __future__ import annotations++import logging+from typing import TYPE_CHECKING+import asyncio+import dataclasses+import inspect+import json+import os+import queue+import threading+import time+from agent.i18n import t+from agent.session_activity import format_iteration_progress+from contextlib import nullcontext, suppress+from contextvars import copy_context+from gateway.config import Platform+from gateway.media_repair import repair_explicit_computer_use_media_paths+from gateway.platforms.base import BasePlatformAdapter+from gateway.platforms.event import MessageEvent+from gateway.session import (+ SessionSource, _session_key_namespace, build_channel_continuity_note,+ build_session_context,+)+from gateway.session_transcript import TranscriptReadError+from gateway.turn_context import TurnContext+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError+from hermes_constants import get_hermes_home_override+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Tuple+from utils import base_url_hostname++if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)+ from gateway.run import GatewayRunner # noqa: F401+ from gateway.run_turn_runner import TurnRunner # noqa: F401++# Log-record parity with the origin module.+logger = logging.getLogger("gateway.run")+++class GatewayTurnHygieneMixin:+ @dataclasses.dataclass+ class _HygienePlan:+ """Hygiene pre-check outcome for one turn."""++ needs_compress: bool+ approx_tokens: int+ msg_count: int+ warn_token_threshold: int++ @staticmethod+ def _hmwa_hygiene_read_config(hs, data):+ """Apply model / compression knobs from the gateway config onto ``hs`` (invalid values keep the defaults)."""+ # Resolve model name (same logic as run_sync)+ _model_cfg = data.get("model", {})+ if isinstance(_model_cfg, str):+ hs.model = _model_cfg+ elif isinstance(_model_cfg, dict):+ hs.model = _model_cfg.get("default") or _model_cfg.get("model") or hs.model+ _raw_ctx = _model_cfg.get("context_length")+ if _raw_ctx is not None:+ with suppress(TypeError, ValueError):+ hs.config_context_length = int(_raw_ctx)+ hs.provider = _model_cfg.get("provider") or None+ hs.base_url = _model_cfg.get("base_url") or None++ # Only the enabled flag is shared with the agent's compression config (hygiene runs higher).+ _comp_cfg = data.get("compression", {})+ if not isinstance(_comp_cfg, dict):+ return+ hs.compression_enabled = str(_comp_cfg.get("enabled", True)).lower() in {"true", "1", "yes"}++ def _knob(key, current, cast, allow_zero=False):+ raw = _comp_cfg.get(key)+ if raw is None:+ return current+ try:+ parsed = cast(raw)+ except (TypeError, ValueError):+ return current+ return parsed if (parsed >= 0 if allow_zero else parsed > 0) else current++ hs.hard_msg_limit = _knob("hygiene_hard_message_limit", hs.hard_msg_limit, int)+ hs.timeout_seconds = _knob("hygiene_timeout_seconds", hs.timeout_seconds, float)+ hs.total_ceiling_seconds = _knob("hygiene_total_ceiling_seconds", hs.total_ceiling_seconds, float)+ # The ceiling can never be tighter than one idle window, or the extension loop would be dead code.+ hs.total_ceiling_seconds = max(hs.total_ceiling_seconds, hs.timeout_seconds)+ hs.max_turn_hold_seconds = _knob("hygiene_max_turn_hold_seconds", hs.max_turn_hold_seconds, float)+ hs.failure_cooldown_seconds = _knob(+ "hygiene_failure_cooldown_seconds", hs.failure_cooldown_seconds, float, allow_zero=True,+ )++ async def _hmwa_hygiene_settings(self, source, session_key):+ """Resolve model/provider/context-length + hygiene knobs (fail-soft: errors keep defaults).++ The 0.85 threshold is deliberately HIGHER than the agent's compressor (0.50): a safety net+ for sessions that grew between turns. ``max_turn_hold_seconds`` bounds the TURN wait+ (compressor keeps running detached, commit fenced); kept below transport idle-timeouts."""+ from gateway.run import _load_gateway_config+ hs = self._HygieneSettings(+ model="anthropic/claude-sonnet-4.6", threshold_pct=0.85, compression_enabled=True,+ hard_msg_limit=5000, timeout_seconds=30.0, total_ceiling_seconds=600.0,+ max_turn_hold_seconds=10.0, failure_cooldown_seconds=300.0, config_context_length=None,+ provider=None, base_url=None, api_key=None, data={},+ )+ try:+ hs.data = _load_gateway_config()+ if hs.data:+ self._hmwa_hygiene_read_config(hs, hs.data)+ configured_model, configured_provider, configured_base_url = hs.model, hs.provider, hs.base_url++ with suppress(Exception):+ hs.model, _hyg_runtime = self._resolve_session_agent_runtime(+ source=source, session_key=session_key,+ user_config=hs.data if isinstance(hs.data, dict) else None,+ )+ hs.provider = _hyg_runtime.get("provider") or hs.provider+ hs.base_url = _hyg_runtime.get("base_url") or hs.base_url+ hs.api_key = _hyg_runtime.get("api_key") or hs.api_key++ if hs.config_context_length is not None:+ try:+ from hermes_cli.route_identity import should_clear_context_pin_async++ if await should_clear_context_pin_async(+ configured_model, hs.model, configured_base_url, hs.base_url,+ configured_provider, hs.provider,+ ):+ hs.config_context_length = None+ except Exception:+ hs.config_context_length = None++ # custom_providers per-model context_length fallback (as in run_agent.py); needs base_url.+ if hs.config_context_length is None and hs.base_url:+ with suppress(TypeError, ValueError):+ try:+ from hermes_cli.config import (+ get_compatible_custom_providers as _gw_gcp,+ get_custom_provider_context_length as _gw_gccl,+ )+ _hyg_custom_providers = _gw_gcp(hs.data)+ except Exception:+ _hyg_custom_providers = hs.data.get("custom_providers")+ if not isinstance(_hyg_custom_providers, list):+ _hyg_custom_providers = []+ _hyg_custom_ctx = _gw_gccl(+ model=hs.model, base_url=hs.base_url, custom_providers=_hyg_custom_providers,+ )+ if _hyg_custom_ctx:+ hs.config_context_length = int(_hyg_custom_ctx)+ except Exception:+ pass+ return hs++ async def _hmwa_hygiene_plan(self, hs, history, session_entry, session_key):+ """Decide whether hygiene compression fires this turn (token/message thresholds, DB-backed+ failure cooldown, in-flight compression)."""+ from agent.model_metadata import estimate_messages_tokens_rough, get_model_context_length_async+ _hyg_context_length = await get_model_context_length_async(+ hs.model, base_url=hs.base_url or "", api_key=hs.api_key or "",+ config_context_length=hs.config_context_length, provider=hs.provider or "",+ )+ _compress_token_threshold = int(_hyg_context_length * hs.threshold_pct)+ _warn_token_threshold = int(_hyg_context_length * 0.95)+ _msg_count = len(history)++ # Real usage decides: the API-reported prompt count, else the anchor persisted on the session+ # row (real count + delta of what was appended since, survives gateway restarts), else the+ # rough estimate (runs 30-50% high, which only fires hygiene early — safe). Do NOT compensate+ # with a threshold multiplier.+ from agent.image_token_cost import image_cost_context, learned_image_token_cost+ _anchored = None+ # Images in any local delta/estimate are priced at the cost learned from this model's usage.+ with image_cost_context(learned_image_token_cost(hs.model, hs.base_url)):+ if session_entry.last_prompt_tokens <= 0:+ from agent.usage_anchor import persisted_anchor_tokens+ _session_db = getattr(self, "_session_db", None)+ _anchored = persisted_anchor_tokens(+ getattr(_session_db, "_db", _session_db), session_entry.session_id, history,+ )+ if session_entry.last_prompt_tokens > 0:+ _approx_tokens, _token_source = session_entry.last_prompt_tokens, "actual"+ elif _anchored is not None:+ _approx_tokens, _token_source = _anchored, "anchored"+ else:+ _approx_tokens, _token_source = estimate_messages_tokens_rough(history), "estimated"++ # Hard safety valve: force compression at an extreme message count regardless of tokens,+ # breaking the disconnect → no token data → no compression spiral. 5000 clears 1M+ sessions.+ _needs_compress = _approx_tokens >= _compress_token_threshold or _msg_count >= hs.hard_msg_limit++ if _needs_compress:+ # DB-backed cooldown (shared with context_compressor.py): survives gateway restarts, so a+ # failing compression is not re-triggered on every restart.+ # The in-memory dict was reset on every restart, re-triggering the same failing compression and+ # wedging session storage (#74136).+ _session_db = getattr(self, "_session_db", None)+ _getter = getattr(getattr(_session_db, "_db", _session_db), "get_compression_failure_cooldown", None)+ if _getter is not None:+ _cooldown_state = None+ with suppress(Exception):+ _cooldown_state = _getter(session_entry.session_id)+ if _cooldown_state and _cooldown_state.get("remaining_seconds", 0) > 0:+ logger.info(+ "Session hygiene: skipping compression for %s; "+ "previous failure cooldown active for %.1fs",+ session_entry.session_id, _cooldown_state["remaining_seconds"],+ )+ _needs_compress = False++ if _needs_compress and await self._session_has_compression_in_flight(session_key):+ # A prior compression still holds the durable lock (e.g. a shielded worker left by /stop):+ # another attempt would wait up to 600s behind a commit the fence will refuse.+ logger.info(+ "Session hygiene: skipping compression for %s; "+ "another compression is already in flight", session_entry.session_id,+ )+ _needs_compress = False++ if _needs_compress:+ logger.info(+ "Session hygiene: %s messages, ~%s tokens (%s) — auto-compressing "+ "(threshold: %s%% of %s = %s tokens)",+ _msg_count, f"{_approx_tokens:,}", _token_source,+ int(hs.threshold_pct * 100), f"{_hyg_context_length:,}", f"{_compress_token_threshold:,}",+ )+ return self._HygienePlan(_needs_compress, _approx_tokens, _msg_count, _warn_token_threshold)++ async def _hmwa_hygiene_wait_for_summary(self, attempt, hs, session_entry):+ """Progress-aware inline wait for the detached hygiene compressor. Returns the compressed+ transcript; raises ``HygieneTurnHoldExceeded`` (turn-hold budget) or+ ``asyncio.TimeoutError`` (idle/ceiling/fence cancel) for the caller's handlers.++ Idle timeout (fence ticks per streamed token) + hard ceiling + turn-hold cap."""+ from gateway.run import HygieneTurnHoldExceeded, hygiene_wait_should_extend+ fence = attempt.commit_fence+ while True:+ if fence.is_cancelled:+ raise asyncio.TimeoutError+ # Charge the idle budget from the LAST PROGRESS event, else silence can approach 2x timeout.+ _hyg_waited = time.monotonic() - attempt.wait_started+ _slice = min(+ max(hs.timeout_seconds - fence.seconds_since_progress(), 0.005),+ max(hs.total_ceiling_seconds - _hyg_waited, 0.005),+ )+ # Cap the slice at the remaining turn-hold budget so a continuously-streaming worker can't+ # hold the turn until the ceiling. Budget exhausted → immediate timeout → abandonment.+ _turn_hold_remaining = hs.max_turn_hold_seconds - (time.monotonic() - attempt.wait_started)+ _slice = 0.005 if _turn_hold_remaining <= 0 else min(_slice, max(_turn_hold_remaining, 0.005))+ # Short poll so a /stop or /restart cancel is not stuck behind a full idle window.+ _idle_left = max(hs.timeout_seconds - fence.seconds_since_progress(), 0.005)+ _slice = min(_slice, 0.25)+ try:+ _compressed, _ = await asyncio.wait_for(asyncio.shield(attempt.future), timeout=_slice)+ return _compressed+ except asyncio.TimeoutError:+ if fence.is_cancelled:+ raise+ _hyg_waited = time.monotonic() - attempt.wait_started+ _idle = fence.seconds_since_progress()+ # Never hold the TURN past the budget even while the summary streams: proceed on the+ # uncompressed transcript so the wire never trips a transport idle-timeout.+ if _hyg_waited >= hs.max_turn_hold_seconds:+ logger.info(+ "Session hygiene compression for session %s exceeded the turn-hold "+ "budget (%.1fs >= %.1fs) — abandoning inline wait, proceeding "+ "without compression this turn",+ session_entry.session_id, _hyg_waited, hs.max_turn_hold_seconds,+ )+ raise HygieneTurnHoldExceeded(+ f"turn-hold budget {hs.max_turn_hold_seconds:.1f}s "+ f"elapsed after {_hyg_waited:.1f}s"+ )+ if hygiene_wait_should_extend(+ idle=_idle, timeout=hs.timeout_seconds, waited=_hyg_waited,+ ceiling=hs.total_ceiling_seconds, fence_cancelled=fence.is_cancelled,+ ):+ if _slice >= _idle_left - 1e-9:+ logger.info(+ "Session hygiene compression for session %s still streaming after "+ "%.0fs (last progress %.1fs ago) — extending wait (ceiling %.0fs)",+ session_entry.session_id, _hyg_waited, _idle, hs.total_ceiling_seconds,+ )+ continue+ raise++ async def _hmwa_hygiene_cancel_or_adopt(self, attempt, context):+ """Cancel the worker at the commit fence; on success release its lease and defer agent+ cleanup, returning ``None``. When the worker already crossed into its commit, consume and+ return the compressed transcript instead (a successful compaction is never a timeout; the+ turn may be held past the budget by up to the commit duration — by design). The lock-free+ ``commit_in_flight`` marker keeps the poll from spinning on a hung commit."""+ fence = attempt.commit_fence+ while not fence.commit_in_flight:+ cancelled = fence.try_cancel_before_commit()+ if cancelled is None:+ await asyncio.sleep(0.025)+ elif cancelled:+ fence.release_cancelled_compression_lock()+ self._hmwa_hygiene_defer_cleanup(attempt, context)+ return None+ else:+ break+ _compressed, _ = await attempt.future+ return _compressed++ def _hmwa_hygiene_defer_cleanup(self, attempt, context):+ """Hand the agent's cleanup to the still-running worker future and mark it deferred."""+ self._defer_agent_cleanup_until_future_done(attempt.future, attempt.agent, context=context)+ attempt.cleanup_deferred = True++ @staticmethod+ def _hmwa_hygiene_stamp(agent, desc, provenance_name, debug_label):+ from agent.session_activity import ActivityProvenance+ from gateway.run import _stamp_hygiene_compression_provenance+ _stamp_hygiene_compression_provenance(agent, desc, getattr(ActivityProvenance, provenance_name), debug_label)++ async def _hmwa_hygiene_notify(self, source, meta, message, what):+ """Best-effort user notice on the hygiene thread; failure is logged, never raised."""+ try:+ _adapter = self._delivery_adapter_for(source)+ if _adapter and source.chat_id:+ await _adapter.emit_warning(source.chat_id, message, metadata=meta,+ logical_platform=source.platform)+ except Exception as _werr:+ logger.warning("Failed to deliver %s to user: %s", what, _werr)++ async def _hmwa_hygiene_record_failure_cooldown(self, hs, session_key, session_id, reason):+ """Escalate the failure streak (off-loop) and persist the cooldown, when enabled."""+ from gateway.run import _hygiene_cooldown_for_failure, _record_hygiene_cooldown+ if hs.failure_cooldown_seconds < 0:+ return+ _hyg_cooldown = await asyncio.to_thread(+ _hygiene_cooldown_for_failure, self, session_key, hs.failure_cooldown_seconds,+ )+ _record_hygiene_cooldown(self, session_id, _hyg_cooldown, reason)++ async def _hmwa_hygiene_on_turn_hold(self, attempt, hs, session_entry, session_key, source):+ """``except HygieneTurnHoldExceeded`` body: keep or cancel the worker's commit admission,+ notify the user, and re-raise; returns the compressed transcript only when the worker+ was already committing.++ Turn-hold expiry is an availability boundary, not a failure: the streak must NOT advance,+ only flat retry spacing is recorded. A watermark-fenced commit (rows appended after+ compression start survive as cloned tail) KEEPS admission: the turn proceeds uncompressed+ now and the summary is adopted at the worker's fenced commit — always cancelling burned+ every attempt for thinking summary models. Without the fence a late commit could clobber+ newer turns, so cancel."""+ from gateway.run import (+ _HYGIENE_TURNHOLD_RETRY_SECONDS, _record_hygiene_cooldown, _reset_hygiene_failure_streak+ )+ fence = attempt.commit_fence+ _hyg_keep_admission = bool(getattr(fence, "commit_watermark_fenced", False)) and not fence.is_cancelled+ if _hyg_keep_admission:+ self._hmwa_hygiene_defer_cleanup(attempt, "session hygiene turn-hold")+ # NO retry-after here (it would also block the agent-side preflight compressor); spacing+ # comes from the durable compression lock. The done-callback records the flat retry-after+ # ONLY if the worker ends without committing anything.+ _sid, _skey, _agent = session_entry.session_id, session_key, attempt.agent++ def _hyg_adopt_or_space_retry(_fut, _gw=self, _sid=_sid, _skey=_skey, _agent=_agent):+ try:+ _exc = _fut.exception()+ except (asyncio.CancelledError, Exception):+ _committed = False+ else:+ _committed = _exc is None and (+ bool(getattr(_agent, "_last_compaction_in_place", False))+ or getattr(_agent, "session_id", _sid) != _sid+ )+ if _committed:+ logger.info(+ "Session hygiene compression for session %s finished after the "+ "turn-hold was released — summary adopted at the watermark-fenced "+ "commit boundary (#97963)", _sid,+ )+ try:+ _reset_hygiene_failure_streak(_gw, _skey)+ except Exception as _rs_err:+ logger.debug("hygiene streak reset after deferred adoption failed: %s", _rs_err)+ else:+ # Nothing to adopt (summary failed / fence refused / superseded): flat spacing so+ # sustained traffic doesn't spawn and abandon a compressor every turn.+ _record_hygiene_cooldown(+ _gw, _sid, _HYGIENE_TURNHOLD_RETRY_SECONDS,+ "hygiene compression deferred: turn-hold budget expired and the "+ "detached attempt did not commit",+ )++ attempt.future.add_done_callback(_hyg_adopt_or_space_retry)+ _log_suffix = (+ " — the watermark-fenced worker keeps its commit admission and the summary "+ "will be adopted when it finishes"+ )+ else:+ _adopted = await self._hmwa_hygiene_cancel_or_adopt(attempt, "session hygiene turn-hold")+ if _adopted is not None:+ return _adopted+ # Short flat retry-after, else every turn re-spawns, holds and cancels a compressor.+ _record_hygiene_cooldown(+ self, session_entry.session_id, _HYGIENE_TURNHOLD_RETRY_SECONDS,+ "hygiene compression deferred: turn-hold budget expired while the "+ "summary was still streaming",+ )+ _log_suffix = ""+ self._hmwa_hygiene_stamp(+ attempt.agent, "session hygiene compression turn-hold",+ "AGENT_COMPRESSION_TURNHOLD", "hygiene compression turn-hold activity stamp failed",+ )+ logger.info(+ "Session hygiene compression for session %s exceeded turn-hold budget (%.1fs); "+ "proceeding without compression this turn%s",+ session_entry.session_id, time.monotonic() - attempt.wait_started, _log_suffix,+ )+ await self._hmwa_hygiene_notify(+ source, attempt.meta, t("gateway.compress.turnhold_deferred"), "compression-turnhold notice",+ )+ raise++ async def _hmwa_hygiene_on_timeout(self, attempt, hs, session_entry, session_key, source):+ """``except asyncio.TimeoutError`` body: cancel at the commit fence, record the failure+ cooldown, warn the user, and re-raise; returns the compressed transcript only when the+ worker crossed the commit boundary first."""+ from gateway.run import _hygiene_compression_timeout_message+ fence = attempt.commit_fence+ _hyg_waited = time.monotonic() - attempt.wait_started+ _hyg_total_exhausted = _hyg_waited >= hs.total_ceiling_seconds or fence.deadline_exceeded+ if _hyg_total_exhausted:+ # The worker checks this deadline between digest calls; keep its lease until it exits so+ # an unchanged session cannot overlap a retry (the release below is then a no-op).+ fence.retain_compression_lock_until_worker_done()+ # Capture fence state BEFORE try_cancel (which itself sets is_cancelled).+ _hyg_fence_cancelled = fence.is_cancelled+ _adopted = await self._hmwa_hygiene_cancel_or_adopt(attempt, "session hygiene timeout")+ if _adopted is not None:+ return _adopted+ await self._hmwa_hygiene_record_failure_cooldown(+ hs, session_key, session_entry.session_id,+ "session hygiene compression " + (+ "cancelled at commit fence" if _hyg_fence_cancelled+ else "total ceiling exhausted" if _hyg_total_exhausted+ else "timed out with no output from the summary model"+ ),+ )+ self._hmwa_hygiene_stamp(+ attempt.agent,+ "session hygiene compression cancelled at commit fence" if _hyg_fence_cancelled+ else "session hygiene compression timed out",+ "AGENT_COMPRESSION_TIMEOUT", "hygiene compression timeout activity stamp failed",+ )+ if _hyg_fence_cancelled:+ logger.warning(+ "Session hygiene compression for session %s was cancelled at the "+ "commit fence; continuing without compression", session_entry.session_id,+ )+ raise+ _hyg_elapsed = time.monotonic() - attempt.wait_started+ if _hyg_total_exhausted:+ logger.warning(+ "Session hygiene compression for session %s reached its total ceiling after "+ "%.1fs (progress observed=%s); continuing without compression",+ session_entry.session_id, _hyg_elapsed, fence.progress_observed,+ )+ else:+ logger.warning(+ "Session hygiene compression for session %s made no progress for %.1fs "+ "(total wait %.1fs, ceiling %.1fs); continuing without compression",+ session_entry.session_id, fence.seconds_since_progress(), _hyg_elapsed, hs.total_ceiling_seconds,+ )+ await self._hmwa_hygiene_notify(+ source, attempt.meta,+ _hygiene_compression_timeout_message(+ total_exhausted=_hyg_total_exhausted, elapsed=_hyg_elapsed,+ idle_timeout=hs.timeout_seconds, progress_observed=fence.progress_observed,+ ),+ "compression-timeout warning",+ )+ raise++ def _hmwa_hygiene_on_unwind(self, attempt, hs, session_entry, session_key):+ """``except BaseException`` body (caller re-raises): revoke commit admission BEFORE the host+ unwinds so the detached worker can never commit later, and record a cooldown — otherwise+ the next turn re-arms hygiene and waits up to 600s behind a fence that refuses again."""+ from gateway.run import _hygiene_cooldown_for_failure, _record_hygiene_cooldown+ attempt.commit_fence.revoke_commit_admission()+ if not attempt.cleanup_deferred:+ self._hmwa_hygiene_defer_cleanup(attempt, "session hygiene unwind")+ if hs.failure_cooldown_seconds >= 0:+ try:+ _record_hygiene_cooldown(+ self, session_entry.session_id,+ _hygiene_cooldown_for_failure(self, session_key, hs.failure_cooldown_seconds),+ "session hygiene compression cancelled at commit fence",+ )+ except Exception as _cd_err:+ logger.debug("hygiene unwind cooldown record failed: %s", _cd_err)++ async def _hmwa_hygiene_adopt_transcript(+ self, attempt, _compressed, history, plan, *, session_entry, source, _quick_key, run_generation,+ ):+ """Adopt a finished compression (rotation / in-place / refused); publishes the transcript to+ continue with on ``attempt.history``. Returns ``(rotated, in_place, new_count, new_tokens)``.++ Rewrite only on rotation (NEW session id): in-place compaction already soft-archived the+ old rows and rewrite_transcript() would DELETE them; neither rotation nor in-place signals+ FAILURE and an unconditional rewrite would leave only the summary. Write-before-repoint:+ a repoint-then-failed-rewrite would point the live entry at an empty session."""+ from gateway.run_turn import hygiene_no_commit_reason+ from agent.model_metadata import estimate_messages_tokens_rough+ _hyg_agent = attempt.agent+ # _compress_context rotates to a NEW session_id so the old transcript stays intact/searchable.+ _hyg_new_sid = _hyg_agent.session_id+ _hyg_rotated = _hyg_new_sid != session_entry.session_id+ _hyg_in_place = bool(getattr(_hyg_agent, "_last_compaction_in_place", False))+ # Anti-growth guard: refuse a compression that did not shrink the transcript (seen 427K→598K).+ _hyg_in_toks = estimate_messages_tokens_rough(history)+ _hyg_out_toks = estimate_messages_tokens_rough(_compressed)+ if _hyg_rotated and _hyg_out_toks > _hyg_in_toks:+ logger.warning(+ "Gateway hygiene compression for session %s would grow transcript (~%s -> ~%s "+ "tokens); keeping the original transcript unchanged",+ session_entry.session_id, f"{_hyg_in_toks:,}", f"{_hyg_out_toks:,}",+ )+ _hyg_rotated = False+ _compressed = history+ # Only rewrite the transcript when rotation produced a NEW session id. In-place compaction does NOT+ # need a rewrite: archive_and_compact() has already soft-archived the previous active rows and+ # inserted the compacted messages as the new active set inside _compress_context(). Calling+ # rewrite_transcript() after in-place compaction would invoke replace_messages(active_only=False)+ # which DELETEs ALL rows — including the archived turns that archive_and_compact() deliberately+ # preserved (silent data loss, #61145). The danger this guards against (mirrors the /compress fix+ # #44794/#39704): if _compress_context returns a summary but neither rotates nor completes+ # archive_and_compact(), the session_id is unchanged for a FAILURE reason, and an unconditional+ # rewrite_transcript() would DELETE the original messages and replace them with only the compressed+ # summary (permanent data loss, #21301). Write-before-repoint (mirrors manual /compress): if we+ # repointed session_entry onto the child SID and rewrite_transcript then failed (lock/ENOSPC), the+ # live entry would already reference a brand-new empty session while the turn continues — the+ # conversation silently vanishes. Persist the child transcript first; only then rebind the live+ # entry.+ if _hyg_rotated:+ if not await self.async_session_store.rewrite_transcript(_hyg_new_sid, _compressed):+ logger.error(+ "Session hygiene: failed to persist compressed transcript for rotated session "+ "%s → %s; keeping the live entry on the original session so the "+ "conversation is not dropped", session_entry.session_id, _hyg_new_sid,+ )+ # Fail closed: treat like no rotation.+ _hyg_rotated = False+ _hyg_in_place = False+ else:+ session_entry.session_id = _hyg_new_sid+ # The held turn lease follows the rotation (alias keys still serialize on this turn).+ self._rebind_turn_lease(_quick_key, run_generation, _hyg_new_sid)+ await self.async_session_store._save()+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="hygiene-compression",+ )++ if _hyg_rotated or _hyg_in_place:+ # Rewritten (rotation) or persisted by archive_and_compact() (in-place): reset token count.+ session_entry.last_prompt_tokens = 0+ attempt.history = _compressed+ _new_count = len(_compressed)+ _new_tokens = estimate_messages_tokens_rough(_compressed)+ else:+ # No rewrite happened — post-compression counts equal the pre-compression ones.+ _new_count = plan.msg_count+ _new_tokens = plan.approx_tokens+ logger.warning(+ "Gateway hygiene compression for session %s did not rotate or compact in place (%s) — "+ "preserving the original transcript instead of overwriting it with the summary (#21301).",+ session_entry.session_id, hygiene_no_commit_reason(_hyg_agent),+ )++ logger.info(+ "Session hygiene: compressed %s → %s msgs, ~%s → ~%s tokens",+ plan.msg_count, _new_count, f"{plan.approx_tokens:,}", f"{_new_tokens:,}",+ )+ if _new_tokens >= plan.warn_token_threshold:+ logger.warning("Session hygiene: still ~%s tokens after compression", f"{_new_tokens:,}")+ return _hyg_rotated, _hyg_in_place, _new_count, _new_tokens++ async def _hmwa_hygiene_apply_result(+ self, attempt, hs, _compressed, history, plan, *,+ session_entry, session_key, source, _quick_key, run_generation,+ ):+ """Adopt a finished hygiene compression, rebind the session + turn lease, record+ streak/cooldown, and warn the user on abort."""+ from gateway.run import _reset_hygiene_failure_streak, hygiene_compaction_recovered+ _hyg_rotated, _hyg_in_place, _new_count, _new_tokens = await self._hmwa_hygiene_adopt_transcript(+ attempt, _compressed, history, plan, session_entry=session_entry, source=source,+ _quick_key=_quick_key, run_generation=run_generation,+ )+ # Summary failure aborts the compressor (nothing dropped). Warn the user visibly — agent.log+ # is invisible on TG/Discord — so they know the chat is "frozen" and can /compress or /reset.+ _comp = getattr(attempt.agent, "context_compressor", None)+ _hyg_aborted = _comp is not None and getattr(_comp, "_last_compress_aborted", False)+ # A fence-cancelled _compress_context returns the original transcript with+ # _last_compress_aborted False: treat that no-op as an abort so hygiene records a cooldown+ # instead of retrying into the 600s wait. A committed rotate/in-place is never an abort.+ _hyg_fence_cancelled = bool(attempt.commit_fence.is_cancelled and not _hyg_rotated and not _hyg_in_place)+ if _hyg_fence_cancelled:+ _hyg_aborted = True+ # Recovery decision lives in the unit-tested predicate: the "neither rotated nor in place"+ # path reuses pre-compression counts, so a numbers-only check would read a no-op as success.+ if not _hyg_aborted and hygiene_compaction_recovered(+ aborted=_hyg_aborted, rotated=_hyg_rotated, in_place=_hyg_in_place,+ msg_count=plan.msg_count, new_count=_new_count, approx_tokens=plan.approx_tokens,+ new_tokens=_new_tokens,+ ):+ await asyncio.to_thread(_reset_hygiene_failure_streak, self, session_key)+ if _hyg_aborted:+ await self._hmwa_hygiene_record_failure_cooldown(+ hs, session_key, session_entry.session_id,+ "session hygiene compression cancelled at commit fence" if _hyg_fence_cancelled+ else getattr(_comp, "_last_summary_error", None),+ )+ self._hmwa_hygiene_stamp(+ attempt.agent, "session hygiene compression aborted",+ "AGENT_COMPRESSION_COOLDOWN", "hygiene compression abort activity stamp failed",+ )+ if not _hyg_fence_cancelled:+ # Force-redact: provider exception text may contain credentials; this reaches users.+ from agent.redact import redact_sensitive_text+ _err = redact_sensitive_text(getattr(_comp, "_last_summary_error", None) or "unknown error", force=True)+ logger.warning("Session hygiene compression aborted: %s", _err)+ await self._hmwa_hygiene_notify(+ source, attempt.meta,+ "⚠️ Shortening the conversation history failed, so I kept everything as-is. "+ "Run /compress to try again or /new to start fresh. If this keeps happening, "+ "run `hermes doctor` on the host.",+ "compression-failure warning",+ )+ # Configured aux model failed, recovered on the main model: only the user can fix that config.+ elif _comp is not None and getattr(_comp, "_last_aux_model_failure_model", None):+ _aux_model = getattr(_comp, "_last_aux_model_failure_model", "")+ _aux_err = getattr(_comp, "_last_aux_model_failure_error", None) or "unknown error"+ await self._hmwa_hygiene_notify(+ source, attempt.meta, f"ℹ️ Configured compression model `{_aux_model}` "+ f"failed ({_aux_err}). Recovered using your main "+ "model — context is intact — but you may want to "+ "check `auxiliary.compression.model` in config.yaml.",+ "aux-model-fallback notice",+ )++ async def _hmwa_hygiene_codex_compaction(self, hs, plan, history, session_entry, session_key, _hyg_runtime):+ """codex app-server runtime: the real context is the server-side thread, not the transcript+ mirror. The detached-agent path would only rewrite the mirror and its finally-eviction+ would destroy the live thread (next turn starts blank), so use the cached agent's+ thread/compact/start and KEEP it cached."""+ from gateway.run import run_codex_hygiene_compaction+ # codex app-server runtime: the model's real context is the app-server's server-side thread, not the+ # transcript mirror. See #73503.+ _hyg_codex_auto = "native"+ _hyg_comp_cfg = hs.data.get("compression") if isinstance(hs.data, dict) else None+ if isinstance(_hyg_comp_cfg, dict):+ _hyg_codex_auto = str(_hyg_comp_cfg.get("codex_app_server_auto", "native") or "native")+ _hyg_codex_outcome = await run_codex_hygiene_compaction(+ self, session_key, session_entry.session_id, auto_mode=_hyg_codex_auto, history=history,+ approx_tokens=plan.approx_tokens, timeout_seconds=hs.total_ceiling_seconds,+ failure_cooldown_seconds=hs.failure_cooldown_seconds,+ )+ logger.info(+ "Session hygiene (codex app-server): %s (session=%s, mode=%s, ~%s tokens)",+ _hyg_codex_outcome, session_entry.session_id, _hyg_codex_auto, f"{plan.approx_tokens:,}",+ )++ async def _hmwa_hygiene_build_agent(self, _hyg_model, _hyg_runtime, session_entry):+ """Build the detached hygiene ``AIAgent`` with the live session's system prompt. Returns+ ``(agent, sync_session_db)``."""+ from gateway.run import _GATEWAY_HYGIENE_PLATFORM, _seed_hygiene_system_prompt+ from run_agent import AIAgent+ try:+ _hyg_session_row = await self._session_db.get_session(session_entry.session_id)+ except Exception as exc:+ _hyg_session_row = None+ logger.warning(+ "Session hygiene could not restore the system prompt for session %s: %s. "+ "Preserving an empty prompt so the live turn rebuilds it with its "+ "configured providers.", session_entry.session_id, exc, exc_info=True,+ )+ _hyg_session_db = getattr(self._session_db, "_db", self._session_db)+ # With compression.checkpoint_required on, load the memory provider so the checkpoint exists+ # before any mutation; otherwise keep the fast path (no provider init).+ from hermes_cli.config import load_config as _load_cfg+ from utils import is_truthy_value as _is_truthy++ _hyg_checkpoint_required = _is_truthy(+ ((_load_cfg() or {}).get("compression") or {}).get("checkpoint_required"), default=False,+ )+ _hyg_agent = AIAgent(+ **_hyg_runtime, model=_hyg_model, max_iterations=4, quiet_mode=True,+ skip_memory=not _hyg_checkpoint_required, enabled_toolsets=["memory"],+ session_id=session_entry.session_id, session_db=_hyg_session_db,+ )+ _seed_hygiene_system_prompt(_hyg_agent, _hyg_session_row)- # A rebuilt (not retained) prompt is deliberately stale for every real gateway surface.++ # The stamp only marks this agent as no real surface. Since #104414 Platform is not a++ # restore-identity field, so it no longer forces the next live turn to rebuild; the seed's++ # retain flag is what keeps the reduced-toolset build out of the session row (#122822).+ _hyg_agent.platform = _GATEWAY_HYGIENE_PLATFORM+ return _hyg_agent, _hyg_session_db++ async def _hmwa_hygiene_detached_attempt(+ self, attempt, hs, plan, history, _hyg_msgs, _hyg_model, _hyg_runtime,+ source, session_entry, session_key, _quick_key, run_generation,+ ):+ """Run one detached hygiene compression attempt end to end; publishes the transcript to+ continue with (compressed or original) on ``attempt.history``."""+ from gateway.run import HygieneTurnHoldExceeded+ from agent.conversation_compression import CompressionCommitFence+ _hyg_agent, _hyg_session_db = await self._hmwa_hygiene_build_agent(_hyg_model, _hyg_runtime, session_entry)+ attempt.agent = _hyg_agent+ try:+ # Hygiene owns the session binding, so prefer in-place compaction over minting a+ # continuation child. Without a SessionDB this stays False.+ _hyg_agent.compression_in_place = True+ _bind_hyg_state = getattr(getattr(_hyg_agent, "context_compressor", None), "bind_session_state", None)+ if callable(_bind_hyg_state):+ _bind_hyg_state(_hyg_session_db, session_entry.session_id)+ # Never finalize on close() — that would end the live gateway session row.+ _hyg_agent._end_session_on_close = False+ _hyg_agent._print_fn = lambda *a, **kw: None++ loop = asyncio.get_running_loop()+ _hyg_commit_fence = CompressionCommitFence(total_ceiling_seconds=hs.total_ceiling_seconds)+ # Default executor (NOT self._get_executor): a hung summary must never occupy an+ # agent-work slot. MUST run in the caller's contextvars (multiplex secret scope).+ attempt.commit_fence = _hyg_commit_fence+ attempt.future = loop.run_in_executor(+ None,+ # But it MUST run inside the caller's contextvars: under multiplex_profiles the profile+ # secret scope / HERMES_HOME override live in ContextVars, and a bare run_in_executor worker+ # starts with an empty Context — the summary model's get_secret(<PROVIDER>_API_KEY) then+ # fails closed (UnscopedSecretError) and every hygiene compaction silently degrades to a+ # lossy truncation (#100849 bundle).+ copy_context().run,+ # task_id = the live turn's dedup bucket (session row id), never "" (= reset every task).+ lambda: _hyg_agent._compress_context(+ _hyg_msgs, "", approx_tokens=plan.approx_tokens, commit_fence=_hyg_commit_fence,+ task_id=session_entry.session_id or "default",+ ),+ )++ # Register the live worker with shutdown NOW, not only once it is deferred: the default++ # executor is outside self._executor's quiesce, so an untracked in-flight summary would let++ # stop() close/checkpoint state.db under its late write (mirrors run_codex_hygiene_compaction).++ self._track_deferred_agent_worker(attempt.future, _hyg_agent)+ attempt.wait_started = time.monotonic()+ try:+ _compressed = await self._hmwa_hygiene_wait_for_summary(attempt, hs, session_entry)+ except HygieneTurnHoldExceeded:+ _compressed = await self._hmwa_hygiene_on_turn_hold(attempt, hs, session_entry, session_key, source)+ except asyncio.TimeoutError:+ _compressed = await self._hmwa_hygiene_on_timeout(attempt, hs, session_entry, session_key, source)+ except BaseException:+ self._hmwa_hygiene_on_unwind(attempt, hs, session_entry, session_key)+ raise++ await self._hmwa_hygiene_apply_result(+ attempt, hs, _compressed, history, plan, session_entry=session_entry,+ session_key=session_key, source=source, _quick_key=_quick_key,+ run_generation=run_generation,+ )+ finally:+ # Evict the cached agent so the next turn rebuilds its system prompt.+ self._evict_cached_agent(session_key)+ if not attempt.cleanup_deferred:+ await self._cleanup_agent_resources_off_loop(_hyg_agent, context="session hygiene")++ async def _hmwa_run_session_hygiene(+ self, event, source, session_entry, session_key, history, _quick_key, run_generation,+ ):+ """Auto-compress pathologically large transcripts before the agent starts so oversized+ histories don't cause repeated truncation/context failures. Token source: the API's+ prompt_tokens from the last turn, else a char/4 estimate."""+ from gateway.run import HygieneTurnHoldExceeded+ if not history or len(history) < 4:+ return history++ hs = await self._hmwa_hygiene_settings(source, session_key)+ # Hygiene can never land with compression disabled; a sub-limit transcript is the identity (#111988).+ if not hs.compression_enabled:+ return self._bound_hygiene_payload(history, hs, session_entry)+ plan = await self._hmwa_hygiene_plan(hs, history, session_entry, session_key)+ # No compression this turn (under both thresholds, cooldown, or one already in flight): without+ # the bound the model would get the full uncompressed transcript.+ if not plan.needs_compress:+ return self._bound_hygiene_payload(history, hs, session_entry)++ attempt = self._HygieneAttempt(agent=None, meta=self._event_thread_metadata(event, source), history=history)+ try:+ _hyg_model, _hyg_runtime = self._resolve_session_agent_runtime(+ source=source, session_key=session_key,+ user_config=hs.data if isinstance(hs.data, dict) else None,+ )+ if str(_hyg_runtime.get("api_mode") or "").lower() == "codex_app_server":+ await self._hmwa_hygiene_codex_compaction(hs, plan, history, session_entry, session_key, _hyg_runtime)+ elif _hyg_runtime.get("api_key"):+ # Pass the FULL transcript (tool results included) as the agent loop does: filtering+ # to user/assistant starved the compressor (tool results are the bulk of context).+ _hyg_msgs = [m for m in history if m.get("role") in {"user", "assistant", "tool"}]+ if len(_hyg_msgs) >= 4:+ await self._hmwa_hygiene_detached_attempt(+ attempt, hs, plan, history, _hyg_msgs, _hyg_model, _hyg_runtime,+ source, session_entry, session_key, _quick_key, run_generation,+ )+ except HygieneTurnHoldExceeded:+ # Availability boundary, not a failure — already logged at INFO by the turn-hold handler.+ # Must not hit the generic "auto-compress failed" warning below: that log is how thinking-model+ # deployments read as permanently broken (#97963; surfaced by @686f6c61 in PR #99657).+ pass+ except Exception as e:+ logger.warning("Session hygiene auto-compress failed: %s", e)+ # A landed compression published a NEW transcript on attempt.history: leave it byte-identical.+ # Anything else (turn-hold, timeout, unwind, codex path) left the FULL uncompressed transcript+ # there — that is the fail-closed case (#111988).+ if attempt.history is history:+ return self._bound_hygiene_payload(history, hs, session_entry)+ return attempt.history++ @staticmethod+ def _bound_hygiene_payload(history, hs, session_entry):+ """``bound_model_input_without_hygiene`` over ``hs.hard_msg_limit``, with one INFO line when the+ cut is real. Below the limit this is the identity — no allocation, no behaviour change."""+ from gateway.run_turn import bound_model_input_without_hygiene+ bounded = bound_model_input_without_hygiene(history, hs.hard_msg_limit)+ if bounded is not history:+ logger.info(+ "Session hygiene did not land for %s: bounding the model payload to %s of %s "+ "messages (hard limit %s) — the stored transcript is unchanged",+ session_entry.session_id, len(bounded), len(history), hs.hard_msg_limit,+ )+ return boundeddiff --cc gateway/run_turn_persistence.pyindex 82331aada74,00000000000..7ead8ff3608mode 100644,000000..100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@@ -1,575 -1,0 +1,583 @@@+"""Gateway turn persistence phases; inherited by GatewayTurnMixin."""+from __future__ import annotations++import logging+from typing import TYPE_CHECKING+import asyncio+import dataclasses+import inspect+import json+import os+import queue+import threading+import time+from agent.i18n import t+from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE+from agent.session_activity import format_iteration_progress+from contextlib import nullcontext, suppress+from contextvars import copy_context+from gateway.config import Platform+from gateway.media_repair import repair_explicit_computer_use_media_paths+from gateway.platforms.base import BasePlatformAdapter+from gateway.platforms.event import MessageEvent+from gateway.session import (+ SessionSource, _session_key_namespace, build_channel_continuity_note,+ build_session_context,+)+from gateway.session_transcript import TranscriptReadError+from gateway.turn_context import TurnContext+from gateway.warning_notifications import diagnostic_wake_muted+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError+from hermes_constants import get_hermes_home_override+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Tuple+from utils import base_url_hostname++if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)+ from gateway.run import GatewayRunner # noqa: F401+ from gateway.run_turn_runner import TurnRunner # noqa: F401++# Log-record parity with the origin module.+logger = logging.getLogger("gateway.run")+++class GatewayTurnPersistenceMixin:+ async def _hmwa_shape_agent_response(+ self, agent_result, source, history, session_entry, session_key,+ _quick_key, run_generation, _run_start_session_id, _platform_name, _msg_start_time,+ persist_user_display_kind: Optional[str] = None,++ reply_expected: Optional[bool] = None,+ ):+ """Turn the raw agent result into the outbound text: sentinel/silence handling, response+ logging, resume-pending clear, empty-response normalization, and identity-guarded+ post-compression session_id propagation. Returns+ ``(response, _intentional_silence, agent_messages)``."""+ from gateway.run import (+ _is_gateway_hidden_reasoning_incomplete_turn, _normalize_empty_agent_response,+ _sanitize_gateway_final_response, _should_clear_resume_pending_after_turn,+ )+ response = agent_result.get("final_response") or ""+ # Hidden-reasoning-only retry exhaustion: the loop's sentinel text doubles as final_response+ # and would be delivered verbatim (peer agents would ingest it as a completed turn).+ if _is_gateway_hidden_reasoning_incomplete_turn(agent_result):+ response = ""+ _intentional_silence = self._is_intentional_silence(agent_result, response)+ # A queued (/queue) chain's TERMINAL turn owns the silence verdict, not the event that- # opened the chain: an internal follow-up may go silent, a human one must not.- from gateway.response_filters import is_machinery_display_kind++ # opened the chain: an internal follow-up, or a message not addressed to the bot, may go++ # silent; any other human one must not.++ from gateway.response_filters import is_machinery_display_kind, silence_allowed+ from gateway.run_turn import _UNEXPECTED_SILENCE_REPLY+ _silence_kind = agent_result.get("queued_terminal_display_kind", persist_user_display_kind)- if _intentional_silence and not is_machinery_display_kind(_silence_kind):++ _silence_reply_expected = agent_result.get("queued_terminal_reply_expected", reply_expected)++ if _intentional_silence and not silence_allowed(_silence_kind, _silence_reply_expected):+ logger.warning(+ "silence marker rejected on a user turn: platform=%s chat=%s",+ _platform_name, source.chat_id or "unknown",+ )+ _intentional_silence = False+ response = _UNEXPECTED_SILENCE_REPLY++ elif _intentional_silence and not is_machinery_display_kind(_silence_kind):++ logger.debug(++ "silence marker suppressed on an unaddressed turn: platform=%s chat=%s",++ _platform_name, source.chat_id or "unknown",++ )++ # "(empty)" = the model produced no visible content after exhausting all retries. One+ # text with the CLI explainer and the desktop (agent/turn_explainers.py) so the user+ # reads the same words on every surface.+ if response == "(empty)" and not _intentional_silence:+ from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION++ _model = str(agent_result.get("model") or "").strip() or "The model"+ response = "⚠️ " + EMPTY_RESPONSE_EXPLANATION.format(model=_model)+ agent_messages = agent_result.get("messages", [])+ logger.info(+ "response ready: platform=%s chat=%s session=%s time=%.1fs api_calls=%d response=%d chars",+ _platform_name, source.chat_id or "unknown", session_key or "unknown",+ time.time() - _msg_start_time, agent_result.get("api_calls", 0), len(response),+ )++ # Successful turn: clear the consecutive-restart stuck-loop counter and resume_pending (set+ # by drain-timeout shutdown) so later messages don't get the restart-interruption note.+ if session_key and _should_clear_resume_pending_after_turn(agent_result):+ await self._clear_restart_failure_count(session_key)+ try:+ await self.async_session_store.clear_resume_pending(session_key)+ except Exception as _e:+ logger.debug("clear_resume_pending failed for %s: %s", session_key, _e)++ # Normalize empty responses: surface errors, partial failures, and work-without-text.+ # Fix for #18765.+ if not _intentional_silence:+ response = _normalize_empty_agent_response(agent_result, response, history_len=len(history))+ response = _sanitize_gateway_final_response(source.platform, response)++ # The agent thread already updated the contextvar; propagate to SessionEntry + _save() only+ # if the binding still points at the session this run was launched against.+ if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id:+ if session_entry.session_id == _run_start_session_id:+ session_entry.session_id = agent_result["session_id"]+ # The held turn lease follows the rotation (persistence writes to the NEW id).+ self._rebind_turn_lease(_quick_key, run_generation, session_entry.session_id)+ await self.async_session_store._save()+ await self.async_session_store._record_gateway_session_peer(+ session_entry.session_id, session_key, source,+ )+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="agent-result-compression",+ )+ else:+ logger.info(+ "Skipping agent-result session split sync for %s because the session binding "+ "moved from %s to %s before compression finished",+ session_key or "?", _run_start_session_id, session_entry.session_id,+ )+ return response, _intentional_silence, agent_messages++ # reasoning_style → (header line, per-line quote prefix for blank / non-blank lines)+ _REASONING_QUOTE_STYLES = {+ "subtext": ("-# 💭 Reasoning", "-# ", "-#"), "blockquote": ("> 💭 **Reasoning:**", "> ", ">")+ }++ def _hmwa_prepend_reasoning(self, agent_result, response, source, _intentional_silence):+ """Prepend the last reasoning block when show_reasoning is on for this platform. Mattermost+ requires an explicit per-platform opt-in (scratch text, not final-answer content)."""+ from gateway.run import _load_gateway_config, _platform_config_key, _resolve_gateway_display_bool+ try:+ _show_reasoning_effective = _resolve_gateway_display_bool(+ _load_gateway_config(), _platform_config_key(source.platform), "show_reasoning",+ default=bool(getattr(self, "_show_reasoning", False)), platform=source.platform,+ require_platform_override_for={Platform.MATTERMOST},+ )+ except Exception:+ _show_reasoning_effective = (+ False if source.platform == Platform.MATTERMOST else getattr(self, "_show_reasoning", False)+ )+ last_reasoning = agent_result.get("last_reasoning")+ if not (_show_reasoning_effective and response and not _intentional_silence and last_reasoning):+ return response+ from gateway.stream_consumer_fences import escape_code_fences_for_display+ # Collapse long reasoning to keep messages readable+ lines = last_reasoning.strip().splitlines()+ if len(lines) > 15:+ display_reasoning = "\n".join(lines[:15]) + f"\n_... ({len(lines) - 15} more lines)_"+ else:+ display_reasoning = last_reasoning.strip()+ # Per-platform render style: Discord defaults to "-# " subtext, others keep the code block.+ try:+ from gateway.display_config import resolve_display_setting+ _reasoning_style = resolve_display_setting(+ _load_gateway_config(), _platform_config_key(source.platform), "reasoning_style", "code",+ )+ except Exception:+ _reasoning_style = "code"+ _quote = self._REASONING_QUOTE_STYLES.get(_reasoning_style)+ if _quote:+ header, prefix, empty = _quote+ _quoted = "\n".join(f"{prefix}{ln}" if ln else empty for ln in display_reasoning.splitlines())+ return f"{header}\n{_quoted}\n\n{response}"+ # Escape ``` inside reasoning so inner fences don't break the outer code block.+ display_reasoning = escape_code_fences_for_display(display_reasoning)+ return f"💭 **Reasoning:**\n```\n{display_reasoning}\n```\n\n{response}"++ def _hmwa_runtime_footer_line(self, agent_result, source, _turn_seconds):+ """Runtime-metadata footer for the FINAL message of the turn; off by default+ (display.runtime_footer.enabled=false)."""+ from gateway.run import _load_gateway_config, _platform_config_key, _terminal_scope_cwd+ try:+ from gateway.runtime_footer import build_footer_line as _bfl+ return _bfl(+ user_config=_load_gateway_config(),+ platform_key=_platform_config_key(source.platform), model=agent_result.get("model"),+ context_tokens=agent_result.get("last_prompt_tokens", 0) or 0,+ context_length=agent_result.get("context_length") or None,+ cwd=_terminal_scope_cwd(""), turn_seconds=_turn_seconds,+ requested_model=agent_result.get("requested_model"),+ served_model=agent_result.get("served_model"),+ )+ except Exception as _footer_err:+ logger.debug("runtime_footer build failed: %s", _footer_err)+ return ""++ async def _hmwa_post_turn_hooks(self, hook_ctx, agent_result, response):+ """agent:end hook, process-watcher scheduling, and watch-notification drain."""+ await self.hooks.emit("agent:end", {+ **hook_ctx, "response": (response or "")[:500], "model": agent_result.get("model", ""),+ "provider": agent_result.get("provider", ""),+ })++ # Pending process watchers (check_interval on background processes)+ try:+ from tools.process_registry import process_registry+ # Detach the batch atomically (reassign, not clear()) so concurrent appends aren't dropped.+ watchers = process_registry.pending_watchers+ process_registry.pending_watchers = []+ for i, watcher in enumerate(watchers):+ asyncio.create_task(self._run_process_watcher(watcher))+ if i % 100 == 99:+ await asyncio.sleep(0)+ except Exception as e:+ logger.error("Process watcher setup error: %s", e)++ # Drain watch notifications that arrived during the run; the queue also carries process /+ # async-delegation completions owned elsewhere — inject only watch-type events.+ try:+ from tools.process_registry import process_registry as _pr+ await self._drain_watch_notifications(_pr.completion_queue)+ except Exception as e:+ logger.debug("Watch queue drain error: %s", e)++ # One owner for the boundary copy (agent/turn_failure_copy.py): the core closer in+ # agent/conversation_loop.py writes the same row on the paths that never reach this layer.++ def _hmwa_add_failed_turn_notice(self, response, notice):+ """Make failed-turn delivery explicit without replacing the provider-specific guidance."""+ response = str(response or "").strip()+ return f"{response}\n\n{notice}" if response else notice++ def _hmwa_failed_turn_notice(self, agent_result):+ """Choose retry guidance without assuming completed tool effects can be repeated safely."""+ from gateway.media_repair import _current_turn_messages+ # Compression during the failed turn can move the slice boundary; the shared helper falls+ # back to the last user row so tool evidence is not silently dropped.+ turn_messages = _current_turn_messages(+ agent_result.get("messages", []) or [], agent_result.get("history_offset", 0),+ )+ if any(+ message.get("role") == "tool"+ or (message.get("role") == "assistant" and message.get("tool_calls"))+ for message in turn_messages+ ):+ return PARTIAL_FAILED_TURN_NOTICE+ return FAILED_TURN_NOTICE++ async def _hmwa_close_failed_turn(self, session_id, notice):+ """Append the gateway-owned assistant boundary iff the durable tail is an open user row.++ The tail, not "did the gateway write the user row", is the key: on the primary path the+ agent's turn-start flush already persisted the row (so the platform-id dedupe skips the+ gateway write), and a platform redelivery of an already-closed turn must not stack a+ second assistant row."""+ if await self.async_session_store.transcript_tail_role(session_id) != "user":+ return+ await self.async_session_store.append_to_transcript(session_id, {+ "role": "assistant", "content": notice, "timestamp": time.time(), "display_kind": FAILED_TURN_DISPLAY_KIND,+ })++ def _hmwa_classify_turn_failure(self, agent_result, history, session_entry):+ """Classify a finished turn for transcript persistence. Returns+ ``(agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure)``.++ Context-overflow failures must NOT persist the user message (session would grow and+ reproduce the failure forever); transient failures (429/timeout/5xx) DO."""+ from gateway.run import _is_gateway_hidden_reasoning_incomplete_turn+ # Save the full conversation to the transcript, including tool calls. This preserves the complete+ # agent loop (tool_calls, tool results, intermediate reasoning) so sessions can be resumed with full+ # context and transcripts are useful for debugging and training data. IMPORTANT: For+ # context-overflow failures (compression exhausted, generic 400 on large sessions) we must NOT+ # persist the user's message — doing so would grow the session further and cause the same failure on+ # the next attempt, an infinite loop. (#1630, #9893) Transient failures (429, timeout, connection+ # error, provider 5xx) are different: the session is not oversized, and silently dropping the user+ # message causes severe context loss on retry — the agent forgets what was just asked. Persist the+ # user turn so the conversation is preserved. (#7100)+ agent_failed_early = bool(agent_result.get("failed"))+ hidden_reasoning_incomplete = _is_gateway_hidden_reasoning_incomplete_turn(agent_result)+ from gateway.run_turn import is_context_overflow_failure_result+ is_context_overflow_failure = is_context_overflow_failure_result(agent_result, len(history))+ if is_context_overflow_failure:+ logger.info(+ "Skipping transcript persistence for context-overflow "+ "failure in session %s to prevent session growth loop.", session_entry.session_id,+ )+ elif agent_failed_early:+ logger.info(+ "Transient agent failure in session %s — persisting user "+ "message so conversation context is preserved on retry.", session_entry.session_id,+ )+ elif hidden_reasoning_incomplete:+ logger.warning(+ "Suppressing hidden-reasoning-only incomplete gateway turn for session %s: %s",+ session_entry.session_id, agent_result.get("error", "processing incomplete"),+ )+ return agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure++ async def _hmwa_compression_exhaustion_reset(+ self, agent_result, response, session_entry, session_key, source,+ ):+ """Auto-reset a permanently oversized session so the next message starts fresh instead of+ replaying the oversized context forever. Never on a lock-contended defer — that is the+ OPPOSITE case (a concurrent path holds the lock and is shrinking it). Returns+ ``(response, session_entry)``."""+ # When compression is exhausted, the session is permanently too large to process. (#9893) Never wipe+ # the session for that — retry-next-message semantics apply (#69870 lock-skip consumer; salvaged+ # from #49874).+ if agent_result.get("compression_deferred"):+ logger.info(+ "Compression deferred for session %s — the compression "+ "lock is held by a concurrent compressor. Keeping the "+ "session intact; the next message retries normally.",+ session_entry.session_id if session_entry else "?",+ )+ elif agent_result.get("compression_exhausted") and session_entry and session_key:+ logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)+ new_entry = await self.async_session_store.reset_session(session_key)+ self._evict_cached_agent(session_key)+ # Conversation boundary: the funnel clears every conversation-scoped per-session dict.+ self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")+ if new_entry is not None:+ # Re-point the Telegram topic binding at the fresh session, or the binding-heal walk+ # switches the next message back onto the bloated child and re-triggers exhaustion+ # forever. No-op on non-topic lanes.+ # Compression rotated session_entry.session_id to the oversized compressed child earlier+ # this turn (the agent-result sync above), and that _sync also rewrote the (chat_id,+ # thread_id) -> bloated-child binding. reset_session swaps in a clean, parentless session,+ # but without re-syncing the binding the next inbound message in this topic gets+ # switch_session'd back onto the bloated child by the binding-heal walk, reloads the+ # oversized transcript, and re-triggers compression exhaustion forever (#35809 — regression+ # of the #9893/#10063 auto-reset).+ session_entry = new_entry+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-exhausted-reset",+ )+ response = (response or "") + (+ "\n\n🔄 Session auto-reset — the conversation exceeded the maximum context size and "+ "could not be compressed further. Your next message will start a fresh session."+ )+ return response, session_entry++ @staticmethod+ def _hmwa_user_transcript_entry(event, prepared, ts):+ """Transcript row for the inbound user turn (clean text + event time when captured)."""+ # Transient failure (429/timeout/5xx): persist only the user message so the next message can load a+ # transcript that reflects what was said. Skip the assistant error text since it's a+ # gateway-generated hint, not model output. Hidden- reasoning-only incomplete turns follow the same+ # persistence rule so peer-agent channels don't ingest them as completed assistant turns. (#7100,+ # #51628)+ _user_entry = {+ "role": "user",+ "content": (+ prepared.persist_user_message if prepared.persist_user_message is not None+ else prepared.message_text+ ),+ "timestamp": prepared.persist_user_timestamp if prepared.persist_user_timestamp is not None else ts,+ }+ if prepared.persist_user_display_kind:+ _user_entry["display_kind"] = prepared.persist_user_display_kind+ if prepared.persistence_owner:+ _user_entry["display_metadata"] = {"gateway_input_owner": prepared.persistence_owner}+ if getattr(event, "message_id", None):+ _user_entry["message_id"] = str(event.message_id)+ return _user_entry++ async def _hmwa_persist_turn_transcript(+ self, *, event, source, session_entry, session_key, agent_result, agent_messages,+ prepared, response, agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure,+ ):+ """Persist this turn to the transcript (session_meta on first turn, user-only on transient+ failure, nothing on context overflow), update last_prompt_tokens, and re-baseline the+ cached agent's message count."""+ from gateway.run import _resolve_gateway_model+ ts = time.time() # Unix epoch float — consistent with DB storage+ store = self.async_session_store+ sid = session_entry.session_id+ history = prepared.history+ # The agent already persisted this turn's rows (codex app-server reports agent_persisted=True+ # too); skip the DB write. Default = a session DB exists; non-persisting runtimes pass False.+ # The agent already persisted these messages to SQLite via _flush_messages_to_session_db(), so skip+ # the DB write here to prevent the duplicate-write bug (#860 / #42039). This holds for the codex+ # app-server runtime too: although it early-returns and bypasses conversation_loop's per-step+ # flushes, it flushes its own projected assistant/tool messages before returning and reports+ # agent_persisted=True (see agent/codex_runtime.py). Reading the flag (default = self._session_db is+ # not None) keeps the persistence contract explicit and lets any future non-persisting runtime opt+ # into a gateway-side write by returning False.+ agent_persisted = agent_result.get("agent_persisted", self._session_db is not None)+ _user_row = self._hmwa_user_transcript_entry(event, prepared, ts)++ if is_context_overflow_failure:+ pass # Skip all transcript writes — don't grow a broken session+ else:+ if not history and source.platform != Platform.LOCAL:+ # Fresh session: the tool definitions (as sent in the API request) make the transcript+ # self-describing. A LOCAL route (one-shot, chat -q, ACP, TUI attach) keeps the classic+ # in-process CLI's transcript shape: the marker is gateway bookkeeping every local+ # reader filters out, and the session row already carries model/model_config.+ await store.append_to_transcript(sid, {+ "role": "session_meta",+ "tools": agent_result.get("tools", []) or [],+ "model": _resolve_gateway_model(),+ "platform": source.platform.value if source.platform else "",+ "timestamp": ts,+ })+ if agent_failed_early or hidden_reasoning_incomplete:+ # Transient failure / hidden-reasoning incomplete: persist only the user message (the+ # assistant error text is a gateway hint, not model output). Dedupe on platform+ # message_id (Telegram retries after transient failures).+ if event.message_id and await store.has_platform_message_id(sid, str(event.message_id)):+ logger.info(+ "Skipping duplicate user turn (message_id=%s) in session %s",+ event.message_id, sid,+ )+ else:+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)+ # Close the failed turn: a user-only tail lets alternation repair merge this request+ # into an unrelated future message and replay stale side effects (#107070).+ await self._hmwa_close_failed_turn(sid, self._hmwa_failed_turn_notice(agent_result))+ else:+ # Only the NEW messages: history_offset (what the agent saw), not len(history), which+ # counts session_meta entries stripped before the agent saw them.+ history_len = agent_result.get("history_offset", len(history))+ new_messages = agent_messages[history_len:] if len(agent_messages) > history_len else []+ if not new_messages:+ # Edge case: fall back to simple user/assistant rows.+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)+ if response:+ await store.append_to_transcript(+ sid, {"role": "assistant", "content": response, "timestamp": ts},+ skip_db=agent_persisted,+ )+ else:+ # Attach the inbound platform message_id to the first user entry so platform-level+ # quote-resolution (e.g. Yuanbao) can find earlier @bot messages by original id.+ _user_msg_id_attached = False+ for msg in new_messages:+ if msg.get("role") == "system":+ continue # rebuilt each run+ entry = {**msg, "timestamp": ts}+ if (+ not _user_msg_id_attached+ and msg.get("role") == "user"+ and event.message_id+ and "message_id" not in entry+ ):+ entry["message_id"] = str(event.message_id)+ _user_msg_id_attached = True+ await store.append_to_transcript(sid, entry, skip_db=agent_persisted)++ # The agent persists token counts/model itself; keep only last_prompt_tokens for hygiene.+ await store.update_session(+ session_entry.session_key, last_prompt_tokens=agent_result.get("last_prompt_tokens", 0),+ touch_activity=not bool(getattr(event, "internal", False)),+ )++ # Re-baseline the cached agent's message_count now that ALL of this turn's writes are done:+ # the coherence guard snapshots at agent-BUILD time, so our own writes would otherwise+ # trigger a rebuild next turn (destroying prompt caching).+ await self._refresh_agent_cache_message_count(session_key, sid)++ async def _hmwa_deliver_turn_response(+ self, event, source, session_entry, session_key, run_generation,+ agent_result, agent_messages, response, _footer_line, _intentional_silence,+ ):+ """Final delivery decisions: intentional silence, voice reply, streamed-turn media/footer.+ Returns the text for the adapter to send, or ``None`` when already delivered."""+ if diagnostic_wake_muted(event):+ return None+ # Intentional silence is a delivery decision: the [SILENT] turn stays persisted (alternation).+ if _intentional_silence:+ logger.info("Suppressing intentional silence marker for session %s", session_entry.session_id)+ response = ""++ adapter = self._delivery_adapter_for(source)+ # Auto voice reply (TTS audio before the text) unless streaming TTS already delivered audio.+ _streaming_tts_done = adapter is not None and bool(+ getattr(adapter, "_streaming_tts_turn_completed", lambda *_a, **_k: False)(session_key, run_generation)+ )+ if not _streaming_tts_done and self._should_send_voice_reply(+ event, response, agent_messages, already_sent=bool(agent_result.get("already_sent")),+ ):+ await self._send_voice_reply(event, response)++ # Streamed responses still need MEDIA: files delivered (chunks carry the tags verbatim). Never+ # skip when the agent failed: the error text is new content streaming didn't show.+ if agent_result.get("already_sent") and not agent_result.get("failed"):+ # The queued-follow-up lane uploads this response's attachments itself; re-scanning here+ # would upload every file a second time.+ if response and adapter and not agent_result.get("media_already_delivered"):+ await self._deliver_media_from_response(response, event, adapter)+ # Streaming delivered the body, but the footer was held back (`not already_sent` gate).+ if _footer_line and adapter:+ try:+ await adapter.send(source.chat_id, _footer_line, metadata=self._event_thread_metadata(event, source))+ except Exception as _e:+ logger.debug("trailing footer send failed: %s", _e)+ # Return None so the body isn't sent twice; stash the delivered text on the event for the+ # /loop and /goal hooks that read the return value.+ with suppress(Exception):+ event._streamed_final_response = str(response or "")+ return None++ return response++ # Chat-side next steps keyed by HTTP status; Hermes commands only (/login is the gateway's own+ # sign-in, `{relogin}` the profile-aware host equivalent, filled from the turn's agent provider).+ _STATUS_HINTS = {+ 401: (" Your sign-in to the AI model service has expired or the API key is wrong. "+ "Use /login here, or run `{relogin}` on the host."),+ 402: " Your AI model service balance or quota is used up. Top it up on the service's website, or use /model to switch models.",+ 529: " The AI model service is temporarily overloaded. Wait a moment, then use /retry.",+ }++ async def _hmwa_agent_error_reply(self, e, event, source, session_entry, session_key, prepared):+ """``except Exception`` body of the agent turn: stop typing, log, persist the inbound user+ turn once, and build the sanitized user-facing error reply."""+ # Retain Slack thread/workspace routing so a failed turn cannot leave its status visible.+ await self._hmwa_stop_typing_for_turn(event, source)+ logger.exception("Agent error in session %s", session_key)+ status_code = getattr(e, "status_code", None)+ if status_code in {400, 500} and len(prepared.history) > 50:+ # Context overflow / payload too large: a deterministic rejection (#107567), and the same+ # no-grow rule as the persist path (#1630) — nothing is written into an oversized session.+ from gateway.run import _CONTEXT_OVERFLOW_REPLY+ return _CONTEXT_OVERFLOW_REPLY+ # Replay can coalesce inputs; only this input's durable marker establishes ownership.+ try:+ if prepared.message_text is not None and session_entry is not None:+ _owned = await self.async_session_store.has_input_owner(+ prepared.persistence_session_id, prepared.persistence_owner,+ )+ if not _owned:+ await self.async_session_store.append_to_transcript(+ session_entry.session_id, self._hmwa_user_transcript_entry(event, prepared, time.time()),+ )+ # Tool effects are unknown after an exception.+ await self._hmwa_close_failed_turn(session_entry.session_id, PARTIAL_FAILED_TURN_NOTICE)+ except Exception:+ logger.debug("Failed to persist inbound user message after agent exception", exc_info=True)+ # Never expose raw exception types/messages to end users (info-leakage risk).+ status_hint = self._STATUS_HINTS.get(status_code, "")+ if status_code == 401:+ from agent.turn_failure_copy import relogin_command_hint++ _turn_agent = getattr(self._session_state(session_key).turn, "agent", None)+ status_hint = status_hint.format(relogin=relogin_command_hint(getattr(_turn_agent, "provider", None)))+ elif status_code == 429:+ # Plan usage limit (resets on a schedule) vs a transient rate limit+ _err_json = {}+ with suppress(Exception):+ _err_json = e.response.json().get("error", {})+ if not isinstance(_err_json, dict):+ _err_json = {}+ _resets_in = _err_json.get("resets_in_seconds")+ if _err_json.get("type") != "usage_limit_reached":+ status_hint = " You are being rate-limited. Please wait a moment and try again."+ elif _resets_in and _resets_in > 0:+ import math+ status_hint = f" Your plan's usage limit has been reached. It resets in ~{math.ceil(_resets_in / 3600)}h."+ else:+ status_hint = " Your plan's usage limit has been reached. Please wait until it resets."+ elif status_code == 400:+ status_hint = " The AI model service rejected the request."+ return self._hmwa_add_failed_turn_notice(+ f"⚠️ Something went wrong and I couldn't finish this reply.{status_hint}\n"+ "Use /retry to try again, or /new to start a fresh conversation. "+ "Technical details are in the gateway log (`hermes logs`).",+ PARTIAL_FAILED_TURN_NOTICE,+ )++ def _hmwa_discard_stale_result(self, source, _quick_key, run_generation):+ """A newer run generation superseded this turn: drop its deferred post-delivery callback."""+ logger.info(+ "Discarding stale agent result for %s — generation %d is no longer current",+ _quick_key or "?", run_generation,+ )+ self._pop_post_delivery_callback(self._delivery_adapter_for(source), _quick_key, run_generation)diff --cc gateway/run_turn_prepare.pyindex c8c4dc5a139,00000000000..5fc6402dd28mode 100644,000000..100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@@ -1,726 -1,0 +1,714 @@@+"""Gateway turn prepare phases; inherited by GatewayTurnMixin."""+from __future__ import annotations++import logging+from typing import TYPE_CHECKING+import asyncio+import dataclasses+import inspect+import json+import os+import queue+import threading+import time+from agent.i18n import t+from agent.session_activity import format_iteration_progress+from contextlib import nullcontext, suppress+from contextvars import copy_context+from gateway.config import Platform+from gateway.media_repair import repair_explicit_computer_use_media_paths+from gateway.platforms.base import BasePlatformAdapter+from gateway.platforms.event import MessageEvent+from gateway.session import (+ SessionSource, _session_key_namespace, build_channel_continuity_note,+ build_session_context,+)+from gateway.session_transcript import TranscriptReadError+from gateway.turn_context import TurnContext+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError+from hermes_constants import get_hermes_home_override+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Tuple+from utils import base_url_hostname++if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)+ from gateway.run import GatewayRunner # noqa: F401+ from gateway.run_turn_runner import TurnRunner # noqa: F401++# Log-record parity with the origin module.+logger = logging.getLogger("gateway.run")+++class GatewayTurnPrepareMixin:+ def _resolve_session_agent_runtime(+ self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,+ user_config: Optional[dict] = None,+ ) -> tuple[str, dict]:+ """Resolve model/runtime for a session.++ Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env+ (``_resolve_gateway_model(user_config)`` and default provider resolution)."""+ from gateway.run import (+ _credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,+ _resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,+ )+ from gateway.session_policy import policy_for_source+ # Every exit path starts clean: a stale notice must never attach to another session's next+ # turn (#74349). Set again below only when THIS resolution fell back.+ self._pre_agent_fallback_notice = None+ policy = policy_for_source(self, source) if source is not None else None+ if policy is not None:+ from gateway.run import _runtime_agent_kwargs+ from gateway.session_policy import launch_key+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime+ from gateway.session_authorities import active_authority+ authority = active_authority(self)+ frozen = policy.config(authority)+ key = launch_key(authority, policy)+ import json+ runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,+ explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),+ target_model=policy.model, config=frozen)+ if runtime is None:+ if key is None:+ key = frozen.get('model', {}).get('api_key')+ # Same resolution-time walker the in-process one-shot used (#81209): an AuthError from+ # the frozen primary (expired token, Portal down, exhausted pool) tries the route's own+ # ``fallback_providers`` before the turn is refused.+ from hermes_cli.runtime_provider import resolve_runtime_with_fallback+ # Only a launch-supplied URL is explicit (classic one-shot parity): config's own+ # ``model.base_url`` is resolved by the provider chain, which keeps the credential pool+ # an explicit URL would drop (no pool = no refresh/rotation on a 401).+ runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=policy.provider,+ explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),+ target_model=policy.model)+ if fallback_entry is not None:+ from hermes_cli.fallback_config import pre_agent_fallback_notice+ self._pre_agent_fallback_notice = pre_agent_fallback_notice(+ policy.provider or '', policy.model or '',+ runtime.get('provider') or fallback_entry.get('provider') or 'unknown',+ fallback_entry.get('model') or 'default')+ return fallback_entry['model'], _runtime_agent_kwargs(runtime)+ return policy.model, _runtime_agent_kwargs(runtime)+ skey = self._resolve_session_key_or_none(source, session_key)+ model = _resolve_gateway_model(user_config)+ if skey:+ self._rehydrate_session_model_override(skey)+ _override_state = self._peek_session_state(skey) if skey else None+ override = _override_state.conversation.model_override if _override_state else None+ if override:+ override_model = override.get("model", model)+ override_runtime = {+ k: override.get(k) for k in (+ "provider", "requested_provider", "api_key", "base_url", "api_mode",+ "max_tokens", "credential_pool", "request_overrides", "capabilities",+ )+ }+ override_runtime["capabilities"] = dict(override_runtime["capabilities"] or {})+ if override_runtime.get("api_key"):+ if override_runtime.get("credential_pool") is None:+ override_runtime["credential_pool"] = _credential_pool_for_provider(override.get("provider"))+ logger.debug(+ "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",+ skey or "", model, override_model, override_runtime.get("provider"),+ )+ return override_model, override_runtime+ # No api_key on the override (credentials failed to re-resolve at rehydrate): resolve them+ # for the override's own provider below, never layer it over the default provider's runtime.+ logger.debug(+ "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",+ skey or "", model, override_model,+ )+ elif logger.isEnabledFor(logging.DEBUG):+ # The override_keys scan walks every session; only pay for it when DEBUG is on.+ logger.debug(+ "No session model override: session=%s config_model=%s override_keys=%s",+ skey or "", model,+ [+ _key for _key, _st in list(self._sessions_map().items())+ if _st.conversation.model_override is not None+ ][:5] or "[]",+ )++ runtime_kwargs, unavailable_override = None, None+ if override and override.get("provider"):+ try:+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(+ override["provider"], target_model=override.get("model") or None)+ except Exception as exc:+ # Layering the override on the default runtime sent its model to the default provider's+ # endpoint (openai-codex on the Nous URL). Run this turn on the whole default route and say+ # so; the persisted override is kept, so the next turn retries it.+ logger.warning("Session /model override provider %s unavailable: %s", override["provider"], exc)+ unavailable_override, override = override, None+ if runtime_kwargs is None:+ runtime_kwargs = _resolve_runtime_agent_kwargs()+ # Private notice metadata must never reach an ``AIAgent(**runtime_kwargs)`` spread; the turn+ # runner surfaces it through the agent's one-shot fallback notice (#74349).+ self._pre_agent_fallback_notice = runtime_kwargs.pop("_fallback_notice", None)+ runtime_model = runtime_kwargs.pop("model", None)+ if runtime_model:+ logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)+ model = runtime_model+ if unavailable_override and not self._pre_agent_fallback_notice:+ from hermes_cli.fallback_config import pre_agent_fallback_notice+ self._pre_agent_fallback_notice = pre_agent_fallback_notice(+ unavailable_override["provider"], unavailable_override.get("model"), runtime_kwargs.get("provider"), model)++ cfg = getattr(self, "config", None) # getattr: bare object.__new__ test runners+ if cfg and source is not None:+ ch = _get_channel_override(+ cfg, source.platform, str(source.chat_id) if source.chat_id else "",+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,+ )+ if ch:+ if ch.model:+ model = ch.model+ if ch.provider:+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider, target_model=model or None)+ ch_runtime_model = runtime_kwargs.pop("model", None)+ # Adopt the provider's bundled model only when the override named none.+ if ch_runtime_model and not ch.model:+ model = ch_runtime_model++ if override and skey:+ model, runtime_kwargs = self._apply_session_model_override(skey, model, runtime_kwargs)++ # Provider resolved but no model.default (`hermes auth add` without `hermes model`): use the+ # provider's first catalog model.+ if not model and runtime_kwargs.get("provider"):+ with suppress(Exception):+ from hermes_cli.models import get_default_model_for_provider+ model = get_default_model_for_provider(runtime_kwargs["provider"])+ if model:+ logger.info(+ "No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],+ )++ # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and+ # the session goes silent — reuse the last model resolved for this session, else process-wide.+ if not model:+ _lr_state = self._peek_session_state(skey) if skey else None+ _lr_star = self._peek_session_state("*")+ _recovered = (+ (_lr_state.conversation.last_resolved_model if _lr_state else "")+ or (_lr_star.conversation.last_resolved_model if _lr_star else "")+ )+ if _recovered:+ logger.warning(+ "Empty model resolved for session=%s — recovering "+ "last-known-good model %s (config read likely returned "+ "empty; see #35314)", skey or "", _recovered,+ )+ model = _recovered+ else:+ # Cache the good resolution for future recovery turns.+ if skey:+ self._session_state(skey).conversation.last_resolved_model = model+ self._session_state("*").conversation.last_resolved_model = model++ return model, runtime_kwargs++ def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:+ """Effective model/runtime config for one turn. With `/fast` priority on, fast-mode+ ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model."""+ from gateway.run import _deep_merge_request_overrides+ from hermes_cli.models import resolve_fast_mode_overrides+ # Tests bind this method onto bare namespaces, so no class-level tables here.+ runtime = {+ k: runtime_kwargs.get(k) for k in (+ "api_key", "base_url", "provider", "requested_provider", "api_mode", "command", "args",+ "credential_pool", "max_tokens", "capabilities",+ )+ }+ runtime["args"] = list(runtime["args"] or [])+ runtime["capabilities"] = dict(runtime["capabilities"] or {})+ base_request_overrides = dict(runtime_kwargs.get("request_overrides") or {})+ route = {+ "model": model,+ "runtime": runtime,+ "signature": (+ model, runtime["provider"], runtime["requested_provider"], runtime["base_url"],+ runtime["api_mode"], runtime["command"], tuple(runtime["args"]),+ ),+ }+ if getattr(self, "_service_tier", None) != "priority":+ # None / auto / cold: the bounded window is applied per request by agent.fast_mode.+ route["request_overrides"] = base_request_overrides+ return route+ try:+ overrides = resolve_fast_mode_overrides(+ route["model"], provider=runtime["provider"], base_url=runtime["base_url"],+ )+ except Exception:+ overrides = None+ # Fast-mode keys (service_tier / speed) are top-level and don't collide with extra_body.+ route["request_overrides"] = _deep_merge_request_overrides(base_request_overrides, overrides or {})+ return route++ def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:+ """Persist the runtime model/provider a gateway turn actually used (provider fallback can+ switch them after the row was created). Runs in the ``run_sync`` executor thread, so it+ uses the sync ``SessionDB`` (``_db``), not the AsyncSessionDB forwarder."""+ if not session_id or agent is None or self._session_db is None:+ return+ model = getattr(agent, "model", None)+ if not model:+ return+ runtime = {k: getattr(agent, k, None) for k in ("provider", "base_url", "api_mode")}+ runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False))+ runtime = {k: v for k, v in runtime.items() if v not in (None, "")}+ try:+ db = self._session_db._db+ row = db.get_session(session_id)+ if not row:+ return+ # Legacy backfill: canonical Bot Chats created BEFORE the follow_profile_config contract existed+ # carry no marker, yet they are still the plugin-owned forever-DM. The plugin's own identity+ # rule is "the profile's session titled exactly 'Bot Chat'" (UNIQUE(title) makes that an exact+ # registry, and pre-policy rows may be visible OR hidden), so mirror that rule here. Without+ # this, every Bot Chat that already exists in the field stays pinned to its stale stored+ # provider until the user deletes it — the exact live-report shape (#89497 / #94818).+ raw_config = row.get("model_config")+ config = {}+ with suppress(Exception):+ config = json.loads(raw_config) if raw_config else {}+ if not isinstance(config, dict):+ config = {}+ gateway_runtime = dict(config.get("gateway_runtime") or {})+ if row.get("model") == model and all(gateway_runtime.get(k) == v for k, v in runtime.items()):+ return+ config["gateway_runtime"] = runtime+ db.update_session_meta(session_id, json.dumps(config), model=model)+ except Exception:+ logger.debug("Failed to sync gateway session model metadata", exc_info=True)++ async def _hmwa_resolve_session(self, event, source):+ """Resolve ``source`` to its session entry (topic recovery, internal-route guards, Telegram+ topic-binding heal). Returns ``(source, session_entry, session_key)`` or ``None`` to drop+ the event."""+ # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's last-active topic so a+ # cross-topic Reply doesn't fragment the conversation.+ event_metadata = getattr(event, "metadata", None) or {}+ expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()+ recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)+ if not expected_session_key else None)+ if recovered is not None:+ logger.info(+ "telegram topic recovery: chat=%s user=%s %r -> %s",+ source.chat_id, source.user_id, source.thread_id, recovered,+ )+ source = dataclasses.replace(source, thread_id=recovered)+ with suppress(Exception):+ event.source = source++ if expected_session_key:+ derived_session_key = self._session_key_for_source(source)+ if derived_session_key != expected_session_key:+ logger.warning(+ "Dropping internally routed event after route recovery: expected session=%s derived=%s",+ expected_session_key, derived_session_key,+ )+ return++ strict_session = bool(event_metadata.get("gateway_session_strict"))+ pinned_session_id = str(event_metadata.get("gateway_session_id") or "").strip()+ if strict_session:+ session_entry = await self.async_session_store.lookup_by_session_key(expected_session_key)+ if session_entry is None or not pinned_session_id or session_entry.session_id != pinned_session_id:+ logger.warning(+ "Dropping internally routed event: expected session id=%s is no longer current for key=%s",+ pinned_session_id or "missing", expected_session_key or "missing",+ )+ return+ else:+ # Internal wakes observe reset policy without counting as user activity, or periodic+ # notifications keep the routing key alive across every daily/idle boundary.+ session_entry = await self.async_session_store.get_or_create_session(+ source, touch_activity=not bool(getattr(event, "internal", False)),+ )+ session_key = session_entry.session_key+ if not strict_session and pinned_session_id:+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id)+ if resolved_entry is None:+ return+ session_entry = resolved_entry+ self._cache_session_source(session_key, source)+ if await asyncio.to_thread(self._is_telegram_topic_lane, source):+ session_entry = await self._hmwa_heal_telegram_topic_binding(source, session_entry, session_key)+ from gateway.run_heartbeat_acceptance import resolve_heartbeat_owner+ if not await resolve_heartbeat_owner(self, event, session_entry):+ return+ return source, session_entry, session_key++ async def _hmwa_heal_telegram_topic_binding(self, source, session_entry, session_key):+ """Follow the (chat_id, thread_id) topic binding — healed to its compression tip — or record+ a fresh one. Returns the (possibly switched) session entry."""+ binding = None+ try:+ if self._session_db:+ binding = await self._session_db.get_telegram_topic_binding(+ chat_id=str(source.chat_id), thread_id=str(source.thread_id),+ profile_name=self._telegram_topic_profile_name(source),+ )+ except Exception:+ logger.debug("Failed to read Telegram topic binding", exc_info=True)+ if not binding:+ try:+ await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)+ except Exception:+ logger.debug("Failed to record Telegram topic binding", exc_info=True)+ return session_entry+ stored_session_id = str(binding.get("session_id") or "")+ bound_session_id = stored_session_id+ # A binding pointing at a pre-compression parent is walked forward to the tip so the next+ # message resumes the compressed child instead of reloading the oversized parent.+ # Returns the input unchanged when the session isn't a compression parent, so this is cheap and+ # safe. See #20470, #29712, #33414.+ if bound_session_id and self._session_db is not None:+ try:+ canonical_session_id = await self._session_db.get_compression_tip(bound_session_id)+ except Exception:+ logger.debug("compression-tip lookup failed for %s", bound_session_id, exc_info=True)+ canonical_session_id = bound_session_id+ if canonical_session_id and canonical_session_id != bound_session_id:+ bound_session_id = canonical_session_id+ if bound_session_id and bound_session_id != session_entry.session_id:+ # Route through SessionStore so the key → id mapping persists and the previous lane+ # session ends cleanly (in-place mutation split-brained the JSON index). The two DB+ # awaits above are a window for /new or /resume to move the route; the CAS on the+ # snapshot id lets that win instead of being clobbered by a stale binding.+ switched = await self.async_session_store.switch_session(+ session_key, bound_session_id, expected_session_id=session_entry.session_id,+ )+ if switched is not None:+ session_entry = switched+ if bound_session_id and bound_session_id != stored_session_id:+ # The stored binding pointed at a parent: rewrite it to the canonical descendant.+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-tip-walk",+ )+ return session_entry++ async def _hmwa_open_session(self, session_entry, session_key, source):+ """Consume auto-reset / fresh-reset flags and emit ``session:start`` for new sessions.+ Returns ``(_was_auto_reset, _is_new_session)``."""+ # Consume was_auto_reset immediately so it cannot re-fire and wipe overrides set between turns.+ # Capture and immediately consume was_auto_reset so it does not re-fire on subsequent messages —+ # preventing the cleanup from wiping model/reasoning overrides set between turns (Closes #48031).+ _was_auto_reset = getattr(session_entry, "was_auto_reset", False)+ if _was_auto_reset:+ # Conversation boundary: the funnel clears every conversation-scoped dict; evict the cached+ # agent so context_compressor._previous_summary cannot leak into new summaries.+ # Treat auto-reset as a full conversation boundary — clear every conversation-scoped per-session+ # dict in one funnel call so the fresh session does not inherit the previous conversation's+ # model/reasoning overrides, a queued "/model switched" note, or a stale resolved-model cache+ # (#48031, #58403). See _CONVERSATION_SCOPED_STATE.+ self._clear_conversation_scope(session_key, reason="auto_reset")+ self._evict_cached_agent(session_key)+ session_entry.was_auto_reset = False++ _is_fresh_reset = getattr(session_entry, "is_fresh_reset", False)+ _is_new_session = session_entry.created_at == session_entry.updated_at or _was_auto_reset or _is_fresh_reset+ # Consume is_fresh_reset so it doesn't leak onto later messages in the same session.+ if _is_fresh_reset:+ # See #6508.+ session_entry.is_fresh_reset = False+ if _is_new_session:+ await self.hooks.emit("session:start", {+ "platform": source.platform.value if source.platform else "",+ "user_id": source.user_id,+ "session_id": session_entry.session_id,+ "session_key": session_key,+ })+ return _was_auto_reset, _is_new_session++ async def _hmwa_deliver_auto_reset_notice(self, session_entry, source, turn_sidecar_notes):+ """Stage the auto-reset sidecar note for the agent and notify the user (policy-gated)."""+ from gateway.run import _AUTO_RESET_CONTEXT_NOTES+ reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'suspended'+ context_note = _AUTO_RESET_CONTEXT_NOTES.get(reset_reason, _AUTO_RESET_CONTEXT_NOTES["suspended"])+ # Long-lived channels: point the agent at the prior same-channel session for session_search.+ try:+ # Returns None (appends nothing) for other platforms or when there's no prior activity to+ # recall. Deterministic — no extra API/DB calls (#36220).+ continuity_note = build_channel_continuity_note(session_entry, source)+ except Exception:+ continuity_note = None+ if continuity_note:+ context_note = context_note + "\n\n" + continuity_note+ turn_sidecar_notes.append(context_note)++ try:+ should_notify = reset_reason == "suspended"+ adapter = self._delivery_adapter_for(source) if should_notify else None+ if adapter:+ notice = (+ "◐ Session reset after being stopped. "+ f"Conversation history cleared.\n"+ f"Use /resume to browse and restore a previous session.\n"+ )+ with suppress(Exception):+ session_info = await asyncio.to_thread(self._reset_notice_session_info, source)+ if session_info:+ notice = f"{notice}\n\n{session_info}"+ await adapter.send(source.chat_id, notice, metadata=self._thread_metadata_for_source(source))+ except Exception as e:+ logger.debug("Auto-reset notification failed (non-fatal): %s", e)++ # was_auto_reset was consumed in _hmwa_open_session; only the reason needs clearing.+ session_entry.auto_reset_reason = None++ def _hmwa_auto_load_skills(self, event, _auto, _quick_key, session_key):+ """Prepend topic/channel-bound skill payload(s) to ``event.text`` on a new session."""+ _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)+ try:+ from agent.skill_commands import _load_skill_payload, _build_skill_message+ _combined_parts: list[str] = []+ _loaded_names: list[str] = []+ for _sname in _skill_names:+ _loaded = _load_skill_payload(_sname, task_id=_quick_key)+ if not _loaded:+ logger.warning("[Gateway] Auto-skill '%s' not found", _sname)+ continue+ _loaded_skill, _skill_dir, _display_name = _loaded+ _part = _build_skill_message(+ _loaded_skill, _skill_dir,+ f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '+ f"Follow its instructions for this session.]",+ )+ if _part:+ _combined_parts.append(_part)+ _loaded_names.append(_sname)+ if _combined_parts:+ _combined_parts.append(event.text) # user's original text after the payloads+ event.text = "\n\n".join(_combined_parts)+ logger.info("[Gateway] Auto-loaded skill(s) %s for session %s", _loaded_names, session_key)+ except Exception as e:+ logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)++ async def _hmwa_acquire_turn_lease(self, _quick_key, run_generation, session_entry, _session_env_tokens):+ """Serialize [load history → run → flush] per resolved SESSION_ID so another routing key on+ the same session waits for the prior flush. Fail-closed on timeout (outer dispatch returns+ a resend notice). Released in _handle_message's finally, granted per (routing key, run+ generation) so a stale unwind can't release a newer turn's."""+ from gateway.run import _float_env+ _lease_registry = getattr(self, "_turn_leases", None)+ if _lease_registry is None:+ return+ try:+ _lease_token = await _lease_registry.acquire(+ session_entry.session_id, owner_key=_quick_key, generation=run_generation,+ timeout=_float_env("HERMES_TURN_LEASE_TIMEOUT", DEFAULT_LEASE_WAIT),+ )+ except TurnLeaseTimeoutError:+ # The cleanup finally starts later; restore the tokens here or this exit leaks identity.+ self._clear_session_env(_session_env_tokens)+ raise+ if _lease_token is not None:+ self._session_state(_quick_key).turn.lease_tokens[run_generation] = _lease_token++ async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes):+ """First-ever-message onboarding note + one-time 'no home channel' prompt (both only when+ the session has no history). Delivered on the user message (sidecar), NOT the ephemeral+ system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed prompt diff + rebuild."""+ from gateway.run import _hermes_home, _home_target_env_var, _load_gateway_config+ if history:+ return+ # LOCAL sessions (one-shot, chat -q, ACP, TUI attach) are the classic in-process CLI's+ # surfaces: it never appended this note, and mark_seen would rewrite config.yaml under+ # an ordinary launch that promises to leave the profile's files untouched.+ if source.platform == Platform.LOCAL:+ return+ if not await self.async_session_store.has_any_sessions():- _intro_note = (- "[System note: This is the user's very first message ever. "- "Briefly introduce yourself and mention that /help shows available commands. "- "Keep the introduction concise -- one or two sentences max.]"++ # Same branch logic as the TUI (profile-build offer once when "ask", else plain intro);++ # first_contact_turn_note already falls back to the plain intro on error.++ from agent.onboarding import first_contact_turn_note++ note = first_contact_turn_note(++ _load_gateway_config(), _hermes_home / "config.yaml",++ session_history_empty=True, install_has_prior_sessions=False,+ )- # onboarding.profile_build == "ask" (default) and not yet offered: swap the plain intro for- # a consent-gated profile-build directive. Fires at most once.- try:- from agent.onboarding import (- PROFILE_BUILD_FLAG, is_seen, mark_seen, profile_build_directive,- profile_build_mode,- )- _onb_cfg = _load_gateway_config()- if profile_build_mode(_onb_cfg) == "ask" and not is_seen(_onb_cfg, PROFILE_BUILD_FLAG):- turn_sidecar_notes.append(profile_build_directive().strip())- mark_seen(_hermes_home / "config.yaml", PROFILE_BUILD_FLAG)- else:- turn_sidecar_notes.append(_intro_note)- except Exception as _pb_err:- logger.debug("Profile-build onboarding directive failed, using plain intro: %s", _pb_err)- turn_sidecar_notes.append(_intro_note)++ if note:++ turn_sidecar_notes.append(note)++ # One-time prompt if no home channel is set (webhooks deliver to configured targets instead).+ if not source.platform or source.platform in (Platform.LOCAL, Platform.WEBHOOK):+ return+ platform_name = source.platform.value+ env_key = _home_target_env_var(platform_name)+ # Multiplex: the home channel may live only in the profile secret scope, not os.environ.+ home_env = ""+ if env_key:+ # A secondary with no home channel must not borrow the default profile's from+ # os.environ; only an UNSCOPED single-profile read may fall back to the process env.+ from agent.secret_scope import UnscopedSecretError, get_secret+ try:+ home_env = (get_secret(env_key) or "").strip()+ except UnscopedSecretError:+ home_env = (os.getenv(env_key) or "").strip()+ except Exception:+ home_env = ""+ # Also honor in-memory / yaml home_channel on this platform.+ with suppress(Exception):+ if not home_env and self.config.get_home_channel(source.platform):+ home_env = "set"+ # Secondary-profile platforms may only exist under that profile's config — re-read in scope.+ if not home_env:+ with suppress(Exception):+ from gateway.config import load_gateway_config as _lgc+ prof = (getattr(source, "profile", None) or "").strip()+ if prof and prof != "default" and _lgc().get_home_channel(source.platform):+ home_env = "set"+ if not home_env:+ # Slack routes every command through the parent `/hermes`; bare `/sethome` would fail.+ sethome_cmd = "/hermes sethome" if source.platform == Platform.SLACK else "/sethome"+ await self._deliver_platform_notice(+ source, f"📬 No home channel is set for {platform_name.title()}. "+ f"A home channel is where Hermes delivers cron job results and cross-platform "+ f"messages.\n\nType {sethome_cmd} to make this chat your home channel, or ignore "+ f"to skip.",+ )++ def _hmwa_apply_message_timestamp(self, event, message_text):+ """Capture the platform event time as message metadata and keep the persisted transcript+ clean — strip any leading timestamp prefix and the Discord triggering-message note (a+ model instruction, not authored text) — regardless of the toggle; only the in-context+ RENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""+ from gateway.run import _load_gateway_config, _message_timestamps_enabled+ from gateway.run_inbound import strip_discord_triggering_note+ persist_user_message = None+ persist_user_timestamp = None+ try:+ from hermes_time import get_timezone as _get_evt_tz+ from gateway.message_timestamps import (+ coerce_message_timestamp as _coerce_msg_ts,+ render_user_content_with_timestamp as _render_msg_ts,+ strip_leading_message_timestamps as _strip_msg_ts,+ )+ _evt_tz = _get_evt_tz()+ if message_text and isinstance(message_text, str):+ _clean_message_text, _embedded_ts = _strip_msg_ts(message_text, tz=_evt_tz)+ persist_user_message = strip_discord_triggering_note(event, _clean_message_text)+ _event_epoch = _coerce_msg_ts(getattr(event, "timestamp", None), tz=_evt_tz)+ persist_user_timestamp = _event_epoch if _event_epoch is not None else _embedded_ts+ if _message_timestamps_enabled(_load_gateway_config()):+ message_text = _render_msg_ts(_clean_message_text, persist_user_timestamp, tz=_evt_tz)+ else:+ # Toggle off: the model sees the clean message; timestamp stored for later opt-in.+ message_text = _clean_message_text+ except Exception as _ts_err:+ logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)+ return message_text, persist_user_message, persist_user_timestamp++ @dataclasses.dataclass+ class _PreparedTurn:+ """Inputs to the agent run assembled by ``_hmwa_prepare_turn``."""++ history: Any+ context_prompt: str+ message_text: Any+ persist_user_message: Any+ persist_user_timestamp: Any+ persist_user_display_kind: Optional[str]+ persistence_session_id: Optional[str] = None+ persistence_owner: Optional[str] = None++ async def _hmwa_prepare_turn(self, event, source, session_entry, session_key, _quick_key, run_generation):+ """Everything between session resolution and the agent run: session open, task-local env,+ context prompt, sidecar notes, turn lease, transcript load + hygiene, inbound text. Returns+ ``(_PreparedTurn, env_tokens)``; a ``str`` first element is a reply to send instead of+ running (history unreadable); ``None`` drops the turn (inbound text rejected)."""+ from gateway.run import _load_gateway_config+ _was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)+ context = build_session_context(source, self.config, session_entry)+ # Session context variables for tools (task-local, concurrency-safe)+ _session_env_tokens = self._set_session_env(context)+ # Self-injected turns (MessageEvent(internal=True)) persist with a DB-only display_kind so+ # UIs render timeline notices, not user bubbles; role/content untouched.+ from gateway.response_filters import display_kind_for_event+ persist_user_display_kind = display_kind_for_event(event)+ _redact_pii = False # privacy.redact_pii, re-read per message+ with suppress(Exception):+ _redact_pii = bool((_load_gateway_config().get("privacy") or {}).get("redact_pii", False))++ # The context prompt render is pinned per session, keyed by a hash of the renderer inputs, so+ # the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.+ # A LOCAL session (CLI one-shot, ACP, cron run-now, TUI attach) is the operator's own machine:+ # the messaging block ("Source: Local", connected platforms, cron delivery targets) was never+ # part of the classic in-process prompt, and the TUI gateway still builds that prompt in-process.+ # Rendering it here would make every surface hop of one durable session a system-prompt+ # (and prompt-cache) break.+ context_prompt = "" if source.platform == Platform.LOCAL else \- self._pinned_session_context_prompt(context, _redact_pii, session_key)++ self._pinned_session_context_prompt(context, _redact_pii, session_key, internal=event.internal)++ # Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt+ # (appending to the ephemeral system prompt forced a full agent rebuild).+ turn_sidecar_notes: List[str] = []+ if _was_auto_reset:+ await self._hmwa_deliver_auto_reset_notice(session_entry, source, turn_sidecar_notes)++ # Auto-load bound skill(s) only on NEW sessions; ongoing ones carry the content in history.+ _auto = getattr(event, "auto_skill", None)+ if _is_new_session and _auto:+ self._hmwa_auto_load_skills(event, _auto, _quick_key, session_key)++ await self._hmwa_acquire_turn_lease(_quick_key, run_generation, session_entry, _session_env_tokens)++ # A turn becomes durable recovery work only after it owns the per-session lease; marking+ # earlier would falsely recover a message that never began processing.+ await self._mark_durable_active_turn(event, session_entry.session_key)++ # An unreadable store is not an empty conversation: stop before the agent invents continuity+ # from []. Restore task-local context here (before the broad cleanup finally).+ try:+ history = await self.async_session_store.load_transcript(session_entry.session_id)+ history = await self._hmwa_run_session_hygiene(+ event, source, session_entry, session_key, history, _quick_key, run_generation,+ )+ except TranscriptReadError:+ self._clear_session_env(_session_env_tokens)+ return (+ "⚠️ This session's history is temporarily unavailable, so this message was not "+ "processed. Ask the operator to inspect state.db, then resend after it is healthy. "+ "Use /reset only if you intentionally want to start a new conversation."+ ), _session_env_tokens++ await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes)++ # Voice channel state rides the user message ONLY when changed (in the system prompt it+ # forced a rebuild + prompt-cache re-key per message).+ _vc_note = self._voice_channel_sidecar_note(event, source, session_key)+ if _vc_note:+ turn_sidecar_notes.append(_vc_note)++ # Auto-analyze user images so the model gets a description plus the local path.+ message_text = await self._prepare_profile_scoped_inbound_message_text(+ event=event, source=source, history=history, session_key=session_key,+ )+ if message_text is None:+ return None, _session_env_tokens++ message_text, persist_user_message, persist_user_timestamp = (+ self._hmwa_apply_message_timestamp(event, message_text)+ )++ # Stage the notes (one-shot; consumed in run_sync) AFTER the early-out so an aborted turn+ # cannot leak them into the next turn.+ if turn_sidecar_notes and session_key:+ self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)++ # Bind this run generation to the adapter so deferred post-delivery callbacks are released+ # by the run that registered them.+ self._bind_adapter_run_generation(self._delivery_adapter_for(source), session_key, run_generation)+ # Delivery IDs are only unique in their transport namespace. Keyless turns+ # need their own identity, even when another process writes to this session.+ import uuid+ namespace = [source.platform.value, source.profile, source.scope_id,+ source.chat_id, source.thread_id, str(event.message_id)]+ owner = (str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(namespace)))+ if event.message_id else str(uuid.uuid4()))+ return self._PreparedTurn(+ history, context_prompt, message_text, persist_user_message, persist_user_timestamp,+ persist_user_display_kind, session_entry.session_id, owner,+ ), _session_env_tokensdiff --cc gateway/session_automation.pyindex 088ca287291,00000000000..f13a32c87e8mode 100644,000000..100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@@ -1,173 -1,0 +1,186 @@@+"""Trusted producer admission; not a client-selectable internal input flag.++Reuse the private native route envelope and FIFO, retaining nonhuman turn semantics.+A producer ACK means committed input, not successful inference or outbound delivery.+"""+from copy import deepcopy+from datetime import datetime, timezone+import json++from gateway.config import Platform+from gateway.platforms.event import MessageEvent, MessageType+from gateway.session_contract import SessionRef+from hermes_state_runtime import RuntimeStoreError, admit_session_input+++def producer_identity(runner, event):+ identity = runner._completion_delivery_identity(event)+ if identity is None:+ raise RuntimeStoreError('invalid_params')+ return json.dumps(identity, separators=(',', ':'))+++def completion_admission(runner, event):+ from gateway.session_authorities import active_authority+ authority = active_authority(runner)+ if authority is None:+ return None+ entry = runner.session_store.lookup_by_session_key(str(event.get('session_key') or ''))+ if entry is None:+ return None+ from hermes_state_runtime import list_session_admissions+ identity = producer_identity(runner, event)+ sid = entry.origin.chat_id if entry.origin.platform == Platform.LOCAL else entry.session_id+ for row in list_session_admissions(authority.db, session_id=sid, pending_only=False):+ descriptor = row['payload'].get('local_automation_v1') or row['payload'].get('native_text_v1', {}).get('automation', {})+ if identity in descriptor.get('identities', [descriptor.get('identity')]):+ return row+ return None+++def _owner(runner, event):+ route = event.metadata.get('gateway_session_key') or runner.session_store._generate_session_key(event.source)+ entry = runner.session_store.lookup_by_session_key(route)+ if entry is None or entry.suspended:+ raise RuntimeStoreError('not_found')+ if runner.session_store._generate_session_key(event.source) != route:+ raise RuntimeStoreError('admission_conflict')+ expected = event.metadata.get('gateway_session_id')+ if not expected:+ raise RuntimeStoreError('admission_conflict')+ if expected != entry.session_id:+ # A completed child may follow compression, but never /new or an unrelated resume.+ from gateway.session_authorities import active_authority+ if active_authority(runner).db.get_compression_tip(expected) != entry.session_id:+ raise RuntimeStoreError('admission_conflict')+ return entry++++# notification_origin / original_trigger_message_id are producer debug context (#52694) and are not++# persisted; notification_category="diagnostic" rides the snapshot so the replayed wake still mutes.++_AUTOMATION_METADATA = frozenset({'gateway_session_key', 'gateway_session_id', 'automation_identities',++ 'turn_author', 'notification_origin', 'original_trigger_message_id', 'notification_category'})+++++def snapshot_automation(authority, adapter, event, identity):+ runner = authority.runner+ if (not event.internal or event.message_type != MessageType.TEXT or event.is_command()+ or not isinstance(event.text, str) or not identity+ or event.media_urls or event.prompt_response or event.source.platform == Platform.API_SERVER- or set(event.metadata) - {'gateway_session_key', 'gateway_session_id', 'automation_identities', 'turn_author'}):++ or set(event.metadata) - _AUTOMATION_METADATA++ or event.metadata.get('notification_category', 'diagnostic') != 'diagnostic'):+ raise RuntimeStoreError('invalid_params')+ entry = _owner(runner, event)+ if event.source.platform == Platform.LOCAL:+ return snapshot_local_automation(authority, adapter, event, identity, entry)+ from gateway.session_envelope import restore_native+ from hermes_state_runtime import list_session_admissions+ prior = list_session_admissions(authority.db, session_id=entry.session_id, pending_only=False)+ envelope = next((r['payload']['native_text_v1'] for r in reversed(prior)+ if 'native_text_v1' in r['payload']), None)+ if envelope is None or 'provenance' not in envelope:+ raise RuntimeStoreError('not_found')+ # Persisted origins deliberately omit relay trust. Borrow only an exact+ # committed source's private proof, revalidated against the live connector.+ restored = restore_native({'text': event.text, 'native_text_v1': envelope}, runner)+ if (restored.source.to_dict() != event.source.to_dict()+ or runner._adapter_for_source(restored.source) is not adapter):+ raise RuntimeStoreError('admission_conflict')+ provenance = deepcopy(envelope['provenance'])+ source = deepcopy(envelope['source'])+ # Producer timestamps and platform reply IDs change on retry. Neither belongs+ # in the identity/fingerprint of the same immutable completion.+ envelope = {'source': source, 'route': entry.session_key,+ 'timestamp': datetime.fromtimestamp(0, timezone.utc).isoformat(),+ 'event': {'message_id': identity}, 'provenance': provenance,+ 'automation': {'identity': identity, 'owner': entry.session_id}}+ if getattr(event, '_heartbeat_session_id', None):+ envelope['automation']['heartbeat'] = event._heartbeat_session_id+ identities = event.metadata.get('automation_identities')+ if identities:+ envelope['automation']['identities'] = sorted(set(identities))++ if event.metadata.get('notification_category'):++ envelope['automation']['notification_category'] = 'diagnostic'+ return {'text': event.text, 'native_text_v1': envelope}, entry+++def check_automation_route(runner, payload, session_id, available_source, adapter):+ from gateway.session_envelope import restore_native+ event = restore_native(payload, runner)+ envelope = payload['native_text_v1']+ entry = _owner(runner, event)+ if (entry.session_id != session_id or envelope['automation']['owner'] != session_id+ or runner.session_store._generate_session_key(available_source) != entry.session_key+ or adapter is None or runner._adapter_for_source(event.source) is not adapter):+ raise RuntimeStoreError('admission_conflict')+ return event.source, entry.session_key+++def snapshot_local_automation(authority, adapter, event, identity, entry):+ from gateway.session_local_recovery import restore_local_session+ ref = restore_local_session(authority, event.source.chat_id)+ live = authority.sessions[ref.session_id]+ if (live.source is not event.source or not adapter.authorize_source(event.source)+ or authority.runner._adapter_for_source(live.source) is not adapter):+ raise RuntimeStoreError('permission_denied')+ descriptor = {'identity': identity, 'owner': ref.session_id,+ 'route': entry.session_key, 'target': entry.session_id}+ if event.metadata.get('turn_author') is not None:+ from agent.turn_author import parse_turn_author+ descriptor['turn_author'] = parse_turn_author(event.metadata['turn_author'])+ if descriptor['turn_author'] is None:+ raise RuntimeStoreError('invalid_params')+ if event.metadata.get('automation_identities'):+ descriptor['identities'] = sorted(set(event.metadata['automation_identities']))+ if getattr(event, '_heartbeat_session_id', None):+ descriptor['heartbeat'] = event._heartbeat_session_id++ if event.metadata.get('notification_category'):++ descriptor['notification_category'] = 'diagnostic'+ return {'text': event.text, 'local_automation_v1': descriptor}, entry+++def check_local_automation(authority, ref, row):+ live = authority.sessions[ref.session_id]+ payload = row['payload']+ descriptor = payload['local_automation_v1']+ if (set(payload) != {'text', 'local_automation_v1'}+ or row['principal_id'] != 'automation:' + live.route+ or descriptor['owner'] != ref.session_id or descriptor['route'] != live.route+ or descriptor['identity'] != row['request_id']):+ raise RuntimeStoreError('permission_denied')+ entry = authority.runner.session_store.lookup_by_session_key(live.route)+ if (entry is None or entry.suspended or (entry.session_id != descriptor['target']+ and authority.db.get_compression_tip(descriptor['target']) != entry.session_id)):+ raise RuntimeStoreError('admission_conflict')+++def restore_local_automation(authority, ref, row):+ check_local_automation(authority, ref, row)+ live = authority.sessions[ref.session_id]+ descriptor = row['payload']['local_automation_v1']+ entry = authority.runner.session_store.lookup_by_session_key(live.route)+ event = MessageEvent(text=row['payload']['text'], source=live.source, internal=True,+ message_id=descriptor['identity'], metadata={'gateway_session_key': live.route,+ 'gateway_session_id': entry.session_id})+ if descriptor.get('turn_author') is not None:+ event.metadata['turn_author'] = deepcopy(descriptor['turn_author'])+ if descriptor.get('heartbeat'):+ event._heartbeat_session_id = descriptor['heartbeat']++ if descriptor.get('notification_category') == 'diagnostic':++ event.metadata['notification_category'] = 'diagnostic'+ return event+++async def admit_automation(authority, adapter, event, identity):+ authority._require_admission_open()+ payload, entry = snapshot_automation(authority, adapter, event, identity)+ from gateway.session_authority import LiveSession+ sid = payload.get('local_automation_v1', {}).get('owner', entry.session_id)+ ref = SessionRef(authority.profile_id, sid)+ authority.sessions.setdefault(ref.session_id, LiveSession(event.source, entry.session_key))+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id='automation:' + entry.session_key,+ session_id=ref.session_id, request_id=identity, payload=deepcopy(payload))+ event._gateway_accepted = True+ authority._publish_pending(ref)+ authority._schedule(ref)+ return authority._receipt(row)diff --cc gateway/session_envelope.pyindex 58d6d937551,00000000000..0cc27fb85e7mode 100644,000000..100644--- a/gateway/session_envelope.py+++ b/gateway/session_envelope.py@@@ -1,184 -1,0 +1,186 @@@+"""Owner-only durable native input codec; never a client-supplied wire format.++Ordinary context and local media are retained without serializing delegated trust.+Multiplex callbacks bind current connector ownership; roles require fresh preflight.+Relay snapshots bind the authenticated connector and exact source; replay rechecks both.+"""+from copy import copy, deepcopy+from datetime import datetime++from gateway.platforms.event import MessageEvent, MessageType+from gateway.session import SessionSource+from gateway.session_ingress_media import capture_native_media, restore_native_media+from hermes_state_runtime import RuntimeStoreError++_EVENT_FIELDS = (+ 'user_id', 'user_name', 'message_id', 'platform_update_id',+ 'reply_to_message_id', 'reply_to_text', 'reply_to_author_id',+ 'reply_to_author_name', 'reply_to_is_own_message', 'allow_gateway_control',+)+_CONTEXT_FIELDS = ('auto_skill', 'channel_prompt', 'channel_context')+++def _validate_native(runner, event, provenance=None, fresh_roles=False):+ source = event.source+ if (source is None or not isinstance(event.text, str)+ or not isinstance(event.message_type, MessageType)+ or event.message_type == MessageType.COMMAND or event.is_command()+ or event.internal or event.metadata or event.prompt_response+ or (source.role_authorized and not fresh_roles)+ or (source.delivered_via_upstream_relay and not (provenance and 'relay' in provenance))+ or source.profile_route_rejected+ or (getattr(source, '_authorization_profile_home', None) is not None and provenance is None)+ or (getattr(runner.config, 'multiplex_profiles', False) and provenance is None)):+ raise RuntimeStoreError('invalid_params')+ if provenance is not None:+ from gateway.session_ingress_context import restore_provenance+ restore_provenance(runner, source, provenance)+ delegated = fresh_roles or bool(provenance and 'relay' in provenance)+ if not runner._is_user_authorized_for_source(source, allow_adapter_delegation=delegated):+ raise RuntimeStoreError('permission_denied')+ if any(value is not None and not isinstance(value, str)+ for value in (event.channel_prompt, event.channel_context)):+ raise RuntimeStoreError('invalid_params')+ skill = event.auto_skill+ if not (skill is None or isinstance(skill, str)+ or isinstance(skill, list) and all(isinstance(item, str) for item in skill)):+ raise RuntimeStoreError('invalid_params')+ if (not isinstance(event.media_urls, list) or not all(isinstance(item, str) for item in event.media_urls)+ or not isinstance(event.media_types, list) or not all(isinstance(item, str) for item in event.media_types)+ or not isinstance(event.media_text_inlined, list)+ or not all(item is None or type(item) is bool for item in event.media_text_inlined)+ or len(event.media_types) not in (0, len(event.media_urls))+ or len(event.media_text_inlined) not in (0, len(event.media_urls))):+ raise RuntimeStoreError('invalid_params')+ encoded_source = source.to_dict()+ encoded_source['is_bot'] = source.is_bot+ restored_source = SessionSource.from_dict(encoded_source)+ restored_source.is_bot = source.is_bot+ if provenance is not None:+ restore_provenance(runner, restored_source, provenance)+ adapter = runner._adapter_for_source(source)+ if adapter is None or runner._adapter_for_source(restored_source) is not adapter:+ raise RuntimeStoreError('not_found')+ return encoded_source+++def snapshot_native(runner, event):+ from gateway.session_ingress_context import capture_provenance+ provenance = capture_provenance(runner, event)+ return _snapshot_native(runner, event, provenance)+++async def prepare_native(runner, event):+ from dataclasses import replace+ from gateway.session_ingress_context import capture_provenance, reauthorize_roles+ provenance = capture_provenance(runner, event)+ # Freeze caller-owned identity and content before the first network yield.+ # Preserve dynamic trust fields too: validation must reject forged ones,+ # not silently discard them while freezing the caller's source identity.+ frozen = replace(event, source=copy(event.source))+ fresh_roles = await reauthorize_roles(runner, frozen.source, provenance)+ return _snapshot_native(runner, frozen, provenance, fresh_roles)+++def _snapshot_native(runner, event, provenance, fresh_roles=False):+ encoded_source = _validate_native(runner, event, provenance, fresh_roles)+ envelope = {'source': encoded_source,+ 'route': runner.session_store._generate_session_key(event.source),+ 'event': deepcopy({name: getattr(event, name) for name in _EVENT_FIELDS}),+ 'timestamp': event.timestamp.isoformat()}+ if event.source.platform.value == 'webhook':+ from gateway.platforms.webhook_delivery import route_digest, snapshot_destination+ adapter = runner._adapter_for_source(event.source)+ if provenance is None:+ raise RuntimeStoreError('permission_denied')+ delivery = snapshot_destination(adapter, adapter._delivery_info.get(event.source.chat_id))+ envelope['webhook_delivery'] = delivery+ envelope['webhook_route'] = route_digest(adapter, event.source.chat_id)+ if event.source.role_authorized:+ envelope['reauthorize'] = 'roles'+ if provenance is not None:+ envelope['provenance'] = provenance+ # Omit new defaults so an identical retry of an older text admission retains+ # its fingerprint. Explicit context (including an empty skill list) is exact.+ envelope['event'].update({name: deepcopy(getattr(event, name)) for name in _CONTEXT_FIELDS+ if getattr(event, name) is not None})+ if event.message_type != MessageType.TEXT:+ envelope['message_type'] = event.message_type.value+ if event.media_urls:+ envelope['media'] = capture_native_media(event.media_urls)+ envelope['event'].update(media_types=list(event.media_types),+ media_text_inlined=list(event.media_text_inlined))+ # Keep the private dispatch key so previously committed text-only rows recover+ # under the same authority; optional media/context fields extend that envelope.+ payload = {'text': event.text, 'native_text_v1': envelope}+ # Only an exact persisted legacy retry retains its old fingerprint. New+ # ordinary admissions must bind homes too, including execution after restart.+ if provenance is not None and not getattr(runner.config, 'multiplex_profiles', False):+ from hermes_state_runtime import list_session_admissions+ from gateway.session_authorities import active_authority+ authority = active_authority(runner)+ entry = runner.session_store.lookup_by_session_key(envelope['route'])+ if entry is not None:+ legacy = deepcopy(payload)+ legacy['native_text_v1'].pop('provenance')+ for row in list_session_admissions(authority.db, session_id=entry.session_id, pending_only=False):+ if row['request_id'] == event.message_id and row['payload'] == legacy:+ return legacy+ return payload+++def restore_native(payload, runner=None):+ envelope = payload['native_text_v1']+ source = SessionSource.from_dict(envelope['source'])+ source.is_bot = envelope['source']['is_bot']+ # Private descriptor requests a fresh check, never supplies the verdict.+ source.role_authorized = envelope.get('reauthorize') == 'roles'+ if 'provenance' in envelope:+ from gateway.session_ingress_context import callback_runner, restore_provenance+ runner = runner or callback_runner()+ if runner is not None:+ restore_provenance(runner, source, envelope['provenance'])+ event = MessageEvent(text=payload['text'], source=source,+ timestamp=datetime.fromisoformat(envelope['timestamp']),+ message_type=MessageType(envelope.get('message_type', 'text')),+ media_urls=restore_native_media(envelope.get('media', [])),+ **deepcopy(envelope['event']))+ if 'automation' in envelope:+ event.internal = True+ if envelope['automation'].get('heartbeat'):+ event._heartbeat_session_id = envelope['automation']['heartbeat']+ event.metadata = {'gateway_session_key': envelope['route'],+ 'gateway_session_id': envelope['automation']['owner']}++ if envelope['automation'].get('notification_category') == 'diagnostic':++ event.metadata['notification_category'] = 'diagnostic'+ return event+++async def check_native_route(runner, payload, session_id, available_source, adapter):+ """Read-only preflight: route/auth rejection must never consume a queued row."""+ if 'automation' in payload['native_text_v1']:+ from gateway.session_automation import check_automation_route+ return check_automation_route(runner, payload, session_id, available_source, adapter)+ event = restore_native(payload, runner)+ # Validate the stored sender without recapturing files or trusting the binding caller.+ from gateway.session_ingress_context import reauthorize_roles+ provenance = payload['native_text_v1'].get('provenance')+ fresh_roles = await reauthorize_roles(runner, event.source, provenance)+ _validate_native(runner, event, provenance, fresh_roles)+ route = payload['native_text_v1']['route']+ store = runner.session_store+ if (store._generate_session_key(event.source) != route+ or store._generate_session_key(available_source) != route):+ raise RuntimeStoreError('admission_conflict')+ entry = store.lookup_by_session_key(route)+ if entry is None or entry.session_id != session_id:+ raise RuntimeStoreError('admission_conflict')+ if adapter is None or runner._adapter_for_source(event.source) is not adapter:+ raise RuntimeStoreError('not_found')+ if event.source.platform.value == 'webhook':+ from gateway.platforms.webhook_delivery import route_digest, validate_destination+ envelope = payload['native_text_v1']+ validate_destination(envelope.get('webhook_delivery'))+ if envelope.get('webhook_route') != route_digest(adapter, event.source.chat_id):+ raise RuntimeStoreError('admission_conflict')+ return event.source, routediff --cc gateway/session_group_controls.pyindex 7d3ef808d03,00000000000..d3df6be7899mode 100644,000000..100644--- a/gateway/session_group_controls.py+++ b/gateway/session_group_controls.py@@@ -1,320 -1,0 +1,320 @@@+"""Profile-owned room controls over the canonical hosted service."""+import asyncio+from pathlib import Path++from hermes_state_runtime import RuntimeStoreError+++GROUP_METHODS = {+ 'groups.capabilities': 'session:read',+ 'groups.list': 'session:read',+ 'groups.state': 'session:read',+ 'groups.log': 'session:read',+ 'groups.create': 'session:control',+ 'groups.rename': 'session:control',+ 'groups.disband': 'session:control',+ 'groups.send': 'session:submit',+ 'groups.attachment.upload': 'session:submit',+ 'groups.attachment.download': 'session:read',+ 'groups.stop': 'session:control',+ 'groups.retry': 'session:control',+ 'groups.discard': 'session:control',+ 'groups.approve': 'session:approve',+}+_FIELDS = {+ 'groups.capabilities': set(),+ 'groups.list': {'limit', 'offset', 'include_disbanded'},+ 'groups.state': {'room_id', 'include_disbanded'},+ 'groups.log': {'room_id', 'since_seq', 'limit', 'include_disbanded'},+ 'groups.create': {'room_id', 'name', 'members'},+ 'groups.rename': {'room_id', 'event_id', 'name'},+ 'groups.disband': {'room_id', 'cancel_id'},+ 'groups.send': {'room_id', 'event_id', 'payload'},+ 'groups.attachment.upload': {'room_id', 'upload_id', 'kind', 'name', 'mime', 'data_base64'},+ 'groups.attachment.download': {'room_id', 'event_id', 'attachment_id'},+ 'groups.stop': {'room_id', 'cancel_id'},+ 'groups.retry': {'room_id', 'member_id', 'task_id', 'execution_generation'},+ 'groups.discard': {'room_id', 'member_id', 'task_id', 'execution_generation'},+ 'groups.approve': {'room_id', 'member_id', 'task_id', 'execution_generation',+ 'choice', 'request_id'},+ 'profiles.list': {'include_sessions'},+}+++async def dispatch_group_control(connection, method, params):+ authority, actor = connection.authority, connection.actor+ capability = GROUP_METHODS.get(method, 'session:read')+ if capability not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ if actor.profile_id != authority.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if method not in _FIELDS or not isinstance(params, dict) or set(params) - (_FIELDS[method] | {'profile'}):+ raise RuntimeStoreError('invalid_params')+ home = Path(authority.profile_id)+ if Path(authority.db.db_path).resolve().parent != home.resolve():+ raise RuntimeStoreError('profile_mismatch')+ from hermes_cli.profiles import profile_matches_home+ profile = params.get('profile')+ if profile is not None and not isinstance(profile, str):+ raise RuntimeStoreError('invalid_params')+ if profile and not profile_matches_home(profile, home):+ raise RuntimeStoreError('profile_mismatch')+ supplied = {key: value for key, value in params.items() if key != 'profile'}++ def invoke():+ from gateway.run import _profile_runtime_scope+ from gateway.hosted_rooms import HostedRoomError+ with _profile_runtime_scope(home):+ if method == 'profiles.list':+ return _profiles(authority, actor, home, supplied)+ try:+ return _group(authority, actor, home, method, supplied)+ except RuntimeStoreError:+ raise+ except HostedRoomError as exc:+ raise RuntimeStoreError(getattr(exc, 'reason', None) or 'invalid_params') from exc+ except (ValueError, TypeError) as exc:+ raise RuntimeStoreError('invalid_params') from exc+ return await asyncio.to_thread(invoke)+++def _group(authority, actor, home, method, params):+ from gateway import hosted_rooms as rooms+ db_path = authority.db.db_path+ gateway_id = rooms.local_authority_gateway_id()+ service = getattr(authority, 'hosted_room_service', None)+ room_authorizer = getattr(service, 'authorize_room', None)+ if service is not None:+ if Path(service.db_path).resolve() != Path(db_path).resolve():+ raise RuntimeStoreError('profile_mismatch')+ status = service.runtime.status()+ if not status.get('running') or status.get('stopping'):+ service = None++ execution_methods = {'groups.send', 'groups.stop', 'groups.retry', 'groups.discard', 'groups.approve'}+ if getattr(authority, 'hosted_room_service', None) is not None and 'room_id' in params:+ if room_authorizer is None:+ raise RuntimeStoreError('permission_denied')+ room_authorizer(actor.subject, params['room_id'], create=method == 'groups.create')+ if method in {'groups.attachment.upload', 'groups.attachment.download'}:+ if service is None:+ raise RuntimeStoreError('runtime_coordination_required')+ from gateway.session_hosted_attachments import upload, download+ handler = upload if method == 'groups.attachment.upload' else download+ return handler(service, actor, params)+ if method in execution_methods:+ if service is None:+ raise RuntimeStoreError('runtime_coordination_required')+ if not params.get('room_id'):+ raise RuntimeStoreError('invalid_params')+ return _execution_control(service, method, params)++ def capabilities():+ return {'protocol_version': rooms.PROTOCOL_VERSION, 'driver': service is not None,+ 'persistent_process': True, 'authority_gateway_id': gateway_id,+ 'room_link': {'enabled': False, 'reason': 'canonical_driver_required'},+ 'features': ['room_identity', 'monotonic_log', 'replayable_disband'],+ 'methods': list(GROUP_METHODS), 'max_log_limit': rooms.MAX_LOG_LIMIT}++ def listing():+ limit, offset = params.get('limit', rooms.MAX_ROOM_LIST_LIMIT), params.get('offset', 0)+ result = rooms.list_rooms(db_path, **params)+ next_offset = offset + limit if len(result) == limit else None+ if getattr(authority, 'hosted_room_service', None) is not None:+ visible = []+ for room in result:+ if room_authorizer is None:+ raise RuntimeStoreError('permission_denied')+ try:+ room_authorizer(actor.subject, room['room_id'])+ except RuntimeStoreError as exc:+ if exc.reason != 'permission_denied':+ raise+ else:+ visible.append(room)+ result = visible+ return {'rooms': result, 'next_offset': next_offset}++ def create():+ if service is not None:+ return {'room': service.create_room(**params)}+ from gateway.hosted_room_discussion import validate_roster+ from gateway.session_authorities import served_profile_name+ name = served_profile_name(home)+ profiles = {name}+ if name == 'default' and (home / 'profiles').is_dir():+ profiles.update(path.name for path in (home / 'profiles').iterdir() if path.is_dir())+ members = validate_roster(params.get('members'), local_profiles=profiles)+ normalized = [{'member_id': m.member_id, 'profile': m.profile, 'handle': m.handle,+ 'target': dict(m.target or {}),+ **({'display_name': m.display_name} if m.display_name else {})} for m in members]+ return {'room': rooms.create_room(db_path, room_id=params.get('room_id'),+ name=params.get('name'), members=normalized, authority_gateway_id=gateway_id)}++ def disband():+ from gateway.hosted_room_driver import list_tasks+ state = rooms.room_state(db_path, room_id=params.get('room_id'), include_disbanded=True)+ if service is not None and state.get('disbanded_at') is None:+ service.stop_room(params.get('room_id'),+ cancel_id=params.get('cancel_id') or 'room-disbanded',+ require_acknowledged=True)+ service.revoke_room_routes(params.get('room_id'))+ # Metadata control must not destroy an active execution or bypass Stop.+ if service is None and any(list_tasks(db_path, room_id=params.get('room_id'), status=status)+ for status in ('queued', 'running', 'stopping', 'indeterminate', 'deferred')):+ raise RuntimeStoreError('runtime_coordination_required')+ state = rooms.room_state(db_path, room_id=params.get('room_id'), include_disbanded=True)+ return {'tombstone': rooms.disband_room(db_path, room_id=params.get('room_id'),+ expected_gateway_id=gateway_id, expected_epoch=state['authority_epoch'])}++ def state():+ room = rooms.room_state(db_path, **params)+ result = {'room': room}+ if service is not None and room.get('disbanded_at') is None:+ result['driver_status'] = service.status(room['room_id'])+ return result++ handlers = {+ 'groups.capabilities': capabilities,+ 'groups.list': listing,+ 'groups.create': create,+ 'groups.state': state,+ 'groups.log': lambda: rooms.read_events(db_path, **params),+ 'groups.rename': lambda: {'room': rooms.rename_room(db_path, **params)},+ 'groups.disband': disband,+ }+ return handlers[method]()+++def _execution_control(service, method, params):+ def send():+ from gateway.hosted_rooms import user_event_id+ event = service.send(room_id=params.get('room_id'),+ event_id=user_event_id(params.get('event_id')),+ payload=params.get('payload'))+ return {'event': event, 'client_event_id': params.get('event_id'),+ 'accepted': True, 'driver_started': True}++ def attempt_control():+ if (type(params.get('execution_generation')) is not int+ or params['execution_generation'] < 1+ or not params.get('member_id') or not params.get('task_id')):+ raise RuntimeStoreError('invalid_params')+ operation = service.discard_room_task if method == 'groups.discard' else service.retry_room_task+ task = operation(**params)+ identity = task['identity']+ receipt = {field: getattr(identity, field) for field in+ ('room_id', 'task_id', 'thread_id', 'turn_id')}+ receipt.update({field: task[field] for field in+ ('status', 'execution_generation', 'cancel_generation')})+ return {'discarded' if method == 'groups.discard' else 'retried': True, 'task': receipt}++ def approve():+ if (type(params.get('execution_generation')) is not int+ or params['execution_generation'] < 1+ or params.get('choice') not in {'once', 'deny'}+ or not isinstance(params.get('request_id'), str) or not params['request_id']):+ raise RuntimeStoreError('invalid_params')+ return {'approved': True, 'result': service.approve_room_task(**params)}++ handlers = {+ 'groups.send': send,+ 'groups.stop': lambda: {'cancelled': service.stop_room(+ params.get('room_id'), cancel_id=params.get('cancel_id') or 'desktop-stop')},+ 'groups.retry': attempt_control,+ 'groups.discard': attempt_control,+ 'groups.approve': approve,+ }+ return handlers[method]()+++def _profiles(authority, actor, home, params):+ from hermes_cli.profiles import _profile_info, read_profile_meta- import yaml++ import hermes_yaml as yaml+ include_sessions = params.get('include_sessions', True)+ if type(include_sessions) is not bool:+ raise RuntimeStoreError('invalid_params')+ from gateway.session_authorities import served_profile_name+ name = served_profile_name(home)+ profile = _profile_info(name, home, is_default=name == 'default')+ row = {'name': name, 'path': str(home), 'is_default': profile.is_default,+ 'model': profile.model, 'provider': profile.provider,+ 'description': profile.description or '', 'display_name': profile.display_name or '',+ 'skill_count': profile.skill_count or 0}+ path = home / 'profile.yaml'+ meta = yaml.safe_load(path.read_text(encoding='utf-8')) if path.is_file() else {}+ meta = meta if isinstance(meta, dict) else {}+ revisions = meta.get('_ui_meta_revisions')+ row['ui_meta_revisions'] = {str(k): max(0, v) for k, v in revisions.items()+ if type(v) is int} if isinstance(revisions, dict) else {}+ if isinstance(meta.get('ui_meta'), dict):+ row['ui_meta'] = meta['ui_meta']+ row['has_avatar'] = any((home / 'assets' / f'avatar.{ext}').is_file() for ext in ('png', 'jpg', 'webp'))+ if include_sessions:+ row.update(last_session=None, worker_session=None, canonical_session=None)+ # Discovery is read-only: no legacy restore/unarchive or new SessionDB handle.+ def summary(session):+ tip = authority.db.get_compression_tip(session['id']) or session['id']+ target = authority.db.get_session(tip) or session+ with authority.db._lock:+ message = authority.db._conn.execute(+ "SELECT content FROM messages WHERE session_id=? AND active=1 "+ "AND role IN ('user','assistant') AND TRIM(COALESCE(content,''))!='' "+ "ORDER BY id DESC LIMIT 1", (tip,)).fetchone()+ text = ' '.join(str(message[0] or '').split()) if message else ''+ return {'id': session['id'], 'resolved_id': tip, 'title': target.get('title') or '',+ 'root_title': session.get('title') or '',+ 'preview': text[:80] + '...' if len(text) > 80 else text,+ 'started_at': target.get('started_at') or 0,+ 'last_active': target.get('last_activity_at') or target.get('started_at') or 0,+ 'message_count': target.get('message_count') or 0}++ # The named registry is not a recency window and canonical chats are hidden.+ canonical = authority.db.get_session_by_title('Bot Chat')+ if (canonical and (canonical.get('user_id') == actor.subject+ or 'session:operator' in actor.capabilities)+ and str(canonical.get('chat_id') or '').startswith('local-') and not canonical.get('archived')):+ row['canonical_session'] = summary(canonical)+ if 'session:operator' in actor.capabilities:+ owner_filter, owner_params = '', ()+ else:+ owner_filter, owner_params = 'user_id=? AND ', (actor.subject,)+ with authority.db._lock:+ latest = authority.db._conn.execute(+ f"SELECT id FROM sessions WHERE {owner_filter}chat_id LIKE 'local-%' AND archived=0 "+ "ORDER BY COALESCE(last_activity_at,started_at) DESC LIMIT 1",+ owner_params).fetchone()+ if latest:+ row['last_session'] = summary(authority.db.get_session(latest[0]))+ profiles = [row]+ seen = {home.resolve()}++ def discovered(configured, target):+ # Discovery metadata only: never a licence to read another owner's state/configuration.+ if target.resolve() in seen:+ return+ seen.add(target.resolve())+ entry = {'name': configured, 'path': str(target), 'is_default': configured == 'default',+ 'model': '', 'provider': '', 'description': '', 'display_name': configured,+ 'skill_count': 0}+ meta_path = target / 'profile.yaml'+ try:+ meta = yaml.safe_load(meta_path.read_text(encoding='utf-8')) if meta_path.is_file() else {}+ except (OSError, yaml.YAMLError):+ meta = {}+ if isinstance(meta, dict):+ entry['display_name'] = str(meta.get('display_name') or configured)+ if isinstance(meta.get('ui_meta'), dict):+ entry['ui_meta'] = meta['ui_meta']+ profiles.append(entry)++ # Sibling profiles this process multiplexes: the roster lists them with the same+ # standing as a hosted-room destination, and the client routes their sessions by name.+ registry = getattr(getattr(authority, 'runner', None), 'session_authorities', None)+ for sibling in (registry or ()):+ discovered(served_profile_name(Path(sibling.profile_id)), Path(sibling.profile_id))+ service = getattr(authority, 'hosted_room_service', None)+ if service is not None:+ for configured, target in service.profile_homes().items():+ discovered(configured, target)+ return {'profiles': profiles, 'bot_mode_protocol': True}diff --cc gateway/session_policy.pyindex 2ab9d5be9da,00000000000..89a774fe71amode 100644,000000..100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@@ -1,301 -1,0 +1,307 @@@+"""Frozen, explicit local-client launch policy for the existing TurnRunner."""+from contextlib import contextmanager+from dataclasses import dataclass+import json+from pathlib import Path++from hermes_state_runtime import RuntimeStoreError++CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',+ 'provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor',+ 'yolo', 'safe_mode', 'ignore_user_config'})+BYPASS_FIELDS = ('safe_mode', 'ignore_user_config')+SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp'}+++@dataclass(frozen=True)+class LocalSessionPolicy:+ source: str+ platform: str+ cwd: str+ model: str | None+ toolsets: tuple[str, ...]+ config_json: str+ request_json: str+ terminal_json: str+ credential_ref: str | None = None+ config_secret_ref: str | None = None+ editor_mcp_json: str | None = None+ kanban_json: str | None = None+ # Troubleshooting isolation is derived by the owner at creation and frozen with the+ # route; safe_mode always implies ignore_user_config (normalized once in build_policy).+ safe_mode: bool = False+ ignore_user_config: bool = False++ def config(self, authority=None):+ config = json.loads(self.config_json)+ if self.config_secret_ref is not None and authority is not None:+ from gateway.session_policy_credentials import recover_config_secrets+ secrets = recover_config_secrets(authority, self)+ for path, value in secrets.items():+ if path[0] is None: # private terminal projection, not config+ continue+ target = config+ for key in path[:-1]:+ target = target[key]+ target[path[-1]] = value+ return config++ @property+ def provider(self):+ return self.config().get('model', {}).get('provider')++ @property+ def base_url(self):+ return self.config().get('model', {}).get('base_url')++ @property+ def ignore_rules(self):+ return self.safe_mode or json.loads(self.request_json).get('ignore_rules', False)++ @property+ def yolo(self):+ """`hermes chat --yolo`: this session's dangerous-command approvals are bypassed, exactly the+ scope `/yolo` gives a messaging chat; never the process-wide HERMES_YOLO_MODE."""+ return json.loads(self.request_json).get('yolo', False)++ @property+ def max_turns(self):+ from hermes_cli.config import resolve_turn_limit+ cfg = self.config()+ return resolve_turn_limit(cfg.get('agent', {}).get('max_turns', cfg.get('max_turns')))++ @property+ def reasoning_config(self):+ from hermes_constants import resolve_reasoning_config+ return resolve_reasoning_config(self.config(), self.model or '')+++def build_policy(params, config, *, private_secrets=None, profile_terminal=True):+ from hermes_cli.tools_config import _get_platform_tools+ from toolsets import validate_toolset+ from agent.runtime_cwd import resolve_agent_cwd+ from tools.terminal_scope import build_profile_terminal_scope, default_terminal_scope+ from hermes_constants import get_hermes_home++ source = params.get('source', 'cli')+ if source == 'a2a':+ from gateway.session_a2a import build_forward_policy+ return build_forward_policy(params, config, private_secrets=private_secrets)+ if set(params) - CREATE_FIELDS or not isinstance(source, str) or source not in SURFACES:+ raise RuntimeStoreError('invalid_params')+ if any(name in params and type(params[name]) is not bool for name in BYPASS_FIELDS):+ raise RuntimeStoreError('invalid_params')+ safe_mode = params.get('safe_mode', False)+ ignore_user_config = safe_mode or params.get('ignore_user_config', False)+ if 'api_key' in params and (not isinstance(params['api_key'], str) or not params['api_key'].strip()):+ raise RuntimeStoreError('invalid_params')+ model = params.get('model')+ if 'model' in params and (not isinstance(model, str) or not model.strip()):+ raise RuntimeStoreError('invalid_params')+ cwd = params.get('cwd', str(resolve_agent_cwd()))+ if not isinstance(cwd, str) or not Path(cwd).is_absolute() or not Path(cwd).is_dir():+ raise RuntimeStoreError('invalid_params')+ from gateway.session_local_editor import validate_editor+ validate_editor(source, params.get('editor'))+ config = json.loads(json.dumps(config))+ from urllib.parse import urlsplit+ from hermes_constants import parse_reasoning_effort+ for key in ('provider', 'base_url'):+ if key in params:+ value = params[key]+ if not isinstance(value, str) or not value.strip():+ raise RuntimeStoreError('invalid_params')+ if key == 'base_url':+ url = urlsplit(value)+ if (url.scheme not in {'http', 'https'} or not url.hostname+ or url.username or url.password or url.query or url.fragment):+ raise RuntimeStoreError('invalid_params')+ config.setdefault('model', {})[key] = value+ for flag in ('ignore_rules', 'yolo'):+ if flag in params and type(params[flag]) is not bool:+ raise RuntimeStoreError('invalid_params')+ if 'max_turns' in params:+ value = params['max_turns']+ if type(value) is not int or value <= 0:+ raise RuntimeStoreError('invalid_params')+ config.setdefault('agent', {})['max_turns'] = value+ if 'reasoning' in params:+ if not isinstance(params['reasoning'], str) or parse_reasoning_effort(params['reasoning']) is None:+ raise RuntimeStoreError('invalid_params')+ config.setdefault('agent', {})['reasoning_effort'] = params['reasoning']+ # An explicit launch level wins over a per-model default, just like CLI.+ config['agent'].pop('reasoning_overrides', None)+ explicit = params.get('toolsets')+ if 'toolsets' in params:+ if (not isinstance(explicit, list) or any(not isinstance(x, str) or not validate_toolset(x) for x in explicit)+ or ('desktop_ui' in explicit and source != 'gui')):+ raise RuntimeStoreError('invalid_params')+ config.setdefault('platform_toolsets', {})['acp' if source == 'acp' else 'cli'] = explicit+ enabled = _get_platform_tools(config, 'acp' if source == 'acp' else 'cli')+ if explicit is not None:+ from toolsets import resolve_toolset+ requested = {t for name in explicit for t in resolve_toolset(name)}+ effective = {t for name in enabled for t in resolve_toolset(name)}+ if not requested <= effective:+ raise RuntimeStoreError('invalid_params')+ elif source in {'tui', 'gui'}:+ # Same surface toolsets as the native TUI factory, without its env inference.- enabled.add('project')++ # The fold-in lands after _get_platform_tools subtracted agent.disabled_toolsets, so++ # subtract again or `disabled_toolsets: [project]` is a no-op here (#54433).++ # desktop_ui is the client's own control surface, not a model toolset.++ from agent.skill_utils import parse_config_string_list++ disabled = set(parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')))++ if 'project' not in disabled:++ enabled.add('project')+ if source == 'gui':+ enabled.add('desktop_ui')+ if safe_mode:+ # Plugin toolsets are user customizations; the safe worker never imports them.+ from hermes_cli.tools_config import _get_plugin_toolset_keys+ enabled -= _get_plugin_toolset_keys()+ terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()+ terminal['TERMINAL_CWD'] = cwd+ request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key'}}+ request.setdefault('source', 'cli')+ from gateway.session_local_mcp import private_editor_request+ private_editor_request(request, private_secrets)+ _extract_config_secrets(config, private_secrets)+ _extract_config_secrets(terminal, private_secrets, (None,))+ return LocalSessionPolicy(source, SURFACES[source], cwd, model, tuple(sorted(enabled)),+ json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal),+ safe_mode=safe_mode, ignore_user_config=ignore_user_config)+++def _extract_config_secrets(value, private, path=()):+ # Reuse the configuration owner's structural classification; opaque keys need+ # not match a vendor prefix. Only the authority keeps their original values.+ from hermes_cli.config import _SECRET_CONFIG_KEYS+ from agent.credential_persistence import _is_secret_payload_key+ containers = {'env', 'headers', 'extra_headers', 'docker_env', 'docker_extra_args',+ 'terminal_docker_env', 'terminal_docker_extra_args'}+ items = value.items() if isinstance(value, dict) else enumerate(value) if isinstance(value, list) else ()+ for key, child in items:+ child_path = path + (key,)+ sensitive = isinstance(key, str) and (key.lower() in _SECRET_CONFIG_KEYS+ or key.lower() in containers or _is_secret_payload_key(key))+ if sensitive and child and child not in ('{}', '[]'):+ if private is None:+ raise RuntimeStoreError('launch_credentials_unavailable')+ private[child_path] = child+ value[key] = None+ else:+ _extract_config_secrets(child, private, child_path)+++def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None):+ """CLI keys live only in this authority lifetime, never its durable receipt.++ Restart deliberately revokes them. History remains readable; inference must+ report launch_credentials_unavailable, never select a profile fallback key.+ """+ from dataclasses import replace+ import hmac+ from gateway.session_local_mcp import PRIVATE_KEY, bind_editor_mcp+ config_secrets = dict(config_secrets or {})+ policy = bind_editor_mcp(authority, session_id, policy, config_secrets.pop(PRIVATE_KEY, None))+ if api_key is None and not config_secrets:+ return policy+ keys = getattr(authority, '_local_launch_keys', None)+ if keys is None:+ keys = authority._local_launch_keys = {}+ ref = f'{authority.instance_id}:{authority.epoch}:{session_id}'+ old = keys.get(ref)+ if old is not None and (api_key is None or not hmac.compare_digest(old, api_key)):+ raise RuntimeStoreError('admission_conflict')+ configs = getattr(authority, '_local_config_secrets', None)+ if configs is None:+ configs = authority._local_config_secrets = {}+ config_ref = ref+ if config_secrets and getattr(authority, 'db', None) is not None:+ from gateway.session_policy_credentials import config_reference+ config_ref = config_reference(authority, session_id, policy, config_secrets)+ if config_ref in configs and configs[config_ref] != config_secrets:+ raise RuntimeStoreError('admission_conflict')+ if config_secrets:+ configs[config_ref] = dict(config_secrets)+ if api_key is not None:+ keys[ref] = api_key+ return replace(policy, credential_ref=ref if api_key is not None else None,+ config_secret_ref=config_ref if config_secrets else None)+++def launch_key(authority, policy):+ if policy.credential_ref is None:+ return None+ value = getattr(authority, '_local_launch_keys', {}).get(policy.credential_ref)+ if value is None:+ raise RuntimeStoreError('launch_credentials_unavailable')+ return value+++def restore_policy(data):+ """Reject incomplete private policy rather than rebuilding from current defaults."""+ try:+ policy = LocalSessionPolicy(**data)+ from gateway.session_a2a import is_forward_policy+ surfaces = {**SURFACES, 'cron': 'cron', 'kanban': 'cli', 'bot_room': 'bot_room'}+ if ((not is_forward_policy(policy) and+ (policy.source not in surfaces or policy.platform != surfaces[policy.source]))+ or not isinstance(policy.cwd, str) or not Path(policy.cwd).is_absolute()+ or not Path(policy.cwd).is_dir()+ or not isinstance(policy.model, str) or not policy.model.strip()+ or not isinstance(policy.toolsets, (list, tuple))+ or any(not isinstance(name, str) for name in policy.toolsets)+ or type(policy.safe_mode) is not bool or type(policy.ignore_user_config) is not bool+ or (policy.safe_mode and not policy.ignore_user_config)):+ raise ValueError('invalid policy')+ from dataclasses import replace+ for value in (policy.config_json, policy.request_json, policy.terminal_json):+ if not isinstance(json.loads(value), dict):+ raise ValueError('invalid policy object')+ if json.loads(policy.terminal_json).get('TERMINAL_CWD') != policy.cwd:+ raise ValueError('terminal policy mismatch')+ return replace(policy, toolsets=tuple(policy.toolsets))+ except (KeyError, TypeError, ValueError) as exc:+ raise RuntimeStoreError('storage_unavailable') from exc+++def policy_for_source(runner, source):+ from gateway.session_local import LocalSessionAdapter+ from gateway.config import Platform+ if source.platform != Platform.LOCAL:+ return None+ adapter = runner._adapter_for_source(source)+ if isinstance(adapter, LocalSessionAdapter) and adapter.authorize_source(source):+ policy = adapter.policies.get(source.chat_id)+ if policy is None:+ # Cold recovery must restore the frozen policy before executing, not+ # reinterpret a LOCAL route as a default CLI launch.+ raise RuntimeStoreError('storage_unavailable')+ return policy+ return None+++@contextmanager+def policy_scope(policy, *, authority=None):+ if policy is None:+ yield+ return+ from agent.runtime_cwd import set_session_cwd+ from tools.terminal_scope import set_terminal_scope, reset_terminal_scope+ terminal = json.loads(policy.terminal_json)+ if policy.config_secret_ref is not None:+ from gateway.session_policy_credentials import recover_config_secrets+ for path, value in recover_config_secrets(authority, policy).items():+ if path[0] is None:+ terminal[path[1]] = value+ cwd_token = set_session_cwd(policy.cwd)+ terminal_token = set_terminal_scope(terminal)+ from gateway.session_local_editor import editor_scope+ try:+ from gateway.session_local_mcp import editor_mcp_scope+ with editor_scope(policy), editor_mcp_scope(authority, policy):+ yield+ finally:+ reset_terminal_scope(terminal_token)+ cwd_token.var.reset(cwd_token)diff --cc gateway/status.pyindex 55e1f56d36d,afab9838c8c..99aa0a81625--- a/gateway/status.py+++ b/gateway/status.py@@@ -518,18 -606,24 +606,29 @@@ def _gateway_command_subcommand(commandif not tokens:return Nonebasenames = [t.rsplit("/", 1)[-1] for t in tokens]+ # ``python -c <src> … -m hermes_cli.main gateway run``: the trailing argv belongs to the program+ # the inline source will spawn later, not to this process (#107002). Case-preserving tokens:+ # the operand-taking ``-X``/``-W``/``-Q`` must not be conflated with ``-q``/``-b``.+ if command_line_runs_inline_source(cased_tokens):+ return None# The launchd job's osascript wrapper (gateway_launchd.launchd_program_arguments) carries the gateway argv- # inside one AppleScript string; the gateway itself is its child and is matched on its own command line.+ # inside one JXA script string; the gateway itself is its child and is matched on its own command line.if basenames[0] == "osascript":return None- # Gateway-dedicated entrypoints carry no subcommand to inspect.+ # Gateway-dedicated entrypoints carry no subcommand to inspect (``python -m gateway.run`` is the+ # module spelling of the same script: its PID record renders argv as ``gateway/run.py``, and a+ # liveness probe that read the live ``-m`` cmdline as "not a gateway" made every fixture-launched+ # standalone owner invisible to the multiplex preflight).if any(t == "gateway/run.py" or t.endswith("/gateway/run.py") for t in tokens):return "run"+ if any(tokens[i] == "-m" and tokens[i + 1] == "gateway.run" for i in range(len(tokens) - 1)):+ return "run"+ # Atomic Hermes' bundled desktop runner shares HERMES_HOME with the CLI; without this,+ # `gateway run --replace` does not recognise it as a running gateway, skips the+ # terminate-and-scoped-lock-handoff path, and collides with its still-held scoped locks+ # (e.g. the Discord bot-token lock). See #22418.+ if any(b == "desktop-gateway.py" for b in basenames):+ return "run"if any(b in ("hermes-gateway", "hermes-gateway.exe") for b in basenames):return "run"joined = " ".join(tokens)@@@ -1035,7 -1189,8 +1165,8 @@@ def _prepare_runtime_status_updateactive_agents: Any = _UNSET, active_work: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,error_code: Any = _UNSET, error_message: Any = _UNSET, needs_attention: Any = _UNSET,retrying_since: Any = _UNSET, served_profiles: Any = _UNSET, session_store: Any = _UNSET,- multiplex_standalone_reason: Any = _UNSET,+ parked_profiles: Any = _UNSET, multiplex_standalone_reason: Any = _UNSET,+ platform_metrics: Any = _UNSET,ingress_url: Any = _UNSET, listener_base: Any = _UNSET, clear_profile_platforms: bool = False,drop_profile_platforms: Optional[str] = None,load_existing: bool = True, reload_existing: bool = False,diff --cc hermes_cli/backup.pyindex b3e8c3585fa,5d6c0a73595..9f3bb97b587--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@@ -22,15 -22,32 +22,33 @@@ from hermes_constants importdisplay_hermes_home,)from hermes_state_dbfile import RETIRED_GENERATION_DIR_SUFFIX- from utils import (- _preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,- default_new_file_mode,- )+ from hermes_state_holders import read_only_db_uri+ from hermes_cli.archive_safe import normalize_archive_parts+ from hermes_cli.backup_sqlite import _close_quietly, _safe_copy_db+ from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS, profile_root_entryfrom hermes_cli.sizefmt import format_bytes as _format_size+ from hermes_cli.backup_restore import (+ _count_session_rows,+ _default_new_file_mode,+ _detect_prefix,+ _extract_member_atomically,+ _import_db_member,++ _restore_destination_epoch,+ _safe_restore_db,+ _validate_backup_zip,+ )+logger = logging.getLogger(__name__)++ def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:+ # Shim to stop the old updater doing work until relaunch. None means unknown,+ # not permission to restore over a database whose holders we did not scan.+ return None++# --- Exclusion rules ---# Where ``hermes backup --quick`` / ``/snapshot`` / the pre-update safety net write state@@@ -894,396 -684,329 +685,359 @@@ def _import_member_rel(member: str, prereturn rel, _import_skipped(rel)- def _detect_prefix(zf: zipfile.ZipFile) -> str:- """Detect if the zip has a common directory prefix wrapping all entries."""- names = [n for n in zf.namelist() if not n.endswith("/")]- first_parts = {Path(n).parts[0] for n in names if len(Path(n).parts) > 1}- if len(first_parts) == 1 and first_parts <= {".hermes", "hermes"}:- return first_parts.pop() + "/"- return ""+ def run_import(args) -> Optional[int]:+ """Restore a Hermes backup; return 1 on damaged archives or incomplete restores."""+ zip_path = Path(args.zipfile).expanduser().resolve()+ if not zip_path.is_file():+ print(f"Error: File not found: {zip_path}")+ sys.exit(1)- def _extract_member_atomically(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Restore one zip member onto *target* with no truncation window.+ if not zipfile.is_zipfile(zip_path):+ print(f"Error: Not a valid zip file: {zip_path}")+ sys.exit(1)- ``open(target, "wb")`` would truncate the user's file before any replacement bytes exist.- ``atomic_replace`` (not bare ``os.replace``) resolves a symlinked target first, so a- dotfiles-linked ``config.yaml`` keeps the link (#16743), and falls back to copy/fsync/unlink- on ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs.- """- # Mode is None when the target does not exist: the umask-derived create-mode applies.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- if mode is None:- mode = new_file_mode- else:- # Deliberately NOT a faithful copy: setuid/setgid are dropped. The bytes come from the- # archive, so carrying elevated bits would hand the zip's author the identity an existing- # setuid file runs as — and ``_external/`` publishes members anywhere under ``$HOME``.- mode &= ~(stat.S_ISUID | stat.S_ISGID)- # Truncate the stem: mkstemp adds ~16 chars and a member near NAME_MAX would otherwise fail.- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial")- try:- with os.fdopen(fd, "wb") as dst:- if mode is not None:- # Apply the mode BEFORE the replace so the target never transits through mkstemp's- # 0600 and the EXDEV/EBUSY ``copystat`` fallback copies the intended bits.- if hasattr(os, "fchmod"): # Unix-only; Windows takes the path-based chmod- os.fchmod(dst.fileno(), mode)- else:- os.chmod(tmp_name, mode)- # Stream: a multi-gigabyte state.db member must not be held in memory in one piece.- with zf.open(member) as src:- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- real_path = Path(atomic_replace(tmp_name, target))- # Owner first, mode second (as ``atomic_yaml_write``): chown drops setuid/setgid and- # ``mode`` no longer carries them, so neither step can re-elevate the restored file.- _restore_file_owner(real_path, owner)- _restore_file_mode(real_path, mode)- except BaseException:- with suppress(OSError):- os.unlink(tmp_name)- raise+ # The restore target must be the home the command operates under — the+ # same path printed as "Target:" via display_hermes_home(). Resolving+ # through get_default_hermes_root() instead maps a profile home+ # (<root>/profiles/<name>) back to <root>, silently retargeting the+ # restore at the live root while the profile directory stays empty.+ hermes_root = get_hermes_home()+ with zipfile.ZipFile(zip_path, "r") as zf:+ # Validate+ ok, reason = _validate_backup_zip(zf)+ if not ok:+ print(f"Error: {reason}")+ sys.exit(1)- def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:- """``(sessions, messages)`` in session database *path*; read-only, best effort.+ prefix = _detect_prefix(zf)+ members = [n for n in zf.namelist() if not n.endswith("/")]+ file_count = len(members)- ``None`` means "unknown" (missing, not a Hermes session store, unreadable) — never "zero":- acting on an unreadable database would mask the very loss this count exists to surface.- Same contract as :func:`_count_cron_jobs`.- """- if not path.is_file():- return None- try:- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)- except sqlite3.Error:- return None- try:- sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]- messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]- return int(sessions), int(messages)- except (sqlite3.Error, TypeError, ValueError):- return None- finally:- conn.close()+ print(f"Backup contains {file_count} files")+ print(f"Target: {display_hermes_home()}")+ if prefix:+ print(f"Detected archive prefix: {prefix!r} (will be stripped)")- def _import_db_member(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance- try:- with exclusive_maintenance([target.absolute().parent, target.resolve().parent]):- _import_db_member_exclusive(zf, member, target, new_file_mode)- except OwnershipConflict as exc:- raise OSError(str(exc)) from exc+ # Check for existing installation+ has_config = (hermes_root / "config.yaml").exists()+ has_env = (hermes_root / ".env").exists()+ if (has_config or has_env) and not args.force:+ print()+ print("Warning: Target directory already has Hermes configuration.")+ print("Importing will overwrite existing files with backup contents.")+ print()+ try:+ answer = input("Continue? [y/N] ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ print("\nAborted.")+ sys.exit(1)+ if answer not in {"y", "yes"}:+ print("Aborted.")+ return++ # Refuse damaged archives before writing any user files. Runtime and PM-local+ # members skipped below cannot block restoration of the portable data.+ print("\nChecking archive integrity ...")+ corrupt = _find_corrupt_members(zf, [m for m in members if not _import_member_rel(m, prefix)[1]])+ if corrupt:+ _print_capped(f"Error: backup archive is damaged ({len(corrupt)} member(s) fail to "+ f"decompress or fail their CRC); nothing was restored:", corrupt, " ")+ return 1- def _import_db_member_exclusive(- zf: zipfile.ZipFile, member: str, target: Path, new_file_mode: Optional[int] = None) -> None:- """Publish a SQLite ``.db`` member onto *target* without replacing its inode.+ # Extract+ print(f"\nImporting {file_count} files ...")+ hermes_root.mkdir(parents=True, exist_ok=True)- A rename-publish over a live database is the #65942 / #90950 corruption class: a gateway,- dashboard, or WebUI holding it open keeps serving the unlinked inode and writing sessions no- other process will see, and a sidecar WAL beside the new file describes the old database —- nothing fails, the sessions are simply gone (#100960). Route the member through the same- ``_safe_restore_db`` page copy ``/snapshot restore`` uses, so the live inode is preserved and- every open connection converges. Raises ``OSError`` when the database could not be- replaced safely, so the caller reports a skipped file instead of a silent success.- """- if not target.exists():- # "Missing" is not "unheld": a gateway or dashboard that had the database open when it- # was unlinked still writes the deleted inode (the ``(deleted)`` fingerprint of #90950).- # Publishing a fresh inode here re-creates the same split brain the branch below exists- # to prevent, so refuse and name the holders instead (#110179).- holders = _foreign_db_holder_pids(target)- if holders:- raise OSError(- f"{target.name} was deleted but is still open in PID(s) "- f"{', '.join(str(pid) for pid in sorted(holders))}; publishing a new file would "- "leave them writing an invisible database. Stop those processes and re-run the import."- errors = []- restored = 0- restored_external = 0- skipped_runtime: list[str] = []- # (rel, live_counts, imported_counts) for every session database the- # import replaced with one holding fewer rows. A restore is allowed to- # do that — it just must not do it silently (issue #100960).- db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []- home_dir = Path.home().resolve()- # Resolved once: every member is published via a temp file, and mkstemp- # would otherwise create newly restored files as 0600.- new_file_mode = _default_new_file_mode()+ t0 = time.monotonic()-- for member in members:- # External memory-provider state captured under the reserved- # ``_external/`` arc prefix restores to its original home-relative- # location (e.g. ~/.honcho/config.json), NOT under HERMES_HOME.- if member.startswith(_EXTERNAL_PREFIX):- ext_rel = member[len(_EXTERNAL_PREFIX):]- if not ext_rel:- continue- target = home_dir / ext_rel- # Security: the resolved target must stay under the home dir.- try:- target.resolve().relative_to(home_dir)- except ValueError:- errors.append(f" {member}: path traversal blocked")- continue- try:- target.parent.mkdir(parents=True, exist_ok=True)- _extract_member_atomically(zf, member, target, new_file_mode)- # External provider configs commonly hold credentials.- if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:- try:- os.chmod(target, 0o600)- except OSError:- pass- restored += 1- restored_external += 1- except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:- errors.append(f" {member}: {exc}")- if restored % 500 == 0:- print(f" {restored}/{file_count} files ...")- continue-- # Strip prefix if detected- if prefix and member.startswith(prefix):- rel = member[len(prefix):]- else:- rel = member-- if not rel:- continue-- try:- parts = tuple(normalize_archive_parts(rel))- except ValueError:- errors.append(f" {rel}: path traversal blocked")- continue-- # Never overwrite volatile gateway/process runtime state. These are- # namespaced to the machine/container the backup was taken on;- # clobbering them (especially gateway_state.json) breaks the gateway- # reconciler on the target and disconnects hosted instances from the- # Nous portal. Matched by basename so both the root profile and- # named profiles (profiles/<name>/gateway_state.json) are covered.- if parts[-1] in _IMPORT_SKIP_NAMES:- skipped_runtime.append(rel)- continue-- # Older archives may contain PM selections pointing at another machine.- # Match their home-root paths; a plugin's own facts.json is user data.- if profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS:- skipped_runtime.append(rel)- continue-- # A ``.db`` member is page-restored into the live file below; a- # WAL/SHM/journal member from the archive describes a different- # database image, and installing it beside the restored file (over- # a live sidecar, via os.replace) would replay a foreign WAL on- # the next open. Current backups never ship these- # (_EXCLUDED_SUFFIXES); older or hand-built archives might.- if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):- skipped_runtime.append(rel)- continue-- target = hermes_root.joinpath(*parts)-- # Security: reject absolute paths and traversals- try:- target.resolve().relative_to(hermes_root.resolve())- except ValueError:- errors.append(f" {rel}: path traversal blocked")- continue-- try:- target.parent.mkdir(parents=True, exist_ok=True)- if target.suffix == ".db":- # Count before the write: afterwards the rows this import- # drops are gone and there is nothing left to compare.- before = _count_session_rows(target)- _import_db_member(zf, member, target, new_file_mode)- after = _count_session_rows(target)- if before and after and after[1] < before[1]:- db_shrunk.append((rel, before, after))- else:- _extract_member_atomically(zf, member, target, new_file_mode)- if target.name in _SECRET_FILE_NAMES:- os.chmod(target, 0o600)- restored += 1- except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:- errors.append(f" {rel}: {exc}")-- if restored % 500 == 0:- print(f" {restored}/{file_count} files ...")-++ 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++ # Summary+ print()+ print(f"Import {'incomplete' if errors else 'complete'}: {restored} files restored in {elapsed:.1f}s")+ print(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()}.")- _extract_member_atomically(zf, member, target, new_file_mode)- return- # The database keeps its own mode/ownership: the bytes come from the archive, the file does not.- mode = _preserve_file_mode(target)- owner = _preserve_file_owner(target)- fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport")- try:- with os.fdopen(fd, "wb") as dst:- with zf.open(member) as src: # stream: never hold a multi-GB state.db in memory- shutil.copyfileobj(src, dst)- dst.flush()- os.fsync(dst.fileno())- if not _safe_restore_db(Path(tmp_name), target):- raise OSError(- "live-safe restore refused or failed; the existing database was "- "left untouched. Stop the gateway/dashboard processes holding it "- "open and re-run the import."++ if errors:+ print(f"\n Warnings ({len(errors)} files skipped):")+ for e in errors[:10]:+ print(e)+ if len(errors) > 10:+ print(f" ... and {len(errors) - 10} more")++ if db_shrunk:+ # The backup predates work that is now overwritten. Say so: the+ # reported incident was twelve sessions disappearing with nothing+ # logged anywhere (issue #100960).+ print("\n ⚠ Session data replaced by older backup contents:")+ for rel, before, after in db_shrunk:+ print(+ f" {rel}: {before[0]} session(s) / {before[1]} message(s)"+ f" -> {after[0]} / {after[1]}"+ )+ print(+ " Anything recorded after the backup was taken is not in it. "+ f"{_snapshot_recovery_hint()}")- _restore_file_owner(target, owner)- _restore_file_mode(target, mode)- finally:- with suppress(OSError):- os.unlink(tmp_name)+ if skipped_runtime:+ print(+ f"\n Preserved {len(skipped_runtime)} runtime state "+ f"file(s) (kept this machine's, not the backup's):"+ )+ for rel in sorted(skipped_runtime)[:10]:+ print(f" {rel}")+ if len(skipped_runtime) > 10:+ print(f" ... and {len(skipped_runtime) - 10} more")++ # Post-import: restore profile wrapper scripts+ profiles_dir = hermes_root / "profiles"+ restored_profiles = []+ if profiles_dir.is_dir():+ try:+ from hermes_cli.profiles import (+ create_wrapper_script, check_alias_collision,+ _is_wrapper_dir_in_path, _get_wrapper_dir,+ )+ for entry in sorted(profiles_dir.iterdir()):+ if not entry.is_dir():+ continue+ profile_name = entry.name+ # Only create wrappers for directories with config+ if not (entry / "config.yaml").exists() and not (entry / ".env").exists():+ continue+ collision = check_alias_collision(profile_name)+ if collision:+ print(f" Skipped alias '{profile_name}': {collision}")+ restored_profiles.append((profile_name, False))+ else:+ wrapper = create_wrapper_script(profile_name)+ restored_profiles.append((profile_name, wrapper is not None))++ if restored_profiles:+ created = [n for n, ok in restored_profiles if ok]+ skipped = [n for n, ok in restored_profiles if not ok]+ if created:+ print(f"\n Profile aliases restored: {', '.join(created)}")+ if skipped:+ print(f" Profile aliases skipped: {', '.join(skipped)}")+ if not _is_wrapper_dir_in_path():+ print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.")+ print(' Add to your shell config (~/.bashrc or ~/.zshrc):')+ print(' export PATH="$HOME/.local/bin:$PATH"')+ except ImportError:+ # hermes_cli.profiles might not be available (fresh install)+ if any(profiles_dir.iterdir()):+ print("\n Profiles detected but aliases could not be created.")+ print(" Run: hermes profile list (after installing hermes)")++ # Guidance+ print()+ if not (hermes_root / "hermes-agent").is_dir():+ print("Note: The hermes-agent codebase was not included in the backup.")+ print(" If this is a fresh install, run: hermes update")- def _confirm_import_overwrite(hermes_root: Path) -> bool:- """Prompt before importing over an existing installation; True when import may proceed."""- if not any((hermes_root / m).exists() for m in ("config.yaml", ".env")):- return True- print("\nWarning: Target directory already has Hermes configuration.\n"- "Importing will overwrite existing files with backup contents.\n")- try:- answer = input("Continue? [y/N] ").strip().lower()- except (EOFError, KeyboardInterrupt):- print("\nAborted.")- sys.exit(1)- if answer in {"y", "yes"}:- return True- print("Aborted.")- return False+ if restored_profiles:+ gw_profiles = [n for n, _ in restored_profiles]+ print("\nTo re-enable gateway services for profiles:")+ for pname in gw_profiles:+ print(f" hermes -p {pname} gateway install")+- # Bring the restored install to life: the backup may contain bot- # tokens and registered cron jobs, but they're inert without a- # gateway process. Install/start the service automatically (a- # platform-less gateway is a supported mode, so this is safe even- # for backups with no messaging config). Best-effort and prompt-free;- # failures print a manual fallback and never fail the import.- native_default = _get_platform_default_hermes_home()- default_has_install = any(- (native_default / marker).exists()- for marker in ("config.yaml", ".env", "state.db")- )- # A restore into a sandbox or profile home must not silently install- # a second gateway pointed at it — on the default service name that- # would shadow or hijack the machine's primary install. Only revive- # the service automatically when the restore landed in the default- # home, or when no other install exists on this machine.- if hermes_root != native_default and default_has_install:- print(- "\nRestored into a non-default home; leaving the gateway service "- "alone to avoid clashing with the install at "- f"{native_default}."- )- print("To start a gateway for this home, run: hermes gateway install")- else:- try:- from hermes_cli.gateway import ensure_gateway_service, _is_service_running-- if not _is_service_running():- print()- ensure_gateway_service(context="import")- except Exception:- print("\nStart the gateway to activate cron jobs and messaging:")- print(" hermes gateway install")++ _revive_gateway_after_import(hermes_root)++ if errors:+ print(f"Import incomplete: {len(errors)} file(s) were not restored (see Warnings above). "+ "Fix the cause and re-run the import.")+ return 1+ print("Done. Your Hermes configuration has been restored.")+def _import_members(+ zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int+) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:+ """Reserve all affected profiles before publishing even the first config file."""+ from gateway.runtime_ownership import exclusive_maintenance++ root_res = hermes_root.resolve()+ homes = {hermes_root}+ for member in members:++ if member.startswith(_EXTERNAL_PREFIX):++ continue # restored under $HOME, outside every runtime authority+ rel = member[len(prefix):] if prefix and member.startswith(prefix) else member+ parts = Path(rel).parts- if len(parts) >= 3 and parts[0] == 'profiles':++ if len(parts) >= 3 and parts[0] == "profiles":+ home = hermes_root / parts[0] / parts[1]- if _is_within(home, hermes_root.resolve()):++ if home.resolve().is_relative_to(root_res):+ homes.add(home)+ target = hermes_root / rel- if target.suffix == '.db' and _is_within(target, hermes_root.resolve()):++ if target.suffix == ".db" and target.resolve().is_relative_to(root_res):+ homes.update([target.absolute().parent, target.resolve().parent])+ with exclusive_maintenance(homes):+ return _import_members_exclusive(zf, members, prefix, hermes_root, file_count)+++def _import_members_exclusive(+ zf: zipfile.ZipFile, members: List[str], prefix: str, hermes_root: Path, file_count: int+) -> tuple[int, int, list[str], list[str], list[tuple[str, tuple[int, int], tuple[int, int]]]]:+ """Publish every member; return ``(restored, restored_external, errors, skipped_runtime, db_shrunk)``.++ ``db_shrunk`` holds ``(rel, live_counts, imported_counts)`` for every session database the- import replaced with one holding fewer rows — allowed, but never silent (#100960).++ import replaced with one holding fewer rows — allowed, but never silently (#100960).+ """- errors: list[str] = []++ errors = []++ restored = 0++ restored_external = 0+ skipped_runtime: list[str] = []+ db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []- restored = restored_external = 0+ home_dir = Path.home().resolve()- new_file_mode = default_new_file_mode() # once: every member is published via mkstemp (0600)- for member in members:- # ``_external/`` members restore to their home-relative location (~/.honcho/config.json),- # NOT under HERMES_HOME; provider configs commonly hold credentials, so tighten to 0600.- external = member.startswith(_EXTERNAL_PREFIX)- rel, skipped = _import_member_rel(member, prefix)- if skipped:- skipped_runtime.append(rel)- continue- if external:- target = home_dir / rel- root = home_dir- tighten = target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES- else:- target = hermes_root / rel- root = hermes_root.resolve()- tighten = target.name in _SECRET_FILE_NAMES- if not rel:- continue++ # Resolved once: every member is published via a temp file, and mkstemp++ # would otherwise create newly restored files as 0600.++ new_file_mode = _default_new_file_mode()+- label = member if external else rel- if not _is_within(target, root):- errors.append(f"{label}: path traversal blocked")- else:++ for member in members:++ # External memory-provider state captured under the reserved++ # ``_external/`` arc prefix restores to its original home-relative++ # location (e.g. ~/.honcho/config.json), NOT under HERMES_HOME.++ if member.startswith(_EXTERNAL_PREFIX):++ ext_rel = member[len(_EXTERNAL_PREFIX):]++ if not ext_rel:++ continue++ target = home_dir / ext_rel++ # Security: the resolved target must stay under the home dir.++ try:++ target.resolve().relative_to(home_dir)++ except ValueError:++ errors.append(f" {member}: path traversal blocked")++ continue+ try:+ target.parent.mkdir(parents=True, exist_ok=True)- if target.suffix == ".db":- # Count before the write: afterwards the dropped rows are gone.- before = _count_session_rows(target)- _import_db_member(zf, member, target, new_file_mode)- after = _count_session_rows(target)- if before and after and after[1] < before[1]:- db_shrunk.append((rel, before, after))- else:- _extract_member_atomically(zf, member, target, new_file_mode)- if tighten:++ _extract_member_atomically(zf, member, target, new_file_mode)++ # External provider configs commonly hold credentials.++ if target.suffix in {".json", ".env", ".conf"} or target.name in _SECRET_FILE_NAMES:+ try:+ os.chmod(target, 0o600)+ except OSError:- if not external: # external configs are tightened best-effort only- raise++ pass+ restored += 1- restored_external += external++ restored_external += 1+ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:- # _ZIP_MEMBER_READ_ERRORS: the pre-flight in run_import already refused- # archives that fail to decompress; this keeps a member that rots between the two- # passes (archive on failing media) from aborting the rest of the restore.- errors.append(f"{label}: {exc}")++ errors.append(f" {member}: {exc}")++ if restored % 500 == 0:++ print(f" {restored}/{file_count} files ...")++ continue++++ # Strip prefix if detected++ if prefix and member.startswith(prefix):++ rel = member[len(prefix):]++ else:++ rel = member++++ if not rel:++ continue++++ try:++ parts = tuple(normalize_archive_parts(rel))++ except ValueError:++ errors.append(f" {rel}: path traversal blocked")++ continue++++ # Never overwrite volatile gateway/process runtime state. These are++ # namespaced to the machine/container the backup was taken on;++ # clobbering them (especially gateway_state.json) breaks the gateway++ # reconciler on the target and disconnects hosted instances from the++ # Nous portal. Matched by basename so both the root profile and++ # named profiles (profiles/<name>/gateway_state.json) are covered.++ if parts[-1] in _IMPORT_SKIP_NAMES:++ skipped_runtime.append(rel)++ continue++++ # Older archives may contain PM selections pointing at another machine.++ # Match their home-root paths; a plugin's own facts.json is user data.++ if profile_root_entry(parts) in PM_RUNTIME_ROOT_DIRS:++ skipped_runtime.append(rel)++ continue++++ # A ``.db`` member is page-restored into the live file below; a++ # WAL/SHM/journal member from the archive describes a different++ # database image, and installing it beside the restored file (over++ # a live sidecar, via os.replace) would replay a foreign WAL on++ # the next open. Current backups never ship these++ # (_EXCLUDED_SUFFIXES); older or hand-built archives might.++ if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):++ skipped_runtime.append(rel)++ continue++++ target = hermes_root.joinpath(*parts)++++ # Security: reject absolute paths and traversals++ try:++ target.resolve().relative_to(hermes_root.resolve())++ except ValueError:++ errors.append(f" {rel}: path traversal blocked")++ continue++++ try:++ target.parent.mkdir(parents=True, exist_ok=True)++ if target.suffix == ".db":++ # Count before the write: afterwards the rows this import++ # drops are gone and there is nothing left to compare.++ before = _count_session_rows(target)++ _import_db_member(zf, member, target, new_file_mode)++ after = _count_session_rows(target)++ if before and after and after[1] < before[1]:++ db_shrunk.append((rel, before, after))++ else:++ _extract_member_atomically(zf, member, target, new_file_mode)++ if target.name in _SECRET_FILE_NAMES:++ os.chmod(target, 0o600)++ restored += 1++ except (OSError, *_ZIP_MEMBER_READ_ERRORS) as exc:++ errors.append(f" {rel}: {exc}")++ if restored % 500 == 0:+ print(f" {restored}/{file_count} files ...")++ return restored, restored_external, errors, skipped_runtime, db_shrunk++- def run_import(args) -> Optional[int]:- """Restore a Hermes backup from a zip file.++def _revive_gateway_after_import(hermes_root: Path) -> None:++ """Start an installed gateway service after a restore, best-effort and prompt-free.+- Return 1 when the archive is damaged (refused before anything is written) or the restore is- incomplete (some members were not written); None on success or when the overwrite prompt is- declined. A missing, non-zip or invalid archive exits 1 via ``sys.exit``.- """- zip_path = Path(args.zipfile).expanduser().resolve()- if not zip_path.is_file():- print(f"Error: File not found: {zip_path}")- sys.exit(1)- if not zipfile.is_zipfile(zip_path):- print(f"Error: Not a valid zip file: {zip_path}")- sys.exit(1)- # The restore target is the home the command operates under (the printed "Target:");- # ``get_default_hermes_root()`` would silently retarget a profile restore at the live root.- hermes_root = get_hermes_home()- with zipfile.ZipFile(zip_path, "r") as zf:- ok, reason = _validate_backup_zip(zf)- if not ok:- print(f"Error: {reason}")- sys.exit(1)- prefix = _detect_prefix(zf)- members = [n for n in zf.namelist() if not n.endswith("/")]- file_count = len(members)- print(f"Backup contains {file_count} files\nTarget: {display_hermes_home()}")- if prefix:- print(f"Detected archive prefix: {prefix!r} (will be stripped)")- if not args.force and not _confirm_import_overwrite(hermes_root):- return- # Every member is decompressed once here and once again below: a damaged archive- # must be refused while the home is still untouched, not half-way through the restore.- print("\nChecking archive integrity ...")- # Members the restore skips anyway (gateway.pid, WAL sidecars) cannot block it.- corrupt = _find_corrupt_members(zf, [m for m in members if not _import_member_rel(m, prefix)[1]])- if corrupt:- _print_capped(f"Error: backup archive is damaged ({len(corrupt)} member(s) fail to "- f"decompress or fail their CRC); nothing was restored:", corrupt, " ")- return 1- print(f"\nImporting {file_count} files ...")- hermes_root.mkdir(parents=True, exist_ok=True)- t0 = time.monotonic()- 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 {'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()}.")- if errors:- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")- if db_shrunk:- # The backup predates work that is now overwritten — say so (#100960: twelve sessions- # disappeared with nothing logged anywhere).- print("\n ⚠ Session data replaced by older backup contents:")- for rel, before, after in db_shrunk:- print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"- f" -> {after[0]} / {after[1]}")- print(f" Anything recorded after the backup was taken is not in it. {_snapshot_recovery_hint()}")- if skipped_runtime:- _print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "- f"file(s) (kept this machine's, not the backup's):",- sorted(skipped_runtime), " ")- restored_profiles = _restore_profile_wrappers(hermes_root)- print()- if not (hermes_root / "hermes-agent").is_dir():- print("Note: The hermes-agent codebase was not included in the backup.\n"- " If this is a fresh install, run: hermes update")- if restored_profiles:- print("\nTo re-enable gateway services for profiles:")- for pname in restored_profiles:- print(f" hermes -p {pname} gateway install")- _revive_gateway_after_import(hermes_root)- if errors:- # A refused state.db leaves the old sessions in place; exit 0 would let scripts and- # the dashboard's "done" badge treat that as a full restore.- print(f"Import incomplete: {len(errors)} file(s) were not restored (see Warnings above). "- "Fix the cause and re-run the import.")- return 1- print("Done. Your Hermes configuration has been restored.")--- def _restore_profile_wrappers(hermes_root: Path) -> List[str]:- """Re-create shell wrapper scripts for restored named profiles; return the profile names seen."""- profiles_dir = hermes_root / "profiles"- restored_profiles: list[tuple[str, bool]] = []- if not profiles_dir.is_dir():- return []- try:- from hermes_cli.profiles import (- create_wrapper_script, check_alias_collision, _is_wrapper_dir_in_path, _get_wrapper_dir)- for entry in sorted(profiles_dir.iterdir()):- if not entry.is_dir() or not any((entry / m).exists() for m in ("config.yaml", ".env")):- continue # only profiles with config get wrappers- profile_name = entry.name- collision = check_alias_collision(profile_name)- if collision:- print(f" Skipped alias '{profile_name}': {collision}")- restored_profiles.append(- (profile_name, not collision and create_wrapper_script(profile_name) is not None))- if restored_profiles:- created = [n for n, ok in restored_profiles if ok]- skipped = [n for n, ok in restored_profiles if not ok]- if created:- print(f"\n Profile aliases restored: {', '.join(created)}")- if skipped:- print(f" Profile aliases skipped: {', '.join(skipped)}")- if not _is_wrapper_dir_in_path():- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"- " Add to your shell config (~/.bashrc or ~/.zshrc):\n"- ' export PATH="$HOME/.local/bin:$PATH"')- except ImportError: # hermes_cli.profiles unavailable (fresh install)- if any(profiles_dir.iterdir()):- print("\n Profiles detected but aliases could not be created.\n"- " Run: hermes profile list (after installing hermes)")- return [n for n, _ in restored_profiles]--- def _revive_gateway_after_import(hermes_root: Path) -> None:- """Install/start the gateway service after a restore, best-effort and prompt-free.-- Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so- this is safe for any backup); failures print a manual fallback, never fail the import. Only- revived when the restore landed in the default home or no other install exists: a sandbox or- profile restore must not install a second gateway on the default service name.++ Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so++ this is safe for any backup); failures print a manual fallback, never fail the import. Only++ revived when the restore landed in the default home or no other install exists: a sandbox or++ profile restore must not install a second gateway on the default service name.+ """+ native_default = _get_platform_default_hermes_home()+ if hermes_root != native_default and any(+ (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):+ print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "+ f"with the install at {native_default}.\n"+ "To start a gateway for this home, run: hermes gateway run")+ return+ try:+ from hermes_cli.gateway import _is_service_running+ from hermes_cli.gateway_setup_service import ensure_gateway_service+ if not _is_service_running():+ print()+ ensure_gateway_service(context="import")+ except Exception:+ print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway run")+# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ---@@@ -1496,76 -1449,82 +1480,110 @@@ def list_quick_snapshotsreturn results- def restore_quick_snapshot(snapshot_id: str, hermes_home: Optional[Path] = None) -> bool:- """Restore the whole snapshot offline, or refuse before changing any file."""+ def restore_quick_snapshot(+ snapshot_id: str,+ hermes_home: Optional[Path] = None,+ ) -> bool:- """Restore state from a quick snapshot.++ """Restore the whole snapshot offline, or refuse before changing any file.++ Overwrites current state files with the snapshot's copies.+ Returns True if at least one file was restored.+ """+ from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenancehome = hermes_home or get_hermes_home()+ try:+ with exclusive_maintenance([home]):+ return _restore_quick_snapshot_exclusive(snapshot_id, home)+ except OwnershipConflict as exc:+ logger.error("%s", exc)+ return False+++def _restore_quick_snapshot_exclusive(snapshot_id: str, home: Path) -> bool:- """Restore state from a quick snapshot."""++ """Restore state from a quick snapshot while ``home`` is reserved."""++ from gateway.runtime_ownership import exclusive_maintenanceroot = _quick_snapshot_root(home)- # Reject ids with separators or traversal so ``root / snapshot_id`` stays inside root.++ # Security: reject snapshot_id values that contain path separators or+ # traversal sequences so that `root / snapshot_id` stays inside root.if not snapshot_id or "/" in snapshot_id or "\\" in snapshot_id or snapshot_id in (".", ".."):logger.error("Invalid snapshot_id: %s", snapshot_id)return False+snap_dir = root / snapshot_id- if not _is_within(snap_dir, root.resolve()): # handles symlinks etc.++ # Confirm the resolved path is still inside root (handles symlinks etc.)+ try:+ snap_dir.resolve().relative_to(root.resolve())+ except ValueError:logger.error("Snapshot path traversal blocked for id: %s", snapshot_id)return False++ if not snap_dir.is_dir():+ return False+manifest_path = snap_dir / "manifest.json"- if not snap_dir.is_dir() or not manifest_path.exists():+ if not manifest_path.exists():return False- with open(manifest_path, encoding="utf-8") as f:++ with open(manifest_path, encoding="utf-8-sig") as f:meta = json.load(f)+- restored = 0- for rel in meta.get("files", {}):+ snap_res, home_res = snap_dir.resolve(), home.resolve()- from gateway.runtime_ownership import exclusive_maintenance++++ def _entry_paths(rel: str) -> Optional[Tuple[Path, Path]]:+ # Security: reject absolute paths and traversals in manifest entries- src = snap_dir / rel- try:- src.resolve().relative_to(snap_dir.resolve())- except ValueError:- logger.error("Manifest path traversal blocked: %s", rel)- continue++ src, dst = snap_dir / rel, home / rel++ if not (src.resolve().is_relative_to(snap_res) and dst.resolve().is_relative_to(home_res)):++ return None++ return src, dst+- dst = home / rel- try:- dst.resolve().relative_to(home.resolve())- except ValueError:- logger.error("Manifest path traversal blocked: %s", rel)- continue+ homes = {home}+ for rel in meta.get("files", {}):- dst = home / rel- if dst.suffix == '.db' and _is_within(dst, home_res):- homes.update([dst.absolute().parent, dst.resolve().parent])++ entry = _entry_paths(rel)++ if entry and entry[1].suffix == ".db":++ homes.update([entry[1].absolute().parent, entry[1].resolve().parent])+ with exclusive_maintenance(homes):+ # Epoch safety is a whole-profile preflight: copying config first would+ # both partially roll back the profile and report a refused DB as success.+ for rel in meta.get("files", {}):- src, dst = snap_dir / rel, home / rel- if (src.exists() and _is_within(src, snap_res) and _is_within(dst, home_res)- and (dst.name == "state.db" or dst.resolve().name == "state.db")):++ entry = _entry_paths(rel)++ if entry and entry[0].exists() and "state.db" in (entry[1].name, entry[1].resolve().name):+ try:- _restore_destination_epoch(dst)++ _restore_destination_epoch(entry[1])+ except OSError as exc:+ logger.error("%s", exc)+ return False+- if not src.exists():- continue+ restored = 0+ for rel in meta.get("files", {}):- src = snap_dir / rel- dst = home / rel- if not (_is_within(src, snap_res) and _is_within(dst, home_res)):++ entry = _entry_paths(rel)++ if entry is None:+ logger.error("Manifest path traversal blocked: %s", rel)+ continue++ src, dst = entry+ if not src.exists():+ continue+- dst.parent.mkdir(parents=True, exist_ok=True)+ dst.parent.mkdir(parents=True, exist_ok=True)+- try:- if dst.suffix == ".db":- # Restore through SQLite backup API so live connections- # (gateway, dashboard, another CLI session) see the- # restored data instead of continuing to serve stale- # cached pages from a replaced inode (issue #65942).- if not _safe_restore_db(src, dst):- # Refused, failed, or source failed its integrity check:- # dst left as it was. Count as a failure, not a restore.- logger.error("Failed to restore %s: refused or source integrity check failed (see previous log)", rel)- continue- else:- shutil.copy2(src, dst)- restored += 1- except (OSError, PermissionError) as exc:- logger.error("Failed to restore %s: %s", rel, exc)+ try:+ if dst.suffix == ".db":- # Through the backup API so live connections see the restored data instead of- # stale pages from a replaced inode (#65942).++ # Restore through SQLite backup API so live connections++ # (gateway, dashboard, another CLI session) see the++ # restored data instead of continuing to serve stale++ # cached pages from a replaced inode (issue #65942).+ if not _safe_restore_db(src, dst):- # Refused (live holder) or failed: destination untouched — a failure, not a restore.- logger.error("Failed to restore %s: live-safe restore refused", rel)++ # Refused, failed, or source failed its integrity check:++ # dst left as it was. Count as a failure, not a restore.++ logger.error("Failed to restore %s: refused or source integrity check failed (see previous log)", rel)+ continue+ else:+ shutil.copy2(src, dst)+ restored += 1+ except (OSError, PermissionError) as exc:+ logger.error("Failed to restore %s: %s", rel, exc)+logger.info("Restored %d files from snapshot %s", restored, snapshot_id)return restored > 0diff --cc hermes_cli/backup_restore.pyindex 00000000000,d6e2a224884..ab149df99f0mode 000000,100644..100644--- a/hermes_cli/backup_restore.py+++ b/hermes_cli/backup_restore.py@@@ -1,0 -1,487 +1,574 @@@+ """SQLite-safe restore and archive-member publish plumbing for backups.++ Owns the restore side of ``hermes_cli.backup``: the page-copy SQLite restore+ (``_safe_restore_db`` plus the foreign-holder scan) and the zip-member publish+ helpers used by ``hermes import`` and ``/snapshot restore``. Backup+ *creation* (``run_backup``, full-zip writing) stays in ``hermes_cli.backup``,+ which composes these helpers.+ """++ import logging+ import os+ import shutil+ import sqlite3+ import stat+ import sys+ import tempfile+ import zipfile++from contextlib import closing, contextmanager+ from pathlib import Path+ from typing import List, Optional, Tuple++ from hermes_state_holders import read_only_db_uri++from hermes_cli.backup_sqlite import _safe_copy_db+ from utils import (+ _preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,+ )++ logger = logging.getLogger(__name__)++ def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:+ """PIDs of OTHER processes holding *db_path* or its WAL/SHM open.++ Linux-only ``/proc/<pid>/fd`` scan (no psutil dependency), preserving the+ kernel's ``(deleted)`` suffix so an already-unlinked sidecar generation —+ the #90950 split-brain fingerprint — still counts as held. Returns+ ``None`` when the scan is unavailable (non-Linux, or /proc unreadable);+ callers must treat ``None`` as "unknown", not as "no holders".+ """+ if not sys.platform.startswith("linux"):+ return None++ def _canonical(path: str) -> str:+ return os.path.normcase(+ os.path.abspath(path.removesuffix(" (deleted)"))+ )++ canonical_db = _canonical(os.fspath(db_path))+ watched = {canonical_db, canonical_db + "-wal", canonical_db + "-shm"}+ pids: List[int] = []+ try:+ own_pid = os.getpid()+ for pid_str in os.listdir("/proc"):+ if not pid_str.isdigit():+ continue+ pid = int(pid_str)+ if pid == own_pid:+ continue+ fd_dir = f"/proc/{pid}/fd"+ try:+ fds = os.listdir(fd_dir)+ except OSError:+ continue+ for fd in fds:+ try:+ target = os.readlink(f"{fd_dir}/{fd}")+ except OSError:+ continue+ if _canonical(target) in watched:+ pids.append(pid)+ break+ except OSError:+ return None+ return pids+++ def _safe_restore_db(src: Path, dst: Path) -> bool:++ """Restore only while holding the destination authority's maintenance reservation.++++ Returns ``False``, without touching *dst*, when *src* fails the SQLite++ integrity check, when the runtime owns the profile, or when a canonical++ ``state.db`` epoch floor cannot be proven.++ """++ from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance++ from hermes_cli.backup import verify_sqlite_integrity++++ # backup() copies pages without validating their contents; its fallback++ # copies bytes even when SQLite rejected the source. Neither may touch the++ # destination until the snapshot passes the existing bounded integrity policy.++ source_check = verify_sqlite_integrity(src)++ if not source_check["valid"]:++ logger.error("Refusing SQLite restore from %s: %s", src, source_check["message"])++ return False++ try:++ with exclusive_maintenance([dst.absolute().parent, dst.resolve().parent]):++ with _restore_epoch_source(src, dst) as prepared:++ return _restore_db_pages(prepared, dst)++ except (OwnershipConflict, OSError, sqlite3.Error) as exc:++ logger.error("%s", exc)++ return False++++++def _restore_epoch(path: Path) -> int:++ if not path.exists():++ return 0++ with closing(sqlite3.connect(read_only_db_uri(path), uri=True)) as conn:++ if not conn.execute("SELECT 1 FROM sqlite_master WHERE name='runtime_epoch'").fetchone():++ return 0++ row = conn.execute("SELECT epoch FROM runtime_epoch WHERE singleton=1").fetchone()++ return int(row[0]) if row else 0++++++def _restore_destination_epoch(dst: Path) -> int:++ try:++ return _restore_epoch(dst)++ except (OSError, sqlite3.Error, ValueError) as exc:++ raise OSError(++ f"Cannot read the canonical runtime epoch at {dst}; refusing in-place restore. "++ "Use `hermes sessions recover --source <snapshot> --output <separate-path>` "++ "to salvage transcripts into a separate output."++ ) from exc++++++@contextmanager++def _restore_epoch_source(src: Path, dst: Path):++ """Stage an epoch floor into the image BEFORE publishing it atomically.++++ Updating the destination after backup() would leave a crash window that++ reuses an older worker epoch. Never modify the user's source snapshot.++ Full restores retain all admissions/worker receipts; normal startup advances++ this floor and reconciles started work to unknown, not replayable queued work.++ An unreadable destination cannot prove its epoch floor: use transcript salvage++ into a separate output rather than silently restoring with a recycled epoch.++ """++ if dst.name != 'state.db' and dst.resolve().name != 'state.db':++ yield src++ return++ floor = _restore_destination_epoch(dst)++ if floor <= _restore_epoch(src):++ yield src++ return++ with tempfile.TemporaryDirectory(prefix='.restore-epoch-', dir=dst.parent) as work:++ prepared = Path(work) / 'state.db'++ if not _safe_copy_db(src, prepared):++ raise OSError('Unable to stage a restore with a safe runtime epoch')++ with closing(sqlite3.connect(prepared)) as conn:++ conn.execute("""CREATE TABLE IF NOT EXISTS runtime_epoch (++ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),++ epoch INTEGER NOT NULL CHECK (epoch > 0), instance_id TEXT NOT NULL)""")++ conn.execute("""INSERT INTO runtime_epoch VALUES(1,?, 'offline-restore')++ ON CONFLICT(singleton) DO UPDATE SET epoch=excluded.epoch,++ instance_id=excluded.instance_id""", (floor,))++ conn.commit()++ prepared.chmod(src.stat().st_mode)++ yield prepared++++++def _restore_db_pages(src: Path, dst: Path) -> bool:+ """Restore a SQLite database from snapshot *src* into live *dst*.++ Uses SQLite's backup() API to write snapshot pages into the live+ database file, preserving the file's inode and WAL state so that+ any other process still holding the DB open (gateway, dashboard,+ another CLI session) sees the restored data on the next read —+ instead of continuing to serve stale cached pages from a replaced+ inode.++ The old approach was ``unlink() + move()``, which replaced the file+ under any live connection. SQLite connections cache pages in+ per-connection page caches keyed by inode; after an unlink+move the+ old inode still existed (the live connection held a reference), so+ that connection continued serving the pre-restore data while new+ connections saw the restored snapshot — a partial/inconsistent+ state (issue #65942).++ By writing pages through the backup API the file inode is preserved,+ the WAL journal is updated correctly, and all connections (old and+ new) converge on the restored data.++ Falls back to the unlink+move approach on failure ONLY when no other+ process or in-process connection holds the file: replacing the inode+ under a live holder is the #90950 split-brain, so that branch fails+ closed (returns ``False``) and the caller reports the file as skipped.- It also returns ``False``, without touching *dst*, when *src* fails the- SQLite integrity check.++ Callers go through ``_safe_restore_db``, which validates *src* and holds++ the maintenance reservation and epoch floor around this publication.+ """- from hermes_cli.backup import verify_sqlite_integrity-- # backup() copies pages without validating their contents; its fallback- # copies bytes even when SQLite rejected the source. Neither may touch the- # destination until the snapshot passes the existing bounded integrity policy.- source_check = verify_sqlite_integrity(src)- if not source_check["valid"]:- logger.error("Refusing SQLite restore from %s: %s", src, source_check["message"])- return False-+ dst_conn: Optional[sqlite3.Connection] = None+ try:+ dst_conn = sqlite3.connect(str(dst))+ try:+ # Force a WAL checkpoint so the backup starts from a clean+ # state rather than writing on top of a deep WAL.+ dst_conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ except Exception:+ pass+ src_conn = sqlite3.connect(read_only_db_uri(src), uri=True)+ try:+ src_conn.backup(dst_conn)+ finally:+ src_conn.close()+ dst_conn.close()+ # Restore original file permissions from the snapshot+ try:+ mode = src.stat().st_mode+ dst.chmod(mode)+ except Exception:+ pass+ return True+ except Exception as exc:+ logger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)+ # Release our own handle on *dst* before the fallback: on Windows an+ # open connection blocks unlink() with WinError 32, which would make+ # the fallback below dead code exactly when it is needed.+ if dst_conn is not None:+ try:+ dst_conn.close()+ except Exception:+ pass+ # Fallback: unlink+move (the old approach). This still works for+ # the common case where no other process holds the DB open.+ from hermes_cli.sqlite_safe_read import (+ LiveConnectionError,+ offline_file_access,+ )++ try:+ holders = _foreign_db_holder_pids(dst)+ if holders:+ # Replacing the inode under a live holder is the #90950+ # corruption class: the holder keeps writing through a+ # deleted-inode fd (split brain), and removing its sidecars+ # detaches the WAL index it is checkpointing through. The+ # backup-API path above is the live-safe route; if it failed,+ # fail closed rather than corrupt.+ logger.error(+ "Refusing unlink+move restore of %s: process(es) %s still "+ "hold the database or its WAL open. Stop them and retry.",+ dst, holders,+ )+ return False+ # The foreign-pid scan above deliberately excludes THIS process,+ # but an in-process SessionDB (the agent's own handle during+ # /snapshot restore, a second SessionDB instance, a read pool)+ # is exactly as much of a live holder: unlinking the DB and its+ # sidecars under it leaves this process on deleted-inode fds —+ # the same #90950 split brain, produced first-party (proven live+ # on main: `/proc/self/fd` shows `state.db-wal (deleted)` right+ # after this fallback ran under a tracked connection).+ # ``offline_file_access`` fails CLOSED when any tracked+ # connection to *dst* is live and holds the connection-lifecycle+ # lock across the whole swap so no new connection can appear+ # mid-replace.+ with offline_file_access(dst, what="unlink+move restore of"):+ tmp = dst.parent / f".{dst.name}.snap_restore"+ shutil.copy2(src, tmp)+ dst.unlink(missing_ok=True)+ # Drop the destination's sidecars before installing the+ # snapshot. The snapshot is a checkpointed ``sqlite3.backup()``+ # image (see ``_safe_copy_db``) that owns no WAL, so any+ # ``-wal``/``-shm`` still sitting here describes the database we+ # just unlinked — an ungracefully killed gateway leaves them+ # behind, which is exactly when a restore gets run. SQLite+ # replays that foreign WAL over the restored file on the next+ # open and the database comes up "malformed" (or silently+ # resurrects post-snapshot rows). Same reasoning as+ # ``_EXCLUDED_SUFFIXES``, applied to the restore destination.+ for _sidecar_suffix in ("-wal", "-shm", "-journal"):+ dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)+ shutil.move(str(tmp), str(dst))+ return True+ except LiveConnectionError as exc2:+ logger.error(+ "Refusing unlink+move restore of %s: %s Close the in-process "+ "database handles (or restart Hermes) and retry.",+ dst, exc2,+ )+ return False+ except Exception as exc2:+ logger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)+ return False+++ def _validate_backup_zip(zf: zipfile.ZipFile) -> tuple[bool, str]:+ """Check that a zip looks like a Hermes backup.++ Returns (ok, reason).+ """+ names = zf.namelist()+ if not names:+ return False, "zip archive is empty"++ # Look for telltale files that a hermes home would have+ markers = {"config.yaml", ".env", "state.db"}+ found = set()+ for n in names:+ # Could be at the root or one level deep (if someone zipped the directory)+ basename = Path(n).name+ if basename in markers:+ found.add(basename)++ if not found:+ return False, (+ "zip does not appear to be a Hermes backup "+ "(no config.yaml, .env, or state databases found)"+ )++ return True, ""+++ def _detect_prefix(zf: zipfile.ZipFile) -> str:+ """Detect if the zip has a common directory prefix wrapping all entries.++ Some tools zip as `.hermes/config.yaml` instead of `config.yaml`.+ Returns the prefix to strip (empty string if none).+ """+ names = [n for n in zf.namelist() if not n.endswith("/")]+ if not names:+ return ""++ # Find common prefix+ parts_list = [Path(n).parts for n in names]++ # Check if all entries share a common first directory+ first_parts = {p[0] for p in parts_list if len(p) > 1}+ if len(first_parts) == 1:+ prefix = first_parts.pop()+ # Only strip if it looks like a hermes dir name+ if prefix in {".hermes", "hermes"}:+ return prefix + "/"++ return ""+++ def _default_new_file_mode() -> Optional[int]:+ """Return the mode ``open(path, "wb")`` gives a file it has to create.++ ``tempfile.mkstemp`` always creates at 0600, so staging an import through a+ temp file would tighten every *newly created* file to owner-only — the same+ hazard ``utils._restore_file_mode`` documents for Docker/NAS volume mounts+ that rely on broader permissions. The umask can only be read by setting it,+ so this is resolved once per import rather than once per member. The probe+ installs a *restrictive* mask rather than 0 so that anything another thread+ creates inside the two-syscall window is owner-only, never world-writable.+ Returns ``None`` if the umask cannot be read, in which case the caller+ leaves mkstemp's mode alone.+ """+ try:+ current = os.umask(0o077)+ os.umask(current)+ except OSError:+ return None+ return 0o666 & ~current+++ def _extract_member_atomically(+ zf: zipfile.ZipFile,+ member: str,+ target: Path,+ new_file_mode: Optional[int] = None,+ ) -> None:+ """Restore one zip member onto *target* with no truncation window.++ ``open(target, "wb")`` truncates the user's existing file to zero *before*+ any replacement bytes exist. A Ctrl-C, an ENOSPC, a corrupt member, or a+ crash between the truncate and the write therefore leaves that file empty+ with nothing behind it — during ``hermes import``, which is the+ disaster-recovery path a user reaches for *because* they already lost+ something. Staging into the target's own directory and publishing with a+ rename means the target only ever moves from its old contents to the+ complete new contents.++ ``atomic_replace`` rather than a bare ``os.replace``: it resolves a+ symlinked target first, so a deployment that links ``config.yaml`` into a+ dotfiles repo keeps the link instead of having it silently swapped for a+ regular file (GitHub #16743), and it falls back to copy/fsync/unlink on+ ``EXDEV``/``EBUSY`` for cross-device and bind-mount installs. That+ fallback uses ``shutil.copyfile``, which does truncate in place, so on the+ cross-device path the guarantee above degrades to today's behaviour rather+ than improving on it; closing that belongs in ``utils.atomic_replace``,+ where every atomic writer in the repo would benefit, not here.++ Permission bits *and* ownership are carried across the replace so routing+ through mkstemp does not change the file the caller would otherwise have+ produced. ``os.replace`` swaps in a temp file owned by the *writing* user,+ so without the chown a ``sudo hermes import`` would silently re-own every+ restored file to root — on the disaster-recovery path, and on exactly the+ Docker/NAS installs ``utils._restore_file_owner`` documents. Both concerns+ delegate to the shared ``utils`` helpers rather than being re-derived here.+ The temp file is removed on any failure so a partial import leaves no+ residue.++ The one bit of the old file *not* carried across is setuid/setgid. The+ replacement bytes come out of the zip, so preserving those would let an+ archive take over the identity an existing privileged file executes as —+ and unlike the other ``utils`` writers, which re-serialize content this+ process produced, the trust boundary here is an untrusted archive. The+ mask is applied once, before the temp file is chmod'd, so neither the+ pre-replace ``fchmod`` nor the post-replace restore can re-elevate the+ target.+ """+ # ``_preserve_file_mode`` returns None when the target does not exist (or+ # cannot be stat'd), in which case the umask-derived create-mode applies —+ # the same shape as ``atomic_yaml_write``'s ``create_mode`` fallback.+ mode = _preserve_file_mode(target)+ owner = _preserve_file_owner(target)+ if mode is None:+ mode = new_file_mode+ else:+ # Deliberately NOT a faithful mode copy: setuid/setgid are dropped.+ # ``_preserve_file_mode`` returns ``stat.S_IMODE``, i.e. all twelve+ # bits, and the content replacing this file comes from the archive.+ # Carrying the elevated bits across would let archive-controlled bytes+ # take over an existing setuid/setgid file, so ``hermes import`` would+ # hand whoever produced the zip the identity that file runs as. Nothing+ # constrains that to Hermes' own state either: the ``_external/`` branch+ # of ``run_import`` publishes members anywhere under ``$HOME``. The+ # sticky bit is kept — it is inert on a regular file.+ mode &= ~(stat.S_ISUID | stat.S_ISGID)++ # Truncate the stem: mkstemp adds ~16 characters, and a member already near+ # NAME_MAX would otherwise fail here on a write that used to succeed.+ fd, tmp_name = tempfile.mkstemp(+ dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".partial"+ )+ try:+ with os.fdopen(fd, "wb") as dst:+ if mode is not None:+ # Apply the mode to the temp file BEFORE the replace so the+ # target never transits through mkstemp's 0600, and so+ # ``atomic_replace``'s EXDEV/EBUSY ``shutil.copystat`` fallback+ # copies the intended bits rather than 0600. fchmod is+ # Unix-only; Windows takes the path-based chmod.+ if hasattr(os, "fchmod"):+ os.fchmod(dst.fileno(), mode)+ else:+ os.chmod(tmp_name, mode)+ # Stream instead of ``src.read()``: a multi-gigabyte state.db member+ # must not be held in memory in one piece.+ with zf.open(member) as src:+ shutil.copyfileobj(src, dst)+ dst.flush()+ os.fsync(dst.fileno())+ real_path = Path(atomic_replace(tmp_name, target))+ # Owner first, mode second — the ordering ``atomic_yaml_write`` uses,+ # because chown drops setuid/setgid and a mode restore that ran first+ # would be partly undone. Here ``mode`` no longer carries those bits,+ # so the two agree: neither step can re-elevate the restored file.+ _restore_file_owner(real_path, owner)+ _restore_file_mode(real_path, mode)+ except BaseException:+ try:+ os.unlink(tmp_name)+ except OSError:+ pass+ raise+++ def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:+ """Return ``(sessions, messages)`` stored in the session database *path*.++ Read-only and best effort. ``None`` means "unknown" — a missing file, a+ database that is not a Hermes session store, or one that cannot be read.+ Callers must never read ``None`` as "zero rows": acting on an unreadable+ database would mask the very loss this count exists to surface. Same+ contract as :func:`_count_cron_jobs`.+ """+ if not path.is_file():+ return None+ try:+ conn = sqlite3.connect(read_only_db_uri(path), uri=True)+ except sqlite3.Error:+ return None+ try:+ sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]+ messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]+ return int(sessions), int(messages)+ except (sqlite3.Error, TypeError, ValueError):+ return None+ finally:+ conn.close()+++ def _import_db_member(+ zf: zipfile.ZipFile,+ member: str,+ target: Path,+ new_file_mode: Optional[int] = None,++) -> None:++ from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance++ try:++ with exclusive_maintenance([target.absolute().parent, target.resolve().parent]):++ _import_db_member_exclusive(zf, member, target, new_file_mode)++ except OwnershipConflict as exc:++ raise OSError(str(exc)) from exc++++++def _import_db_member_exclusive(++ zf: zipfile.ZipFile,++ member: str,++ target: Path,++ new_file_mode: Optional[int] = None,+ ) -> None:+ """Publish a SQLite ``.db`` member onto *target* without replacing its inode.++ ``_extract_member_atomically`` publishes with a rename. For an ordinary+ file that is the safest write available; for a live SQLite database it is+ the #65942 / #90950 corruption class. A gateway, dashboard, or WebUI+ process holding the database open keeps its descriptor on the now-unlinked+ inode: it goes on serving pre-import pages and writing sessions that no+ other process will ever see, and any sidecar WAL left beside the new file+ describes the database that was just unlinked. Nothing fails, so nothing+ is reported — the sessions simply are not there afterwards (issue #100960).++ ``hermes import`` is the disaster-recovery path, so that failure mode lands+ on users who have already lost something once. Route the member through+ the same ``_safe_restore_db`` page copy that ``/snapshot restore`` has used+ since #65942: the live inode is preserved, every open connection converges+ on the imported data, and the sidecars are handled there.++ Raises ``OSError`` when the database could not be replaced safely, so the+ caller reports a skipped file instead of counting a silent success.+ """+ if not target.exists():+ # "Missing" is not "unheld": a gateway or dashboard that had the database open when it+ # was unlinked still writes the deleted inode (the ``(deleted)`` fingerprint of #90950).+ # Publishing a fresh inode here re-creates the same split brain the branch below exists+ # to prevent, so refuse and name the holders instead (#110179).+ holders = _foreign_db_holder_pids(target)+ if holders:+ raise OSError(+ f"{target.name} was deleted but is still open in PID(s) "+ f"{', '.join(str(pid) for pid in sorted(holders))}; publishing a new file would "+ "leave them writing an invisible database. Stop those processes and re-run the import."+ )+ _extract_member_atomically(zf, member, target, new_file_mode)+ return++ # The database keeps its own mode/ownership: the bytes come from the+ # archive but the file does not, so the archive has no say in either.+ mode = _preserve_file_mode(target)+ owner = _preserve_file_owner(target)++ fd, tmp_name = tempfile.mkstemp(+ dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport"+ )+ try:+ with os.fdopen(fd, "wb") as dst:+ # Stream: a multi-gigabyte state.db member must not be held in+ # memory in one piece.+ with zf.open(member) as src:+ shutil.copyfileobj(src, dst)+ dst.flush()+ os.fsync(dst.fileno())+ if not _safe_restore_db(Path(tmp_name), target):+ from hermes_cli.backup import verify_sqlite_integrity++ # Re-check only on failure so the user gets the real cause; the+ # detailed integrity message was already logged by _safe_restore_db.+ if not verify_sqlite_integrity(Path(tmp_name))["valid"]:+ raise OSError(+ "the archived database failed its integrity check; the existing "+ "database was left untouched."+ )+ raise OSError(+ "live-safe restore refused or failed; the existing database was "+ "left untouched. Stop the gateway/dashboard processes holding it "+ "open and re-run the import."+ )+ _restore_file_owner(target, owner)+ _restore_file_mode(target, mode)+ finally:+ try:+ os.unlink(tmp_name)+ except OSError:+ passdiff --cc hermes_cli/session_schema_history.pyindex f8135ee46a7,ef5c9b4e7d0..fb17853b6f4--- a/hermes_cli/session_schema_history.py+++ b/hermes_cli/session_schema_history.py@@@ -203,11 -203,9 +203,15 @@@ SCHEMA_HISTORY: dict[str, _TableHistory('+', 'compression_recovery_deadline', 'compression_ineffective_count'),)),('26 2026-09-02T14:22Z 8e4366d358', (('+', 'tool_names', 'last_read_at'),)),- ('27 2026-09-08T18:45Z 0695b12b4c', (+ ('27 2026-09-19T00:10Z 922a0c3c87', (('+', 'transport_profile', 'profile_name'),)),+ ('28 2026-09-25T23:25Z 2941aadffa', (('+', 'compression_overload_streak', 'compression_recovery_deadline'),)),+ ('29 2026-09-27T00:29Z d75f29934b', (('+', 'created_source', 'source'),)),++ # Runtime-authority columns (unified gateway runtime, PR #106742): appended after main's++ # 27-29 because they ship after them on main.++ ('30 2026-09-08T18:45Z 0695b12b4c', (+ ('+', 'runtime_revision', 'id'),+ ('+', 'runtime_generation', 'runtime_revision'),+ )),- ('28 2026-09-19T00:10Z 922a0c3c87', (('+', 'transport_profile', 'profile_name'),)),),),"messages": _TableHistory(diff --cc hermes_cli/subcommands/gateway.pyindex 94f0e3acdf4,569e6fbe438..f23e1361e85--- a/hermes_cli/subcommands/gateway.py+++ b/hermes_cli/subcommands/gateway.py@@@ -58,23 -38,41 +58,42 @@@ def build_gateway_parser"""Attach the ``gateway`` and ``proxy`` subcommands to ``subparsers``."""gateway_parser = subparsers.add_parser("gateway", help="Messaging gateway management",description="Manage the messaging gateway (Telegram, Discord, WhatsApp, Weixin, and more)")- gateway_subparsers = gateway_parser.add_subparsers(dest="gateway_command")+ gateway_subparsers = gateway_parser.add_subparsers(+ dest="gateway_command", parser_class=_GatewayCommandParser)gateway_run = gateway_subparsers.add_parser(- "run", help="Run gateway in foreground (recommended for WSL, Docker, Termux)")- gateway_run.add_argument("-v", "--verbose", action="count", default=0,- help="Increase stderr log verbosity (-v=INFO, -vv=DEBUG)")- _flag(gateway_run, "-q", "--quiet", help="Suppress all stderr log output")- _flag(- gateway_run, "--replace", help="Replace any existing gateway instance (useful for systemd)")- _flag(gateway_run, "--force",- help="Start a foreground gateway even when a systemd/launchd/s6 service "+ "run", help="Run gateway in foreground (recommended for WSL and Docker)"+ )+ gateway_run.add_argument(+ "-v",+ "--verbose",+ action="count",+ default=0,+ help="Increase stderr log verbosity (-v=INFO, -vv=DEBUG)",+ )+ gateway_run.add_argument(+ "-q", "--quiet", action="store_true", help="Suppress all stderr log output"+ )+ gateway_run.add_argument(+ "--replace",+ action="store_true",+ help="Replace any existing gateway instance (useful for systemd)",+ )+ gateway_run.add_argument(+ "--force",+ action="store_true",+ help=(+ "Start a foreground gateway even when a systemd/launchd/s6 service ""already supervises this profile. Without --force, the command ""refuses because a second dispatcher escapes the service and can "- "corrupt shared gateway state.")- _flag(gateway_run, "--no-supervise",- help="Inside the s6-overlay Docker image, normally `gateway run` is "+ "corrupt shared gateway state."+ ),+ )+ gateway_run.add_argument(+ "--no-supervise",+ action="store_true",+ help=(+ "Inside the s6-overlay Docker image, normally `gateway run` is ""automatically redirected to the supervised s6 service (so the ""gateway gets auto-restart on crash, plus a supervised dashboard ""if HERMES_DASHBOARD is set). Pass --no-supervise to opt out and "diff --cc hermes_cli/update_cmd.pyindex 308d4967c3c,d8ece26c722..7100ccff71e--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@@ -100,8 -96,8 +96,8 @@@ from hermes_cli.update_cmd_git import_prune_orphan_rescue_refs, _should_skip_upstream_prompt, _sync_fork_with_upstream,_sync_with_upstream_if_needed)from hermes_cli.update_cmd_maint import ( # noqa: F401- _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _clear_stale_sqlite_sidecars,+ _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,- _ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,+ _checkout_version, _ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,_format_time_ago, _post_update_sqlite_runtime_status, _print_bundled_skills_sync_report,_print_curator_first_run_notice, _print_curator_recent_run_notice,_print_fts_optimize_available_notice, _print_update_completion, _print_update_summary,diff --cc hermes_cli/update_cmd_maint.pyindex 6cc4d121fd6,2a503275289..9247f4dd47b--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@@ -8,7 -8,7 +8,6 @@@ test patches on ``update_cmd`` stay effimport loggingfrom contextlib import suppressimport os--import shutilimport subprocessimport sysimport time as _time@@@ -352,61 -391,58 +390,31 @@@ def _print_verified_update_completion(mreturn False-def _clear_stale_sqlite_sidecars(db_path: Path) -> None:- """Delete -wal/-shm/-journal next to *db_path*, immediately before overwriting it with a- snapshot image.-- Snapshots are checkpointed ``sqlite3.backup()`` images with no WAL; copying replaces only- the main file, so a leftover WAL from the OLD database would be replayed over the fresh- image on next open (passes integrity_check while serving old contents). Safe because the- caller has already declared that database corrupt.- """- for suffix in ("-wal", "-shm", "-journal"):- db_path.with_name(db_path.name + suffix).unlink(missing_ok=True)--def _print_update_summary(*, node_failures: list, desktop_build_ok: bool, pre_update_version: str | None) -> bool:- """Final banner. A failed Desktop rebuild is non-fatal but must not print ``✓ Update complete!``.+ """Historical updater hook; old soft-build results cannot establish completion."""+ from hermes_cli._old_updater import stop_for_relaunch- See #88251.- """- from hermes_cli.update_cmd import _post_update_sqlite_runtime_status, _update_complete_message- sqlite_runtime_ok, sqlite_info = _post_update_sqlite_runtime_status()- if sqlite_info is None:- # Grace path: only a POSITIVE vulnerable probe demotes success to partial.- sqlite_runtime_ok = True- print()- if node_failures or not desktop_build_ok or not sqlite_runtime_ok:- parts = []- if node_failures:- parts.append(f"Node.js dependencies for {', '.join(node_failures)} did not refresh")- if not desktop_build_ok:- parts.append("the desktop app was not rebuilt and is still on the previous build")- if parts:- print("⚠ Update partially complete — " + "; ".join(parts) + ".")- if node_failures:- print(" Code and Python deps are updated, but the dashboard/TUI may")- print(" be in a mixed state until the Node deps are rebuilt.")- if not desktop_build_ok:- print(" Run `hermes desktop` to retry the desktop rebuild.")- if not sqlite_runtime_ok:- for line in _sqlite_partial_completion_lines(sqlite_info.sqlite_version_string):- print(line)- else:- _print_update_completion(_update_complete_message(pre_update_version))- # A multi-profile host whose gateway came back standalone on a guard says so here too — the- # update summary is the one line operators read (the boot log under s6 is not).- with suppress(Exception):- from hermes_cli.gateway_multiplex_mode import consume_rewritten_notice, recorded_standalone_warning_lines- for line in [*consume_rewritten_notice(), *recorded_standalone_warning_lines()]:- print(line)- return desktop_build_ok and sqlite_runtime_ok+ stop_for_relaunch()def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:- """Replace *state_path* with the snapshot image; True when the result passes integrity.+ """Restore through backup's authority reservation and pre-publication epoch floor.- Stale sidecars are cleared first so the corrupt DB's WAL can't replay over the image.- Refuses (False) while another process — or a live connection in THIS process — holds the- DB: copying over a live writer's inode desyncs its page cache and its next checkpoint- clobbers pages. Holder scan ``None`` proceeds (gateways drained; refusing on unknown would- disable auto-restore on non-Linux). Raises OSError if the copy fails.+ Use the single-database primitive, not whole-profile restore: post-update config+ and unrelated files must not roll back with a damaged transcript store."""- from hermes_cli.backup import _safe_restore_db, verify_sqlite_integrity+ from hermes_cli.backup import verify_sqlite_integrity- from hermes_cli.backup_restore import _foreign_db_holder_pids- from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access- holders = _foreign_db_holder_pids(state_path)- if holders:- print(- f" ✗ Auto-restore refused: process(es) {holders} still hold "- "state.db or its WAL open. Stop them (hermes gateway stop), "- "then restore manually with /snapshot restore."- )++ from hermes_cli.backup_restore import _safe_restore_db++ snap_state.stat() # Preserve the caller's OSError reporting for missing snapshots.+ if not verify_sqlite_integrity(snap_state, check_header=True, run_pragma=True).get("valid"):return False- # The foreign-pid scan excludes THIS process; an in-process SessionDB handle is just as- # live (it would checkpoint through deleted-inode sidecars). offline_file_access fails- # CLOSED on any tracked connection and holds the lock across clear + copy.- try:- with offline_file_access(state_path, what="restore a snapshot over"):- _clear_stale_sqlite_sidecars(state_path)- shutil.copy2(snap_state, state_path)- except LiveConnectionError as exc:- print(- f" ✗ Auto-restore refused: {exc} Close the in-process database "- "handles (or restart Hermes) and retry."- )+ if not _safe_restore_db(snap_state, state_path):+ print(" ✗ Auto-restore refused or failed; state.db was not restored.")+ print(" Stop the owning runtime and close database handles before retrying.")+ print(" If the canonical runtime epoch is unreadable, do not restore in place:")+ print(" use `hermes sessions recover --source <snapshot> --output <separate-path>`")+ print(" to salvage transcripts into a separate output.")return Falserestored = verify_sqlite_integrity(state_path, check_header=True, run_pragma=True)return bool(restored.get("valid"))diff --cc hermes_cli/web_routers/profiles.pyindex e14cd8f995a,553530b50c1..2eb2ec0455f--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@@ -340,6 -343,44 +343,32 @@@ def _sidebar_profile_cache_clear()_SIDEBAR_PROFILE_CACHE.clear()-def _sidebar_profile_cache_drop(key) -> None:- with _SIDEBAR_PROFILE_CACHE_LOCK:- _SIDEBAR_PROFILE_CACHE.pop(key, None)--+ def _profile_state_db(home) -> Path:+ return Path(home) / "state.db"++-def _profile_heal_exhausted(home) -> bool:- """True when the one-shot writable heal already gave up on this store."""- from hermes_cli.web_server_sessions import _session_db_heal_exhausted-- return str(_profile_state_db(home)) in _session_db_heal_exhausted--+ def _slice_has_rows(slices: Dict[str, Any]) -> bool:+ return any(slices.get(key) for key in ("recents", "cron", "messaging"))+++ def _retryable_profile_errors(errors: List[Dict[str, str]], scanned) -> List[Dict[str, str]]:+ """Scan failures Retry can re-attempt. A latched corrupt store has its own notice."""+ corrupt = set(_corrupt_profile_stores(scanned))+ return [dict(err) for err in errors if err.get("profile") not in corrupt]+++ def _failed_load_slice(errors: List[Dict[str, str]], **extra) -> Dict[str, Any]:+ """Failed load: no ``sessions`` key. An empty list would read as data loss."""+ return {"failed": True, "retry": True, "errors": [dict(err) for err in errors], **extra}+++ def _profiles_failed(errors: List[Dict[str, str]]) -> Dict[str, Dict[str, Any]]:+ return {+ err["profile"]: {"failed": True, "retry": True, "error": err.get("error", "")}+ for err in errors if err.get("profile")+ }++def _sidebar_singleflight_cache(func):"""Coalesce concurrent sidebar scans and briefly reuse their response.@@@ -516,18 -565,33 +553,22 @@@ def get_profiles_sessions_sidebarif recents_scope != "all" and name != recents_scope:continuescanned.append((name, home))- db_path = Path(home) / "state.db"+ db_path = _profile_state_db(home)if not db_path.exists():continue+ recents_subagents = subagent_listing_scope(home, exclude_sources=recents_exclude_list or None)profile_cache_key = (str(db_path), _sidebar_db_fingerprint(db_path), cap["recents"],tuple(recents_exclude_list), cap["cron"], cap["messaging"],- tuple(messaging_exclude_list))+ tuple(messaging_exclude_list), recents_subagents[0])slices = _sidebar_profile_cache_get(profile_cache_key)if slices is None:- slices = _read_profile_db(name, home, errors,- lambda db: _build_slices(db, profile_cache_key))+ slices = _read_profile_db(+ name, home, errors,+ lambda db: _build_slices(db, profile_cache_key, recents_subagents))if slices is None:continue- # Heal already gave up and this read found no rows. That is not "no- # sessions" — the probe-less open can miss the schema the list needs.- # Drop the cached empty page so the next poll does not reuse the lie.- if _profile_heal_exhausted(home) and not _slice_has_rows(slices):- _sidebar_profile_cache_drop(profile_cache_key)- if not any(err.get("profile") == name for err in errors):- errors.append({- "profile": name,- "error": "schema heal exhausted; session list unavailable",- })- continue+ if _slice_has_rows(slices):+ contributed.add(name)# A full window means more rows remain on disk — all "load more" needs, at no cost# beyond the rows already read. Pinned rows count: they occupy LIMIT slots, and a# short list has nothing past the page for the pin back-fill to add, so pins cannotdiff --cc hermes_cli/web_routers/sessions.pyindex b3df1f5bec0,8fa59198092..0867d906775--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@@ -17,9 -18,10 +18,10 @@@ from fastapi import APIRouter, HTTPExcefrom fastapi.encoders import jsonable_encoderfrom fastapi.responses import StreamingResponse+ from hermes_cli.session_listing import subagent_listing_scopefrom 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 (@@@ -714,13 -717,18 +727,21 @@@ async def get_session_messages_around@manage_router.delete("/api/sessions/{session_id}")-async def delete_session_endpoint(session_id: str, profile: Optional[str] = None):- def _delete(db):- # Already-absent is an idempotent success: the desktop optimistically- # removes the row and RESTORES it on any error, so a 404 resurrected- # ghost rows (transient empties racing the sidebar snapshot).- sid = _resolve_session_id(db, session_id)- if not sid:- return {"ok": True, "already_absent": True}- db.delete_session(sid, sessions_dir=_session_files_dir(profile))- return {"ok": True}-- return await asyncio.to_thread(_with_db, profile, _delete, read_only=False)+async def delete_session_endpoint(session_id: str, request: Request, profile: Optional[str] = None,+ request_id: Optional[str] = None, expected_revision: Optional[int] = None,+ expected_generation: Optional[int] = None):+ from hermes_cli.web_server_sessions import _mutate_session_request- return await _mutate_session_request(request, profile, session_id,++ from hermes_state import SessionDB++ result = await _mutate_session_request(request, profile, session_id,+ request_id=request_id, expected_revision=expected_revision,+ expected_generation=expected_generation, operation='delete', payload={})++ # The canonical delete retires rows only: scrub each deleted session's on-disk artifacts++ # (secret-bearing ``session_<id>.json`` snapshots, ``request_dump_<id>_*.json``) as the CLI++ # delete path does (#60207). Idempotent, so an exact retry of the receipt repeats it safely.++ sessions_dir = _session_files_dir(profile)++ for sid in result.get('deleted_ids') or ():++ await asyncio.to_thread(SessionDB._remove_session_files, sessions_dir, str(sid))++ return result@manage_router.post("/api/sessions/owner-backfill")diff --cc hermes_cli/web_server.pyindex 51ffa3e3a40,b14c72001b0..5465896d132--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@@ -165,7 -337,7 +187,7 @@@ def _get_pty_active_session_files(app:return _app_state_default(app, "pty_active_session_files", dict)- app = FastAPI(title="Hermes Agent", version=__version__, lifespan=app_lifespan)-app = FastAPI(title="Hermes Agent", version=get_version_info().base_version, lifespan=_lifespan)++app = FastAPI(title="Hermes Agent", version=get_version_info().base_version, lifespan=app_lifespan)# Memory-provider OAuth connect routes live in the memory layer, not here.diff --cc hermes_state_common.pyindex ffe76e0c1ea,e35e61a06a3..881cd091727--- a/hermes_state_common.py+++ b/hermes_state_common.py@@@ -337,9 -361,8 +361,10 @@@ CREATE TABLE IF NOT EXISTS system_prompCREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY,+ runtime_revision INTEGER NOT NULL DEFAULT 0,+ runtime_generation INTEGER NOT NULL DEFAULT 0,source TEXT NOT NULL,+ created_source TEXT,user_id TEXT,session_key TEXT,chat_id TEXT,diff --cc hermes_state_worker_lifecycle.pyindex 7f345e92411,00000000000..5f4bb5a09f4mode 100644,000000..100644--- a/hermes_state_worker_lifecycle.py+++ b/hermes_state_worker_lifecycle.py@@@ -1,245 -1,0 +1,245 @@@+"""Closed worker lifecycle handlers, called only inside the receipt transaction."""+import json+import time++from hermes_state_runtime import RuntimeStoreError+++_IDENTITY_FIELDS = frozenset({+ 'user_id', 'session_key', 'chat_id', 'chat_type', 'thread_id',+ 'parent_session_id', 'cwd', 'profile_name', 'git_repo_root', 'origin_json', 'display_name',+})+_CREATE_FIELDS = _IDENTITY_FIELDS | {'source', 'model', 'model_config', 'system_prompt'}+_CONSTRUCTOR_CONFIG = frozenset({'max_iterations', 'max_tokens', 'reasoning_config', 'yolo_mode'})+++def worker_create(db, conn, session_id, payload):+ if set(payload) - _CREATE_FIELDS or 'source' not in payload:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()+ # A worker cannot mint a row or supply unreserved routing, lineage or cwd.+ if row is None or payload['source'] != row['source']:+ raise RuntimeStoreError('permission_denied')+ for key in _IDENTITY_FIELDS:+ value = payload.get(key)+ if value is not None and value != row[key]:+ raise RuntimeStoreError('permission_denied')+ for key in _CREATE_FIELDS - {'model_config'}:+ if payload.get(key) is not None and not isinstance(payload[key], str):+ raise RuntimeStoreError('invalid_params')+ config = payload.get('model_config')+ if config is not None and (not isinstance(config, dict) or set(config) - _CONSTRUCTOR_CONFIG):+ raise RuntimeStoreError('invalid_params')+ insert_session_row_in_transaction(db, conn, session_id, **payload)+ return {'value': session_id}+++def worker_end(db, conn, session_id, payload):+ if set(payload) != {'end_reason'} or not isinstance(payload['end_reason'], str) or not payload['end_reason']:+ raise RuntimeStoreError('invalid_params')+ db._end_and_bump(conn,+ 'UPDATE sessions SET ended_at=?,end_reason=? WHERE id=? AND ended_at IS NULL',+ (time.time(), payload['end_reason'], session_id), session_id, payload['end_reason'])+ return {'value': None}+++def worker_lifecycle(db, conn, session_id, payload):+ from hermes_state_sessions import classify_session_status+ if payload:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute("SELECT role,tool_calls IS NOT NULL AS has_tool_calls,finish_reason "+ "FROM messages WHERE session_id=? ORDER BY id DESC LIMIT 1", (session_id,)).fetchone()+ value = classify_session_status(role=row['role'], has_tool_calls=bool(row['has_tool_calls']),+ finish_reason=row['finish_reason']) if row else 'empty'+ return {'value': value}+++def worker_title(db, conn, session_id, payload):+ if (set(payload) != {'title', 'source'} or payload['source'] not in ('user', 'derived', 'llm')+ or not (payload['title'] is None or isinstance(payload['title'], str))):+ raise RuntimeStoreError('invalid_params')+ try:+ value = bool(db._set_session_title_in_transaction(+ conn, session_id, payload['title'], source=payload['source']))+ except ValueError:+ # Expected validation/conflict outcomes must not poison the retry journal.+ # Keep candidate authority in the receipt, not an in-memory worker claim.+ return {'value': False, 'error': 'Title unavailable or invalid', 'title_candidate': payload['title']}+ return {'value': value}+++def worker_title_source(db, conn, session_id, payload):+ if set(payload) != {'source'} or payload['source'] not in ('user', 'derived', 'llm'):+ raise RuntimeStoreError('invalid_params')+ return {'value': conn.execute(+ 'UPDATE sessions SET title_source=? WHERE id=? AND title IS NOT NULL',+ (payload['source'], session_id)).rowcount > 0}+++def worker_next_title(db, conn, session_id, payload):+ from hermes_state_titles import _NUMBERED_TITLE_RE+ from hermes_state_common import escape_like+ if set(payload) != {'base_title'} or not isinstance(payload['base_title'], str):+ raise RuntimeStoreError('invalid_params')+ title = conn.execute('SELECT title FROM sessions WHERE id=?', (session_id,)).fetchone()[0]+ # Only an assigned title or a receipted title attempt authorizes dedupe.+ # Concurrent activity/usage receipts must not invalidate that title attempt.+ candidate = payload['base_title']+ attempted = conn.execute(+ "SELECT 1 FROM worker_receipts r JOIN worker_executions w ON w.execution_id=r.execution_id "+ "WHERE w.session_id=? AND w.status='running' "+ "AND json_extract(r.result_json,'$.title_candidate')=? LIMIT 1",+ (session_id, candidate)).fetchone()+ if candidate != title and attempted is None:+ raise RuntimeStoreError('permission_denied')+ match = _NUMBERED_TITLE_RE.match(candidate)+ base = match.group(1) if match else candidate+ rows = conn.execute("SELECT title FROM sessions WHERE title=? OR title LIKE ? ESCAPE '\\'",+ (base, f'{escape_like(base)} #%')).fetchall()+ if not rows:+ return {'value': base}+ numbers = [int(m.group(2)) for m in (_NUMBERED_TITLE_RE.match(row['title']) for row in rows) if m]+ return {'value': f'{base} #{max([1, *numbers]) + 1}'}+++def worker_activity(db, conn, session_id, payload):+ import math+ from agent.session_activity import bound_activity_description, normalize_activity_provenance+ if (set(payload) != {'ts', 'description', 'provenance'}+ or any(payload[k] is not None and not isinstance(payload[k], str)+ for k in ('description', 'provenance'))):+ raise RuntimeStoreError('invalid_params')+ when = payload['ts']+ if when is not None and (type(when) not in (float, int) or not math.isfinite(when)):+ raise RuntimeStoreError('invalid_params')+ when = time.time() if when is None else float(when)+ conn.execute('UPDATE sessions SET last_activity_at=?,last_activity_description=?,last_activity_provenance=? '+ 'WHERE id=? AND (last_activity_at IS NULL OR last_activity_at<?)',+ (when, bound_activity_description(payload['description']),+ normalize_activity_provenance(payload['provenance']).value, session_id, when))+ return {'value': None}+++def worker_activity_clear(db, conn, session_id, payload):+ from agent.session_activity import ActivityProvenance+ if payload:+ raise RuntimeStoreError('invalid_params')+ conn.execute('UPDATE sessions SET last_activity_description=?,last_activity_provenance=? WHERE id=?',+ ('', ActivityProvenance.UNKNOWN.value, session_id))+ return {'value': None}+++def worker_billing_route(db, conn, session_id, payload):+ if (set(payload) != {'provider', 'base_url', 'billing_mode'}+ or any(payload[k] is not None and not isinstance(payload[k], str) for k in payload)):+ raise RuntimeStoreError('invalid_params')+ conn.execute('UPDATE sessions SET billing_provider=?,billing_base_url=?,billing_mode=COALESCE(?,billing_mode),'+ 'system_prompt=NULL,system_prompt_hash=NULL WHERE id=?',+ (payload['provider'], payload['base_url'], payload['billing_mode'], session_id))+ db._delete_unreferenced_system_prompts(conn)+ return {'value': None}+++def worker_api_content(db, conn, session_id, payload):+ from hermes_state_messages import _scrub_surrogates+ if set(payload) != {'content', 'api_content'} or not isinstance(payload['api_content'], str):+ raise RuntimeStoreError('invalid_params')+ value = conn.execute(+ "UPDATE messages SET api_content=? WHERE id=(SELECT id FROM messages WHERE session_id=? "+ "AND role='user' AND active=1 ORDER BY id DESC LIMIT 1) AND content IS ?",+ (_scrub_surrogates(payload['api_content']), session_id, db._encode_content(payload['content']))).rowcount+ return {'value': value}+++WORKER_LIFECYCLE_HANDLERS = {+ 'session.title': worker_title,+ 'session.title_source': worker_title_source,+ 'session.next_title': worker_next_title,+ 'session.activity': worker_activity,+ 'session.activity_clear': worker_activity_clear,+ 'session.billing_route': worker_billing_route,+ 'session.api_content': worker_api_content,+ 'session.create': worker_create,+ 'session.end': worker_end,+ 'session.lifecycle': worker_lifecycle,+}+++def insert_session_row_in_transaction(+ self, conn, session_id, source, model=None, model_config=None,+ system_prompt=None, user_id=None, session_key=None, chat_id=None,+ chat_type=None, thread_id=None, parent_session_id=None, cwd=None,+ profile_name=None, git_repo_root=None, origin_json=None, display_name=None,+ transport_profile=None):+ """Connection-taking body of the keep-existing constructor upsert.++ The ordinary constructor should delegate here too. Worker identity is+ validated before entry; this helper never opens or commits a DB.+ """+ from hermes_state_sessions import _UPSERT_KEEP_EXISTING_SQL+ from hermes_state_mutation_retirement import RETIRED_PREFIX+ # A delayed constructor/accounting backfill must not recreate a deleted session+ # beside its durable tombstone (the exact delete retry would then report a stale+ # success while a fresh delete collides with the existing marker).+ if (conn.execute('SELECT 1 FROM sessions WHERE id=?', (session_id,)).fetchone() is None+ and conn.execute('SELECT 1 FROM state_meta WHERE key=?', (RETIRED_PREFIX + session_id,)).fetchone()):+ raise RuntimeStoreError('not_found')+ if not (profile_name or "").strip():+ profile_name = self._own_profile_name()+ system_prompt_hash = self._store_system_prompt(conn, system_prompt)+ conn.execute(+ """INSERT INTO sessions (- id, source, user_id, session_key, chat_id, chat_type, thread_id,++ id, source, created_source, user_id, session_key, chat_id, chat_type, thread_id,+ model, model_config, system_prompt, system_prompt_hash,+ parent_session_id, cwd, profile_name, transport_profile, git_repo_root,+ origin_json, display_name, started_at+ )- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)++ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ source = CASE+ WHEN sessions.source = 'unknown'+ THEN COALESCE(excluded.source, 'unknown')+ ELSE sessions.source+ END,+ model = COALESCE(sessions.model, excluded.model),+ model_config = CASE+ WHEN excluded.model_config IS NOT NULL+ AND json_type(+ sessions.model_config, '$._reset_from'+ ) IS NOT NULL+ AND json_remove(+ sessions.model_config, '$._reset_from'+ ) = '{}'+ THEN json_set(+ excluded.model_config,+ '$._reset_from',+ json_extract(+ sessions.model_config, '$._reset_from'+ )+ )+ ELSE COALESCE(+ sessions.model_config, excluded.model_config+ )+ END,+ system_prompt_hash = COALESCE(+ sessions.system_prompt_hash,+ excluded.system_prompt_hash+ ),+ system_prompt = CASE+ WHEN sessions.system_prompt_hash IS NULL+ AND excluded.system_prompt_hash IS NOT NULL+ THEN NULL+ ELSE sessions.system_prompt+ END,+""" + _UPSERT_KEEP_EXISTING_SQL,+ (- session_id, source, user_id, session_key, chat_id, chat_type, thread_id, model,++ session_id, source, source, user_id, session_key, chat_id, chat_type, thread_id, model,+ json.dumps(model_config) if model_config else None, system_prompt_hash,+ parent_session_id, cwd, profile_name, transport_profile, git_repo_root, origin_json,+ display_name, time.time(),+ ),+ )+ if system_prompt_hash is not None:+ self._delete_unreferenced_system_prompts(conn)+ if parent_session_id:+ self._inherit_parent_session_metadata(conn, session_id)diff --cc tests/_fixtures/live_system_guard.pyindex 00000000000,7375f11cfe0..32cf817d577mode 000000,100644..100644--- a/tests/_fixtures/live_system_guard.py+++ b/tests/_fixtures/live_system_guard.py@@@ -1,0 -1,465 +1,497 @@@+ """The autouse live-system guard: no real kills, systemctl writes, gateway spawns or checkout writes.++ Imported into ``tests/conftest.py`` so pytest registers the fixture there;+ ``pytest_plugins`` is not an option because ``tests/conftest.py`` is not the+ rootdir conftest (the rootdir is the repo root, where ``pyproject.toml`` lives).+ """+ from pathlib import Path++ import pytest++ PROJECT_ROOT = Path(__file__).parent.parent.parent+++ # ── Live-system guard ──────────────────────────────────────────────────────+ #+ # Several test files exercise the gateway-restart / kill code paths+ # (``cmd_update``, ``kill_gateway_processes``, ``stop_profile_gateway``).+ # When a single test forgets to mock either ``os.kill`` or the global+ # ``find_gateway_pids`` helper, the real call leaks out of the hermetic+ # environment and finds the developer's live ``hermes-gateway`` process+ # via ``psutil`` — sending it SIGTERM mid-test. The shutdown forensics in+ # PR #23285 caught this happening 5+ times in 3 days, every time+ # correlated with a ``tests/hermes_cli/`` pytest run starting up.+ #+ # This fixture makes the leak impossible by intercepting the two+ # primitives that actually do damage:+ #+ # • ``os.kill`` rejects any PID outside the test process subtree with+ # a hard ``RuntimeError`` so the offending test gets a stack trace+ # instead of silently murdering the real gateway.+ # • ``subprocess.run`` / ``subprocess.Popen`` / ``call`` / ``check_call`` /+ # ``check_output`` reject any ``systemctl ... <verb> hermes-gateway``+ # invocation that would mutate the live unit. Read-only systemctl+ # calls (``status``, ``show``, ``list-units``) still pass through.+ #+ # We intentionally do NOT stub ``find_gateway_pids`` / ``_scan_gateway_pids``+ # here — tests of those functions themselves need the real implementation.+ # Even if a test gets the live gateway PID back from a real scan, the+ # ``os.kill`` guard above catches the actual signal call, and the+ # ``systemctl`` guard catches the systemd path. Discovery without+ # delivery is harmless.++ _LIVE_SYSTEM_GUARD_BYPASS_MARK = "live_system_guard_bypass"+ _GATEWAY_LOOKALIKE_MARK = "spawns_gateway_lookalike"++ # Tests may designate a temporary repo to exercise the real guard safely.+ _LIVE_GUARD_PROTECTED_GIT_ROOTS = (PROJECT_ROOT,)+++ @pytest.fixture(autouse=True)+ def _live_system_guard(request, monkeypatch):+ """Block real os.kill / systemctl / gateway-pid scans during tests.++ See block comment above for the why. Tests that genuinely need+ real signal delivery (e.g. PTY tests that SIGINT their own child)+ can opt out with ``@pytest.mark.live_system_guard_bypass``.++ Coverage (every primitive that can deliver a signal to or otherwise+ terminate a foreign process):+ • os.kill, os.killpg (POSIX)+ • subprocess.run / Popen / call / check_call / check_output+ • subprocess.getoutput / getstatusoutput+ • os.system / os.popen+ • pty.spawn+ • asyncio.create_subprocess_exec / create_subprocess_shell+ Subprocess inspection looks at the WHOLE command string (not just+ tokens[0]), so ``bash -c "systemctl restart hermes-gateway"``,+ ``sudo systemctl ...``, ``env systemctl ...``, ``setsid systemctl ...``+ are all caught. ``pkill``/``killall``/``taskkill`` invocations+ targeting hermes/python patterns are also blocked. Bare ``git``+ commands may not mutate a protected checkout. Git writes against+ temporary repositories and read-only Git commands remain allowed.+ """+ if request.node.get_closest_marker(_LIVE_SYSTEM_GUARD_BYPASS_MARK):+ yield+ return++ import os as _os+ import shlex as _shlex+ import subprocess as _subprocess++ test_pid = _os.getpid()+ lookalike_ok = request.node.get_closest_marker(_GATEWAY_LOOKALIKE_MARK) is not None+ # Capture the test process's existing children at fixture start —+ # any *new* children spawned by the test are also allowlisted via+ # the live psutil walk below. Static set keeps the fast path cheap.+ try:+ import psutil as _psutil+ _initial_children = {+ c.pid for c in _psutil.Process(test_pid).children(recursive=True)+ }+ except Exception:+ _psutil = None+ _initial_children = set()++ def _is_own_subtree(pid: int) -> bool:+ # PID 0 means "our own process group"; -1 means "every process we+ # can signal". Both are dangerous when paired with SIGTERM/SIGKILL,+ # but pid 0 is technically scoped to our group so allow it; pid -1+ # is treated as foreign (refuse).+ if pid == 0:+ return True+ if pid < 0:+ return False+ if pid == test_pid or pid in _initial_children:+ return True+ if _psutil is None:+ return False+ try:+ walker = _psutil.Process(pid)+ except Exception:+ # Stale PID — kill would be a no-op anyway, allow it.+ return True+ try:+ for parent in walker.parents():+ if parent.pid == test_pid:+ return True+ except Exception:+ return False+ return False++ real_kill = _os.kill++ def _guarded_kill(pid, sig, *args, **kwargs):+ # Signal 0 is a pure liveness probe — it cannot terminate anything.+ # psutil.pid_exists() uses os.kill(pid, 0) on POSIX, and probing a+ # just-killed grandchild that was reparented to init (zombie with a+ # foreign parent chain) must not trip the guard. Flaked in CI on+ # test_entire_tree_is_sigkilled_not_just_parent.+ if int(sig) == 0:+ return real_kill(pid, sig, *args, **kwargs)+ if _is_own_subtree(int(pid)):+ return real_kill(pid, sig, *args, **kwargs)+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked os.kill("+ f"{pid}, {sig}) — PID is outside the test process subtree. "+ "If this fired in CI it means the test reached a real "+ "kill_gateway_processes / stop_profile_gateway / cmd_update "+ "code path without mocking find_gateway_pids and os.kill. "+ "Mock both, or mark the test with "+ "@pytest.mark.live_system_guard_bypass if real signal "+ "delivery is genuinely required."+ )++ monkeypatch.setattr(_os, "kill", _guarded_kill)++ # ``os.killpg`` is the same risk class — sends a signal to every+ # process in a group. The gateway is a session leader (its own+ # PGID == its PID), so killpg(gateway_pid, SIGTERM) is a one-shot+ # kill of the live process. Allow it only when the target PGID is+ # the test process's own group.+ if hasattr(_os, "killpg"):+ real_killpg = _os.killpg+ own_pgid = _os.getpgrp()++ def _guarded_killpg(pgid, sig, *args, **kwargs):+ # Signal 0 is a pure liveness probe — never destructive.+ if int(sig) == 0:+ return real_killpg(pgid, sig, *args, **kwargs)+ if int(pgid) == own_pgid or _is_own_subtree(int(pgid)):+ return real_killpg(pgid, sig, *args, **kwargs)+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked "+ f"os.killpg({pgid}, {sig}) — PGID is outside the test "+ "process group. See _live_system_guard for the why."+ )++ monkeypatch.setattr(_os, "killpg", _guarded_killpg)++ # ── Subprocess command-string inspection (whole-line) ──────────+ _HERMES_TOKENS = (+ "hermes-gateway",+ "hermes.service",+ "hermes_cli.main gateway",+ "hermes_cli/main.py gateway",+ "gateway/run.py",+ "hermes gateway",+ )+ _MUTATING_VERBS = (+ "restart", "start", "stop", "kill", "reload",+ "reset-failed", "enable", "disable", "mask", "unmask",+ "daemon-reload", "try-restart", "reload-or-restart",+ )+ _PROCESS_KILLERS = ("pkill", "killall", "taskkill", "skill", "fuser")+ _CONTAINER_RUNTIMES = ("docker", "podman", "nerdctl")++ def _first_token_basename(cmd_str: str) -> str:+ try:+ tokens = _shlex.split(cmd_str)+ except ValueError:+ tokens = cmd_str.split()+ return tokens[0].rsplit("/", 1)[-1].lower() if tokens else ""+ # Shell/launcher executables whose arguments are themselves commands —+ # argv[0]-only scanning must not exempt what they wrap.+ _WRAPPER_COMMANDS = (+ "sh", "bash", "zsh", "dash", "env", "nohup", "setsid",+ "timeout", "sudo", "xargs", "nice", "ionice", "stdbuf", "flock",+ )++ def _cmd_to_string(cmd) -> str:+ if cmd is None:+ return ""+ if isinstance(cmd, (bytes, bytearray)):+ try:+ return bytes(cmd).decode(errors="replace")+ except Exception:+ return ""+ if isinstance(cmd, str):+ return cmd+ if isinstance(cmd, (list, tuple)):+ try:+ return " ".join(str(t) for t in cmd)+ except Exception:+ return ""+ return str(cmd)++ def _matches_hermes_gateway(cmd_str: str) -> bool:+ low = cmd_str.lower()+ return any(tok in low for tok in _HERMES_TOKENS)++ def _is_blocked_systemctl(cmd) -> bool:+ cmd_str = _cmd_to_string(cmd)+ if "systemctl" not in cmd_str:+ return False+ if not _matches_hermes_gateway(cmd_str):+ return False+ try:+ tokens = _shlex.split(cmd_str)+ except ValueError:+ tokens = cmd_str.split()+ return any(verb in tokens for verb in _MUTATING_VERBS)++ def _is_process_killer(cmd) -> bool:+ cmd_str = _cmd_to_string(cmd)+ try:+ tokens = _shlex.split(cmd_str)+ except ValueError:+ tokens = cmd_str.split()+ if not tokens:+ return False++ # For argv-style calls only argv[0] is the executable; scanning every+ # argument blocked innocent commands like ``cat /tmp/.../skill``+ # ("skill" is in _PROCESS_KILLERS). Wrapper executables still get+ # full-token scanning so ``["bash", "-c", "pkill ..."]`` stays caught.+ if isinstance(cmd, (list, tuple)):+ head0 = tokens[0].rsplit("/", 1)[-1].rsplit("\\", 1)[-1]+ killer_tokens = tokens if head0 in _WRAPPER_COMMANDS else tokens[:1]+ else:+ killer_tokens = tokens+ for tok in killer_tokens:+ head = tok.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]+ if head in _PROCESS_KILLERS:+ low = cmd_str.lower()+ # pkill -f pattern: catch hermes-themed patterns + a+ # plain "python" -f which would catch the live gateway+ # whose cmdline contains "python -m hermes_cli.main".+ if (+ "hermes" in low+ or "gateway" in low+ or ("python" in low and "-f" in tokens)+ ):+ return True+ return False++ from tests.git_safety import blocked_git_mutation+++ def _sandboxed_gateway_child(cmd_str: str, env) -> bool:++ """The disposable-daemon fixtures (``tests/gateway/fixtures/*``, the socket-path-length++ probes) launch the bare ``python -m gateway.run`` module entry with an explicit ``env``++ that re-homes BOTH ``HERMES_HOME`` and ``HOME`` away from the developer's account. Such a++ child resolves no developer unit or config, holds no live port, and is reaped by its++ test: the orphan class the guard exists for is the ``hermes gateway run|start|restart``++ CLI spawn against the real home, which the fixtures never use."""++ if not isinstance(env, dict):++ return False++ try:++ tokens = _shlex.split(cmd_str)++ except ValueError:++ tokens = cmd_str.split()++ if "-m" not in tokens or tokens[tokens.index("-m") + 1:][:1] != ["gateway.run"]:++ return False++ hermes_home, home = env.get("HERMES_HOME"), env.get("HOME")++ if not hermes_home or not home:++ return False++ # The developer's account home from the passwd db: tests re-point ``Path.home`` at their++ # tmp user dir, which would make a sandboxed child look like it runs against the real one.++ try:++ import pwd++ real_home = Path(pwd.getpwuid(_os.getuid()).pw_dir).resolve()++ except (ImportError, KeyError):++ real_home = Path.home().resolve()++ try:++ return (Path(home).resolve() != real_home++ and not Path(hermes_home).resolve().is_relative_to(real_home))++ except Exception:++ return False+++ def _check_subprocess_cmd(name, cmd, kwargs=None):+ git_verb = blocked_git_mutation(cmd, kwargs, _LIVE_GUARD_PROTECTED_GIT_ROOTS)+ if git_verb is not None:+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked "+ f"subprocess.{name}({cmd!r}) — `git {git_verb}` would mutate "+ "the protected checkout. Use a temporary repository or mock "+ "the update boundary; live_system_guard_bypass is for deliberate live tests."+ )+ if _is_blocked_systemctl(cmd):+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked "+ f"subprocess.{name}({cmd!r}) — would mutate the "+ "live hermes-gateway systemd unit. Mock "+ "subprocess.run / _run_systemctl in the test, or "+ "mark with @pytest.mark.live_system_guard_bypass."+ )+ if _is_process_killer(cmd):+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked "+ f"subprocess.{name}({cmd!r}) — process-killer command "+ "targeting hermes/python could hit the live gateway. "+ "Mark with @pytest.mark.live_system_guard_bypass if "+ "intentional."+ )+ # Block any subprocess that would run `hermes update` (or the+ # equivalent `python -m hermes_cli.main update`). These commands+ # run `git fetch origin + git pull` against the REAL checkout,+ # overwriting files like pyproject.toml mid-test-run and corrupting+ # every subsequent subprocess that reads them. The corruption is+ # especially insidious because the spawned process uses setsid/+ # start_new_session=True, making it invisible to pytest's process+ # tree (PPid=1) and nearly impossible to trace without explicit+ # inotify/SHA watchdogs. Any test that legitimately needs to exercise+ # the update-spawn path must mock subprocess.Popen explicitly.+ cmd_str = _cmd_to_string(cmd)+ low = cmd_str.lower()+ if "update" in low and (+ # hermes update / hermes update --gateway / setsid bash -c ... hermes update+ ("hermes" in low and "update" in low.split())+ or+ # python -m hermes_cli.main update --gateway+ ("hermes_cli" in low and "update" in low.split())+ or+ # venv/bin/hermes update (absolute path variant used in tests)+ (".venv/bin/hermes" in low and "update" in low)+ ):+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked "+ f"subprocess.{name}({cmd!r}) — this command would run "+ "`hermes update` against the real checkout, fetching "+ "from origin and overwriting repo files (e.g. "+ "pyproject.toml) mid-test-run. This corrupts every "+ "subsequent subprocess in the same runner. "+ "Mock subprocess.Popen (and subprocess.run if used) "+ "in the test instead, or mark with "+ "@pytest.mark.live_system_guard_bypass if genuinely "+ "needed (e.g. an integration test testing the update "+ "flow against a dedicated throwaway repo)."+ )+ # Block spawning a REAL gateway runtime (``python -m hermes_cli.main+ # gateway run|start|restart``). ``_spawn_hermes_action`` launches it+ # with start_new_session=True, so it outlives the pytest worker; the+ # child inherits the pytest-tmp HERMES_HOME, resolves the DEVELOPER's+ # ``hermes-gateway`` systemd unit (a tmp home hashes to no profile+ # suffix), restarts the live gateway, and the survivors squat the+ # webhook port. 2026-09-03: 39 such orphans lived 6 days after a+ # sibling refactor moved the spawn seam and left tests patching the+ # facade. The canonical matcher, never an argv substring.+ from gateway.status import gateway_spawn_intent_subcommand+ # A gateway launched INSIDE a container (`docker exec … hermes gateway start`) cannot+ # reach the host's systemd unit or webhook port; tests/docker/ exists to exercise it.+ in_container = _first_token_basename(cmd_str) in _CONTAINER_RUNTIMES+ if (+ not lookalike_ok+ and not in_container+ and gateway_spawn_intent_subcommand(cmd_str) in ("run", "start", "restart")++ and not _sandboxed_gateway_child(cmd_str, (kwargs or {}).get("env"))+ ):+ raise RuntimeError(+ f"tests/conftest.py live-system guard: blocked "+ f"subprocess.{name}({cmd!r}) — this would spawn a REAL "+ "hermes gateway runtime that outlives the test (it is "+ "detached), restarts the developer's live gateway, and "+ "holds the webhook port. Patch the spawn seam where "+ "production reads it (hermes_cli.web_server_gateway."+ "_spawn_hermes_action), or mark with "+ "@pytest.mark.spawns_gateway_lookalike a test that spawns "+ "and reaps its own stub child."+ )++ def _wrap_subprocess(name, real):+ def _guarded(cmd, *args, **kwargs):+ _check_subprocess_cmd(name, cmd, kwargs)+ return real(cmd, *args, **kwargs)+ _guarded.__name__ = f"_guarded_{name}"+ # Make the wrapper subscriptable like the wrapped callable when+ # the wrapped object is. ``subprocess.Popen[bytes]`` is used as+ # a type annotation in third-party packages (mcp, etc.); replacing+ # ``Popen`` with a plain function breaks ``Popen[bytes]`` at+ # import time. Defer ``__class_getitem__`` to the original.+ if hasattr(real, "__class_getitem__"):+ _guarded.__class_getitem__ = real.__class_getitem__+ return _guarded++ def _wrap_popen():+ """Subclass Popen so isinstance checks AND Popen[bytes] still work."""+ real = _subprocess.Popen++ class _GuardedPopen(real): # type: ignore[misc, valid-type]+ def __init__(self, cmd, *args, **kwargs):+ _check_subprocess_cmd("Popen", cmd, kwargs)+ super().__init__(cmd, *args, **kwargs)++ _GuardedPopen.__name__ = "Popen"+ _GuardedPopen.__qualname__ = "Popen"+ return _GuardedPopen++ real_run = _subprocess.run+ real_popen = _subprocess.Popen+ real_call = _subprocess.call+ real_check_call = _subprocess.check_call+ real_check_output = _subprocess.check_output+ real_getoutput = _subprocess.getoutput+ real_getstatusoutput = _subprocess.getstatusoutput++ monkeypatch.setattr(_subprocess, "run", _wrap_subprocess("run", real_run))+ monkeypatch.setattr(_subprocess, "Popen", _wrap_popen())+ monkeypatch.setattr(_subprocess, "call", _wrap_subprocess("call", real_call))+ monkeypatch.setattr(+ _subprocess, "check_call", _wrap_subprocess("check_call", real_check_call)+ )+ monkeypatch.setattr(+ _subprocess,+ "check_output",+ _wrap_subprocess("check_output", real_check_output),+ )+ monkeypatch.setattr(+ _subprocess, "getoutput", _wrap_subprocess("getoutput", real_getoutput)+ )+ monkeypatch.setattr(+ _subprocess,+ "getstatusoutput",+ _wrap_subprocess("getstatusoutput", real_getstatusoutput),+ )++ # os.system / os.popen — same risk class, completely unwrapped before.+ real_os_system = _os.system+ real_os_popen = _os.popen++ def _guarded_os_system(command):+ _check_subprocess_cmd("os.system", command)+ return real_os_system(command)++ def _guarded_os_popen(cmd, *args, **kwargs):+ _check_subprocess_cmd("os.popen", cmd, kwargs)+ return real_os_popen(cmd, *args, **kwargs)++ monkeypatch.setattr(_os, "system", _guarded_os_system)+ monkeypatch.setattr(_os, "popen", _guarded_os_popen)++ # pty.spawn — POSIX-only.+ try:+ import pty as _pty+ if hasattr(_pty, "spawn"):+ real_pty_spawn = _pty.spawn++ def _guarded_pty_spawn(argv, *args, **kwargs):+ _check_subprocess_cmd("pty.spawn", argv, kwargs)+ return real_pty_spawn(argv, *args, **kwargs)++ monkeypatch.setattr(_pty, "spawn", _guarded_pty_spawn)+ except Exception:+ pass++ # asyncio.create_subprocess_* — bypasses subprocess module entirely.+ try:+ import asyncio as _asyncio+ real_async_exec = _asyncio.create_subprocess_exec+ real_async_shell = _asyncio.create_subprocess_shell++ async def _guarded_async_exec(program, *args, **kwargs):+ _check_subprocess_cmd(+ "asyncio.create_subprocess_exec", [program, *args], kwargs+ )+ return await real_async_exec(program, *args, **kwargs)++ async def _guarded_async_shell(cmd, *args, **kwargs):+ _check_subprocess_cmd("asyncio.create_subprocess_shell", cmd, kwargs)+ return await real_async_shell(cmd, *args, **kwargs)++ monkeypatch.setattr(_asyncio, "create_subprocess_exec", _guarded_async_exec)+ monkeypatch.setattr(+ _asyncio, "create_subprocess_shell", _guarded_async_shell+ )+ except Exception:+ pass++ yielddiff --cc tests/acp_adapter/test_gateway_editor_mcp.pyindex d83e83c8843,00000000000..feac73398c1mode 100644,000000..100644--- a/tests/acp_adapter/test_gateway_editor_mcp.py+++ b/tests/acp_adapter/test_gateway_editor_mcp.py@@@ -1,182 -1,0 +1,182 @@@+"""Native ACP stdio through ordinary gateway source, real model and MCP peers."""+import asyncio+from http.server import BaseHTTPRequestHandler+import json+import os+import re+import signal+import subprocess+import sys+import time++import psutil+import pytest++from tests.acp_adapter.test_gateway_sessions import daemon, editor, viewer, model_peer, control # noqa: F401+++class MCPModelPeer(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ request = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ self.server.requests.append(request)+ messages = request.get('messages', [])+ tail = messages[next((i for i in range(len(messages)-1, -1, -1)+ if messages[i]['role'] == 'user'), 0):]+ results = [m for m in tail if m['role'] == 'tool']+ names = [t['function']['name'] for t in request.get('tools', [])+ if t['function']['name'].startswith('mcp__')]+ if not names:+ names = re.findall(r'mcp__editor_[a-z0-9_]+__echo', json.dumps(results))+ finished = next((m['content'] for m in results if 'OWNED_RESULT_' in str(m['content'])), None)+ message = {'role': 'assistant', 'content': 'DONE ' + str(finished)}+ if not finished:+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'mcp-fixture-' + str(len(results)), 'type': 'function', 'function': {+ 'name': ('tool_describe' if len(results) == 1 else 'tool_call') if names else 'tool_search',+ 'arguments': json.dumps(({'names': [names[0]]} if len(results) == 1 else+ {'name': names[0], 'arguments': {}}) if names else {'queries': ['owned echo']})}}]}+ tool = 'tool_calls' in message+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream' if request.get('stream') else 'application/json')+ self.end_headers()+ if request.get('stream'):+ if tool:+ message['tool_calls'][0]['index'] = 0+ for delta, finish in [(message, None), ({}, 'tool_calls' if tool else 'stop')]:+ frame = {'id': 'local-mcp', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'local-control', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': finish}]}+ self.wfile.write(('data: ' + json.dumps(frame) + '\n\n').encode())+ self.wfile.write(b'data: [DONE]\n\n')+ else:+ self.wfile.write(json.dumps({'id': 'local-mcp', 'object': 'chat.completion', 'created': 1,+ 'model': 'local-control', 'choices': [{'index': 0, 'message': message,+ 'finish_reason': 'tool_calls' if tool else 'stop'}]}).encode())+ self.wfile.flush()+++def specs(tmp_path, model_peer):+ model_peer.RequestHandlerClass = MCPModelPeer+ script = tmp_path / 'peer.py'+ script.write_text('''import json, os, sys, time+from pathlib import Path+for line in sys.stdin:+ r=json.loads(line); method=r.get('method'); ident=r.get('id')+ if ident is None: continue+ if method=='initialize': result={'protocolVersion':r['params']['protocolVersion'],'capabilities':{'tools':{}},'serverInfo':{'name':'owned-peer','version':'1'}}+ elif method=='tools/list': result={'tools':[{'name':'echo','description':'owned echo','inputSchema':{'type':'object','properties':{}}}]}+ elif method=='tools/call':+ marker=os.environ['MARKER']; gate=Path(os.environ['GATE'])+ Path(str(gate)+'.entered').write_text(marker)+ while not gate.exists(): time.sleep(.02)+ result={'content':[{'type':'text','text':'OWNED_RESULT_'+marker}]}+ else: result={}+ print(json.dumps({'jsonrpc':'2.0','id':ident,'result':result}),flush=True)+''')+ def spec(marker):+ return {'name': 'same-name', 'command': sys.executable, 'args': [str(script)], 'env': [+ {'name': 'MARKER', 'value': marker}, {'name': 'GATE', 'value': str(tmp_path / marker)},+ {'name': 'BORROWED_TOKEN', 'value': 'opaque-secret-' + marker}]}+ return spec('A'), spec('B')+++async def initialize(acp):+ assert 'result' in await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})+++async def prompt(acp, sid, text='Use owned echo'):+ return await acp.rpc('session/prompt', sessionId=sid, prompt=[{'type': 'text', 'text': text}])++- @pytest.mark.linux_only[email protected]("linux")+async def test_native_opposing_editor_mcp_survives_viewer_exit(daemon, specs, tmp_path, model_peer):+ (tmp_path / 'A').write_text('release')+ async with editor(daemon, tmp_path) as b:+ await initialize(b)+ bc = await b.rpc('session/new', cwd=str(tmp_path), mcpServers=[specs[1]])+ assert 'result' in bc, bc+ bs = bc['result']['sessionId']+ pending = asyncio.create_task(prompt(b, bs))+ try:+ async with asyncio.timeout(25):+ while not (tmp_path / 'B.entered').exists():+ await asyncio.sleep(.05)+ async with editor(daemon, tmp_path) as a:+ await initialize(a)+ ac = await a.rpc('session/new', cwd=str(tmp_path), mcpServers=[specs[0]])+ assert 'result' in ac, ac+ sid = ac['result']['sessionId']+ assert 'result' in await prompt(a, sid)+ assert 'OWNED_RESULT_A' in json.dumps(a.frames)+ assert 'OWNED_RESULT_B' not in json.dumps(a.frames)+ # A has exited and its scoped server is released; B's real call is still waiting.+ (tmp_path / 'B').write_text('release')+ assert 'result' in await pending+ assert 'OWNED_RESULT_B' in json.dumps(b.frames)+ assert 'OWNED_RESULT_A' not in json.dumps(b.frames)+ finally:+ (tmp_path / 'B').touch()+ await asyncio.gather(pending, return_exceptions=True)+ async with viewer(daemon) as ws:+ for session_id in (sid, bs):+ saved = await ws.rpc('session.resume', session_id=session_id)+ assert 'OWNED_RESULT_' in json.dumps(saved['messages'])+ import sqlite3+ with sqlite3.connect(daemon[0] / 'state.db') as db:+ dump = '\n'.join(db.iterdump())+ assert all('opaque-secret-' + marker not in dump for marker in ('A', 'B'))+ print('ACP_MCP_NATIVE_RECEIPT=' + json.dumps({'sessions': [sid, bs],+ 'model_requests': len(model_peer.requests), 'surviving_blocked_tool': 'OWNED_RESULT_B'}))++- @pytest.mark.linux_only[email protected]("linux")+async def test_native_cold_editor_rebind_refuses_changed_secret(daemon, specs, tmp_path, model_peer):+ (tmp_path / 'A').touch()+ async with editor(daemon, tmp_path) as acp:+ await initialize(acp)+ created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[specs[0]])+ assert 'result' in created, created+ sid = created['result']['sessionId']+ assert 'result' in await prompt(acp, sid)+ home, descriptor, env, root = daemon+ owned = psutil.Process(descriptor['pid'])+ os.kill(owned.pid, signal.SIGINT)+ await asyncio.to_thread(owned.wait, 20)+ with (tmp_path / 'cold.log').open('w') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ current = {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ current = control(home, 'identify')+ if current.get('state') == 'ready' and current['instance_id'] != descriptor['instance_id']:+ break+ except (OSError, ValueError):+ pass+ await asyncio.sleep(.1)+ assert current.get('state') == 'ready'+ cold = home, current, env, root+ async with editor(cold, tmp_path) as acp:+ await initialize(acp)+ changed = json.loads(json.dumps(specs[0]))+ changed['env'][-1]['value'] = 'changed-secret'+ refused = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[changed])+ assert 'acp_mcp_policy_conflict' in json.dumps(refused), refused+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[specs[0]])+ assert 'result' in loaded, loaded+ acp.frames.clear() # Old replay is not evidence of new execution.+ assert 'result' in await prompt(acp, sid, 'Use owned echo after restart')+ assert 'OWNED_RESULT_A' in json.dumps(acp.frames)+ print('ACP_MCP_COLD_RECEIPT=' + json.dumps({'session_id': sid,+ 'old_pid': descriptor['pid'], 'new_pid': process.pid, 'changed_secret_refused': True}))+ finally:+ if process.poll() is None:+ process.send_signal(signal.SIGINT)+ await asyncio.to_thread(process.wait, 20)diff --cc tests/acp_adapter/test_gateway_editor_wire.pyindex d0fba59c249,00000000000..247cd20f7b5mode 100644,000000..100644--- a/tests/acp_adapter/test_gateway_editor_wire.py+++ b/tests/acp_adapter/test_gateway_editor_wire.py@@@ -1,104 -1,0 +1,104 @@@+"""Real ACP editor permissions over an ordinary daemon's canonical ACP route."""+import asyncio+from contextlib import suppress+from http.server import BaseHTTPRequestHandler+import json++import pytest++from tests.acp_adapter.test_gateway_sessions import daemon, editor, viewer, model_peer # noqa: F401+++class EditPeer(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ request = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ self.server.requests.append(request)+ # write_file refuses to replace an existing file this task never read in full+ # (stale-overwrite guard), so the scripted model reads first, then edits.+ seen = sum(1 for m in request.get('messages', []) if m['role'] == 'tool')+ tool = seen < 2+ message = {'role': 'assistant', 'content': 'EDITOR_FINISHED'}+ if seen == 0:+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'owned-read', 'type': 'function', 'function': {+ 'name': 'read_file', 'arguments': json.dumps({'path': str(self.server.target)})}}]}+ elif seen == 1:+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'owned-edit', 'type': 'function', 'function': {+ 'name': 'write_file', 'arguments': json.dumps({+ 'path': str(self.server.target), 'content': 'approved edit'})}}]}+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream' if request.get('stream') else 'application/json')+ self.end_headers()+ if request.get('stream'):+ if tool:+ message['tool_calls'][0]['index'] = 0+ for delta, finish in [(message, None), ({}, 'tool_calls' if tool else 'stop')]:+ self.wfile.write(('data: ' + json.dumps({'id': 'edit', 'object': 'chat.completion.chunk',+ 'created': 1, 'model': 'fixture', 'choices': [{'index': 0, 'delta': delta,+ 'finish_reason': finish}]}) + '\n\n').encode())+ self.wfile.write(b'data: [DONE]\n\n')+ else:+ self.wfile.write(json.dumps({'id': 'edit', 'object': 'chat.completion', 'created': 1,+ 'model': 'fixture', 'choices': [{'index': 0, 'message': message,+ 'finish_reason': 'tool_calls' if tool else 'stop'}]}).encode())+ self.wfile.flush()++- @pytest.mark.linux_only[email protected]("linux")+async def test_acp_load_checks_authoritative_cwd(daemon, tmp_path):+ other = tmp_path / 'other'+ other.mkdir()+ async with viewer(daemon) as ws:+ created = await ws.rpc('session.create', source='acp', cwd=str(tmp_path), request_id='cwd')+ sid = created['session_id']+ assert created['info']['cwd'] == str(tmp_path)+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})+ refused = await acp.rpc('session/load', sessionId=sid, cwd=str(other), mcpServers=[])+ assert 'cwd_policy_conflict' in json.dumps(refused)+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])+ assert 'result' in loaded++- @pytest.mark.linux_only[email protected]("linux")+async def test_real_editor_diff_requires_native_consent_before_write(daemon, tmp_path, model_peer):+ target = tmp_path / 'owned.txt'+ target.write_text('original edit')+ model_peer.target = target+ model_peer.RequestHandlerClass = EditPeer+ async with viewer(daemon) as ws:+ created = await ws.rpc('session.create', source='acp', cwd=str(tmp_path), request_id='editor-diff')+ sid = created['session_id']+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])+ assert 'result' in loaded, loaded+ task = asyncio.create_task(acp.rpc('session/prompt', sessionId=sid,+ prompt=[{'type': 'text', 'text': 'Edit the owned fixture'}]))+ try:+ async with asyncio.timeout(20):+ while not any(f.get('method') == 'session/request_permission' for f in acp.frames):+ await asyncio.sleep(.05)+ permission = next(f for f in acp.frames if f.get('method') == 'session/request_permission')+ call = permission['params']['toolCall']+ assert call['kind'] == 'edit', permission+ assert call['content'][0]['oldText'] == 'original edit'+ assert call['content'][0]['newText'] == 'approved edit'+ assert target.read_text() == 'original edit'+ acp.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'id': permission['id'], 'result': {+ 'outcome': {'outcome': 'selected', 'optionId': 'allow_once'}}}).encode() + b'\n')+ await acp.process.stdin.drain()+ assert (await task)['result']['stopReason'] == 'end_turn'+ assert target.read_text() == 'approved edit'+ print('ACP_EDITOR_RECEIPT=' + json.dumps({'session_id': sid, 'permission': permission,+ 'owned_write_after_consent': True}))+ finally:+ task.cancel()+ with suppress(asyncio.CancelledError):+ await taskdiff --cc tests/acp_adapter/test_gateway_new_cold.pyindex 815601c5619,00000000000..26a8ed90a19mode 100644,000000..100644--- a/tests/acp_adapter/test_gateway_new_cold.py+++ b/tests/acp_adapter/test_gateway_new_cold.py@@@ -1,97 -1,0 +1,97 @@@+"""New ACP handoff advert and unmodified cold canonical ACP restoration."""+import asyncio+import json+import os+import signal+import subprocess+import sys+import time++import psutil+import pytest++from tests.acp_adapter.test_gateway_sessions import daemon, editor, viewer, model_peer, control # noqa: F401++- @pytest.mark.linux_only[email protected]("linux")[email protected]('daemon', ['proposed-acp-descriptor'], indirect=True)+async def test_native_new_with_proposed_advert_executes_canonical_acp(daemon, tmp_path):+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})+ created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[])+ assert 'result' in created, created+ sid = created['result']['sessionId']+ result = await acp.rpc('session/prompt', sessionId=sid,+ prompt=[{'type': 'text', 'text': 'WS_SHARED fresh ACP'}])+ assert result['result']['stopReason'] == 'end_turn', result+ assert 'LOCAL_ACK_WS_SHARED' in json.dumps(acp.frames)+ async with viewer(daemon) as ws:+ info = await ws.rpc('session.info', session_id=sid)+ assert info['source'] == 'acp' and info['cwd'] == str(tmp_path)+ saved = await ws.rpc('session.resume', session_id=sid)+ assert 'WS_SHARED fresh ACP' in json.dumps(saved['messages'])+ print('ACP_FRESH_HANDOFF_RECEIPT=' + json.dumps({'session_id': sid, 'info': info,+ 'only_injected_boundary': 'AuthorityConnection.describe acp source/capability advertisement'}))++- @pytest.mark.linux_only[email protected]("linux")+async def test_cold_acp_load_retains_policy_and_executes_after_daemon_restart(daemon, tmp_path, model_peer):+ home, descriptor, env, root = daemon+ async with viewer(daemon) as ws:+ snapshot = await ws.rpc('session.create', source='acp', cwd=str(tmp_path),+ toolsets=['file'], request_id='cold-editor')+ sid = snapshot['session_id']+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})+ assert 'result' in await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])+ assert 'result' in await acp.rpc('session/prompt', sessionId=sid,+ prompt=[{'type': 'text', 'text': 'WS_SHARED before cold restart'}])+ original_pid = descriptor['pid']+ owned = psutil.Process(original_pid)+ os.kill(original_pid, signal.SIGINT)+ await asyncio.to_thread(owned.wait, 20)- import yaml++ import hermes_yaml as yaml+ config = yaml.safe_load((home / 'config.yaml').read_text())+ config['platform_toolsets'] = {'acp': ['terminal']}+ (home / 'config.yaml').write_text(json.dumps(config))+ with (tmp_path / 'restart.log').open('w') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ current = {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ current = control(home, 'identify')+ if current.get('state') == 'ready' and current['instance_id'] != descriptor['instance_id']:+ break+ except (OSError, ValueError):+ pass+ await asyncio.sleep(.1)+ assert current.get('state') == 'ready', (tmp_path / 'restart.log').read_text()+ cold = home, current, env, root+ async with editor(cold, tmp_path) as acp:+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])+ assert 'result' in loaded, loaded+ assert 'WS_SHARED before cold restart' in json.dumps(acp.frames)+ reply = await acp.rpc('session/prompt', sessionId=sid,+ prompt=[{'type': 'text', 'text': 'WS_SHARED after cold restart'}])+ assert 'result' in reply, reply+ assert 'LOCAL_ACK_WS_SHARED' in json.dumps(acp.frames)+ async with viewer(cold) as ws:+ info = await ws.rpc('session.info', session_id=sid)+ assert info['source'] == 'acp' and info['cwd'] == str(tmp_path)+ messages = (await ws.rpc('session.resume', session_id=sid))['messages']+ assert 'WS_SHARED after cold restart' in json.dumps(messages)+ tool_names = [{t['function']['name'] for t in r.get('tools', [])} for r in model_peer.requests]+ assert len(tool_names) == 2 and tool_names[0] == tool_names[1]+ assert 'write_file' in tool_names[1] and 'terminal' not in tool_names[1]+ print('ACP_COLD_RECEIPT=' + json.dumps({'session_id': sid, 'info': info,+ 'original_pid': original_pid, 'restored_pid': process.pid, 'frozen_tools': sorted(tool_names[1])}))+ finally:+ if process.poll() is None:+ process.send_signal(signal.SIGINT)+ await asyncio.to_thread(process.wait, 20)diff --cc tests/acp_adapter/test_gateway_sessions.pyindex 8473d0a252b,00000000000..a1010cb67ddmode 100644,000000..100644--- a/tests/acp_adapter/test_gateway_sessions.py+++ b/tests/acp_adapter/test_gateway_sessions.py@@@ -1,264 -1,0 +1,264 @@@+"""Actual ACP stdio and WS clients against an ordinary isolated gateway."""+import asyncio+from contextlib import asynccontextmanager+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import time++import pytest+from websockets.asyncio.client import connect++from hermes_cli.gateway_client import GatewayClient+from tests.gateway.test_normal_runtime_boot import control, model_peer # noqa: F401+++def daemon(tmp_path, model_peer, request):+ home = tmp_path / "state"+ home.mkdir(mode=0o700)+ user = tmp_path / "user"+ user.mkdir()+ root = Path(__file__).resolve().parents[2]+ model_url = f"http://127.0.0.1:{model_peer.server_port}/v1"+ config = {+ "gateway": {"multiplex_profiles": False},+ "approvals": {"mode": "manual", "timeout": 60},+ "model": {"provider": "custom", "default": "local-wire-stub", "base_url": model_url},+ "auxiliary": {"title_generation": {"enabled": False}},+ }+ for key, value in (request.param.items() if isinstance(getattr(request, 'param', None), dict) else ()):+ config.setdefault(key, {}).update(value)+ (home / "config.yaml").write_text(json.dumps(config))+ env = {k: os.environ[k] for k in ("PATH", "LANG", "TZ") if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED="1",+ OPENAI_API_KEY="loopback-only", OPENAI_BASE_URL=model_url,+ HERMES_ACP_SKIP_CONFIGURED_MCP="1")+ command = [sys.executable, "-m", "gateway.run"]+ if getattr(request, 'param', None) == 'proposed-acp-descriptor':+ # API-owner handoff only: execution/create/policy stay unmodified. This+ # fixture explicitly distinguishes the proposed advert from shipped HEAD.+ command = [sys.executable, '-c', '''+from gateway.session_controls import AuthorityConnection+original = AuthorityConnection.describe+async def describe(self, ref, params):+ result = await original(self, ref, params)+ result['session_create']['sources'].append('acp')+ result['capabilities'].append('acp-editor-policy-v1')+ return result+AuthorityConnection.describe = describe+import runpy+runpy.run_module('gateway.run', run_name='__main__')+''']+ log_path = tmp_path / "gateway.log"+ with log_path.open("w") as log:+ process = subprocess.Popen(command, cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ descriptor = {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, "identify")+ if descriptor.get("state") == "ready":+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ assert descriptor.get("state") == "ready", log_path.read_text()+ yield home, descriptor, env, root+ finally:+ if process.poll() is None:+ process.send_signal(signal.SIGINT)+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++@asynccontextmanager+async def viewer(daemon):+ home, descriptor, _, _ = daemon+ grant = control(home, "session-ticket", {"profile_id": str(home),+ "instance_id": descriptor["instance_id"], "purpose": "interactive"})+ url = descriptor["api_origin"].replace("http:", "ws:") + "/api/ws"+ async with connect(url, subprotocols=["hermes-gateway-v1", "hermes-gateway-ticket." + grant["ticket"]]) as ws:+ async with GatewayClient(ws) as client:+ yield client+++class ACPPeer:+ def __init__(self, process):+ self.process = process+ self.frames = []+ self.requests = {}+ self.serial = 0+ self.reader = asyncio.create_task(self.read())++ async def read(self):+ while line := await self.process.stdout.readline():+ frame = json.loads(line)+ self.frames.append(frame)+ future = self.requests.get(frame.get("id"))+ if future and ("result" in frame or "error" in frame):+ future.set_result(frame)++ async def rpc(self, method, **params):+ self.serial += 1+ rid = self.serial+ future = asyncio.get_running_loop().create_future()+ self.requests[rid] = future+ self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}).encode() + b"\n")+ await self.process.stdin.drain()+ return await asyncio.wait_for(future, 40)+++@asynccontextmanager+async def editor(daemon, tmp_path):+ _, _, env, root = daemon+ with (tmp_path / "acp.log").open("w") as log:+ process = await asyncio.create_subprocess_exec(sys.executable, "-m", "acp_adapter.entry",+ cwd=root, env=env, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=log)+ peer = ACPPeer(process)+ try:+ yield peer+ finally:+ process.stdin.close()+ try:+ await asyncio.wait_for(process.wait(), 5)+ except asyncio.TimeoutError:+ process.kill()+ await process.wait()+ await peer.reader++- @pytest.mark.linux_only[email protected]("linux")+async def test_acp_transport_shares_canonical_history_and_order(daemon, tmp_path, model_peer):+ async with viewer(daemon) as ws:+ created = await ws.rpc("session.create", request_id="shared-acp", source="cli", cwd=str(tmp_path))+ sid = created["session_id"]+ async with editor(daemon, tmp_path) as acp:+ init = await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})+ assert "result" in init, init+ loaded = await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])+ assert "result" in loaded, loaded+ reply = await acp.rpc("session/prompt", sessionId=sid, prompt=[{"type": "text", "text": "WS_SHARED ACP"}])+ assert reply.get("result", {}).get("stopReason") == "end_turn", reply+ assert "LOCAL_ACK_WS_SHARED" in json.dumps(acp.frames)+ accepted = await ws.rpc("prompt.submit", session_id=sid, input_id="after-acp-disconnect", text="WS_SHARED WS")+ async with asyncio.timeout(30):+ while True:+ receipt = await ws.rpc("prompt.receipt", session_id=sid, admission_id=accepted["admission_id"])+ if receipt["status"] == "terminal":+ assert receipt["outcome"] == "completed", receipt+ break+ await asyncio.sleep(.05)+ snapshot = await ws.rpc("session.resume", session_id=sid)+ assert "WS_SHARED ACP" in json.dumps(snapshot["messages"])+ assert "WS_SHARED WS" in json.dumps(snapshot["messages"])+ replay = await ws.rpc("session.events.since", session_id=sid, replay_epoch=created["replay_epoch"], last_sequence=0)+ events = replay["events"]+ assert [e["seq"] for e in events] == sorted({e["seq"] for e in events})+ assert len([e for e in events if e["type"] == "message.complete"]) == 2+ assert len(model_peer.requests) == 2+ print("ACP_SHARED_RECEIPT=" + json.dumps({"session_id": sid, "events": events, "messages": snapshot["messages"]}))+++- @pytest.mark.linux_only[email protected]("linux")+async def test_acp_permission_detach_keeps_canonical_waiter(daemon, tmp_path, model_peer):+ import shlex+ from contextlib import suppress+ from hermes_cli.gateway_client import GatewayClientError+ from tests.gateway.fixtures.authority_controls_peer import ModelPeer as ApprovalPeer++ target = tmp_path / "owned-removal"+ target.mkdir()+ (target / "owned.txt").write_text("disposable")+ model_peer.command = "rm -r -- " + shlex.quote(str(target))+ model_peer.RequestHandlerClass = ApprovalPeer+ async with viewer(daemon) as ws:+ created = await ws.rpc("session.create", request_id="acp-permission", source="cli", cwd=str(tmp_path))+ sid = created["session_id"]+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})+ assert "result" in await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])+ prompt_task = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,+ prompt=[{"type": "text", "text": "Remove the owned fixture"}]))+ try:+ async with asyncio.timeout(15):+ while not any(f.get("method") == "session/request_permission" for f in acp.frames):+ await asyncio.sleep(.05)+ permission = next(f for f in acp.frames if f.get("method") == "session/request_permission")+ assert target.exists()+ snapshot = await ws.rpc("session.resume", session_id=sid)+ pending = snapshot["prompts"][0]+ with pytest.raises(GatewayClientError, match="stale_generation"):+ await ws.rpc("approval.respond", session_id=sid, prompt_id=pending["prompt_id"],+ execution_generation=pending["execution_generation"] + 1, choice="once")+ assert target.exists()+ finally:+ prompt_task.cancel()+ with suppress(asyncio.CancelledError):+ await prompt_task+ assert target.exists(), "Editor detach must not synthesize approval or denial"+ response = await ws.rpc("approval.respond", session_id=sid, prompt_id=pending["prompt_id"],+ execution_generation=pending["execution_generation"], choice="once")+ assert response["status"] == "resolved", response+ async with asyncio.timeout(20):+ while target.exists():+ await asyncio.sleep(.05)+ print("ACP_PERMISSION_RECEIPT=" + json.dumps({"session_id": sid, "permission": permission,+ "stale_generation_rejected": True, "detached_waiter_resolved_by_ws": True,+ "real_owned_deletion": not target.exists()}))+++# 1x1 transparent PNG: smallest valid image an editor can attach.+_ONE_PX_PNG = bytes.fromhex(+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"+ "890000000a49444154789c6300010000000500010d0a2db40000000049454e44ae426082"+)++- @pytest.mark.linux_only[email protected]("linux")+# A loopback custom provider has no catalog entry; declaring vision is the documented+# knob and is exactly what a user of a self-hosted vision model does.[email protected]("daemon", [{"model": {"supports_vision": True}}], indirect=True)+async def test_acp_image_prompt_reaches_model_as_image_part(daemon, tmp_path, model_peer):+ import base64+ async with viewer(daemon) as ws:+ created = await ws.rpc("session.create", request_id="acp-image", source="cli", cwd=str(tmp_path))+ sid = created["session_id"]+ async with editor(daemon, tmp_path) as acp:+ init = await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})+ assert init["result"]["agentCapabilities"]["promptCapabilities"]["image"] is True, init+ assert "result" in await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])+ reply = await acp.rpc("session/prompt", sessionId=sid, prompt=[+ {"type": "text", "text": "WS_SHARED what is in this image?"},+ {"type": "image", "mimeType": "image/png", "data": base64.b64encode(_ONE_PX_PNG).decode()},+ ])+ assert reply.get("result", {}).get("stopReason") == "end_turn", reply+ (request,) = model_peer.requests+ user = next(m for m in reversed(request["messages"]) if m["role"] == "user")+ parts = user["content"]+ assert isinstance(parts, list), parts+ (image,) = [p for p in parts if p.get("type") == "image_url"]+ url = image["image_url"]["url"]+ assert url.startswith("data:image/png;base64,")+ assert base64.b64decode(url.split(",", 1)[1]) == _ONE_PX_PNG+ assert "WS_SHARED what is in this image?" in json.dumps([p for p in parts if p.get("type") == "text"])+ replay = await ws.rpc("session.events.since", session_id=sid, replay_epoch=created["replay_epoch"], last_sequence=0)+ completes = [e for e in replay["events"] if e["type"] == "message.complete"]+ assert len(completes) == 1+ receipt = await ws.rpc("prompt.receipt", session_id=sid, admission_id=completes[0]["admission_id"])+ assert (receipt["status"], receipt["outcome"]) == ("terminal", "completed"), receipt+ print("ACP_IMAGE_RECEIPT=" + json.dumps({"session_id": sid, "admission": receipt,+ "image_part_bytes": len(url), "text_parts": [p["text"] for p in parts if p.get("type") == "text"]}))diff --cc tests/acp_adapter/test_gateway_wire_controls.pyindex 930a6b3977f,00000000000..e2161c38e25mode 100644,000000..100644--- a/tests/acp_adapter/test_gateway_wire_controls.py+++ b/tests/acp_adapter/test_gateway_wire_controls.py@@@ -1,66 -1,0 +1,66 @@@+"""Additional real-wire controls for the ACP authority client."""+import asyncio+from contextlib import suppress+import json+import shlex++import pytest++from acp_adapter.server import HermesACPAgent+from hermes_cli.gateway_client import GatewayClientError+from tests.acp_adapter.test_gateway_sessions import daemon, editor, viewer, model_peer # noqa: F401++- @pytest.mark.linux_only[email protected]("linux")+async def test_profile_mismatch_refuses_before_creation(daemon, tmp_path, monkeypatch):+ import acp_adapter.gateway_server as server+ agent = HermesACPAgent()+ agent._home = tmp_path / "foreign-profile"+ # A real authenticated connection to the wrong profile, not a fake descriptor.+ monkeypatch.setattr(server, "connect_gateway", lambda: viewer(daemon))+ with pytest.raises(GatewayClientError, match="profile_mismatch"):+ await agent.new_session(cwd=str(tmp_path))+ assert agent._gateway is None+ async with viewer(daemon) as ws:+ assert (await ws.rpc("session.list"))["sessions"] == []++- @pytest.mark.linux_only[email protected]("linux")+async def test_real_acp_answer_resolves_the_exact_pending_control(daemon, tmp_path, model_peer):+ from tests.gateway.fixtures.authority_controls_peer import ModelPeer as ApprovalPeer+ target = tmp_path / "native-answer-owned"+ target.mkdir()+ (target / "owned.txt").write_text("disposable")+ model_peer.command = "rm -r -- " + shlex.quote(str(target))+ model_peer.RequestHandlerClass = ApprovalPeer+ async with viewer(daemon) as ws:+ snapshot = await ws.rpc("session.create", source="cli", cwd=str(tmp_path), request_id="native-acp-answer")+ sid = snapshot["session_id"]+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})+ await acp.rpc("session/resume", cwd=str(tmp_path), sessionId=sid, mcpServers=[])+ task = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,+ prompt=[{"type": "text", "text": "Remove owned fixture after consent"}]))+ try:+ async with asyncio.timeout(15):+ while not any(f.get("method") == "session/request_permission" for f in acp.frames):+ await asyncio.sleep(.05)+ permission = next(f for f in acp.frames if f.get("method") == "session/request_permission")+ assert target.exists()+ pending = (await ws.rpc("session.resume", session_id=sid))["prompts"][0]+ acp.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": permission["id"], "result": {+ "outcome": {"outcome": "selected", "optionId": "allow_once"}}}).encode() + b"\n")+ await acp.process.stdin.drain()+ response = await task+ assert response["result"]["stopReason"] == "end_turn"+ assert not target.exists()+ assert "APPROVAL_FINISHED" in json.dumps(acp.frames)+ print("ACP_NATIVE_ANSWER_RECEIPT=" + json.dumps({"session_id": sid,+ "prompt_id": pending["prompt_id"], "generation": pending["execution_generation"],+ "owned_effect_after_acp_answer": True}))+ finally:+ task.cancel()+ with suppress(asyncio.CancelledError):+ await taskdiff --cc tests/agent/test_safe_worker_policy.pyindex b116a355596,00000000000..68f107d01b9mode 100644,000000..100644--- a/tests/agent/test_safe_worker_policy.py+++ b/tests/agent/test_safe_worker_policy.py@@@ -1,323 -1,0 +1,323 @@@+"""Fresh exec probes for the private managed safe-worker bootstrap contract."""+import json+import os+from pathlib import Path+import subprocess+import sys+import textwrap++import pytest+++def run_worker(tmp_path, body, mode="safe"):+ home = tmp_path / mode+ home.mkdir(exist_ok=True)+ (home / "config.yaml").write_text("agent:\n max_turns: 17\n", encoding="utf-8")+ env = dict(os.environ, HERMES_HOME=str(home), HOME=str(home), PROBE_MODE=mode)+ for key in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG", "HERMES_IGNORE_RULES"):+ env.pop(key, None)+ root = Path(__file__).resolve().parents[2]+ script = home / "worker_probe.py"+ script.write_text(f"import sys; sys.path.insert(0, {str(root)!r})\n" + textwrap.dedent(body), encoding="utf-8")+ result = subprocess.run(+ [sys.executable, str(script)], env=env,+ cwd=root, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=45,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ return json.loads(result.stdout.strip().splitlines()[-1])++[email protected]("mode", ["safe", "config", "ordinary"])+def test_worker_config_is_frozen_before_any_profile_read(tmp_path, mode):+ result = run_worker(tmp_path, '''+ import json, os, sys, threading+ from pathlib import Path+ mode = os.environ["PROBE_MODE"]+ if mode != "ordinary":+ from agent.safe_worker_policy import _bind_safe_worker_policy+ snapshot = {"agent": {"max_turns": 3}, "terminal": {"cwd": "/explicit"}}+ _bind_safe_worker_policy(safe_mode=mode == "safe", ignore_user_config=True, config=snapshot)+ snapshot["agent"]["max_turns"] = 999+ reads = []+ def audit(event, args):+ if event == "open" and str(args[0]).endswith("config.yaml") and args[1] != "w":+ reads.append(str(args[0]))+ sys.addaudithook(audit)+ from hermes_cli.config import load_config, load_config_readonly, read_raw_config, read_raw_config_readonly, DEFAULT_CONFIG+ from hermes_cli import env_loader+ callbacks = []+ env_loader._apply_managed_env = lambda **kw: callbacks.append("managed")+ env_loader._apply_external_secret_sources = lambda home: callbacks.append("secrets")+ env_loader._reapply_terminal_config_bridge = lambda home: callbacks.append("terminal")+ env_loader.load_hermes_dotenv()+ cfg = load_config()+ assert cfg["compression"] == DEFAULT_CONFIG["compression"]+ first = cfg["agent"]["max_turns"]+ cfg["agent"]["max_turns"] = 123+ if mode != "ordinary":+ Path(os.environ["HERMES_HOME"], "config.yaml").write_text("[broken YAML")+ # Audit excludes this fixture write, not the preceding reads.+ results = []+ def check():+ for loader in (load_config, load_config_readonly, read_raw_config, read_raw_config_readonly):+ results.append(loader()["agent"]["max_turns"])+ t = threading.Thread(target=check); t.start(); t.join()+ print(json.dumps({"first": first, "values": results, "reads": reads, "callbacks": callbacks}))+ ''', mode)+ if mode == "ordinary":+ assert result["first"] == 17 and result["reads"]+ assert result["callbacks"] == ["secrets", "managed", "terminal"]+ else:+ assert result == {"first": 3, "values": [3, 3, 3, 3], "reads": [], "callbacks": []}+++def test_private_worker_binding_is_one_shot_typed_and_not_env_selected(tmp_path):+ result = run_worker(tmp_path, '''+ import json, os+ from dataclasses import FrozenInstanceError+ from agent.safe_worker_policy import _bind_safe_worker_policy, safe_worker_enabled, worker_config_snapshot+ os.environ["HERMES_SAFE_MODE"] = "1"+ assert not safe_worker_enabled()+ for value in (1, "true", None):+ try:+ _bind_safe_worker_policy(safe_mode=value, ignore_user_config=True, config={})+ except (TypeError, ValueError):+ pass+ else:+ raise AssertionError("non-boolean accepted")+ policy = _bind_safe_worker_policy(safe_mode=True, ignore_user_config=False, config={})+ assert policy.ignore_user_config and safe_worker_enabled()+ try:+ policy.safe_mode = False+ except FrozenInstanceError:+ pass+ else:+ raise AssertionError("mutable policy")+ try:+ _bind_safe_worker_policy(safe_mode=False, ignore_user_config=True, config={})+ except RuntimeError:+ pass+ else:+ raise AssertionError("rebound policy")+ assert worker_config_snapshot() == {}+ print(json.dumps({"bound": safe_worker_enabled()}))+ ''')+ assert result == {"bound": True}++[email protected]("mode", ["safe", "config", "ordinary"])+def test_safe_worker_never_discovers_or_invokes_customizations(tmp_path, mode):+ result = run_worker(tmp_path, r"""+ import json, os, sys+ from pathlib import Path+ mode = os.environ["PROBE_MODE"]+ home = Path(os.environ["HERMES_HOME"])+ (home / "config.yaml").write_text("plugins:\n enabled: [sentinel]\n")+ events = home / "events"+ def mark(value):+ with events.open("a") as f: f.write(value + "\n")+ for name, kind in (("sentinel", "standalone"), ("model-providers/nested", "model-provider"), ("flat", "model-provider")):+ p = home / "plugins" / name+ p.mkdir(parents=True)+ (p / "plugin.yaml").write_text("name: " + name.split("/")[-1] + "\nversion: 1.0.0\nkind: " + kind + "\n")+ prefix = "from pathlib import Path\nimport os\ndef mark(s):\n with (Path(os.environ['HERMES_HOME']) / 'events').open('a') as f: f.write(s + '\\n')\n"+ if kind == "standalone":+ code = "mark('plugin-import')\ndef register(ctx):\n mark('plugin-register')\n ctx.register_hook('on_session_start', lambda **kw: mark('plugin-hook'))\n"+ else:+ code = "from providers import register_provider\nfrom providers.base import ProviderProfile\nmark('" + name + "')\nregister_provider(ProviderProfile(name='" + name.split("/")[-1] + "'))\n"+ (p / "__init__.py").write_text(prefix + code)+ if mode != "ordinary":+ from agent.safe_worker_policy import _bind_safe_worker_policy+ _bind_safe_worker_policy(safe_mode=mode == "safe", ignore_user_config=True, config={"plugins": {"enabled": ["sentinel"]}})+ reads = []+ def audit(event, args):+ if event == "open" and "/plugins/" in str(args[0]) and args[1] != "w":+ reads.append(str(args[0]))+ sys.addaudithook(audit)+ import providers+ from hermes_cli import plugins, lifecycle+ plugins.discover_plugins()+ providers.list_providers()+ from providers.base import ProviderProfile+ providers.register_provider(ProviderProfile(name="injected"))+ injected = providers.get_provider_profile("injected")+ manager = plugins.get_plugin_manager()+ manager._hooks.setdefault("on_session_start", []).append(lambda **kw: mark("direct-hook"))+ manager._middleware.setdefault("probe", []).append(lambda **kw: mark("middleware"))+ manager.invoke_hook("on_session_start")+ manager.invoke_middleware("probe")+ lifecycle._observe = lambda *a, **kw: mark("observer")+ lifecycle.invoke_hook("on_session_start")+ from agent import shell_hooks, outbound_webhooks+ shell_hooks._spawn = lambda *a: (mark("shell") or {"returncode": 0, "stdout": "", "stderr": "", "error": None, "timed_out": False})+ outbound_webhooks._enqueue = lambda *a: mark("outbound")+ shell_hooks._make_callback(shell_hooks.ShellHookSpec(event="on_session_start", command="inert"))()+ outbound_webhooks._make_callback("on_session_start", outbound_webhooks.WebhookTarget(url="http://127.0.0.1/inert", events=["on_session_start"]))()+ if mode == "safe": assert not reads+ print(json.dumps({"events": events.read_text().splitlines() if events.exists() else [], "reads": reads, "injected": injected is not None}))+ """, mode)+ if mode == "safe":+ assert result == {"events": [], "reads": [], "injected": False}+ else:+ assert {"plugin-import", "plugin-register", "plugin-hook", "model-providers/nested", "flat", "direct-hook", "middleware", "observer", "shell", "outbound"} <= set(result["events"])+ assert result["reads"] and result["injected"]++[email protected]("mode", ["safe", "config", "ordinary"])+def test_safe_worker_bypasses_rule_readers_even_without_cli_flags(tmp_path, mode):+ result = run_worker(tmp_path, r"""+ import json, os, sys+ from pathlib import Path+ mode = os.environ["PROBE_MODE"]+ home = Path(os.environ["HERMES_HOME"])+ project = home / "project"; project.mkdir()+ (project / "AGENTS.md").write_text("PROJECT_SENTINEL")+ sub = project / "sub"; sub.mkdir()+ (sub / "AGENTS.md").write_text("SUB_SENTINEL")+ (home / "SOUL.md").write_text("SOUL_SENTINEL")+ mem = home / "memories"; mem.mkdir()+ (mem / "MEMORY.md").write_text("MEMORY_SENTINEL")+ skill = home / "skills" / "probe"; skill.mkdir(parents=True)+ (skill / "SKILL.md").write_text("---\nname: probe\ndescription: SKILL_SENTINEL\n---\nSKILL_SENTINEL\n")+ if mode != "ordinary":+ from agent.safe_worker_policy import _bind_safe_worker_policy+ _bind_safe_worker_policy(safe_mode=mode == "safe", ignore_user_config=True, config={})+ reads = []+ selected = {"SOUL.md", "AGENTS.md", "MEMORY.md", "USER.md", "SKILL.md"}+ def audit(event, args):+ if event == "open" and Path(str(args[0])).name in selected and args[1] != "w":+ reads.append(Path(str(args[0])).name)+ sys.addaudithook(audit)+ from agent.prompt_builder import build_context_files_prompt, load_soul_md, build_skills_system_prompt+ from agent.skill_commands import build_preloaded_skills_prompt+ from agent.subdirectory_hints import SubdirectoryHintTracker+ context = build_context_files_prompt(cwd=str(project))+ soul = load_soul_md()+ skills = build_skills_system_prompt()+ preloaded = build_preloaded_skills_prompt(["probe"])+ hints = SubdirectoryHintTracker(str(project)).check_tool_call("read_file", {"path": str(sub / "file.py")})+ from agent.agent_init import _init_memory, _select_context_engine+ from types import SimpleNamespace+ agent = SimpleNamespace(enabled_toolsets=["memory"], disabled_toolsets=[])+ _init_memory(agent, {"memory": {"memory_enabled": True, "user_profile_enabled": True}}, False, "cli")+ # Explicit custom-engine selection must not escape the process policy.+ import plugins.context_engine+ engines = []+ plugins.context_engine.load_context_engine = lambda name: engines.append(name)+ _select_context_engine({"context": {"engine": "sentinel"}})+ print(json.dumps({"context": context, "soul": soul, "skills": skills,+ "preloaded": preloaded, "hints": hints, "reads": reads, "engines": engines,+ "memory": agent._memory_store is not None}))+ """, mode)+ if mode == "safe":+ assert result == {"context": "", "soul": None, "skills": "", "preloaded": ["", [], ["probe"]],+ "hints": None, "reads": [], "engines": [], "memory": False}+ else:+ assert "PROJECT_SENTINEL" in result["context"] and "SOUL_SENTINEL" in result["soul"]+ assert "SKILL_SENTINEL" in result["skills"] and "SKILL_SENTINEL" in result["preloaded"][0]+ assert "SUB_SENTINEL" in result["hints"]+ assert {"AGENTS.md", "SOUL.md", "SKILL.md", "MEMORY.md"} <= set(result["reads"])+ assert result["engines"] == ["sentinel"] and result["memory"]++[email protected]("mode", ["safe", "config", "ordinary"])+def test_bare_agent_constructor_cannot_restore_safe_customizations(tmp_path, mode):+ result = run_worker(tmp_path, r"""+ import json, os, sys+ from pathlib import Path+ mode = os.environ["PROBE_MODE"]+ home = Path(os.environ["HERMES_HOME"])+ (home / "SOUL.md").write_text("IDENTITY_SENTINEL")+ if mode != "ordinary":+ from agent.safe_worker_policy import _bind_safe_worker_policy+ _bind_safe_worker_policy(safe_mode=mode == "safe", ignore_user_config=True,+ config={"agent": {"environment_probe": False}})+ reads = []+ def audit(event, args):+ if event == "open" and str(args[0]).endswith("config.yaml") and args[1] != "w":+ reads.append(str(args[0]))+ sys.addaudithook(audit)+ from run_agent import AIAgent+ agent = AIAgent(model="safe-fixture", provider="custom", base_url="http://127.0.0.1:9/v1",+ api_key="fixture", enabled_toolsets=[], quiet_mode=True, skip_context_files=False,+ load_soul_identity=True, skip_background_review=False,+ prefill_messages=[{"role": "user", "content": "PREFILL_SENTINEL"}],+ save_trajectories=False)+ from agent.background_review import load_background_review_settings+ from agent.system_prompt import build_system_prompt+ prompt = build_system_prompt(agent)+ if mode == "safe":+ assert "IDENTITY_SENTINEL" not in prompt+ flags = [agent.skip_context_files, agent.load_soul_identity, agent.skip_background_review]+ print(json.dumps({"flags": flags, "prefill": agent.prefill_messages,+ "review": load_background_review_settings()[0], "reads": reads}))+ """, mode)+ if mode == "safe":+ assert result == {"flags": [True, False, True], "prefill": [], "review": False, "reads": []}+ else:+ assert result["flags"] == [False, True, False]+ assert result["prefill"] and result["review"]+ if mode == "ordinary":+ assert result["reads"]+ else:+ assert result["reads"] == []++[email protected]("mode", ["safe", "config", "ordinary"])+def test_direct_secret_hydration_cannot_read_bypassed_yaml(tmp_path, mode):+ result = run_worker(tmp_path, r"""+ import json, os, sys+ from pathlib import Path+ mode = os.environ["PROBE_MODE"]+ home = Path(os.environ["HERMES_HOME"])+ if mode != "ordinary":+ from agent.safe_worker_policy import _bind_safe_worker_policy+ _bind_safe_worker_policy(safe_mode=mode == "safe", ignore_user_config=True, config={})+ reads = []+ def audit(event, args):+ if event == "open" and str(args[0]).endswith("config.yaml") and args[1] != "w":+ reads.append(str(args[0]))+ sys.addaudithook(audit)+ from hermes_cli.env_loader import hydrate_profile_secret_sources+ assert hydrate_profile_secret_sources(home) == {}+ other = home / "other"; other.mkdir()+ (other / "config.yaml").write_text("agent: {}")+ assert hydrate_profile_secret_sources(other) == {}+ print(json.dumps({"reads": reads}))+ """, mode)+ assert bool(result["reads"]) == (mode == "ordinary")++- @pytest.mark.linux_only[email protected]("linux")+def test_private_policy_refuses_late_binding_and_fork_inheritance(tmp_path):+ late = run_worker(tmp_path, r"""+ import json+ import hermes_cli.config+ from agent.safe_worker_policy import _bind_safe_worker_policy+ try:+ _bind_safe_worker_policy(safe_mode=True, ignore_user_config=True, config={})+ except RuntimeError as exc:+ assert "before runtime imports" in str(exc)+ else:+ raise AssertionError("late binding accepted")+ print(json.dumps({"refused": True}))+ """, "late")+ assert late == {"refused": True}+ fork = run_worker(tmp_path, r"""+ import json, os+ from agent.safe_worker_policy import _bind_safe_worker_policy, safe_worker_enabled+ _bind_safe_worker_policy(safe_mode=True, ignore_user_config=True, config={})+ pid = os.fork()+ if pid == 0:+ try:+ safe_worker_enabled()+ except RuntimeError as exc:+ os._exit(0 if "fresh exec" in str(exc) else 2)+ os._exit(3)+ _, status = os.waitpid(pid, 0)+ assert os.waitstatus_to_exitcode(status) == 0+ assert safe_worker_enabled()+ print(json.dumps({"refused": True}))+ """, "fork")+ assert fork == {"refused": True}diff --cc tests/agent/test_session_row_under_live_agent_persist.pyindex 00000000000,a2e3cad8647..4caa2b64777mode 000000,100644..100644--- a/tests/agent/test_session_row_under_live_agent_persist.py+++ b/tests/agent/test_session_row_under_live_agent_persist.py@@@ -1,0 -1,163 +1,190 @@@+ """A session row deleted under a live agent must heal on the next flush (#123583).++ Before the fix, ``_flush_messages_to_session_db`` trusts the cached+ ``_session_db_created`` flag: after ``hermes sessions delete`` (or Desktop delete /+ bulk prune / profile-repair move / in-place store rebuild) removes the row, every+ later turn's append fails the FK and is dropped with one WARNING per turn — the+ durable transcript silently stops growing and leaves no trace in the store.++ Maintainer triage direction (issue #123583, maintainer pass): classify the FK+ failure as ``session_row_missing``, recreate the row, and replay the FULL+ in-memory transcript — not just the current tail.+ """++ import os+ import tempfile+ from pathlib import Path+ from unittest.mock import patch++++def _drop_row(db, session_id):++ """The row vanishes under the agent WITHOUT a retirement tombstone (in-place store rebuild,++ profile-repair move). A canonical delete retires the id instead; see the last test."""++ def _do(conn):++ conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))++ assert conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,)).rowcount == 1++ db._execute_write(_do)+++++ def _make_agent(session_db, session_id):+ with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):+ from run_agent import AIAgent++ return AIAgent(+ api_key="test-key",+ base_url="https://openrouter.ai/api/v1",+ model="test/model",+ quiet_mode=True,+ session_db=session_db,+ session_id=session_id,+ skip_context_files=True,+ skip_memory=True,+ )+++ def test_flush_recreates_row_deleted_under_live_agent():+ """Real turn shape (messages = history + tail, conversation_history=history): every+ deletion round replays the whole in-memory transcript onto the recreated row."""+ from hermes_state import SessionDB++ with tempfile.TemporaryDirectory() as tmpdir:+ db = SessionDB(db_path=Path(tmpdir) / "test.db")+ agent = _make_agent(db, "sess-live")++ history = []+ for n in ("one", "two", "three"):+ if history:- # Row removed under the idle live agent (sessions delete / Desktop / prune).- assert db.delete_session("sess-live") is True++ # Row removed under the idle live agent (store rebuild / repair move).++ _drop_row(db, "sess-live")+ tail = [{"role": "user", "content": f"turn {n}"}, {"role": "assistant", "content": f"answer {n}"}]+ messages = list(history) + tail+ assert agent._flush_messages_to_session_db(messages, history) is True+ history = messages+ assert [r["content"] for r in db.get_messages("sess-live")] == [m["content"] for m in history]++ # A heal during a muted notification turn hides only that turn's new rows; the replayed+ # history rows (and their in-memory dicts) keep their visibility.- assert db.delete_session("sess-live") is True++ _drop_row(db, "sess-live")+ agent._mute_notification_reply = True+ tail = [{"role": "user", "content": "notif"}, {"role": "assistant", "content": "muted"}]+ assert agent._flush_messages_to_session_db(list(history) + tail, history) is True+ rows = db.get_messages("sess-live")+ assert [(r["content"], r.get("display_kind")) for r in rows] == (+ [(m["content"], None) for m in history] + [("notif", "hidden"), ("muted", "hidden")]+ )+ assert [m.get("display_kind") for m in history] == [None] * len(history)+ db.close()+++ def test_flush_fails_closed_when_row_cannot_be_recreated(monkeypatch):+ """Scenario B: if row creation fails too, the flush fails closed — returns False+ instead of appending into a guaranteed rollback, and the batch stays unmarked. A FK+ failure is only healed when the row is confirmed gone, and a failed lookup is no proof."""+ import sqlite3 as _sqlite3++ from hermes_state import SessionDB++ with tempfile.TemporaryDirectory() as tmpdir:+ db = SessionDB(db_path=Path(tmpdir) / "test.db")+ agent = _make_agent(db, "sess-gone")++ turn1 = [{"role": "user", "content": "a"}]+ agent._flush_messages_to_session_db(turn1, [])+ assert len(db.get_messages("sess-gone")) == 1- assert db.delete_session("sess-gone") is True++ _drop_row(db, "sess-gone")++ # Row creation inside the heal now raises (transient store trouble).+ def _broken_create(*a, **kw):+ raise _sqlite3.OperationalError("unable to open database file")++ monkeypatch.setattr(db, "create_session", _broken_create)++ turn2 = turn1 + [{"role": "user", "content": "b"}]+ healed = agent._flush_messages_to_session_db(turn2, turn1)+ assert healed is False+ assert agent._session_db_created is False+ monkeypatch.undo()++ # The next flush recreates the row before any FK error (so no heal runs) and must still+ # replay the history prefix the failed heal left unwritten.+ turn3 = turn2 + [{"role": "assistant", "content": "c"}]+ assert agent._flush_messages_to_session_db(turn3, turn2) is True+ assert [r["content"] for r in db.get_messages("sess-gone")] == ["a", "b", "c"]+ assert agent._session_row_replay_pending is None++ # The heal recreates the row but its single retry write fails (lock/lease/disk): the next+ # flush finds a live row (no FK, no heal) and must still replay the history prefix.+ retry = _make_agent(db, "sess-retry")+ t1 = [{"role": "user", "content": "one"}, {"role": "assistant", "content": "a1"}]+ assert retry._flush_messages_to_session_db(t1, []) is True- assert db.delete_session("sess-retry") is True++ _drop_row(db, "sess-retry")+ real_append, calls = db.append_messages_batch, []++ def _fk_then_locked(*a, **kw):+ calls.append(1)+ if len(calls) == 2:+ raise _sqlite3.OperationalError("database is locked")+ return real_append(*a, **kw) # call 1 hits the real FK error -> heal++ monkeypatch.setattr(db, "append_messages_batch", _fk_then_locked)+ t2 = t1 + [{"role": "user", "content": "two"}]+ assert retry._flush_messages_to_session_db(t2, t1) is False+ t3 = t2 + [{"role": "assistant", "content": "a2"}]+ assert retry._flush_messages_to_session_db(t3, t2) is True+ assert [r["content"] for r in db.get_messages("sess-retry")] == ["one", "a1", "two", "a2"]+ monkeypatch.undo()++ # FK failure while the session row still exists (e.g. a sessions-table FK): no heal, and+ # no replay of the history prefix onto the live transcript.+ live = _make_agent(db, "sess-fk-live")+ history = [{"role": "user", "content": "one"}, {"role": "assistant", "content": "a1"}]+ assert live._flush_messages_to_session_db(history, []) is True+ real_append, calls = db.append_messages_batch, []++ def _fk_once(*a, **kw):+ calls.append(1)+ if len(calls) == 1:+ raise _sqlite3.IntegrityError("FOREIGN KEY constraint failed")+ return real_append(*a, **kw)++ monkeypatch.setattr(db, "append_messages_batch", _fk_once)+ assert live._flush_messages_to_session_db(list(history) + [{"role": "user", "content": "two"}], history) is False+ assert [r["content"] for r in db.get_messages("sess-fk-live")] == ["one", "a1"]+ monkeypatch.undo()++ # Delegate child whose row is gone: a raising parent-row lookup fails the flush closed+ # instead of letting the OperationalError escape.+ db.create_session("sess-parent", source="cli")+ child = _make_agent(db, "sess-child")+ child._parent_session_id = "sess-parent"+ assert child._flush_messages_to_session_db([{"role": "user", "content": "x"}], []) is True+ db.delete_session("sess-parent")+ db.delete_session("sess-child")+ real_get = db.get_session++ def _parent_lookup_raises(sid):+ if sid == "sess-parent":+ raise _sqlite3.OperationalError("disk I/O error")+ return real_get(sid)++ monkeypatch.setattr(db, "get_session", _parent_lookup_raises)+ assert child._flush_messages_to_session_db([{"role": "user", "content": "y"}], []) is False+ db.close()++++++def test_retired_session_is_never_resurrected_by_a_stale_writer():++ """A canonical delete retires the id; the heal must not bring the session back from a++ leftover in-memory agent (the owner evicts live agents before retiring)."""++ from hermes_state import SessionDB++++ with tempfile.TemporaryDirectory() as tmpdir:++ db = SessionDB(db_path=Path(tmpdir) / "test.db")++ agent = _make_agent(db, "sess-retired")++ turn1 = [{"role": "user", "content": "a"}]++ assert agent._flush_messages_to_session_db(turn1, []) is True++ assert db.delete_session("sess-retired") is True++ turn2 = turn1 + [{"role": "user", "content": "b"}]++ assert agent._flush_messages_to_session_db(turn2, turn1) is False++ assert db.get_session("sess-retired") is None++ assert db.get_messages("sess-retired") == []++ db.close()diff --cc tests/cron/test_cron_bot_chat_create_if_missing.pyindex 5b48e15d736,00000000000..e727d705f30mode 100644,000000..100644--- a/tests/cron/test_cron_bot_chat_create_if_missing.py+++ b/tests/cron/test_cron_bot_chat_create_if_missing.py@@@ -1,60 -1,0 +1,60 @@@+"""Cron Bot Chat delivery creates the profile's canonical Bot Chat when it does not exist yet.++Main's lane was ``hermes chat -c "Bot Chat" --create-if-missing``; the canonical authority+door must keep that semantics, or a fresh profile's very first ``deliver: bot-chat`` job is+recorded as failed with nowhere to land.+"""+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+from pathlib import Path+import sqlite3+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon++- @pytest.mark.linux_only[email protected]("linux")+def test_cron_bot_chat_delivery_creates_the_missing_bot_chat_and_admits(tmp_path, monkeypatch):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ model.requests = []+ model.blocked, model.release = threading.Event(), threading.Event()+ threading.Thread(target=model.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{model.server_port}/v1'+ try:+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}),+ encoding='utf-8')+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.setattr(Path, 'home', lambda: user)+ with daemon(root, home, env, barrier=False):+ from cron.scheduler_delivery import _deliver_to_bot_chat+ job = {'id': 'digest', 'name': 'Digest', 'execution_id': 'run-1'}+ first = _deliver_to_bot_chat(job, 'FIRST_PAYLOAD', '')+ receipt = job['_bot_chat_delivery_receipts']['bot-chat:(own)']+ assert receipt['status'] in ('queued', 'claimed', 'settled'), (first, receipt)+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ titled = db.execute("SELECT id FROM sessions WHERE title='Bot Chat'").fetchall()+ assert len(titled) == 1, titled+ admitted = db.execute('SELECT target_session_id, payload_json FROM session_admissions').fetchall()+ assert len(admitted) == 1 and 'FIRST_PAYLOAD' in admitted[0][1], admitted+ # The next run lands in the SAME Bot Chat: created once, then resolved by name.+ second = _deliver_to_bot_chat({**job, 'execution_id': 'run-2'}, 'SECOND_PAYLOAD', '')+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ assert db.execute("SELECT count(*) FROM sessions WHERE title='Bot Chat'").fetchone()[0] == 1+ targets = {row[0] for row in db.execute('SELECT target_session_id FROM session_admissions')}+ assert len(targets) == 1, (first, second, targets)+ finally:+ model.shutdown()+ model.server_close()diff --cc tests/cron/test_cron_mcp_toolset_empty_block.pyindex ae23c896044,ee38fbafa08..b13de40db78--- a/tests/cron/test_cron_mcp_toolset_empty_block.py+++ b/tests/cron/test_cron_mcp_toolset_empty_block.py@@@ -81,10 -38,9 +79,9 @@@ def _run(job, tmp_path)agent_cls.return_value.run_conversation.return_value = {"final_response": "ok"}with cron_jobs.use_cron_store(tmp_path):cron_jobs.save_jobs([job])- result = run_job(job)+ result = _run_owned_job(job, tmp_path)return result, agent_cls.called-def _register_notion_in_scope(scope):from tools.registry import registryregistry.register(@@@ -146,12 -95,9 +141,11 @@@ def _park_notion(home, *, ever_connecteserver._ever_connected = ever_connectedserver._park_reason = park_reasonregistry.register_toolset_alias("notion", "mcp-notion")- core._servers["notion"] = server- return lambda: core._servers.pop("notion", None)+ with _profile_runtime_scope(Path(home).resolve()):+ key = _resolve_server_key("notion")+ core._servers[key] = server+ return lambda: core._servers.pop(key, None)-def test_requested_mcp_server_reconnecting_runs_without_its_tools(tmp_path):"""A server that connected in this process and is parked/self-probing after a network blipis recoverable: the job runs with the tools that did resolve instead of blocking (#112871)."""@@@ -165,10 -111,9 +159,9 @@@assert agent_built is Trueassert success is True and error is None-def test_requested_mcp_server_never_connected_still_blocks(tmp_path):"""A parked server that never connected here (bad URL, wrong credentials) keeps the block."""- undo = _park_notion(ever_connected=False)+ undo = _park_notion(tmp_path, ever_connected=False)try:(success, _output, _final, error), agent_built = _run(_job(enabled_toolsets=["terminal", "notion"]), tmp_path)diff --cc tests/cron/test_cron_memory_contract.pyindex 95f4101b34b,0da94aeb28d..abaca650e97--- a/tests/cron/test_cron_memory_contract.py+++ b/tests/cron/test_cron_memory_contract.py@@@ -47,9 -46,8 +47,8 @@@ from __future__ import annotationimport contextlibfrom unittest.mock import MagicMock, patch-from cron.scheduler import run_job+from tests.cron.test_scheduler import _run_owned_job-@contextlib.contextmanagerdef _run_job_patches(tmp_path):"""Patch bundle so run_job runs offline; yields (fake_db, mock_agent_cls).diff --cc tests/cron/test_cron_workdir.pyindex d5409e6187b,21d238547f1..3bd2f795df1--- a/tests/cron/test_cron_workdir.py+++ b/tests/cron/test_cron_workdir.py@@@ -11,10 -11,7 +11,11 @@@ Covers"""from __future__ import annotations++import asyncio+import json+ import sys+from types import SimpleNamespaceimport pytestdiff --cc tests/cron/test_scheduler.pyindex 1928651cda9,1e4a475ba1e..8d6f3eaf7ea--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@@ -24,53 -23,6 +24,55 @@@ from cron.scheduler importfrom cron.scheduler_delivery import _resolve_origin, _send_media_via_adapterfrom tools.env_passthrough import clear_env_passthrough++def _run_owned_job(job, tmp_path, db=None):+ """Run the production owner bridge, preserving each test's agent/DB probes."""+ from gateway.session_contract import SessionRef+ from gateway.session_cron import current_execution, execute+ from hermes_state_registry import acquire, release++ ref = SessionRef("test-profile", "canonical-cron-session")+ admission_id = "cron-owner-admission"+ request_id = "cron-owner-request"+ owns_db = db is None+ if owns_db:+ db = acquire(tmp_path / "state.db")+ db.create_session(ref.session_id, source="cron")+ else:+ db.db_path = str(tmp_path / "state.db")+ authority = SimpleNamespace(+ db=db,+ sessions={ref.session_id: SimpleNamespace(source=SimpleNamespace(user_id="cron-owner"))},+ pending_results={},+ )+ row = {+ "admission_id": admission_id, "request_id": request_id,+ "principal_id": "cron-owner", "payload": {"text": ""},+ }+ policy = SimpleNamespace(request_json=json.dumps({+ "cron_job": job, "extra_prompt": None, "request_id": request_id,+ }))++ async def run():+ previous = current_execution()+ try:+ await execute(authority, ref, row, policy)+ except RuntimeError as exc:+ saved = authority.pending_results.get(admission_id)+ if saved is None:+ raise+ assert str(exc) == saved["result"]["cron_result"][3]+ assert current_execution() is previous+ assert authority._cron_cancellations == {}+ return tuple(authority.pending_results[admission_id]["result"]["cron_result"])++ try:+ return asyncio.run(run())+ finally:+ if owns_db:+ release(db)++++def test_cron_cleanup_worker_inherits_caller_contextvars():"""Profile-scoped secrets must remain visible during threaded cleanup."""profile_scope = contextvars.ContextVar("test_cron_cleanup_profile_scope")@@@ -1335,13 -1280,13 +1303,12 @@@ class TestRunJobModelResolutionmock_agent = MagicMock()mock_agent.run_conversation.return_value = {"final_response": "ok"}mock_agent_cls.return_value = mock_agent- success, _, _, error = run_job(job)+ success, _, _, error = _run_owned_job(job, tmp_path, fake_db)- # Explicit job model survives the corrupt-config fall-through.- assert success is True- assert error is None- assert mock_agent_cls.call_args.kwargs["model"] == "explicit-model"+ assert success is False+ assert "Hermes stopped because your settings file" in error+ mock_agent_cls.assert_not_called()-class TestRunJobSkillBacked:def test_run_job_preserves_skill_env_passthrough_into_worker_thread(self, tmp_path):job = {diff --cc tests/cron/test_tick_without_gateway.pyindex ec9b47f671d,00000000000..ff6809ddf3dmode 100644,000000..100644--- a/tests/cron/test_tick_without_gateway.py+++ b/tests/cron/test_tick_without_gateway.py@@@ -1,147 -1,0 +1,147 @@@+"""``hermes cron tick`` with no live gateway refuses agent jobs instead of spawning one.++The external-scheduler mode (system crontab calling ``hermes cron tick``) used to reach+``run_canonical_job`` -> ``connect_gateway`` -> ``ensure_gateway_runtime``, which spawns an+unmanaged daemon when nothing owns the profile. Headless surfaces refuse rather than spawn:+the agent job is skipped (not failed), keeps its due instant, and one warning names the fix.+"""+from datetime import timedelta+import os++import pytest++import cron.jobs as J+import cron.scheduler as S+from cron import scheduler_authority+++def cron_home(tmp_path, monkeypatch):+ home = tmp_path / "home"+ (home / "cron").mkdir(parents=True)+ (home / "scripts").mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(J, "HERMES_DIR", home)+ monkeypatch.setattr(J, "CRON_DIR", home / "cron")+ monkeypatch.setattr(J, "JOBS_FILE", home / "cron" / "jobs.json")+ monkeypatch.setattr(J, "OUTPUT_DIR", home / "cron" / "output")+ monkeypatch.setattr(S, "_hermes_home", home)+ monkeypatch.setattr(S, "_sweep_mcp_orphans", lambda: None)+ S._running_job_ids.clear()+ return home+++def _make_due(job_id: str) -> None:+ stored = J.load_jobs()+ slot = (J._hermes_now() - timedelta(minutes=1)).replace(microsecond=0).isoformat()+ next(r for r in stored if r["id"] == job_id)["next_run_at"] = slot+ J.save_jobs(stored)+++def test_tick_without_gateway_skips_agent_jobs_without_spawning_or_drift(cron_home, monkeypatch, caplog):+ from hermes_cli import gateway_runtime, gateway_runtime_start++ spawned = []+ monkeypatch.setattr(gateway_runtime_start, "spawn_unmanaged_gateway",+ lambda *a, **k: spawned.append(a))+ monkeypatch.setattr(gateway_runtime, "ensure_gateway_runtime",+ lambda *a, **k: pytest.fail("a headless tick must never ensure-or-spawn"))++ agent = J.create_job(prompt="summarise inbox", schedule="every 1h", name="agent", deliver="local")+ other = J.create_job(prompt="digest", schedule="every 1h", name="agent-2", deliver="local")+ _make_due(agent["id"])+ _make_due(other["id"])+ due_before = {j["id"]: j["next_run_at"] for j in J.load_jobs()}++ with caplog.at_level("WARNING", logger="cron.scheduler_authority"):+ ran = S.tick(verbose=False, headless=True)++ assert ran == 0 and spawned == []+ stored = {j["id"]: j for j in J.load_jobs()}+ for job_id in (agent["id"], other["id"]):+ # Skipped, not failed: no run recorded, the due instant is untouched (no drift), no+ # orphaned dispatch stamp for the next tick to "restore", and the reason is visible.+ assert stored[job_id]["last_run_at"] is None+ assert stored[job_id]["next_run_at"] == due_before[job_id]+ assert "pending_slot" not in stored[job_id]+ assert "hermes gateway start" in stored[job_id]["last_fire_error"]["detail"]+ refusals = [r for r in caplog.records if "not running" in r.getMessage()]+ assert len(refusals) == 1, "one log line per tick, not one per job"+ assert agent["id"] in refusals[0].getMessage() and "hermes gateway start" in refusals[0].getMessage()++- @pytest.mark.linux_only[email protected]("linux")[email protected]("stand_in", ["starting_lock", "silent_socket"])+def test_tick_holds_agent_jobs_while_gateway_is_starting_or_silent(cron_home, monkeypatch, caplog, stand_in):+ """A gateway mid-restart (lock held, no socket) or one whose control socket accepts but never+ answers is 'not ready', not 'failed': the tick must hold the slot exactly like ``absent`` —+ no run row, next_run_at kept — and decide well inside the crontab minute."""+ import fcntl+ import socket+ import threading+ import time++ from hermes_cli import gateway_runtime_start++ os.chmod(cron_home, 0o700)+ spawned = []+ monkeypatch.setattr(gateway_runtime_start, "spawn_unmanaged_gateway", lambda *a, **k: spawned.append(a))+ keep = []+ if stand_in == "starting_lock":+ lock = open(cron_home / "gateway.lock", "w")+ os.chmod(cron_home / "gateway.lock", 0o600)+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ keep.append(lock)+ else:+ from gateway.control_socket import resolve_server_socket_path+ bind_path, pointer = resolve_server_socket_path(cron_home) # same sun_path fallback as the daemon+ bind_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ server.bind(str(bind_path))+ os.chmod(bind_path, 0o600)+ if pointer is not None:+ pointer.write_text(str(bind_path), encoding="utf-8")+ os.chmod(pointer, 0o600)+ server.listen(4)+ keep.append(server)++ def hold(): # accept and hold every peer open: an owner that never answers identify+ while True:+ try:+ keep.append(server.accept()[0])+ except OSError:+ return+ threading.Thread(target=hold, daemon=True).start()++ agent = J.create_job(prompt="summarise inbox", schedule="every 1h", name="agent", deliver="local")+ _make_due(agent["id"])+ due_before = J.load_jobs()[0]["next_run_at"]+ started = time.monotonic()+ with caplog.at_level("WARNING", logger="cron.scheduler_gateway_gate"):+ ran = S.tick(verbose=False, headless=True)+ elapsed = time.monotonic() - started+ for handle in keep:+ handle.close()++ assert ran == 0 and spawned == []+ assert elapsed < 20, f"headless probe must decide inside the crontab minute, took {elapsed:.1f}s"+ stored = J.load_jobs()[0]+ assert stored["last_run_at"] is None and stored["last_status"] is None+ assert stored["next_run_at"] == due_before, "the slot is held, not consumed"+ assert "pending_slot" not in stored+ assert "hermes gateway status" in stored["last_fire_error"]["detail"]+ assert len([r for r in caplog.records if "skipped" in r.getMessage()]) == 1+++def test_no_agent_jobs_still_fire_without_a_gateway(cron_home, monkeypatch):+ counter = cron_home / "fires.txt"+ script = cron_home / "scripts" / "fire.sh"+ script.write_text(f"#!/bin/sh\necho fired >> {counter}\necho fired\n", encoding="utf-8")+ script.chmod(0o755)+ monkeypatch.setattr(scheduler_authority, "reconcile_pending", lambda: None)+ job = J.create_job(prompt=None, schedule="every 1h", name="script", script="fire.sh",+ no_agent=True, deliver="local")+ _make_due(job["id"])++ assert S.tick(verbose=False, headless=True) == 1+ assert counter.read_text(encoding="utf-8").count("fired") == 1diff --cc tests/fixtures/resolution_allowlist.jsonindex f7750927b81,6b8893b5d80..b969cf51b8b--- a/tests/fixtures/resolution_allowlist.json+++ b/tests/fixtures/resolution_allowlist.json@@@ -69,6 -74,16 +74,11 @@@"symbol": "BitwardenLoginBackend._bw","kind": "bare_which"},+ {+ "path": "apps/desktop/electron/fixtures/source-backend.py",+ "symbol": "main",+ "kind": "bare_which"+ },- {- "path": "cron/scheduler_delivery.py",- "symbol": "_deliver_to_bot_chat",- "kind": "bare_which"- },{"path": "cron/scheduler_script.py","symbol": "_script_argv",diff --cc tests/gateway/fixtures/shared_authority_peer.pyindex a5e5dd33888,00000000000..3b35fa5fcd9mode 100644,000000..100644--- a/tests/gateway/fixtures/shared_authority_peer.py+++ b/tests/gateway/fixtures/shared_authority_peer.py@@@ -1,280 -1,0 +1,282 @@@+"""Disposable production-runtime peer; only provider and vendor wire are synthetic."""++import asyncio+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import importlib.util+import json+import os+from pathlib import Path+import socket+import sys+import threading+import traceback+++class ModelPeer(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(json.dumps({"data": [{"id": "local-wire-stub", "object": "model"}]}).encode())++ def do_POST(self):+ request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ last = next((m.get("content", "") for m in reversed(request.get("messages", []))+ if m.get("role") == "user"), "")+ marker = "WS_SHARED" if "WS_SHARED" in json.dumps(last) else "MESSAGING_WARM"+ reply = f"LOCAL_ACK_{marker}"+ if 'BLOCK_FIFO' in json.dumps(last):+ self.server.blocked.set()+ assert self.server.release.wait(15), 'fixture model gate timed out'+ self.server.requests.append(request) if 'messages' in request else self.server.metadata_requests.append(request)+ base = {"id": "chatcmpl-local", "model": "local-wire-stub", "created": 1}+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream" if request.get("stream") else "application/json")+ self.end_headers()+ if request.get("stream"):+ for delta, finish in [({"role": "assistant", "content": reply}, None), ({}, "stop")]:+ chunk = {**base, "object": "chat.completion.chunk", "choices": [+ {"index": 0, "delta": delta, "finish_reason": finish}]}+ self.wfile.write(("data: " + json.dumps(chunk) + "\n\n").encode())+ self.wfile.flush()+ self.wfile.write(b"data: [DONE]\n\n")+ else:+ self.wfile.write(json.dumps({**base, "object": "chat.completion", "choices": [+ {"index": 0, "message": {"role": "assistant", "content": reply}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}).encode())+++async def probe():+ import uvicorn+ import websockets+ from gateway.config import Platform, PlatformConfig+ from gateway.platforms.base import BasePlatformAdapter, SendResult+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session import SessionSource+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket+ from tui_gateway import server+ from run_agent import AIAgent+ from shared_authority_recovery import prepare_crash, recover_probe, verify_envelope_guards++ class CaptureAdapter(BasePlatformAdapter):+ def __init__(self):+ super().__init__(PlatformConfig(enabled=True, token="local-fixture"), Platform.TELEGRAM)+ self.sent = []+ self.deliveries = []++ async def connect(self, *, is_reconnect=False):+ return True++ async def disconnect(self):+ pass++ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.deliveries.append({'chat_id': chat_id, 'content': content, 'reply_to': reply_to, 'metadata': metadata})+ self.sent.append(content)+ return SendResult(success=True, message_id=str(len(self.sent)))++ async def edit_message(self, chat_id, message_id, content, *, finalize=False):+ self.sent.append(content)+ return SendResult(success=True, message_id=message_id)++ async def send_typing(self, chat_id, metadata=None):+ pass++ async def get_chat_info(self, chat_id):+ return {"id": chat_id}++ runner = GatewayRunner()+ if importlib.util.find_spec("gateway.session_authority") is not None:+ from gateway.session_authority import initialize_session_authority+ await initialize_session_authority(runner, profile_id="default", instance_id="test-owner")+ adapter = CaptureAdapter()+ runner.adapters[Platform.TELEGRAM] = adapter+ adapter.set_message_handler(runner._handle_message)+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="fixture-chat", chat_type="dm", user_id="fixture-user")+ if os.environ.get('AUTHORITY_PROBE_MODE') == 'recover':+ await recover_probe(runner, adapter, source, peer)+ return+ event = MessageEvent(text="MESSAGING_WARM", source=source, message_id="warm-1")+ await adapter.handle_message(event)+ async with asyncio.timeout(35):+ while adapter._active_sessions:+ await asyncio.sleep(0.05)+ assert event._gateway_accepted, adapter.sent+ assert any("LOCAL_ACK_MESSAGING_WARM" in text for text in adapter.sent), adapter.sent+ entry = runner.session_store.get_or_create_session(source)+ warm_agent = runner._cached_agent_for(entry.session_key)+ assert isinstance(warm_agent, AIAgent), "Messaging warmup must retain a real live agent"++ api_handle = None+ if importlib.util.find_spec("gateway.run_api") is not None:+ from gateway.run_api import start_gateway_api+ api_handle = await start_gateway_api(runner)+ port = api_handle.socket.getsockname()[1]+ else:+ # Retain the historical transport only for the pre-authority A/B tree.+ app = web_server.app+ app.state.auth_required = True+ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ listener.setblocking(False)+ port = listener.getsockname()[1]+ http = uvicorn.Server(uvicorn.Config(app, log_level="warning", lifespan="off", ws="websockets"))+ task = asyncio.create_task(http.serve(sockets=[listener]))+ async with asyncio.timeout(10):+ while not http.started:+ if task.done():+ await task+ await asyncio.sleep(0.01)+ frames = []+ receipt = {"messaging_completed": True, "stored_id": entry.session_id,+ "unauthenticated_rejected": False, "ws_completed": False, "same_agent": False}+ try:+ try:+ async with websockets.connect(f"ws://127.0.0.1:{port}/api/ws"):+ raise AssertionError("Missing WS credential was accepted")+ except websockets.exceptions.InvalidStatus as exc:+ assert exc.response.status_code == 403, str(exc)+ receipt["unauthenticated_rejected"] = True+ if api_handle is not None:+ credential = f"token={web_server._SESSION_TOKEN}"+ else:+ credential = f"ticket={mint_ticket(user_id='fixture-user', provider='fixture')}"+ async with websockets.connect(f"ws://127.0.0.1:{port}/api/ws?{credential}") as ws:+ async def until(predicate):+ async with asyncio.timeout(35):+ while True:+ frame = json.loads(await ws.recv())+ frames.append(frame)+ if predicate(frame):+ return frame++ await until(lambda f: f.get("params", {}).get("type") == "gateway.ready")+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "session.resume",+ "params": {"session_id": entry.session_id}}))+ resumed = await until(lambda f: f.get("id") == 1)+ receipt["resume"] = resumed+ if "result" in resumed:+ sid = resumed["result"]["session_id"]+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "prompt.submit",+ "params": {"session_id": sid, "text": "WS_SHARED", "input_id": "ws-1"}}))+ submitted = await until(lambda f: f.get("id") == 2)+ receipt["submit"] = submitted+ if "result" in submitted:+ terminal = await until(lambda f: f.get("params", {}).get("type") in {"message.complete", "error"})+ receipt["terminal"] = terminal+ receipt["ws_completed"] = "LOCAL_ACK_WS_SHARED" in json.dumps(terminal)+ authority = getattr(runner, 'session_authority', None)+ if authority is not None:+ from gateway.session_contract import SessionRef+ receipt["same_agent"] = authority.agent(SessionRef('default', sid)) is warm_agent+ else:+ receipt["same_agent"] = server._sessions[sid].get("agent") is warm_agent+ receipt["messaging_outputs"] = adapter.sent+ if getattr(runner, 'session_authority', None) is not None:+ from hermes_state_runtime import list_session_admissions+ await adapter.handle_message(MessageEvent(text='BLOCK_FIFO', source=source, message_id='fifo-1'))+ assert await asyncio.to_thread(peer.blocked.wait, 5)+ queued_event = MessageEvent(text='FIFO_SECOND', source=source, message_id='fifo-2')+ queued_task = asyncio.create_task(adapter.handle_message(queued_event))+ try:+ async with asyncio.timeout(3):+ while not any(r['request_id'] == 'fifo-2' for r in list_session_admissions(+ runner.session_authority.db, session_id=entry.session_id)):+ await asyncio.sleep(0.01)+ assert not adapter._pending_messages, 'second frontend queue owns accepted work'+ receipt['durable_native_fifo'] = True+ pending = list_session_admissions(runner.session_authority.db, session_id=entry.session_id)+ queued_row = next(r for r in pending if r['request_id'] == 'fifo-2')+ envelope = queued_row['payload'].get('native_text_v1')+ assert envelope is not None, 'ACK has no durable native source envelope'+ assert envelope['source']['user_id'] == 'fixture-user'+ assert envelope['route'] == entry.session_key+ published = await until(lambda f: f.get('params', {}).get('type') == 'session.info'+ and any(r.get('input_id') == 'fifo-2' for r in f['params'].get('payload', {}).get('pending', [])))+ assert any(r['text'] == 'FIFO_SECOND' for r in published['params']['payload']['pending'])+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 'queue-snapshot',+ 'method': 'session.resume', 'params': {'session_id': entry.session_id}}))+ projected = (await until(lambda f: f.get('id') == 'queue-snapshot'))['result']['pending']+ visible = next(r for r in projected if r['admission_id'] == queued_row['admission_id'])+ assert visible['text'] == 'FIFO_SECOND' and visible['input_id'] == 'fifo-2', visible+ assert not {'payload', 'native_text_v1', 'source', 'principal_id'} & visible.keys(), visible+ receipt['queue_snapshot_text'] = visible['text']+ queued_event.text = 'MUTATED_AFTER_ACK'+ queued_event.source = SessionSource(platform=Platform.TELEGRAM, chat_id='wrong-chat', user_id='foreign')+ finally:+ peer.release.set()+ await queued_task+ async with asyncio.timeout(10):+ while adapter._active_sessions:+ await asyncio.sleep(0.01)+ task_owner = runner.session_authority.sessions[entry.session_id].task+ if task_owner is not None:+ await task_owner+ rows = list_session_admissions(runner.session_authority.db,+ session_id=entry.session_id, pending_only=False)+ assert [r['request_id'] for r in rows] == ['warm-1', 'ws-1', 'fifo-1', 'fifo-2'], rows+ assert all(r['status'] == 'terminal' and r['outcome'] == 'completed' for r in rows), rows+ assert runner._cached_agent_for(entry.session_key) is warm_agent+ last_users = [next((m.get('content', '') for m in reversed(r.get('messages', []))+ if m['role'] == 'user'), '') for r in peer.requests]+ assert 'FIFO_SECOND' in json.dumps(last_users[-1]), last_users+ assert 'MUTATED_AFTER_ACK' not in json.dumps(last_users), last_users+ assert any('LOCAL_ACK_WS_SHARED' in text for text in adapter.sent), adapter.sent+ before = len(rows)+ rejected = MessageEvent(text='UNAUTHORIZED', message_id='denied', source=SessionSource(+ platform=Platform.TELEGRAM, chat_id='fixture-chat', chat_type='group', user_id='foreign'))+ await runner._handle_message(rejected)+ assert len(list_session_admissions(runner.session_authority.db,+ session_id=entry.session_id, pending_only=False)) == before+ receipt['admissions'] = rows+ await verify_envelope_guards(runner, source)+ if os.environ.get('AUTHORITY_PROBE_MODE') == 'crash':+ await prepare_crash(runner, adapter, source, peer)+ finally:+ Path(os.environ["HERMES_HOME"], "receipt.json").write_text(json.dumps(receipt, indent=2))+ Path(os.environ["HERMES_HOME"], "frames.json").write_text(json.dumps(frames, indent=2))+ if api_handle is not None:+ from gateway.run_api import stop_gateway_api+ await stop_gateway_api(api_handle)+ else:+ http.should_exit = True+ await asyncio.wait_for(task, 10)+ listener.close()+ print(json.dumps(receipt))+++if __name__ == "__main__":+ peer = ThreadingHTTPServer(("127.0.0.1", 0), ModelPeer)+ peer.requests = []+ peer.metadata_requests = []+ peer.blocked = threading.Event()+ peer.release = threading.Event()+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ base_url = f"http://127.0.0.1:{peer.server_port}/v1"+ os.environ.update(OPENAI_API_KEY="explicit-loopback-fixture", OPENAI_BASE_URL=base_url,+ TELEGRAM_ALLOWED_USERS="fixture-user")+ Path(os.environ["HERMES_HOME"], "config.yaml").write_text(+ f"model:\n default: local-wire-stub\n provider: custom\n base_url: {base_url}\n"- f"auxiliary:\n title_generation:\n enabled: false\nterminal:\n cwd: {os.environ['HERMES_HOME']}\n")++ f"auxiliary:\n title_generation:\n enabled: false\nterminal:\n cwd: {os.environ['HERMES_HOME']}\n"++ # The durable-FIFO proof needs queue semantics; interrupt mode redirects the running turn.++ "display:\n busy_input_mode: queue\n")+ status = 0+ try:+ asyncio.run(probe())+ except BaseException:+ traceback.print_exc()+ status = 1+ finally:+ peer.shutdown()+ peer.server_close()+ sys.stdout.flush()+ sys.stderr.flush()+ # Disposable child owns all runtime background threads (heartbeats, reapers,+ # provider pools); don't leave a lease-wait executor holding pytest hostage.+ os._exit(status)diff --cc tests/gateway/test_api_server_runs.pyindex 5fbe066d78d,e5066808f05..140ffcf1ce4--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@@ -580,43 -652,6 +653,47 @@@ class TestRunEventsassert "run.completed" in bodyassert "Hello!" in body+ @pytest.mark.asyncio+ async def test_two_subscribers_each_receive_every_event_and_survive_one_disconnect(self, adapter):+ """/events is fanout, not a work queue: every subscriber sees the whole ordered stream,+ and one client's disconnect never tears down the stream another client still reads."""++ from gateway.platforms.api_server_runs import _mark_run_event++ async def frame(resp):- return (await asyncio.wait_for(resp.content.readuntil(b"\n\n"), timeout=2.0)).decode()++ # Skip SSE comment frames (``: open`` head flush, keepalives): only events count.++ while True:++ chunk = (await asyncio.wait_for(resp.content.readuntil(b"\n\n"), timeout=2.0)).decode()++ if not chunk.startswith(":"):++ return chunk++ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent") as mock_create:+ mock_agent, agent_ready, _ = _make_slow_agent()+ mock_create.return_value = mock_agent+ run_id = (await (await cli.post("/v1/runs", json={"input": "hello"})).json())["run_id"]+ assert agent_ready.wait(timeout=3.0)+ first = await cli.get(f"/v1/runs/{run_id}/events")+ second = await cli.get(f"/v1/runs/{run_id}/events")+ assert first.status == second.status == 200++ _mark_run_event(adapter, run_id, "run.steered", accepted=True)+ assert "run.steered" in await frame(first)+ assert "run.steered" in await frame(second)++ first.close()+ # The server only notices the dropped socket on its next write.+ _mark_run_event(adapter, run_id, "run.steered", accepted=False)+ assert "run.steered" in await frame(second)+ await asyncio.sleep(0.05)+ _mark_run_event(adapter, run_id, "approval.responded", choice="once")+ assert "approval.responded" in await frame(second)++ assert (await cli.post(f"/v1/runs/{run_id}/stop")).status == 200+ tail = await asyncio.wait_for(second.content.read(), timeout=5.0)+ assert b"stream closed" in tail+@pytest.mark.asyncioasync def test_completed_event_carries_served_runtime_and_cache_tokens(self, adapter):"""The run.completed SSE event discloses the same served runtime and cache tokens as thediff --cc tests/gateway/test_api_source_binding.pyindex 1a4c2479944,00000000000..8d2800eae22mode 100644,000000..100644--- a/tests/gateway/test_api_source_binding.py+++ b/tests/gateway/test_api_source_binding.py@@@ -1,53 -1,0 +1,55 @@@+"""API source restoration cannot mint a parallel native conversation."""+from types import SimpleNamespace++import pytest++from gateway.config import Platform, GatewayConfig+from gateway.session import SessionStore+from gateway.session_authority import SessionAuthority+from gateway.session_contract import Principal, SessionRef, Submission+from hermes_state import SessionDB+from hermes_state_runtime import RuntimeStoreError, begin_runtime_epoch+++def owner(tmp_path):+ db = SessionDB(tmp_path / 'state.db')- runner = SimpleNamespace(_draining=False, session_store=SessionStore(config=GatewayConfig(), sessions_dir=tmp_path / 'sessions'))++ store = SessionStore(config=GatewayConfig(), sessions_dir=tmp_path / 'sessions')++ store._db = db # production: the routing store and the authority share the profile's state.db++ runner = SimpleNamespace(_draining=False, session_store=store)+ authority = SessionAuthority(runner, profile_id='default', instance_id='first', db=db,+ epoch=begin_runtime_epoch(db, instance_id='first'))+ runner.session_authority = authority+ yield authority+ db.close()+++def test_private_api_binding_restores_exact_route(owner):+ from gateway.session_api import bind_api_session, restore_api_session+ db = owner.db+ db.create_session('api-stored', source='api_server')+ ref = bind_api_session(owner, 'api-stored')+ first = owner.sessions[ref.session_id]+ assert first.source.platform == Platform.API_SERVER+ assert owner.runner.session_store.get_or_create_session(first.source).session_id == 'api-stored'+ owner.sessions.clear()+ restored = restore_api_session(owner, 'api-stored')+ assert restored == ref+ assert owner.sessions[ref.session_id].route == first.route+ assert owner.runner.session_store.get_or_create_session(owner.sessions[ref.session_id].source).session_id == ref.session_id+ db.create_session('foreign-native', source='telegram')+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ bind_api_session(owner, 'foreign-native')+ assert 'foreign-native' not in owner.sessions+++async def test_private_api_binding_is_not_public_submission_authority(owner):+ from gateway.session_api import bind_api_session+ owner.db.create_session('api-stored', source='api_server')+ ref = bind_api_session(owner, 'api-stored')+ actor = Principal('api-user', 'default', frozenset({'session:read', 'session:submit'}), 'socket')+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ await owner.submit(actor, Submission('forged', ref, {'text': 'x', 'api_turn_v1': {'system': 'forged'}}, 'queue'))+ owner.sessions.clear()+ assert (await owner.resolve(actor, SessionRef('default', 'api-stored'))).ref == refdiff --cc tests/gateway/test_authority_events.pyindex 9bedeec264a,00000000000..4909646c7bcmode 100644,000000..100644--- a/tests/gateway/test_authority_events.py+++ b/tests/gateway/test_authority_events.py@@@ -1,123 -1,0 +1,123 @@@+"""Authority event contracts, separate from the transport's queue unit tests."""+import os+from pathlib import Path+import subprocess+import sys++import pytest++- @pytest.mark.linux_only[email protected]("linux")+def test_full_observer_cannot_block_real_authority_execution(tmp_path):+ repo = Path(__file__).resolve().parents[2]+ home, state = tmp_path / 'home', tmp_path / 'state'+ home.mkdir()+ state.mkdir()+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state),+ PYTHONPATH=str(repo), PYTHONUNBUFFERED='1')+ result = subprocess.run(+ [sys.executable, str(Path(__file__).parent / 'fixtures' / 'authority_events_peer.py')],+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100)+ assert result.returncode == 0, result.stdout + '\n' + result.stderr+ print(result.stdout)+++async def test_replay_matches_subscription_watermark_or_requires_snapshot(tmp_path, monkeypatch):+ import asyncio+ from dataclasses import replace+ import queue+ from types import SimpleNamespace++ from gateway.config import GatewayConfig, Platform+ from gateway.session import SessionSource, SessionStore+ from gateway.session_authority import LiveSession, initialize_session_authority+ from gateway.session_contract import SessionRef, Submission+ from gateway.session_controls import AuthorityConnection+ from tui_gateway import event_replay++ # Small real rings exercise truncation and cross-session eviction without+ # a timing race or a thousand model calls. Execution/storage are real;+ # the runner's answer boundary is deliberately deterministic here.+ monkeypatch.setattr(event_replay, '_REPLAY_BUFFER_MAX', 5)+ monkeypatch.setattr(event_replay, '_REPLAY_SESSIONS_MAX', 1)+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ db = store._db+ async def answer(event):+ return event.text+ runner = SimpleNamespace(_session_db=db, session_store=store, _draining=False,+ _handle_message=answer, _adapter_for_source=lambda source: None)+ authority = await initialize_session_authority(runner, profile_id='replay', instance_id='owner')+ ref = SessionRef('replay', 'shared')+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='replay')+ for sid in ('shared', 'other'):+ db.create_session(sid, source='telegram')+ authority.sessions[sid] = LiveSession(source, sid)+ class Peer:+ def __init__(self):+ self.frames = queue.Queue()+ def write(self, frame):+ self.frames.put(frame)+ return True+ peers = [Peer(), Peer()]+ a, b = [AuthorityConnection(authority, peer, {'user_id': 'viewer'}) for peer in peers]+ async def since(epoch, seq, sid='shared'):+ return await b.dispatch({'id': 1, 'method': 'session.events.since', 'params': {+ 'session_id': sid, 'replay_epoch': epoch, 'last_sequence': seq}})+ async def turn(n, target=ref):+ await authority.submit(b.actor, Submission(str(n), target, {'text': str(n)}, 'queue'))+ await authority.sessions[target.session_id].task+ try:+ initial = await a.resume(ref, {})+ await b.resume(ref, {})+ assert 'replay_epoch' in initial and 'last_sequence' in initial, 'resume omits replay watermark'+ await turn(1)+ frames = []+ for peer in peers:+ observed = []+ while not observed or observed[-1]['params']['type'] != 'message.complete':+ observed.append(await asyncio.to_thread(peer.frames.get, True, 5))+ frames.append(observed)+ assert frames[0] == frames[1]+ replay = (await since(initial['replay_epoch'], initial['last_sequence']))['result']+ assert not replay['snapshot_required']+ assert replay['events'] == [frame['params'] for frame in frames[0]]+ current = await b.resume(ref, {})+ assert current['last_sequence'] == frames[0][-1]['params']['seq']+ assert len(authority.sessions['shared'].subscribers) == 2+ assert (await since('old-owner', 0))['result']['snapshot_required']+ assert (await since(current['replay_epoch'], current['last_sequence'] + 1))['result']['snapshot_required']+ assert (await since(current['replay_epoch'], True))['error']['data']['reason'] == 'invalid_params'+ assert (await since(current['replay_epoch'], 0, 'missing'))['error']['data']['reason'] == 'not_found'+ original = b.actor+ b.actor = replace(original, profile_id='foreign')+ assert (await since(current['replay_epoch'], 0))['error']['data']['reason'] == 'profile_mismatch'+ b.actor = original+ await turn(2)+ await turn(3)+ assert (await since(initial['replay_epoch'], 0))['result']['snapshot_required']+ await turn(4, SessionRef('replay', 'other'))+ assert (await since(current['replay_epoch'], current['last_sequence']))['result']['snapshot_required']+ refreshed = await b.resume(ref, {})+ await turn(5)+ after = (await since(refreshed['replay_epoch'], refreshed['last_sequence']))['result']+ assert not after['snapshot_required']+ assert after['events'][-1]['type'] == 'message.complete'+ assert after['events'][-1]['payload']['text'] == '5'+ before_race = await b.resume(ref, {})+ stamp = event_replay._stamp_event+ def evict_then_stamp(frame):+ stamp({'method': 'event', 'params': {'session_id': 'competing-owner'}})+ stamp(frame)+ with monkeypatch.context() as race:+ race.setattr(event_replay, '_stamp_event', evict_then_stamp)+ await turn(6)+ raced = (await since(before_race['replay_epoch'], before_race['last_sequence']))['result']+ assert raced['snapshot_required'], 'eviction during stamp reused an old epoch/sequence'+ assert raced['replay_epoch'] != before_race['replay_epoch']+ finally:+ await a.close()+ await b.close()+ store.close_all_db_handles()diff --cc tests/gateway/test_authority_stream.pyindex 8625f26cdba,00000000000..fd715c4d122mode 100644,000000..100644--- a/tests/gateway/test_authority_stream.py+++ b/tests/gateway/test_authority_stream.py@@@ -1,24 -1,0 +1,24 @@@+"""Canonical execution stream through production API binding and real model SSE."""+import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++- @pytest.mark.parametrize("mode", ["ordinary", pytest.param("blocked", marks=pytest.mark.linux_only)])[email protected]("mode", ["ordinary", pytest.param("blocked", marks=pytest.mark.platforms("linux"))])+def test_authority_stream_has_one_order_and_rejects_retired_callbacks(tmp_path, mode):+ repo = Path(__file__).resolve().parents[2]+ home, state = tmp_path / 'home', tmp_path / 'state'+ home.mkdir()+ state.mkdir()+ env = {k: os.environ[k] for k in ('PATH', 'SYSTEMROOT', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo), STREAM_PROBE_MODE=mode)+ result = subprocess.run([sys.executable, str(Path(__file__).parent / 'fixtures' / 'authority_stream_peer.py')],+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100)+ assert result.returncode == 0, result.stdout + '\n' + result.stderr+ receipt = json.loads((state / 'receipt.json').read_text())+ print(json.dumps(receipt))+ assert receipt['real_terminal_effect'] and receipt['same_stamps'] and receipt['stale_callback_inert']diff --cc tests/gateway/test_canonical_desktop_metadata.pyindex bebb585bbed,00000000000..9101a7bd7e5mode 100644,000000..100644--- a/tests/gateway/test_canonical_desktop_metadata.py+++ b/tests/gateway/test_canonical_desktop_metadata.py@@@ -1,60 -1,0 +1,60 @@@+"""Canonical GUI metadata follows the authenticated local-session route."""+import asyncio+import json++import pytest++from tests.gateway.fixtures.local_recovery_probe import rpc, websocket+from tests.gateway.test_session_busy_controls import owner, settled++- @pytest.mark.linux_only[email protected]("linux")+def test_canonical_desktop_metadata_survives_create_info_and_reattach(tmp_path):+ """The native protocol, not the legacy contract number, identifies this route."""+ with owner(tmp_path) as (home, _peer, desc):+ async def probe():+ async with websocket(home, desc) as creator:+ created = await rpc(creator, 'session.create', request_id='desktop-metadata',+ source='gui', toolsets=[])+ assert 'result' in created, created+ sid = created['result']['session_id']+ created_info = created['result']['info']+ assert created_info['desktop_protocol'] == creator.subprotocol+ assert 'desktop_contract' not in created_info+ assert created_info['lazy'] is True++ lazy_info = await rpc(creator, 'session.info', session_id=sid)+ assert lazy_info['result']['desktop_protocol'] == creator.subprotocol+ assert lazy_info['result']['lazy'] is True++ # Read every frame: the RPC helper deliberately skips events,+ # but Desktop reconciles their metadata throughout each turn.+ await creator.send(json.dumps({'jsonrpc': '2.0', 'id': 'initialize',+ 'method': 'prompt.submit', 'params': {'session_id': sid,+ 'input_id': 'initialize', 'text': 'INITIALIZE'}}))+ submitted = saw_pending = finished = False+ async with asyncio.timeout(30):+ while not submitted or not finished:+ frame = json.loads(await creator.recv())+ if frame.get('id') == 'initialize':+ assert frame['result']['status'] == 'queued', frame+ submitted = True+ event = frame.get('params', {})+ if event.get('type') == 'session.info' and event.get('session_id') == sid:+ info = event['payload']+ assert info['desktop_protocol'] == creator.subprotocol+ assert 'desktop_contract' not in info+ saw_pending |= bool(info['pending'])+ finished = saw_pending and not info['pending'] and not info['running']+ await settled(home)++ initialized_info = await rpc(creator, 'session.info', session_id=sid)+ assert initialized_info['result']['desktop_protocol'] == creator.subprotocol+ assert initialized_info['result']['lazy'] is False++ async with websocket(home, desc) as reattached:+ resumed = await rpc(reattached, 'session.resume', session_id=sid)+ assert resumed['result']['info']['desktop_protocol'] == reattached.subprotocol+ assert resumed['result']['info']['lazy'] is False++ asyncio.run(probe())diff --cc tests/gateway/test_command_discovery.pyindex ee5a4b91c22,00000000000..97b33aa35e1mode 100644,000000..100644--- a/tests/gateway/test_command_discovery.py+++ b/tests/gateway/test_command_discovery.py@@@ -1,202 -1,0 +1,202 @@@+"""Discovery stays transport-independent and cannot select another profile."""+import asyncio+import json+import os+from pathlib import Path+import re+import shutil+import signal+import subprocess+import sys+import time+from types import SimpleNamespace++import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus++from tests.gateway.test_normal_runtime_boot import control+++async def _legacy_ws_snapshot(root, home, env, requests):+ legacy_home = home.parent / 'legacy-state'+ legacy_home.mkdir(mode=0o700)+ shutil.copy2(home / 'config.yaml', legacy_home / 'config.yaml')+ for directory in ('skills', 'plugins'):+ shutil.copytree(home / directory, legacy_home / directory)+ legacy_env = {**env, 'HERMES_HOME': str(legacy_home),+ 'HERMES_DASHBOARD_SESSION_TOKEN': 'disposable-discovery-token'}+ with (home.parent / 'legacy-serve.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'hermes_cli.main', 'serve',+ '--host', '127.0.0.1', '--port', '0', '--skip-build', '--isolated'],+ cwd=root, env=legacy_env, stdin=subprocess.DEVNULL,+ stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ port = None+ output = ''+ while process.poll() is None and time.monotonic() < deadline:+ log.seek(0)+ output = log.read()+ if match := re.search(r'HERMES_BACKEND_READY port=(\d+)', output):+ port = int(match.group(1))+ break+ await asyncio.sleep(.1)+ assert port, output+ results = []+ async with connect(f'ws://127.0.0.1:{port}/api/ws?token=disposable-discovery-token') as ws:+ for rid, (method, params) in enumerate(requests):+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': rid, 'method': method, 'params': params}))+ async with asyncio.timeout(20):+ while True:+ reply = json.loads(await ws.recv())+ if reply.get('id') == rid:+ assert 'result' in reply, reply+ results.append(reply['result'])+ break+ process.send_signal(signal.SIGINT)+ assert process.wait(timeout=20) == 0+ return results, {'legacy_ws_pid': process.pid, 'legacy_ws_port': port,+ 'legacy_ws_exit': process.returncode}+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=15)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)++- @pytest.mark.linux_only[email protected]("linux")+def test_ordinary_daemon_discovery_matches_legacy_extensions(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'discovery-fixture',+ 'base_url': 'http://127.0.0.1:1/v1'},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'quick_commands': {'probe-quick': {'type': 'alias', 'target': '/help',+ 'description': 'Disposable quick discovery'}},+ 'plugins': {'enabled': ['probe_plugin']},+ }))+ skill = home / 'skills' / 'probe-skill'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text('---\nname: probe-skill\ndescription: Disposable skill discovery\n---\n# Probe\nOnly a discovery fixture.\n')+ plugin = home / 'plugins' / 'probe_plugin'+ plugin.mkdir(parents=True)+ (plugin / 'plugin.yaml').write_text('name: probe_plugin\nversion: 0.1.0\ndescription: Discovery fixture\n')+ (plugin / '__init__.py').write_text(+ "def register(ctx):\n ctx.register_command('probe-plugin', lambda args: args, description='Disposable plugin discovery')\n")+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1')+ requests = [('commands.catalog', {}), *[('complete.slash', {'text': text})+ for text in ('/', '/probe', '/probe-quick', '/help', '/details c', 'plain')]]+ legacy_code = '''import json, sys+from tui_gateway import server+requests = json.loads(sys.argv[1])+results = [server._methods[method](i, params)['result'] for i, (method, params) in enumerate(requests)]+sys.__stdout__.write(json.dumps(results) + '\\n')+'''++ async def probe(descriptor):+ ws_baseline, legacy_receipt = await _legacy_ws_snapshot(root, home, env, requests)+ assert ws_baseline == expected+ url = descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws'+ with pytest.raises(InvalidStatus):+ async with connect(url):+ pass+ ticket = control(home, 'session-ticket', {+ 'profile_id': str(home), 'instance_id': descriptor['instance_id'], 'purpose': 'interactive'})+ async with connect(url, subprotocols=['hermes-gateway-v1',+ 'hermes-gateway-ticket.' + ticket['ticket']]) as ws:+ async def rpc(method, params):+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))+ async with asyncio.timeout(20):+ while True:+ reply = json.loads(await ws.recv())+ if reply.get('id') == method:+ return reply+ for (method, params), baseline in zip(requests, expected):+ reply = await rpc(method, params)+ got = reply.get('result')+ if got != baseline and isinstance(got, dict) and 'skills' in got:+ a, b = got['skills'], baseline['skills']+ delta = {k: (a.get(k), b.get(k)) for k in set(a) | set(b) if a.get(k) != b.get(k)}+ raise AssertionError(f'skills delta daemon vs legacy: {delta}')+ assert got == baseline, reply+ for method in ('commands.catalog', 'complete.slash'):+ reply = await rpc(method, {'profile': 'foreign-profile', **({'text': '/probe'} if method == 'complete.slash' else {})})+ assert reply['error']['message'] == 'profile_mismatch', reply+ return {**legacy_receipt, 'legacy_pid_exit': legacy.returncode, 'catalog_pairs': len(pairs),+ 'skill_count': expected[0]['skill_count'], 'compared_requests': len(requests),+ 'unauthenticated_ws': 'rejected', 'foreign_profile': 'rejected'}++ with (tmp_path / 'gateway.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ descriptor = {}+ deadline = time.monotonic() + 40+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ # Ordinary startup syncs bundled skills; compare both transports on that same snapshot.+ legacy = subprocess.run([sys.executable, '-c', legacy_code, json.dumps(requests)],+ cwd=root, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=45)+ assert legacy.returncode == 0, legacy.stderr+ expected = json.loads(legacy.stdout.splitlines()[-1])+ pairs = dict(expected[0]['pairs'])+ for name in ('/probe-skill', '/probe-quick', '/probe-plugin'):+ assert name in pairs, (name, expected[0]['warning'])+ assert {'probe-skill', 'probe-plugin'} <= {+ row['text'].strip().lstrip('/') for row in expected[2]['items']}+ receipt = asyncio.run(probe(descriptor))+ process.send_signal(signal.SIGINT)+ assert process.wait(timeout=20) == 0+ print(json.dumps({**receipt, 'pid': process.pid, 'daemon_exit': process.returncode,+ 'instance_id': descriptor['instance_id'], 'api_origin': descriptor['api_origin']}))+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=15)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++async def test_discovery_authorizes_before_scanning(tmp_path, monkeypatch):+ from agent import skill_commands+ from hermes_cli import plugins+ from gateway.session_controls import AuthorityConnection++ def forbidden(*args, **kwargs):+ pytest.fail('unauthorized request reached discovery')+ monkeypatch.setattr(skill_commands, 'scan_skill_commands', forbidden)+ monkeypatch.setattr(plugins, 'get_plugin_commands', forbidden)+ authority = SimpleNamespace(instance_id='owned', profile_id=str(tmp_path), events={})+ for identity in ({}, {'user_id': 'reader', 'capabilities': []},+ {'user_id': 'reader', 'profile_id': 'foreign'},+ {'user_id': 'reader', 'instance_id': 'stale'}):+ connection = AuthorityConnection(authority, object(), identity)+ try:+ for method in ('commands.catalog', 'complete.slash'):+ reply = await connection.dispatch({'id': 1, 'method': method,+ 'params': {'text': '/probe'} if method == 'complete.slash' else {}})+ assert reply['error']['message'] == 'permission_denied', reply+ finally:+ await connection.close()diff --cc tests/gateway/test_local_session_lineage.pyindex f8a96b4338d,00000000000..62f7119c507mode 100644,000000..100644--- a/tests/gateway/test_local_session_lineage.py+++ b/tests/gateway/test_local_session_lineage.py@@@ -1,136 -1,0 +1,136 @@@+"""A local conversation keeps one admission owner across physical transcript boundaries."""+import json+from types import SimpleNamespace++import pytest+++async def test_local_lineage_transitions_preserve_owner_or_roll_back(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig, Platform+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal, SessionRef+ from gateway.session_local import create_local_session+ from hermes_state_local import local_receipt+ from hermes_state_runtime import (RuntimeStoreError, admit_session_input, claim_session_input,+ get_session_admission, list_session_admissions)++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {})+ def runner():+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ return SimpleNamespace(session_store=store, _session_db=store._db,+ adapters={}, _draining=False)+ first = runner()+ authority = await initialize_session_authority(first, profile_id='fixture', instance_id='first')+ actor = Principal('owner', 'fixture', frozenset({'session:create', 'session:read'}), 'socket')+ params = dict(request_id='lineage', source='gui', cwd=str(tmp_path), model='frozen', toolsets=[])+ ref = create_local_session(authority, actor, params)+ db = authority.db+ live = authority.sessions[ref.session_id]+ original = local_receipt(db, ref.session_id)+ queued = admit_session_input(db, epoch=authority.epoch, principal_id=actor.subject,+ session_id=ref.session_id, request_id='pending', payload={'text': 'pending'})+ history = [{'role': 'user', 'content': 'retained'}, {'role': 'assistant', 'content': 'history'}]+ def compress(parent, child):+ assert db.try_acquire_compression_lock(parent, 'fixture')+ try:+ db.publish_compression_child(parent_session_id=parent, child_session_id=child,+ source='gui', messages=history, compression_lock_holder='fixture')+ finally:+ db.release_compression_lock(parent, 'fixture')+ publish_row = db._publish_child_session_row+ def abort_publication(*args, **kwargs):+ publish_row(*args, **kwargs)+ raise RuntimeError('publication abort')+ monkeypatch.setattr(db, '_publish_child_session_row', abort_publication)+ with pytest.raises(RuntimeError, match='publication abort'):+ compress(ref.session_id, 'aborted-child')+ monkeypatch.setattr(db, '_publish_child_session_row', publish_row)+ assert db.get_session('aborted-child') is None+ assert local_receipt(db, ref.session_id) == original+ assert db.get_session(ref.session_id)['end_reason'] is None+ compress(ref.session_id, 'compressed')+ second = runner()+ cold = await initialize_session_authority(second, profile_id='fixture', instance_id='second')+ assert ref.session_id in cold.sessions, 'atomic compression lost the private local owner'+ assert create_local_session(cold, actor, params) == ref+ snapshot = await cold.attach(actor, ref)+ assert [(m['role'], m['content']) for m in snapshot.history] == [(m['role'], m['content']) for m in history]+ assert snapshot.pending[0].admission_id == queued['admission_id']+ assert second.session_store._entries[live.route].session_id == 'compressed'+ assert local_receipt(db, ref.session_id)['policy'] == original['policy']+ write = db._execute_write+ def abort(callback, **kwargs):+ def fail(conn):+ callback(conn)+ raise RuntimeError('transaction abort')+ return write(fail, **kwargs)+ # Use the owning SessionStore DB: reset must not publish any in-memory target on failure.+ db = cold.db+ write = db._execute_write+ before = local_receipt(db, ref.session_id)+ monkeypatch.setattr(db, '_execute_write', abort)+ with pytest.raises(RuntimeError, match='transaction abort'):+ second.session_store.reset_session(live.route)+ monkeypatch.setattr(db, '_execute_write', write)+ assert local_receipt(db, ref.session_id) == before+ assert second.session_store._entries[live.route].session_id == 'compressed'+ reset = second.session_store.reset_session(live.route)+ assert reset.session_id != 'compressed'+ assert db.get_session(reset.session_id)['cwd'] == params['cwd']+ assert db.get_session(reset.session_id)['model'] == params['model']+ third = runner()+ recovered = await initialize_session_authority(third, profile_id='fixture', instance_id='third')+ snapshot = await recovered.attach(actor, ref)+ assert snapshot.history == () # reset is a deliberate history boundary, not a fork+ assert snapshot.pending[0].admission_id == queued['admission_id']+ assert create_local_session(recovered, actor, params) == ref+ policy = third.adapters[Platform.LOCAL].policies[live.source.chat_id]+ assert policy.cwd == params['cwd'] and policy.source == params['source']+ # An interrupted claim remains owned by the logical conversation, even after another rotation.+ claimed = claim_session_input(recovered.db, epoch=recovered.epoch, session_id=ref.session_id)+ compress(reset.session_id, 'compressed-again')+ fourth = runner()+ restarted = await initialize_session_authority(fourth, profile_id='fixture', instance_id='fourth')+ assert get_session_admission(restarted.db, admission_id=claimed['admission_id'])['status'] == 'unknown'+ with pytest.raises(RuntimeStoreError, match='unknown_execution'):+ claim_session_input(restarted.db, epoch=restarted.epoch, session_id=ref.session_id)+ assert len(list_session_admissions(restarted.db, session_id=ref.session_id)) == 1+ receipt = local_receipt(db, ref.session_id)+ db.set_meta('gateway.local_policy.v1:' + ref.session_id, json.dumps(dict(receipt, profile_id='foreign')))+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):+ compress('compressed-again', 'foreign-child')+ assert db.get_session('foreign-child') is None+ db.set_meta('gateway.local_policy.v1:' + ref.session_id, json.dumps(receipt))+ foreign = Principal('foreign', 'fixture', actor.capabilities, 'foreign')+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await restarted.attach(foreign, ref)+ wrong_profile = Principal('owner', 'other-profile', actor.capabilities, 'other-profile')+ with pytest.raises(RuntimeStoreError, match='profile_mismatch'):+ await restarted.attach(wrong_profile, ref)+ db.create_session('unrelated-fork', source='gui', parent_session_id='compressed-again',+ model_config={'_branched_from': 'compressed-again'}, chat_id=live.source.chat_id,+ user_id=actor.subject, session_key=live.route)+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):+ await restarted.attach(actor, SessionRef('fixture', 'unrelated-fork'))+ # Copying the receipt onto a fork does not turn it into the canonical owner.+ db.set_meta('gateway.local_policy.v1:unrelated-fork', json.dumps(local_receipt(db, ref.session_id)))+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):+ await restarted.attach(actor, SessionRef('fixture', 'unrelated-fork'))+ # Route reuse by a native reset must not pick a departed logical owner's generation.+ from gateway.run_turn_runner import TurnRunner+ from gateway.session import SessionSource+ from gateway.session_authority import LiveSession+ restarted.sessions[reset.session_id] = LiveSession(None, live.route)+ native = SimpleNamespace(session_id=reset.session_id, session_key=live.route,+ source=SessionSource(Platform.TELEGRAM, 'native'))+ turn = TurnRunner(fourth, native)+ assert turn._approval_owner[1] == reset.session_id++- @pytest.mark.linux_only[email protected]("linux")+def test_real_local_lineage_survives_cold_daemon(tmp_path):+ from tests.gateway.fixtures.local_lineage_probe import probe+ print(json.dumps(probe(tmp_path)))diff --cc tests/gateway/test_local_session_recovery.pyindex 297e2b637ce,00000000000..78f297af1c7mode 100644,000000..100644--- a/tests/gateway/test_local_session_recovery.py+++ b/tests/gateway/test_local_session_recovery.py@@@ -1,99 -1,0 +1,99 @@@+"""Local creation is durable before publication and restart never replays a claim."""+import json+from types import SimpleNamespace++import pytest+++async def test_local_create_receipt_survives_cold_authority_atomically(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig, Platform+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from gateway import run+ from hermes_state_runtime import RuntimeStoreError++ config = {'platform_toolsets': {'cli': []}}+ monkeypatch.setattr(run, '_load_gateway_config', lambda: config)+ def runner():+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ return SimpleNamespace(session_store=store, _session_db=store._db,+ adapters={}, _draining=False)+ first = runner()+ authority = await initialize_session_authority(first, profile_id='fixture', instance_id='first')+ actor = Principal('owner', 'fixture', frozenset({'session:create', 'session:read'}), 'socket')+ params = {'request_id': 'retry', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []}+ ref = create_local_session(authority, actor, params)+ policy = first.adapters[Platform.LOCAL].policies[authority.sessions[ref.session_id].source.chat_id]+ second = runner()+ cold = await initialize_session_authority(second, profile_id='fixture', instance_id='second')+ assert ref.session_id in cold.sessions, 'durable creation was lost with process-local registry'+ config['platform_toolsets']['cli'] = ['terminal']+ assert create_local_session(cold, actor, params) == ref+ assert second.adapters[Platform.LOCAL].policies[cold.sessions[ref.session_id].source.chat_id] == policy+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ create_local_session(cold, actor, {**params, 'source': 'tui'})+ foreign = Principal('other', 'fixture', actor.capabilities, 'other-socket')+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await cold.resolve(foreign, ref)++ db = cold.db+ write = db._execute_write+ def abort(callback, **kwargs):+ def fail(conn):+ callback(conn)+ raise RuntimeError('injected transaction abort')+ return write(fail, **kwargs)+ before = db.session_count()+ monkeypatch.setattr(db, '_execute_write', abort)+ with pytest.raises(RuntimeError, match='injected transaction abort'):+ create_local_session(cold, actor, {**params, 'request_id': 'aborted'})+ monkeypatch.setattr(db, '_execute_write', write)+ assert db.session_count() == before+ assert set(cold.sessions) == {ref.session_id}+ with db._read_ctx() as conn:+ policies = conn.execute("SELECT value FROM state_meta WHERE key LIKE 'gateway.local_policy.v1:%'").fetchall()+ assert len(policies) == 1+ assert json.loads(policies[0][0])['principal_id'] == actor.subject+ from hermes_state_runtime import admit_session_input, list_session_admissions+ admit_session_input(db, epoch=cold.epoch, principal_id=actor.subject,+ session_id=ref.session_id, request_id='preclaim', payload={'text': 'never run'})+ db._write_sql('UPDATE state_meta SET value=? WHERE key=?',+ ('{}', 'gateway.local_policy.v1:' + ref.session_id))+ await cold._drain(ref)+ assert list_session_admissions(db, session_id=ref.session_id, pending_only=False)[0]['status'] == 'queued'++- @pytest.mark.linux_only[email protected]("linux")+def test_real_daemon_recovers_only_authorized_never_started_local_work(tmp_path):+ from tests.gateway.fixtures.local_recovery_probe import probe+ print(json.dumps(probe(tmp_path)))+++def test_messaging_session_history_follows_the_compression_tip(tmp_path, monkeypatch):+ """The authority keeps a messaging session's admission identity at the compression root,+ but attach/resume history must come from the current physical transcript."""+ from gateway.config import Platform+ from gateway.session_authority import LiveSession, SessionAuthority+ from gateway.session_contract import SessionRef+ from gateway.session_local_recovery import local_history+ from hermes_state import SessionDB+ from hermes_state_runtime import begin_runtime_epoch+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ db.create_session('root', source='telegram', session_key='agent:telegram:dm:1')+ db.append_message('root', 'user', 'BEFORE_COMPRESSION')+ assert db.try_acquire_compression_lock('root', 'holder')+ db.publish_compression_child(parent_session_id='root', child_session_id='child', source='telegram',+ messages=[{'role': 'user', 'content': 'SUMMARY'}], compression_lock_holder='holder')+ db.append_message('child', 'user', 'AFTER_COMPRESSION')+ authority = SessionAuthority(SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False)),+ profile_id='owned', instance_id='current', db=db,+ epoch=begin_runtime_epoch(db, instance_id='current'))+ source = SimpleNamespace(platform=Platform.TELEGRAM, user_id='human')+ authority.sessions['root'] = LiveSession(source, 'agent:telegram:dm:1')+ contents = [m['content'] for m in local_history(authority, SessionRef('owned', 'root'))]+ assert 'AFTER_COMPRESSION' in contents+ assert 'BEFORE_COMPRESSION' not in contentsdiff --cc tests/gateway/test_managed_worker_launch.pyindex b82c8bba00a,00000000000..503371bfb71mode 100644,000000..100644--- a/tests/gateway/test_managed_worker_launch.py+++ b/tests/gateway/test_managed_worker_launch.py@@@ -1,284 -1,0 +1,284 @@@+"""The ordinary daemon, not a fixture launcher, owns the real tool worker."""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import sys+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+++class Model(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ if not body.get('messages'):+ message = {'role': 'assistant', 'content': 'metadata'}+ elif any(m['role'] == 'user' and m.get('content') == 'RESUME_HISTORY' for m in body['messages']):+ self.server.requests.append(body)+ message = {'role': 'assistant', 'content': 'MANAGED_HISTORY_DONE'}+ elif (self.server.control_mode and any(m['role'] == 'tool' for m in body['messages'])+ and not any(m.get('name') == 'clarify' or m.get('tool_call_id') == 'managed-clarify' for m in body['messages'])):+ self.server.requests.append(body)+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'managed-clarify', 'type': 'function', 'function': {'name': 'clarify',+ 'arguments': json.dumps({'question': 'Choose managed answer', 'choices': ['Alpha', 'Beta']})}}]}+ elif any(m['role'] == 'tool' for m in body['messages']):+ self.server.requests.append(body)+ self.server.blocked.set()+ self.server.release.wait(30)+ message = {'role': 'assistant', 'content': 'MANAGED_TOOL_DONE'}+ else:+ self.server.requests.append(body)+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'managed-tool', 'type': 'function', 'function': {'name': 'terminal',+ 'arguments': json.dumps({'command': self.server.command, 'timeout': 10, **self.server.tool_args})}}]}+ choice = {'index': 0, 'message': message, 'finish_reason': 'tool_calls' if message.get('tool_calls') else 'stop'}+ frame = {'id': 'managed-model', 'model': 'managed-model', 'choices': [choice],+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}+ kind = 'application/json'+ if body.get('stream'):+ choice['delta'] = choice.pop('message')+ for index, call in enumerate(choice['delta'].get('tool_calls', [])):+ call['index'] = index+ payload = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ else:+ payload = json.dumps(frame).encode()+ try:+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError):+ pass+++MCP_PEER = '''import json, os, sys+for line in sys.stdin:+ r = json.loads(line); method = r.get("method"); ident = r.get("id")+ if ident is None: continue+ if method == "initialize":+ result = {"protocolVersion": r["params"]["protocolVersion"], "capabilities": {"tools": {}},+ "serverInfo": {"name": "owned-peer", "version": "1"}}+ elif method == "tools/list":+ result = {"tools": [{"name": "echo", "description": "owned echo",+ "inputSchema": {"type": "object", "properties": {}}}]}+ else:+ result = {}+ print(json.dumps({"jsonrpc": "2.0", "id": ident, "result": result}), flush=True)+'''+++def _model_saw_tool(request, name):+ """Direct definition or the tool_search deferred catalog (bridge description lists names)."""+ return any(name in json.dumps(t) for t in request.get('tools') or [])++- @pytest.mark.linux_only[email protected]("linux")+# The 'background' case probes a process the retired worker reparented to init: the test spawned it+# (through its own daemon), but pid_exists() on it is outside pytest's subtree for the live guard.[email protected]_system_guard_bypass[email protected]('worker_action', ['detach', 'kill', 'controls', 'stop', 'history', 'background', 'mcp'])+def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_path, worker_action):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.control_mode = worker_action in {'controls', 'stop'}+ target = home / 'delete-after-consent'+ target.mkdir()+ (target / 'owned.txt').write_text('owned')+ peer.command = 'rm -rf ' + str(target) if peer.control_mode else 'printf MANAGED_TOOL_EFFECT'+ peer.tool_args = {}+ gate = tmp_path / 'background-exit'+ if worker_action == 'background':+ # A session-owned background process is a turn-boundary survivor, not turn litter (F24).+ peer.command = f'printf MANAGED_TOOL_EFFECT; while test ! -e {gate}; do sleep .1; done'+ peer.tool_args = {'background': True}+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ config = {+ 'gateway': {'multiplex_profiles': False, 'managed_workers': True},+ 'model': {'provider': 'custom', 'default': 'managed-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'approvals': {'mode': 'manual'},+ 'platform_toolsets': {'cli': ['terminal']}}+ if worker_action == 'mcp':+ # A configured stdio MCP server the owner discovered must reach the worker's model too (F25).+ (home / 'peer.py').write_text(MCP_PEER)+ config['mcp_servers'] = {'owned': {'command': sys.executable, 'args': [str(home / 'peer.py')]}}+ config['platform_toolsets']['cli'] = ['terminal', 'owned']+ (home / 'config.yaml').write_text(json.dumps(config))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ audit = tmp_path / 'sqlite-opens.jsonl'+ site = tmp_path / 'audit-site'+ site.mkdir()+ (site / 'sitecustomize.py').write_text(+ "import json, os, sys\ndef witness(event, args):\n"+ " if event == 'sqlite3.connect':\n"+ f" with open({str(audit)!r}, 'a', encoding='utf-8') as f:\n"+ " f.write(json.dumps({'pid': os.getpid(), 'path': str(args[0])}) + '\\n')\n"+ "sys.addaudithook(witness)\n")+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=os.pathsep.join([str(site), str(root)]),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ def query(sql, args=()):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return db.execute(sql, args).fetchall()++ async def exercise(desc, owner):+ import psutil+ async with websocket(home, desc) as ws:+ toolsets = ['terminal', 'clarify'] if peer.control_mode else ['terminal', 'owned'] if worker_action == 'mcp' else ['terminal']+ created = await rpc(ws, 'session.create', request_id='managed', source='cli', cwd=str(home),+ model='managed-model', provider='custom', base_url=url, api_key='loopback-only',+ toolsets=toolsets, ignore_rules=True)+ assert 'result' in created, created+ sid = created['result']['session_id']+ submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='managed-input', text='DO_MANAGED_TOOL')+ assert 'result' in submitted, submitted+ if peer.control_mode:+ async def prompt(kind):+ async with asyncio.timeout(20):+ while True:+ snapshot = await rpc(ws, 'session.resume', session_id=sid)+ found = next((p for p in snapshot['result']['prompts'] if p['kind'] == kind), None)+ if found:+ return found+ await asyncio.sleep(.05)+ approval = await prompt('approval')+ assert target.exists()+ answered = await rpc(ws, 'approval.respond', session_id=sid,+ execution_generation=approval['execution_generation'], prompt_id=approval['prompt_id'], choice='once')+ assert answered['result']['status'] == 'resolved', answered+ clarify = await prompt('clarify')+ assert not target.exists()+ if worker_action == 'stop':+ stopped = await rpc(ws, 'session.interrupt', session_id=sid,+ execution_generation=clarify['execution_generation'])+ assert 'result' in stopped, stopped+ peer.release.set()+ async with asyncio.timeout(15):+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('managed-input',)) == [('started',)]:+ await asyncio.sleep(.05)+ assert query('SELECT status FROM session_admissions') == [('terminal',)], (home / 'restart.log').read_text()+ return+ answered = await rpc(ws, 'clarify.respond', session_id=sid,+ execution_generation=clarify['execution_generation'], prompt_id=clarify['prompt_id'], answer='Beta')+ assert answered['result']['status'] == 'resolved', answered+ assert await asyncio.to_thread(peer.blocked.wait, 240), (home / 'restart.log').read_text()+ workers = query('SELECT execution_id,status FROM worker_executions WHERE session_id=?', (sid,))+ assert len(workers) == 1, workers+ children = [p for p in psutil.Process(owner.pid).children() if p.cmdline()[-2:] == ['-m', 'agent.managed_worker']]+ assert len(children) == 1, [(p.pid, p.cmdline()) for p in psutil.Process(owner.pid).children()]+ pid = children[0].pid+ opened = [json.loads(line) for line in audit.read_text().splitlines()]+ # Positive control: the witness hook is live in the owner, so worker silence is real.+ assert [r for r in opened if r['pid'] == owner.pid and 'state.db' in r['path']], opened+ assert not [r for r in opened if r['pid'] == pid and 'state.db' in r['path']], opened+ canonical_fds = [f.path for f in children[0].open_files() if Path(f.path).name in {'state.db', 'state.db-wal', 'state.db-shm'}]+ assert canonical_fds == [], canonical_fds+ if worker_action == 'kill':+ follower = await rpc(ws, 'prompt.submit', session_id=sid, input_id='follower', text='NEVER_REPLAY')+ assert 'result' in follower, follower+ children[0].kill()+ async with asyncio.timeout(10):+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('managed-input',)) == [('started',)]:+ await asyncio.sleep(.05)+ assert query('SELECT request_id,status FROM session_admissions ORDER BY seq') == [+ ('managed-input', 'unknown'), ('follower', 'queued')]+ restored = await rpc(ws, 'session.resume', session_id=sid)+ assert any(p['status'] == 'unknown' for p in restored['result']['pending']), restored+ assert not query("SELECT value FROM state_meta WHERE key LIKE 'gateway.admission.result.v1.%'")+ peer.release.set()+ print(json.dumps({'owner_pid': owner.pid, 'killed_worker_pid': pid, 'outcome': 'unknown', 'follower': 'queued'}))+ return+ # Viewer connection is gone while the real model still holds the turn.+ assert psutil.Process(pid).is_running()+ peer.release.set()+ async with asyncio.timeout(40):+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('managed-input',)) != [('terminal',)]:+ await asyncio.sleep(.05)+ async with websocket(home, desc) as ws:+ restored = await rpc(ws, 'session.resume', session_id=sid)+ history = restored['result']['messages']+ assert 'MANAGED_TOOL_DONE' in json.dumps(history), restored+ replay = await rpc(ws, 'session.events.since', session_id=sid,+ replay_epoch=restored['result']['replay_epoch'], last_sequence=0)+ tools = [e for e in replay['result']['events'] if e['type'] in {'tool.start', 'tool.complete'}]+ assert tools and tools[0]['type'] == 'tool.start' and tools[-1]['type'] == 'tool.complete', replay+ assert str(target) not in json.dumps(tools) and 'MANAGED_TOOL_EFFECT' not in json.dumps(tools), tools+ rows = query('SELECT role,content FROM messages WHERE session_id=? ORDER BY id', (sid,))+ assert sum(role == 'user' and 'DO_MANAGED_TOOL' in content for role, content in rows) == 1, rows+ assert sum(role == 'assistant' and 'MANAGED_TOOL_DONE' in (content or '') for role, content in rows) == 1, rows+ if peer.control_mode:+ assert any(role == 'tool' and 'Beta' in content for role, content in rows), rows+ elif worker_action == 'background':+ started = json.loads(next(content for role, content in rows if role == 'tool'))+ assert started['output'] == 'Background process started', started+ background = psutil.Process(started['pid'])+ assert background.is_running() and background.status() != psutil.STATUS_ZOMBIE, started+ assert not psutil.pid_exists(pid), 'worker interpreter still alive after settlement'+ # The next admission's worker adopts it from the profile checkpoint (process_manage).+ assert started['pid'] in [e['pid'] for e in json.loads((home / 'processes.json').read_text())]+ gate.touch()+ async with asyncio.timeout(10):+ while psutil.pid_exists(background.pid) and psutil.Process(background.pid).status() != psutil.STATUS_ZOMBIE:+ await asyncio.sleep(.05)+ else:+ assert any(role == 'tool' and 'MANAGED_TOOL_EFFECT' in content for role, content in rows), rows+ assert query('SELECT status FROM worker_executions WHERE session_id=?', (sid,)) == [('terminal',)]+ assert query('SELECT COUNT(*) FROM session_turn_leases') == [(0,)]+ if worker_action == 'mcp':+ assert all(_model_saw_tool(r, 'mcp__owned__echo') for r in peer.requests), [r.get('tools') for r in peer.requests]+ assert len(peer.requests) == (3 if peer.control_mode else 2), json.dumps([+ {'model': r.get('model'), 'roles': [m['role'] for m in r['messages']],+ 'user': [str(m.get('content'))[:120] for m in r['messages'] if m['role'] == 'user']} for r in peer.requests])+ print(json.dumps({'owner_pid': owner.pid, 'worker_pid': pid, 'worker_module': 'agent.managed_worker',+ 'model_requests': len(peer.requests), 'rows': rows, 'detach_survived': True,+ 'canonical_sqlite_opens': [], 'canonical_fds': canonical_fds}))+ if worker_action == 'history':+ config = json.loads((home / 'config.yaml').read_text())+ config['model']['default'] = 'CHANGED_PROFILE_MODEL'+ config['platform_toolsets']['cli'] = []+ (home / 'config.yaml').write_text(json.dumps(config))+ async with websocket(home, desc) as ws:+ await rpc(ws, 'session.resume', session_id=sid)+ next_turn = await rpc(ws, 'prompt.submit', session_id=sid, input_id='history', text='RESUME_HISTORY')+ assert 'result' in next_turn, next_turn+ async with asyncio.timeout(30):+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('history',)) != [('terminal',)]:+ await asyncio.sleep(.05)+ restored = await rpc(ws, 'session.resume', session_id=sid)+ assert 'MANAGED_HISTORY_DONE' in json.dumps(restored['result']['messages']), restored+ request = peer.requests[-1]+ assert request['model'] == 'managed-model'+ assert request['messages'][0] == peer.requests[0]['messages'][0], 'cached prefix changed'+ assert request['tools'] == peer.requests[0]['tools'], 'frozen tools changed'+ assert any(m['role'] == 'tool' and 'MANAGED_TOOL_EFFECT' in m['content'] for m in request['messages'])+ assert query('SELECT status FROM worker_executions WHERE session_id=?', (sid,)) == [('terminal',), ('terminal',)]+++ try:+ with daemon(root, home, env, barrier=False) as (owner, desc):+ asyncio.run(exercise(desc, owner))+ finally:+ gate.touch()+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/gateway/test_managed_worker_stop_before_hello.pyindex 209fe64df1d,00000000000..fd64597e6d0mode 100644,000000..100644--- a/tests/gateway/test_managed_worker_stop_before_hello.py+++ b/tests/gateway/test_managed_worker_stop_before_hello.py@@@ -1,47 -1,0 +1,47 @@@+"""Stop is never acknowledged into a queue nobody drains: a managed child that stays alive+without ever sending hello is terminated on Stop and the admission settles as interrupted."""+import asyncio+import subprocess+import sys+from types import SimpleNamespace++import psutil+import pytest++from gateway.session_contract import Principal, SessionRef++- @pytest.mark.linux_only[email protected]("linux")+def test_stop_before_hello_terminates_child_and_settles_interrupted(monkeypatch):+ from gateway import session_managed_worker as managed+ spawned = []+ original = subprocess.Popen++ def wedged_child(args, **kwargs):+ # An interpreter that starts but never introduces itself (loader/stdio stall).+ child = original([sys.executable, '-c', 'import time\nwhile True: time.sleep(1)'], **kwargs)+ spawned.append(child)+ return child+ monkeypatch.setattr(managed.subprocess, 'Popen', wedged_child)+ ref = SessionRef('profile', 'session')+ checks = []+ authority = SimpleNamespace(profile_id='profile', pending_results={}, waiters={},+ authorize=lambda actor, ref, cap: checks.append(cap),+ check_approval_generation=lambda session_id, generation: checks.append(generation))+ row = {'admission_id': 'adm', 'principal_id': 'owner', 'generation': 3, 'payload': {'text': 'go'}}+ actor = Principal('owner', 'profile', frozenset({'session:control'}), 'transport')++ async def scenario():+ turn = asyncio.create_task(managed.execute_managed(authority, ref, row, policy=None))+ async with asyncio.timeout(10):+ while ref.session_id not in getattr(authority, '_managed_workers', {}):+ await asyncio.sleep(.01)+ assert managed.interrupt_managed(authority, actor, ref, 3) is True+ async with asyncio.timeout(10):+ return await turn+ assert asyncio.run(scenario()) == ''+ assert checks == ['session:control', 3]+ assert authority.pending_results['adm']['result']['interrupted'] is True+ assert ref.session_id not in authority._managed_workers+ child = spawned[0]+ assert child.poll() is not None and not psutil.pid_exists(child.pid) or psutil.Process(child.pid).status() == psutil.STATUS_ZOMBIEdiff --cc tests/gateway/test_managed_worker_trampoline.pyindex 785f8386e84,00000000000..4ca0465c98dmode 100644,000000..100644--- a/tests/gateway/test_managed_worker_trampoline.py+++ b/tests/gateway/test_managed_worker_trampoline.py@@@ -1,157 -1,0 +1,157 @@@+"""Worker identity is verified by the owner through launcher chains, never asserted by the worker.++On Windows the uv venv ``python.exe`` is a trampoline: ``Popen.pid`` is the launcher and the+real interpreter is its child. The owner reserves with the handle pid, the worker reports its+own pid/birth, and the OWNER proves that pid is alive, has that birth, and descends from the+reserved handle before binding the adoption digest to the real worker.+"""+import asyncio+from contextlib import closing+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+from types import SimpleNamespace++import psutil+import pytest++from hermes_state import SessionDB+from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input+from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket++LAUNCHER = ('import subprocess, sys\n'+ 'child = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=sys.stdin)\n'+ 'print(child.pid, flush=True)\n'+ 'sys.exit(child.wait())\n')+++def _hello(pid):+ proc = psutil.Process(pid)+ return {'type': 'hello', 'pid': pid, 'birth': proc.create_time(),+ 'ancestors': [p.pid for p in proc.parents()[:4]]}+++def test_owner_binds_reservation_to_verified_descendant_of_the_handle_only(tmp_path):+ from gateway.session_worker_reservation import reserve_admission_worker+ launcher = subprocess.Popen([sys.executable, '-c', LAUNCHER], stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ stranger = subprocess.Popen([sys.executable, '-c', 'import sys; sys.stdin.read()'], stdin=subprocess.PIPE,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ try:+ real = int(launcher.stdout.readline())+ # One hop on POSIX; a venv trampoline (Windows) nests a second launcher in the chain.+ assert real != launcher.pid and launcher.pid in [p.pid for p in psutil.Process(real).parents()]+ with closing(SessionDB(tmp_path / 'state.db')) as db:+ db.create_session('owned', 'cli')+ epoch = begin_runtime_epoch(db, instance_id='owner')+ authority = SimpleNamespace(db=db, epoch=epoch, profile_id=str(tmp_path), _require_admission_open=lambda: None)+ admitted = admit_session_input(db, epoch=epoch, principal_id='human', session_id='owned', request_id='input', payload={})+ claim_session_input(db, epoch=epoch, session_id='owned')+ kwargs = dict(admission_id=admitted['admission_id'], process=launcher, principal_id='human')+ # Alive, truthful birth, same user — but a sibling, not a descendant of the reserved handle.+ with pytest.raises(Exception, match='permission_denied'):+ reserve_admission_worker(authority, hello=_hello(stranger.pid), **kwargs)+ # The right pid with a forged birth is a recycled-pid claim.+ with pytest.raises(Exception, match='permission_denied'):+ reserve_admission_worker(authority, hello={**_hello(real), 'birth': _hello(real)['birth'] + 1}, **kwargs)+ # A worker claiming the owner's own pid never adopts.+ with pytest.raises(Exception, match='permission_denied'):+ reserve_admission_worker(authority, hello=_hello(os.getpid()), **kwargs)+ assert db._read_one('SELECT COUNT(*) FROM worker_executions')[0] == 0+ scope = reserve_admission_worker(authority, hello=_hello(real), **kwargs)+ assert (scope['pid'], scope['birth']) == (real, psutil.Process(real).create_time())+ assert scope['pid'] != launcher.pid+ finally:+ # The real interpreter first, while it is still the launcher's child: killing the launcher+ # first reparents it outside the test subtree, where the conftest kill guard refuses it.+ if psutil.pid_exists(real):+ psutil.Process(real).kill()+ for proc in (launcher, stranger):+ proc.stdin.close()+ if proc.poll() is None:+ proc.kill()+ proc.wait(timeout=10)++- @pytest.mark.linux_only[email protected]("linux")+def test_managed_worker_completes_through_interpreter_trampoline(tmp_path):+ """The ordinary daemon spawns every child through a launcher that execs the real interpreter as+ its child (uv's Windows python.exe shape). The turn still completes in the real worker and no+ launcher or worker survives the owner's cleanup."""+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ from http.server import ThreadingHTTPServer+ import threading+ from tests.gateway.fixtures.local_recovery_probe import Model+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ launches = tmp_path / 'launches.jsonl'+ trampoline = tmp_path / 'python-launcher'+ trampoline.write_text(f'#!{sys.executable}\n'+ 'import json, os, subprocess, sys\n'+ f'child = subprocess.Popen([{sys.executable!r}, *sys.argv[1:]])\n'+ f'with open({str(launches)!r}, "a", encoding="utf-8") as f:\n'+ ' f.write(json.dumps({"launcher": os.getpid(), "child": child.pid, "argv": sys.argv[1:]}) + "\\n")\n'+ 'sys.exit(child.wait())\n', encoding='utf-8')+ trampoline.chmod(0o755)+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False, 'managed_workers': True},+ 'model': {'provider': 'custom', 'default': 'managed-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}), encoding='utf-8')+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1', UGW_TRAMPOLINE=str(trampoline))++ def query(sql, args=()):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return db.execute(sql, args).fetchall()++ async def exercise(desc, owner):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='tramp', source='cli', cwd=str(home),+ model='managed-model', provider='custom', base_url=url, api_key='loopback-only',+ toolsets=[], ignore_rules=True)+ assert 'result' in created, created+ sid = created['result']['session_id']+ submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='tramp-input', text='TRAMPOLINE_PROBE')+ assert 'result' in submitted, submitted+ async with asyncio.timeout(90):+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('tramp-input',)) in ([('queued',)], [('started',)]):+ await asyncio.sleep(.05)+ evidence = {'admissions': query('SELECT request_id,status FROM session_admissions'),+ 'workers': query('SELECT execution_id,status FROM worker_executions'),+ 'launches': launches.read_text(encoding='utf-8') if launches.exists() else None,+ 'gateway_log': (home / 'logs' / 'gateway.log').read_text(encoding='utf-8', errors='replace')[-3000:]}+ assert query('SELECT status FROM session_admissions WHERE request_id=?', ('tramp-input',)) == [('terminal',)], evidence+ restored = await rpc(ws, 'session.resume', session_id=sid)+ assert 'RECOVERY_ACK_TRAMPOLINE_PROBE' in json.dumps(restored['result']['messages']), restored+ assert query('SELECT status FROM worker_executions WHERE session_id=?', (sid,)) == [('terminal',)], evidence+ workers = [json.loads(l) for l in launches.read_text(encoding='utf-8').splitlines()+ if json.loads(l)['argv'][-2:] == ['-m', 'agent.managed_worker']]+ assert len(workers) == 1 and workers[0]['launcher'] != workers[0]['child'], evidence+ # The launcher chain is fully reaped: neither the launcher nor the real worker survives+ # the owner's close (which runs after the admission commits terminal; bounded wait).+ def leftovers():+ return [(p.pid, p.cmdline()) for p in psutil.Process(owner.pid).children(recursive=True)+ if p.is_running() and p.status() != psutil.STATUS_ZOMBIE]+ async with asyncio.timeout(15):+ while leftovers():+ await asyncio.sleep(.1)+ assert leftovers() == []+ print(json.dumps({'owner_pid': owner.pid, 'launcher_pid': workers[0]['launcher'], 'worker_pid': workers[0]['child']}))++ try:+ with daemon(root, home, env, barrier=True, fixture='trampoline_daemon.py') as (owner, desc):+ asyncio.run(exercise(desc, owner))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()diff --cc tests/gateway/test_multiplex_cold_profile_sidebar_mutation.pyindex 18dd58aac84,00000000000..6a384cc04cfmode 100644,000000..100644--- a/tests/gateway/test_multiplex_cold_profile_sidebar_mutation.py+++ b/tests/gateway/test_multiplex_cold_profile_sidebar_mutation.py@@@ -1,183 -1,0 +1,183 @@@+"""Cold-profile sidebar mutations reach the served profile's own authority under multiplex.++Acceptance case for the Desktop local-backend-pool cutover (PR #106742): archiving a+session that belongs to a profile with no resident client (COLD) used to fail on main with+``LocalBackendSlotWaitTimeoutError`` because the Desktop's archive path reached per-profile+backend startup with background priority. With one multiplexing gateway there is no+per-profile process to start: ``PATCH /api/sessions/{id}`` carrying the owning profile in+routing metadata (``?profile=`` and ``body.profile``, exactly what+``apps/desktop/src/api/sessions.ts::mutateSessionHttp`` sends) lands on that profile's+authority, while another served profile holds a live interactive attachment.++The Desktop's endpoint for a served secondary comes from ``hermes -p <name> gateway ensure``+and its ticket is minted through the endpoint's ``control_home`` (the multiplexer root),+so this test uses that exact discovery + mint path rather than a hand-built socket call.+"""+import asyncio+from contextlib import contextmanager+import json+import os+from pathlib import Path+import signal+import sqlite3+import subprocess+import sys+import time+from types import SimpleNamespace++import httpx+import pytest+from websockets.asyncio.client import connect++from tests.gateway.test_normal_runtime_boot import control+++@contextmanager+def multiplex_daemon(tmp_path, profiles=('warm', 'cold')):+ """One ``gateway.run`` serving default + *profiles*; yields (root, descriptor, env)."""+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ for name in profiles:+ secondary = home / 'profiles' / name+ secondary.mkdir(parents=True)+ (secondary / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'custom', 'default': name + '-model', 'base_url': 'http://127.0.0.1:1/v1'}}))+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': True},+ 'model': {'provider': 'custom', 'default': 'launch-model', 'base_url': 'http://127.0.0.1:1/v1'},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ PYTHONUNBUFFERED='1')+ with (tmp_path / 'gateway.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 60+ descriptor = {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ yield home, descriptor, env+ finally:+ if process.poll() is None:+ process.send_signal(signal.SIGINT)+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++def desktop_ensure(env, root, profile):+ """The exact child the Desktop spawns: ``hermes --profile <p> gateway ensure --json``."""+ result = subprocess.run([sys.executable, '-m', 'hermes_cli.main', '--profile', profile,+ 'gateway', 'ensure', '--json', '--timeout', '30'],+ cwd=root, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60)+ payload = json.loads(result.stdout)+ assert result.returncode == 0 and payload['state'] == 'ready', (result.returncode, payload, result.stderr[-500:])+ return payload['endpoint']+++def native_headers(endpoint):+ from hermes_cli.gateway_client import _session_ticket+ ticket = _session_ticket(Path(endpoint['profile_id']), SimpleNamespace(**endpoint), purpose='native-http')+ return {'X-Hermes-Gateway-Ticket': ticket}+++async def create_via_ws(endpoint, request_id, hold=None):+ """Create a GUI session on *endpoint* over the canonical WS; ``hold`` keeps the attachment+ open while awaiting it (the "other profile is active" arm)."""+ from hermes_cli.gateway_client import _session_ticket+ ticket = _session_ticket(Path(endpoint['profile_id']), SimpleNamespace(**endpoint), purpose='interactive')+ async with connect(endpoint['api_origin'].replace('http:', 'ws:') + '/api/ws',+ subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket]) as ws:+ await ws.send(json.dumps({'id': 1, 'method': 'session.create',+ 'params': {'request_id': request_id, 'source': 'gui'}}))+ while True:+ response = json.loads(await ws.recv())+ if response.get('id') == 1:+ assert 'result' in response, response+ sid = response['result']['session_id']+ break+ if hold is not None:+ await hold+ return sid+++def desktop_sidebar_patch(client, endpoint, profile, sid, payload, request_id):+ """Byte-for-byte what ``mutateSessionHttp`` does: snapshot, then PATCH with identity + profile+ in both the query and the body."""+ snapshot = client.get(f'/api/sessions/{sid}/mutation-snapshot', params={'profile': profile},+ headers=native_headers(endpoint))+ assert snapshot.status_code == 200, snapshot.text+ identity = {'request_id': request_id, 'expected_revision': snapshot.json()['runtime_revision'],+ 'expected_generation': snapshot.json()['runtime_generation']}+ return client.patch(f'/api/sessions/{sid}', params={'profile': profile},+ json={**payload, **identity, 'profile': profile}, headers=native_headers(endpoint))++- @pytest.mark.linux_only[email protected]("linux")+def test_cold_profile_archive_unarchive_while_another_profile_is_attached(tmp_path):+ with multiplex_daemon(tmp_path) as (home, descriptor, env), \+ httpx.Client(base_url=descriptor['api_origin'], trust_env=False, timeout=30) as client:+ root = Path(__file__).resolve().parents[2]+ served = {p['profile_id'] for p in descriptor['served_profiles']}+ cold_home, warm_home = (home / 'profiles' / 'cold').resolve(), (home / 'profiles' / 'warm').resolve()+ assert {str(home.resolve()), str(cold_home), str(warm_home)} <= served, descriptor++ # Desktop discovery for every profile resolves to the SAME instance; secondaries mint via the root.+ endpoints = {name: desktop_ensure(env, root, name) for name in ('default', 'warm', 'cold')}+ assert {e['instance_id'] for e in endpoints.values()} == {descriptor['instance_id']}+ assert endpoints['cold']['profile_id'] == str(cold_home)+ assert endpoints['cold']['control_home'] == str(home.resolve())+ assert endpoints['default']['control_home'] is None++ # The cold profile's session was created earlier through the gateway and its client left.+ cold_sid = asyncio.run(create_via_ws(endpoints['cold'], 'cold-create'))++ # Warm stays attached (live interactive WS) for the whole mutation sequence.+ outcome = {}++ async def with_warm_attached():+ loop = asyncio.get_running_loop()++ def mutate():+ archived = desktop_sidebar_patch(client, endpoints['cold'], 'cold', cold_sid, {'archived': True}, 'archive')+ assert archived.status_code == 200, archived.text+ row = client.get(f'/api/sessions/{cold_sid}', params={'profile': 'cold'},+ headers=native_headers(endpoints['cold'])).json()+ assert (row['archived'], row['profile']) == (1, 'cold'), row+ restored = desktop_sidebar_patch(client, endpoints['cold'], 'cold', cold_sid, {'archived': False}, 'unarchive')+ assert restored.status_code == 200, restored.text+ row = client.get(f'/api/sessions/{cold_sid}', params={'profile': 'cold'},+ headers=native_headers(endpoints['cold'])).json()+ assert (row['archived'], row['profile']) == (0, 'cold'), row+ outcome.update(archive=archived.json(), unarchive=restored.json())++ await create_via_ws(endpoints['warm'], 'warm-create', hold=loop.run_in_executor(None, mutate))++ asyncio.run(with_warm_attached())+ assert outcome['archive']['archived'] is True and outcome['unarchive']['archived'] is False+ assert outcome['unarchive']['revision'] == outcome['archive']['revision'] + 1++ # The write landed in the COLD profile's own store; the launch profile's store is untouched.+ with sqlite3.connect(cold_home / 'state.db') as db:+ assert db.execute('SELECT archived FROM sessions WHERE id=?', (cold_sid,)).fetchone() == (0,)+ with sqlite3.connect(home / 'state.db') as db:+ assert db.execute('SELECT COUNT(*) FROM sessions WHERE id=?', (cold_sid,)).fetchone() == (0,)++ # The default profile's ticket cannot select the cold profile's rows (profile boundary holds).+ foreign = client.get(f'/api/sessions/{cold_sid}/mutation-snapshot', params={'profile': 'cold'},+ headers=native_headers(endpoints['default']))+ assert foreign.status_code == 403, foreign.textdiff --cc tests/gateway/test_multiplex_hot_serve.pyindex 48d23e86184,de5e6b40371..aa3a05826b3--- a/tests/gateway/test_multiplex_hot_serve.py+++ b/tests/gateway/test_multiplex_hot_serve.py@@@ -193,10 -161,10 +193,10 @@@ async def test_profile_control_verbs_roassert runner._profile_adapters["worker"][Platform.DISCORD].token.endswith("new-worker-token\n")- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")@pytest.mark.asyncioasync def test_profile_lifecycle_over_real_control_socket(tmp_path, monkeypatch):- from gateway.run import _start_gateway_start_control_socket+ from gateway.run_bootstrap import _start_gateway_start_control_socketfrom gateway import control_socketrunner, home = _runner(tmp_path, monkeypatch)secondary = _mkprofile(home, "worker")diff --cc tests/gateway/test_multiplex_hot_serve_live.pyindex 4a5bd2d9593,00000000000..de901fee755mode 100644,000000..100644--- a/tests/gateway/test_multiplex_hot_serve_live.py+++ b/tests/gateway/test_multiplex_hot_serve_live.py@@@ -1,263 -1,0 +1,263 @@@+"""Live hot-serve contract of a real ``python -m gateway.run`` multiplexer (Linux; loopback model).++A profile created under the running multiplexer is served by it without a restart: ``identify``+lists the new home, a ticket minted for it opens a session owned by this process, and ``profiles/``+(not the boot-time reservation) is what the next restart reserves — so ``hermes -p new`` finds an+owner instead of spawning a stray per-profile daemon that would later collide with the+multiplexer's all-or-nothing reserve. A secondary whose ``state.db`` is unusable parks only itself.+"""+import asyncio+import contextlib+import json+import os+from pathlib import Path+import signal+import socket+import subprocess+import sys+import time++import pytest+from websockets.asyncio.client import connect++ROOT = Path(__file__).resolve().parents[2]+# The daemon is a foreground child of the test (never detached), boots a disposable custom root+# with HOME redirected (no systemd unit, no webhook port) and is reaped in every path below.- pytestmark = [pytest.mark.linux_only, pytest.mark.spawns_gateway_lookalike]++pytestmark = [pytest.mark.platforms("linux"), pytest.mark.spawns_gateway_lookalike]+++def control(home, verb, params=None, timeout=10):+ request = json.dumps({'protocol': 1, 'id': 1, 'verb': verb, 'params': params or {}}).encode() + b'\n'+ from gateway.control_socket import resolve_client_socket_path+ path = resolve_client_socket_path(home)+ if path is None:+ raise FileNotFoundError('control socket absent')+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:+ peer.settimeout(timeout)+ peer.connect(str(path))+ peer.sendall(request)+ with peer.makefile('rb') as stream:+ raw = stream.readline()+ reply = json.loads(raw.split(b'\n', 1)[0])+ assert reply.get('ok'), reply+ return reply['result']+++def peer():+ from http.server import ThreadingHTTPServer+ import threading+ from tests.gateway.fixtures.shared_authority_peer import ModelPeer+ server = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)+ server.requests, server.metadata_requests = [], []+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield server+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++def mux(tmp_path, peer):+ """Disposable custom root (``<root>/profiles/<name>`` layout, as in Docker) with+ ``multiplex_profiles`` on, plus one boot-time secondary."""+ user = tmp_path / 'user'+ user.mkdir()+ root = tmp_path / 'state'+ root.mkdir(mode=0o700)+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ config = {'gateway': {'multiplex_profiles': True},+ 'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}}+ (root / 'config.yaml').write_text(json.dumps(config))+ boot = root / 'profiles' / 'boot'+ boot.mkdir(parents=True, mode=0o700)+ (boot / 'config.yaml').write_text(json.dumps(config))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(root), PYTHONPATH=str(ROOT),+ PYTHONUNBUFFERED='1', OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ return {'root': root, 'boot': boot, 'env': env, 'config': config, 'log': tmp_path / 'gateway.log'}+++def start_daemon(mux, timeout=90):+ """Boot the multiplexer the way ``hermes gateway run`` does; the canonical gateway command-line+ matcher (``gateway.status.looks_like_gateway_command_line``) is what the CLI's liveness probes+ apply to the recorded PID, so the fixture must spawn a recognisable launcher."""+ log = mux['log'].open('a+', encoding='utf-8', errors='replace')+ proc = subprocess.Popen([sys.executable, '-m', 'hermes_cli.main', 'gateway', 'run', '--quiet'], cwd=ROOT,+ env=mux['env'], stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ desc = {}+ deadline = time.monotonic() + timeout+ while proc.poll() is None and time.monotonic() < deadline:+ try:+ desc = control(mux['root'], 'identify', timeout=2)+ if desc.get('state') == 'ready':+ break+ except (OSError, ValueError, AssertionError):+ pass+ time.sleep(.1)+ log.flush()+ assert desc.get('state') == 'ready', (desc, proc.poll(), tail(mux))+ return proc, desc+++def tail(mux, n=6000):+ """stdout capture plus the daemon's own ``logs/gateway.log`` (``--quiet`` sends records there)."""+ texts = [p.read_text(encoding='utf-8', errors='replace') for p in (mux['log'], mux['root'] / 'logs' / 'gateway.log')+ if p.exists()]+ return '\n'.join(t[-n:] for t in texts)+++def stop(proc, expect=0):+ if proc.poll() is None:+ proc.send_signal(signal.SIGINT)+ try:+ code = proc.wait(timeout=45)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout=10)+ raise+ if expect is not None:+ assert code == expect, code+++def served_homes(desc):+ return {Path(entry['home']).resolve() for entry in desc.get('served_profiles', [])}+++def recorded_served(root):+ return json.loads((root / 'gateway_state.json').read_text(encoding='utf-8')).get('served_profiles')+++async def open_session_for(root, home, desc):+ """A ticket bound to *home* opens a session the multiplexer commits into *home*'s state.db."""+ grant = control(root, 'session-ticket', {'profile_id': str(home.resolve()),+ 'instance_id': desc['instance_id'], 'purpose': 'interactive'})+ url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws'+ async with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']]) as ws:+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'session.create',+ 'params': {'request_id': 'hot-served', 'source': 'cli'}}))+ async with asyncio.timeout(20):+ while True:+ reply = json.loads(await ws.recv())+ if reply.get('id') == 1:+ assert 'result' in reply, reply+ return reply['result']['session_id']+++def test_profile_created_under_live_multiplexer_is_served_and_owned(mux):+ root, env = mux['root'], mux['env']+ proc, desc = start_daemon(mux)+ try:+ assert served_homes(desc) == {root.resolve(), mux['boot'].resolve()}+ # ``hermes profile create`` under the multiplexer's root: the CLI signals the control socket.+ created = subprocess.run([sys.executable, '-m', 'hermes_cli.main', 'profile', 'create', 'fresh'],+ cwd=ROOT, env=env, capture_output=True, text=True, timeout=120)+ assert created.returncode == 0, (created.stdout, created.stderr)+ fresh = root / 'profiles' / 'fresh'+ assert fresh.is_dir()+ deadline = time.monotonic() + 20+ while time.monotonic() < deadline and fresh.resolve() not in served_homes(desc):+ time.sleep(.2)+ desc = control(root, 'identify')+ assert fresh.resolve() in served_homes(desc), (desc, tail(mux))+ assert recorded_served(root) == ['default', 'boot', 'fresh']+ # The new profile's sessions are this multiplexer's: same instance, its own state.db.+ sid = asyncio.run(open_session_for(root, fresh, desc))+ import sqlite3+ with sqlite3.connect(f"file:{fresh / 'state.db'}?mode=ro", uri=True) as db:+ assert db.execute('SELECT instance_id FROM runtime_epoch').fetchone() == (desc['instance_id'],)+ assert db.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone()+ # ``hermes -p fresh`` resolves to the multiplexer instead of spawning a daemon of its own.+ ensured = subprocess.run([sys.executable, '-m', 'hermes_cli.main', '-p', 'fresh', 'gateway', 'ensure',+ '--timeout', '15'], cwd=ROOT, env=env, capture_output=True, text=True, timeout=60)+ payload = json.loads(ensured.stdout.strip().splitlines()[-1])+ assert payload['state'] == 'ready' and payload['endpoint']['instance_id'] == desc['instance_id'], (payload, ensured.stderr)+ assert not (fresh / 'gateway.pid').exists()+ stop(proc)+ # The restart reserves what exists now, the hot-served profile included: no OwnershipConflict.+ proc, desc = start_daemon(mux)+ assert served_homes(desc) == {root.resolve(), mux['boot'].resolve(), fresh.resolve()}+ assert 'Cannot reserve gateway profiles' not in tail(mux)+ finally:+ stop(proc, expect=None)+++def kill_recorded_gateway(root, timeout=45):+ """SIGINT the gateway whose PID ``gateway_state.json`` records (a detached spawn is not our child)."""+ pid = json.loads((root / 'gateway_state.json').read_text(encoding='utf-8')).get('pid')+ if pid:+ with contextlib.suppress(ProcessLookupError):+ os.kill(pid, signal.SIGINT)+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return+ time.sleep(.2)+ with contextlib.suppress(ProcessLookupError):+ os.kill(pid, signal.SIGKILL)++[email protected]_system_guard_bypass+def test_named_profile_ensure_during_multiplexer_downtime_starts_the_multiplexer(mux):+ """The multiplexer is down (restart/update) and ``hermes -p boot gateway ensure`` runs: the client+ must start the MULTIPLEXER, never a per-profile daemon (which would answer this client and then+ block the multiplexer's next all-or-nothing reserve with ``Cannot reserve gateway profiles``)."""+ root, env, boot = mux['root'], mux['env'], mux['boot']+ proc, desc = start_daemon(mux)+ stop(proc)+ assert recorded_served(root) == ['default', 'boot']+ try:+ ensured = subprocess.run([sys.executable, '-m', 'hermes_cli.main', '-p', 'boot', 'gateway', 'ensure',+ '--json', '--timeout', '90'], cwd=ROOT, env=env, capture_output=True, text=True, timeout=120)+ payload = json.loads(ensured.stdout.strip().splitlines()[-1])+ assert payload['state'] == 'ready', (payload, ensured.stderr)+ # The answering owner is the multiplexer at the root, serving boot as a secondary.+ assert Path(payload['endpoint']['control_home']).resolve() == root.resolve(), payload+ assert served_homes(control(root, 'identify')) == {root.resolve(), boot.resolve()}+ assert not (boot / 'gateway.pid').exists() and not (boot / 'gateway.sock').exists()+ finally:+ kill_recorded_gateway(root)+ # A fresh multiplexer boot reserves every profile: nothing stray owns boot's home.+ proc, desc = start_daemon(mux)+ try:+ assert served_homes(desc) == {root.resolve(), boot.resolve()}+ assert 'Cannot reserve gateway profiles' not in tail(mux)+ stop(proc)+ finally:+ stop(proc, expect=None)+++def test_broken_secondary_state_db_parks_only_that_profile(mux):+ root = mux['root']+ broken = root / 'profiles' / 'broken'+ broken.mkdir(parents=True, mode=0o700)+ (broken / 'config.yaml').write_text(json.dumps(mux['config']))+ # Not a SQLite file and not the zero-byte case the quarantine repairs: an unopenable store.+ (broken / 'state.db').mkdir()+ proc, desc = start_daemon(mux)+ try:+ assert served_homes(desc) == {root.resolve(), mux['boot'].resolve()}, desc+ assert recorded_served(root) == ['default', 'boot']+ assert "Profile 'broken' not served" in tail(mux), tail(mux)+ # The park is published (identify + gateway_state.json), so the profile's clients fail fast+ # with the real reason instead of waiting the whole deadline for a service that never comes.+ assert 'broken' in desc.get('parked_profiles', {}), desc+ recorded = json.loads((root / 'gateway_state.json').read_text(encoding='utf-8'))+ assert 'broken' in recorded.get('parked_profiles', {}), recorded+ started = time.monotonic()+ ensured = subprocess.run([sys.executable, '-m', 'hermes_cli.main', '-p', 'broken', 'gateway', 'ensure',+ '--json', '--timeout', '30'], cwd=ROOT, env=mux['env'], capture_output=True,+ text=True, timeout=60)+ payload = json.loads(ensured.stdout.strip().splitlines()[-1])+ assert (payload['state'], payload['reason_code']) == ('inaccessible', 'profile_parked'), (payload, ensured.stderr)+ assert 'unusable' in (payload.get('detail') or ''), payload+ assert ensured.returncode == 7 and time.monotonic() - started < 20, (ensured.returncode, ensured.stderr)+ stop(proc)+ finally:+ stop(proc, expect=None)diff --cc tests/gateway/test_multiplex_requires_default_profile.pyindex caf3a3774f9,00000000000..4455f4e5654mode 100644,000000..100644--- a/tests/gateway/test_multiplex_requires_default_profile.py+++ b/tests/gateway/test_multiplex_requires_default_profile.py@@@ -1,86 -1,0 +1,86 @@@+"""Only the default profile runs the multiplexer; a named launch would split default's sessions."""+import pytest++from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE+++def _root(tmp_path):+ root = tmp_path / '.hermes'+ root.mkdir()+ (root / 'config.yaml').write_text('model: {default: m}\n')+ (root / 'profiles' / 'foo').mkdir(parents=True)+ (root / 'profiles' / 'foo' / 'config.yaml').write_text('gateway:\n multiplex_profiles: true\n')+ return root+++def test_named_profile_launch_with_multiplex_is_a_config_verdict(tmp_path, monkeypatch):+ from gateway import run_bootstrap++ root = _root(tmp_path)+ monkeypatch.setenv('HERMES_HOME', str(root / 'profiles' / 'foo'))+ import hermes_constants+ hermes_constants._default_hermes_root_memo = None+ written = []+ monkeypatch.setattr('gateway.run._write_runtime_status_quiet', lambda **kw: written.append(kw))+ with pytest.raises(SystemExit) as exc:+ run_bootstrap._launch_home_may_multiplex()+ assert exc.value.code == GATEWAY_FATAL_CONFIG_EXIT_CODE+ assert written == [{'gateway_state': 'startup_failed', 'exit_reason': 'multiplex_requires_default_profile'}]+++def test_default_profile_launch_may_multiplex(tmp_path, monkeypatch):+ from gateway import run_bootstrap++ root = _root(tmp_path)+ monkeypatch.setenv('HERMES_HOME', str(root))+ import hermes_constants+ hermes_constants._default_hermes_root_memo = None+ assert run_bootstrap._launch_home_may_multiplex() is True+++async def test_verdict_precedes_replacing_a_running_gateway(tmp_path, monkeypatch):+ """``hermes gateway run --replace`` on a named profile with the flag must exit EX_CONFIG while the+ healthy gateway it would have replaced keeps running."""+ from gateway import run_bootstrap+ from gateway.config import GatewayConfig++ root = _root(tmp_path)+ monkeypatch.setenv('HERMES_HOME', str(root / 'profiles' / 'foo'))+ import hermes_constants+ hermes_constants._default_hermes_root_memo = None+ monkeypatch.setattr('hermes_cli.resource_limits.apply_nofile_soft_limit', lambda: None)+ monkeypatch.setattr('gateway.code_skew.record_boot_fingerprint', lambda: None)+ monkeypatch.setattr('gateway.status.get_running_pid', lambda: 4242)+ monkeypatch.setattr('gateway.run._write_runtime_status_quiet', lambda **kw: None)+ replaced = []++ async def fake_replace(existing_pid, replace):+ replaced.append(existing_pid)+ return False++ monkeypatch.setattr(run_bootstrap, '_start_gateway_replace_existing_instance', fake_replace)+ config = GatewayConfig()+ config.multiplex_profiles = True+ with pytest.raises(SystemExit) as exc:+ await run_bootstrap.start_gateway(config=config, replace=True)+ assert exc.value.code == GATEWAY_FATAL_CONFIG_EXIT_CODE+ assert replaced == []+++def test_cloned_profile_does_not_inherit_the_multiplex_flag(tmp_path, monkeypatch):- import yaml++ import hermes_yaml as yaml+ from hermes_cli.profiles import _strip_multiplex_flag++ nested = tmp_path / 'nested.yaml'+ nested.write_text('model: {default: m}\ngateway:\n multiplex_profiles: true\n service_install_choice: skip\n')+ _strip_multiplex_flag(nested)+ assert yaml.safe_load(nested.read_text()) == {'model': {'default': 'm'}, 'gateway': {'service_install_choice': 'skip'}}+ top = tmp_path / 'top.yaml'+ top.write_text('multiplex_profiles: true\nmodel: {default: m}\n')+ _strip_multiplex_flag(top)+ assert yaml.safe_load(top.read_text()) == {'model': {'default': 'm'}}+ untouched = tmp_path / 'plain.yaml'+ untouched.write_text('# keep my comment\nmodel: {default: m}\n')+ _strip_multiplex_flag(untouched)+ assert untouched.read_text() == '# keep my comment\nmodel: {default: m}\n'diff --cc tests/gateway/test_native_http_auth.pyindex 6eba1ac7341,00000000000..fcdc75e1abfmode 100644,000000..100644--- a/tests/gateway/test_native_http_auth.py+++ b/tests/gateway/test_native_http_auth.py@@@ -1,252 -1,0 +1,252 @@@+"""Private native grants authenticate HTTP, never another purpose or profile."""+import asyncio+from contextlib import contextmanager+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import time++import httpx+import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus++from tests.gateway.test_normal_runtime_boot import control+++@contextmanager+def daemon(tmp_path):+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700, exist_ok=True)+ user.mkdir(exist_ok=True)+ for name in ('other', 'current'):+ sibling = home / 'profiles' / name+ sibling.mkdir(parents=True, exist_ok=True)+ (sibling / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'custom', 'default': 'sibling-' + name}}))+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'native-http-fixture',+ 'base_url': 'http://127.0.0.1:1/v1'},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1',+ HERMES_DASHBOARD_SESSION_TOKEN='normal-http-owner')+ with (tmp_path / 'gateway.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ descriptor = {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ yield home, descriptor+ finally:+ if process.poll() is None:+ process.send_signal(signal.SIGINT)+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++def ticket(home, descriptor, purpose='native-http', **overrides):+ return control(home, 'session-ticket', {+ 'profile_id': str(home.resolve()), 'instance_id': descriptor['instance_id'],+ 'purpose': purpose, **overrides,+ })['ticket']+++def headers(token):+ return {'X-Hermes-Gateway-Ticket': token}+++async def reject_ws(origin, token):+ with pytest.raises(InvalidStatus):+ async with connect(origin.replace('http:', 'ws:') + '/api/ws', subprotocols=[+ 'hermes-gateway-v1', 'hermes-gateway-ticket.' + token]):+ pass++- @pytest.mark.linux_only[email protected]("linux")+def test_native_http_grants_are_single_use_and_bound_to_daemon(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(+ base_url=descriptor['api_origin'], trust_env=False) as client:+ assert client.get('/api/config').status_code == 401+ normal = {'Authorization': 'Bearer normal-http-owner'}+ assert client.get('/api/config', headers=normal).status_code == 200+ assert 'sibling-other' in client.get('/api/config?profile=other', headers=normal).text+ sibling_config = home / 'profiles' / 'other' / 'config.yaml'+ sibling_before = sibling_config.read_bytes()+ first = ticket(home, descriptor)+ response = client.get('/api/config', headers=headers(first))+ assert response.status_code == 200, response.text+ assert 'native-http-fixture' in response.text+ assert client.get('/api/config', headers=headers(first)).status_code == 401+ assert client.get('/api/config', headers={**normal, **headers('invalid')}).status_code == 401+ for origin in ('https://evil.example', '', 'null'):+ assert client.get('/api/config', headers={**headers(ticket(home, descriptor)),+ 'Origin': origin}).status_code == 401+ assert client.get('/api/config', headers=[+ ('X-Hermes-Gateway-Ticket', ticket(home, descriptor)),+ ('X-Hermes-Gateway-Ticket', ticket(home, descriptor)),+ ]).status_code == 401+ for purpose in ('interactive', 'exposure', 'worker-adoption'):+ assert client.get('/api/config', headers=headers(ticket(home, descriptor, purpose))).status_code == 401+ asyncio.run(reject_ws(descriptor['api_origin'], ticket(home, descriptor)))+ for overrides in ({'instance_id': 'stale'}, {'profile_id': str(tmp_path / 'other')}):+ with pytest.raises(AssertionError, match='PermissionError'):+ ticket(home, descriptor, **overrides)+ for path in ('/api/config?profile=other', '/api/config?profile=current&profile=other',+ '/api/profiles/other/soul', '/api/sessions?profile=current'):+ assert client.get(path, headers=headers(ticket(home, descriptor))).status_code == 403+ assert client.put('/api/config', json={'profile': 'other', 'config': {}},+ headers=headers(ticket(home, descriptor))).status_code == 403+ for content_type in ('application/json', 'application/problem+json', ''):+ response = client.put('/api/config', content=json.dumps({'profile': 'other', 'config': {}}),+ headers={**headers(ticket(home, descriptor)), 'Content-Type': content_type})+ assert response.status_code == 403, (content_type, response.text)+ for path in ('/api/profiles/sessions', '/api/profiles/sessions/sidebar',+ '/api/profiles/projects/tree', '/api/cron/jobs'):+ assert client.get(path, headers=headers(ticket(home, descriptor))).status_code == 403+ assert sibling_config.read_bytes() == sibling_before+ assert client.get('/api/config?profile=default',+ headers=headers(ticket(home, descriptor))).status_code == 200+ assert client.get('/api/profiles/sessions/sidebar?recents_profile=default',+ headers=headers(ticket(home, descriptor))).status_code == 200+ assert client.get('/api/config?profile=current',+ headers=headers(ticket(home, descriptor))).status_code == 200+ assert client.get('/api/profiles', headers=headers(ticket(home, descriptor))).status_code == 200+ updated = client.put('/api/config', json={'profile': 'current', 'config': {+ 'display': {'skin': 'ares'}}}, headers=headers(ticket(home, descriptor)))+ assert updated.status_code == 200, updated.text+ assert client.get('/api/config', headers=headers(ticket(home, descriptor))).json()['display']['skin'] == 'ares'- import yaml++ import hermes_yaml as yaml+ assert yaml.safe_load((home / 'config.yaml').read_text())['display']['skin'] == 'ares'+ query_ticket = ticket(home, descriptor)+ assert client.get('/api/config', params={'ticket': query_ticket}).status_code == 401+ assert client.get('/api/config', headers={'Cookie': 'X-Hermes-Gateway-Ticket=' + query_ticket}).status_code == 401+ expired = ticket(home, descriptor)+ time.sleep(31) # Real production TTL, not a patched clock or shortened grant.+ assert client.get('/api/config', headers=headers(expired)).status_code == 401+ stale = ticket(home, descriptor)+ old_instance = descriptor['instance_id']+ assert 'ticket' not in json.dumps(control(home, 'identify')).lower()+ with daemon(tmp_path) as (home, descriptor), httpx.Client(+ base_url=descriptor['api_origin'], trust_env=False) as client:+ assert descriptor['instance_id'] != old_instance+ assert client.get('/api/config', headers=headers(stale)).status_code == 401+ assert client.get('/api/config', headers=headers(ticket(home, descriptor))).status_code == 200+ print(json.dumps({'native_http': 'ordinary daemon config and profiles HTTP passed',+ 'replay_expiry_restart_purpose_origin_profile': 'rejected'}))+++async def test_native_http_preserves_gated_auth_and_actual_socket_boundary(tmp_path):+ import socket+ from gateway.config import GatewayConfig+ from gateway.run import GatewayRunner+ from gateway.run_api import start_gateway_api+ from gateway.run_runtime import initialize_gateway_runtime, publish_gateway_runtime_ready+ from gateway.runtime_ownership import process_ownership+ from hermes_cli import web_server as web+ from hermes_cli.dashboard_auth import register_provider, clear_providers+ from hermes_cli.dashboard_auth.cookies import SESSION_AT_COOKIE+ from hermes_constants import get_hermes_home+ from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider++ home = get_hermes_home()+ (home / 'config.yaml').write_text('dashboard:\n public_url: https://gateway.example.test\n')+ provider = StubAuthProvider()+ register_provider(provider)+ login = provider.start_login(redirect_uri='http://127.0.0.1/callback')+ from urllib.parse import parse_qs+ pkce = parse_qs(login.cookie_payload['hermes_session_pkce'].replace(';', '&'))+ session = provider.complete_login(code='stub_code', state=pkce['state'][0],+ code_verifier=pkce['verifier'][0],+ redirect_uri='http://127.0.0.1/callback')+ process_ownership.reserve([home])+ runner = GatewayRunner(GatewayConfig())+ try:+ await initialize_gateway_runtime(runner)+ from gateway.control_socket import GatewayControlServer+ runner.session_control_server = GatewayControlServer()+ assert await runner.session_control_server.start()+ runner.session_api = await start_gateway_api(runner, host='0.0.0.0')+ port = runner.session_api.socket.getsockname()[1]+ def mint():+ return runner.session_ticket_store.mint(profile_id=str(home), subject='uid:fixture',+ purpose='native-http')+ async with httpx.AsyncClient(base_url=f'http://127.0.0.1:{port}', trust_env=False) as client:+ assert (await client.get('/api/config', headers=headers(mint()))).status_code == 503+ assert await runner.start()+ publish_gateway_runtime_ready(runner)+ assert web.app.state.auth_required is True+ bearer = {'Authorization': 'Bearer ' + session.access_token}+ cookie = {'Cookie': f'{SESSION_AT_COOKIE}={session.access_token}'}+ for normal in (bearer, cookie):+ assert (await client.get('/api/config', headers=normal)).status_code == 200+ assert (await client.get('/api/config', headers={**normal, **headers('bad')})).status_code == 401+ assert (await client.get('/api/config', headers={+ 'Authorization': 'Bearer ' + web._SESSION_TOKEN})).status_code == 401+ assert (await client.get('/api/config', headers=headers(mint()))).status_code == 200+ # Trusted proxy rewrites client.host; native admission must retain actual peer.+ assert (await client.get('/api/config', headers={**headers(mint()),+ 'X-Forwarded-For': '203.0.113.9'})).status_code == 200+ for origin in ('', 'https://gateway.example.test'):+ assert (await client.get('/api/config', headers={**headers(mint()),+ 'Origin': origin, **cookie})).status_code == 401+ # Real non-loopback local interface, not a forged ASGI scope or testclient IP.+ import ipaddress+ import psutil+ addresses = {info.address for entries in psutil.net_if_addrs().values()+ for info in entries if info.family == socket.AF_INET+ and not ipaddress.ip_address(info.address).is_loopback}+ assert addresses, 'real non-loopback interface required for this invariant'+ address = sorted(addresses)[0]+ async with httpx.AsyncClient(base_url=f'http://{address}:{port}', trust_env=False) as remote:+ assert (await remote.get('/api/config', headers={**headers(mint()),+ 'X-Forwarded-For': '127.0.0.1', 'Host': f'127.0.0.1:{port}'})).status_code == 401+ assert (await remote.get('/api/config', headers={**bearer,+ 'Host': f'127.0.0.1:{port}'})).status_code == 200+ runner.session_runtime_descriptor['state'] = 'draining'+ assert (await client.get('/api/config', headers=headers(mint()))).status_code == 503+ finally:+ await runner.stop()+ await runner.session_control_server.stop()+ process_ownership.close()+ clear_providers()+ print(json.dumps({'normal_oauth_bearer_cookie': 'passed',+ 'native_gated_auth_raw_peer_readiness': 'passed'}))++- @pytest.mark.linux_only[email protected]("linux")+def test_native_http_principal_satisfies_route_local_token_policy(tmp_path):+ """Routes that call ``_require_token`` honor the verified native owner (F16).++ Local Desktop runs with authMode=native and no static token; the outer seam+ admitted the ticket, so the route-local check must not 401 the same request.+ """+ with daemon(tmp_path) as (home, descriptor), httpx.Client(+ base_url=descriptor['api_origin'], trust_env=False, timeout=30) as client:+ hub = client.get('/api/dashboard/plugins/hub', headers=headers(ticket(home, descriptor)))+ assert hub.status_code == 200, hub.text+ oauth = client.delete('/api/providers/oauth/__not_a_real_provider__',+ headers=headers(ticket(home, descriptor)))+ assert oauth.status_code == 400, oauth.text+ assert client.delete('/api/providers/oauth/__not_a_real_provider__').status_code == 401diff --cc tests/gateway/test_native_http_secondary_profile_binding.pyindex ea00249452c,00000000000..0db16408f86mode 100644,000000..100644--- a/tests/gateway/test_native_http_secondary_profile_binding.py+++ b/tests/gateway/test_native_http_secondary_profile_binding.py@@@ -1,81 -1,0 +1,81 @@@+"""A secondary-profile native ticket binds every implicit profile selector to its own home."""+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import time++import httpx+import pytest++from tests.gateway.test_normal_runtime_boot import control++- @pytest.mark.linux_only[email protected]("linux")+def test_secondary_native_ticket_implicit_selectors_touch_only_the_secondary_home(tmp_path):+ """R2: omitted / empty / ``current`` selectors used to pass ``_own_profile`` unbound, so the+ route resolved through the LAUNCH home and a valid secondary ticket read and wrote the launch+ profile's config. One read route and one write route, no explicit selector, must resolve+ against the ticket's profile and leave the launch home byte-identical."""+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ beta = home / 'profiles' / 'beta'+ beta.mkdir(parents=True)+ (beta / 'config.yaml').write_text(json.dumps({'model': {'provider': 'custom', 'default': 'beta-model'}}))+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': True},+ 'model': {'provider': 'custom', 'default': 'launch-model', 'base_url': 'http://127.0.0.1:1/v1'},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ launch_before = (home / 'config.yaml').read_bytes()+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ PYTHONUNBUFFERED='1', HERMES_DASHBOARD_SESSION_TOKEN='normal-http-owner')+ with (tmp_path / 'gateway.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 60+ descriptor = {}+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ served = {p['profile_id'] for p in descriptor['served_profiles']}+ assert str(beta.resolve()) in served and str(home.resolve()) in served, descriptor++ def ticket():+ return control(home, 'session-ticket', {'profile_id': str(beta.resolve()),+ 'instance_id': descriptor['instance_id'], 'purpose': 'native-http'})['ticket']++ with httpx.Client(base_url=descriptor['api_origin'], trust_env=False, timeout=30) as client:+ for params in ({}, {'profile': ''}, {'profile': 'current'}):+ response = client.get('/api/config', params=params,+ headers={'X-Hermes-Gateway-Ticket': ticket()})+ assert response.status_code == 200, (params, response.text)+ assert 'beta-model' in response.text and 'launch-model' not in response.text, (params, response.text)+ for body in ({}, {'profile': 'current'}):+ updated = client.put('/api/config', json={**body, 'config': {'display': {'skin': 'ares'}}},+ headers={'X-Hermes-Gateway-Ticket': ticket()})+ assert updated.status_code == 200, (body, updated.text)- import yaml++ import hermes_yaml as yaml+ assert yaml.safe_load((beta / 'config.yaml').read_text())['display']['skin'] == 'ares'+ assert (home / 'config.yaml').read_bytes() == launch_before+ finally:+ if process.poll() is None:+ process.send_signal(signal.SIGINT)+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)diff --cc tests/gateway/test_native_ingress_media.pyindex 60f06f4b9da,00000000000..dbb97d68308mode 100644,000000..100644--- a/tests/gateway/test_native_ingress_media.py+++ b/tests/gateway/test_native_ingress_media.py@@@ -1,57 -1,0 +1,57 @@@+"""Native attachments are committed bytes, not mutable adapter paths."""+import json+import os+from pathlib import Path+import subprocess+import sys+import time++import pytest+++def _peer(tmp_path, mode):+ repo = Path(__file__).resolve().parents[2]+ home, state = tmp_path / 'home', tmp_path / 'state'+ home.mkdir(exist_ok=True)+ state.mkdir(exist_ok=True)+ env = {key: os.environ[key] for key in ('PATH', 'SYSTEMROOT', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state),+ PYTHONPATH=str(repo), PYTHONUNBUFFERED='1')+ return [sys.executable, str(Path(__file__).parent / 'fixtures' / 'native_ingress_media_peer.py'), mode], env, repo, state++- @pytest.mark.linux_only[email protected]("linux")+def test_accepted_media_survives_mutation_cleanup_and_owner_kill(tmp_path):+ command, env, repo, state = _peer(tmp_path, 'capture')+ with (state / 'owner.log').open('w+') as log:+ child = subprocess.Popen(command, cwd=repo, env=env, stdin=subprocess.DEVNULL,+ stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 45+ while not (state / 'accepted.json').exists():+ if child.poll() is not None or time.monotonic() > deadline:+ log.seek(0)+ pytest.fail(log.read())+ time.sleep(0.05)+ child.kill()+ assert child.wait(timeout=10) < 0+ finally:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=10)+ for calls in (1, 0):+ command[-1] = 'recover'+ result = subprocess.run(command, cwd=repo, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=60)+ assert result.returncode == 0, result.stdout + result.stderr+ receipt = json.loads((state / 'recovered.json').read_text())+ assert receipt['model_calls'] == calls, receipt+ print(json.dumps(receipt))+++def test_native_context_never_upgrades_metadata_or_transport_trust(tmp_path):+ command, env, repo, state = _peer(tmp_path, 'guards')+ result = subprocess.run(command, cwd=repo, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=45)+ assert result.returncode == 0, result.stdout + result.stderr+ print((state / 'guards.json').read_text())diff --cc tests/gateway/test_native_pause_notice.pyindex 7e760f926b5,00000000000..d06bb39d49bmode 100644,000000..100644--- a/tests/gateway/test_native_pause_notice.py+++ b/tests/gateway/test_native_pause_notice.py@@@ -1,168 -1,0 +1,171 @@@+"""A messaging user whose session FIFO is paused is told once, and can /reset out of it.++An owner crash mid-turn leaves the started admission ``unknown`` and the session paused+(fail-closed, never weakened here). Before this fix the next Telegram message was admitted,+``admit_message`` awaited it forever and the platform user saw nothing at all.+"""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+from pathlib import Path+import queue+import sqlite3+import threading+import time+++import importlib.machinery+++import pytest++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon+from tests.gateway.test_native_telegram_startup_recovery import BotAPI, wait_for++PAUSE_MARKER = 'This conversation is paused'+++async def test_paused_fifo_releases_the_messaging_waiter_with_one_notice_per_episode(tmp_path, monkeypatch):+ """No daemon: the authority alone. A refused head pauses the FIFO; every messaging waiter+ parked on that session returns (never hangs), the first gets the notice, the rest None,+ and once the FIFO moves again the next pause is a fresh episode with its own notice."""+ from gateway.platforms.event import MessageEvent+ from gateway.session_authority import SessionAuthority+ from gateway.session_contract import Principal, Submission+ from gateway.session_controls import AuthorityConnection+ from gateway.session_ingress import admit_message+ from tests.gateway.test_authority_unknown_resolution import Peer, _restarted_owner_with_unknown_head++ executed = []+ store, authority, ref, unknown, follower = await _restarted_owner_with_unknown_head(tmp_path, monkeypatch, executed)+ try:+ actor = Principal('human', 'p', frozenset({'session:submit'}), 'fixture')++ async def admit_native(event):+ return await authority.submit(actor, Submission(event.text, ref, {'text': event.text}, 'queue'))+ monkeypatch.setattr(authority, 'admit_native', admit_native)+ authority._schedule = lambda ref: SessionAuthority._schedule(authority, ref)+ source = authority.sessions['s'].source+ first = asyncio.create_task(admit_message(authority, MessageEvent(text='one', source=source)))+ second = asyncio.create_task(admit_message(authority, MessageEvent(text='two', source=source)))+ replies = await asyncio.wait_for(asyncio.gather(first, second), 5)+ assert sum(r is not None and PAUSE_MARKER in r for r in replies) == 1, replies+ assert executed == []+ # A restart drain is transient: the saved row runs on the next owner, so the notice must+ # not tell the user to /reset (that would discard the very message that is about to run).+ from gateway.session_ingress import pause_notice+ authority.sessions['s'].pause_notified = False+ draining = pause_notice(authority, ref, 'runtime_draining')+ assert 'restarting' in draining and '/reset' not in draining, draining+ authority.sessions['s'].pause_notified = False+ # The operator resumes the FIFO; the saved followers run, no new notice was owed.+ viewer = AuthorityConnection(authority, Peer(), {'user_id': 'human'})+ await viewer.dispatch({'id': 1, 'method': 'prompt.resolve_unknown', 'params': {+ 'session_id': 's', 'admission_id': unknown['admission_id'], 'execution_generation': unknown['generation']}})+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert executed == ['FOLLOWER', 'one', 'two']+ assert not authority.sessions['s'].pause_notified+ await viewer.close()+ finally:+ store.close_all_db_handles()++- @pytest.mark.linux_only[email protected](importlib.machinery.PathFinder.find_spec("telegram") is None, reason="python-telegram-bot not installed (on-demand extra)")[email protected]("linux")+def test_crash_mid_turn_then_platform_message_gets_one_pause_notice_and_reset_unpauses(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ model.requests = []+ model.blocked, model.release = threading.Event(), threading.Event()+ bot = ThreadingHTTPServer(('127.0.0.1', 0), BotAPI)+ bot.calls, bot.sent, bot.updates = [], [], queue.Queue()+ for peer in (model, bot):+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ base = f'http://127.0.0.1:{model.server_port}/v1'+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},+ 'gateway': {'multiplex_profiles': False},+ 'platforms': {'telegram': {'enabled': True, 'extra': {+ 'base_url': f'http://127.0.0.1:{bot.server_port}/bot', 'dm_policy': 'allowlist'}}},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'platform_toolsets': {'telegram': []}, 'terminal': {'cwd': str(home)}}+ (home / 'config.yaml').write_text(json.dumps(cfg), encoding='utf-8')+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1',+ TELEGRAM_BOT_TOKEN='987654321:owned-loopback-fixture', TELEGRAM_ALLOWED_USERS='202')++ def rows():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return {json.loads(payload)['text']: {'session': sid, 'status': status}+ for sid, status, payload in db.execute(+ 'SELECT target_session_id,status,payload_json FROM session_admissions')}++ def sent_texts():+ # Telegram MarkdownV2 escapes underscores; compare on the unescaped text.+ return [m.get('text', '').replace('\\', '') for m in bot.sent]++ def notices():+ return [t for t in sent_texts() if PAUSE_MARKER in t]++ def diagnostic():+ return repr(rows()) + '\n' + repr(sent_texts()) + '\n' + '\n'.join(+ p.read_text(encoding='utf-8') for p in (home / 'logs').glob('*.log'))++ update_id = 0++ def push(text):+ nonlocal update_id+ update_id += 1+ bot.updates.put({'update_id': update_id, 'message': {+ 'message_id': update_id, 'date': int(time.time()),+ 'chat': {'id': 202, 'type': 'private', 'first_name': 'Owned'},+ 'from': {'id': 202, 'is_bot': False, 'first_name': 'Owned'}, 'text': text}})++ def send(text, status):+ push(text)+ wait_for(lambda: rows().get(text, {}).get('status') == status, diagnostic)++ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ send('WARM_HISTORY', 'terminal')+ send('BLOCK_STARTED', 'started')+ assert model.blocked.wait(20), diagnostic()+ proc.kill()+ assert proc.wait(timeout=10) == -9+ model.release.set()+ with daemon(root, home, env, barrier=False) as (proc, desc):+ wait_for(lambda: rows()['BLOCK_STARTED']['status'] == 'unknown', diagnostic)+ paused_session = rows()['BLOCK_STARTED']['session']+ # First message onto the paused FIFO: admitted (durable), the user is told once,+ # and the adapter loop keeps going (the second message is admitted too).+ send('AFTER_CRASH_ONE', 'queued')+ wait_for(lambda: len(notices()) == 1, diagnostic)+ assert '/reset' in notices()[0], notices()+ send('AFTER_CRASH_TWO', 'queued')+ assert rows()['AFTER_CRASH_TWO']['session'] == paused_session+ # The named escape works from the platform: /reset (confirmed) moves the chat to+ # a fresh session and the next message runs and is answered.+ push('/reset')+ wait_for(lambda: any('Confirm /new' in t for t in sent_texts()), diagnostic)+ push('/approve')+ wait_for(lambda: any('Session reset' in t or 'New session' in t for t in sent_texts()), diagnostic)+ send('AFTER_RESET', 'terminal')+ wait_for(lambda: any('RECOVERY_ACK_AFTER_RESET' in t for t in sent_texts()), diagnostic)+ after = rows()+ assert after['AFTER_RESET']['session'] != paused_session+ # Exactly one notice for the whole pause episode, and the pause itself is intact:+ # the lost turn stays unknown and its followers never ran on their own.+ assert len(notices()) == 1, notices()+ assert after['BLOCK_STARTED']['status'] == 'unknown'+ assert after['AFTER_CRASH_ONE']['status'] == after['AFTER_CRASH_TWO']['status'] == 'queued'+ texts = [next(m['content'] for m in reversed(r['messages']) if m['role'] == 'user') for r in model.requests]+ assert not any('AFTER_CRASH' in t for t in texts), texts+ print(json.dumps({'notice': notices()[0], 'final_rows': rows()}))+ finally:+ model.release.set()+ for peer in (model, bot):+ peer.shutdown()+ peer.server_close()diff --cc tests/gateway/test_native_telegram_startup_recovery.pyindex a75d6eaca1f,00000000000..b44f97c1c64mode 100644,000000..100644--- a/tests/gateway/test_native_telegram_startup_recovery.py+++ b/tests/gateway/test_native_telegram_startup_recovery.py@@@ -1,164 -1,0 +1,167 @@@+"""Actual Telegram polling ingress, SIGKILL, and uninstrumented owner recovery."""+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+from pathlib import Path+import queue+import sqlite3+import threading+import time+from urllib.parse import parse_qs+++import importlib.machinery+++import pytest++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon+++class BotAPI(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ raw = self.rfile.read(int(self.headers.get('Content-Length', 0)))+ body = json.loads(raw) if 'application/json' in self.headers.get('Content-Type', '') else {+ k: values[0] for k, values in parse_qs(raw.decode()).items()+ }+ method = self.path.rsplit('/', 1)[-1]+ self.server.calls.append(method)+ if method == 'getUpdates':+ try:+ result = [self.server.updates.get(timeout=.2)]+ except queue.Empty:+ result = []+ elif method == 'getMe':+ result = {'id': 987654321, 'is_bot': True, 'first_name': 'Fixture', 'username': 'recovery_fixture_bot'}+ elif method == 'getWebhookInfo':+ result = {'url': '', 'pending_update_count': 0}+ elif method in ('sendMessage', 'editMessageText'):+ self.server.sent.append(body)+ result = {'message_id': len(self.server.sent) + 1000, 'date': int(time.time()),+ 'chat': {'id': int(body['chat_id']), 'type': 'private'}, 'text': body.get('text', '')}+ else:+ result = True+ payload = json.dumps({'ok': True, 'result': result}).encode()+ try:+ self.send_response(200)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError):+ pass+++def wait_for(predicate, detail, timeout=30):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(.05)+ pytest.fail(detail())++- @pytest.mark.linux_only[email protected](importlib.machinery.PathFinder.find_spec("telegram") is None, reason="python-telegram-bot not installed (on-demand extra)")[email protected]("linux")+def test_telegram_fifo_unknown_and_current_authorization_survive_sigkill(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ model.requests = []+ model.blocked, model.release = threading.Event(), threading.Event()+ bot = ThreadingHTTPServer(('127.0.0.1', 0), BotAPI)+ bot.calls, bot.sent, bot.updates = [], [], queue.Queue()+ for peer in (model, bot):+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ base = f'http://127.0.0.1:{model.server_port}/v1'+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},+ 'gateway': {'multiplex_profiles': False},+ 'platforms': {'telegram': {'enabled': True, 'extra': {+ 'base_url': f'http://127.0.0.1:{bot.server_port}/bot', 'dm_policy': 'allowlist'}}},+ 'auxiliary': {'title_generation': {'enabled': False}},+ # The default `interrupt` mode redirects a follow-up into the running turn instead of+ # admitting it; the FIFO contract under test needs follow-ups queued behind the head.+ 'display': {'busy_input_mode': 'queue'},+ 'platform_toolsets': {'telegram': []}, 'terminal': {'cwd': str(home)}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1',+ TELEGRAM_BOT_TOKEN='987654321:owned-loopback-fixture', TELEGRAM_ALLOWED_USERS='101,202,303')++ def rows():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return {json.loads(payload)['text']: {'id': aid, 'request_id': rid, 'session': sid, 'status': status}+ for aid, rid, sid, status, payload in db.execute(+ 'SELECT admission_id,request_id,target_session_id,status,payload_json FROM session_admissions')}++ def diagnostic():+ return repr(rows()) + '\n' + '\n'.join(p.read_text() for p in (home / 'logs').glob('*.log'))++ update_id = 0++ def send(uid, text, status):+ nonlocal update_id+ update_id += 1+ bot.updates.put({'update_id': update_id, 'message': {+ 'message_id': update_id, 'date': int(time.time()),+ 'chat': {'id': uid, 'type': 'private', 'first_name': 'Owned'},+ 'from': {'id': uid, 'is_bot': False, 'first_name': 'Owned'}, 'text': text}})+ wait_for(lambda: rows().get(text, {}).get('status') == status, diagnostic)++ boots = []+ try:+ with daemon(root, home, env, barrier=True, fixture='native_telegram_recovery_daemon.py') as (proc, desc):+ # Warm the started route so first-message onboarding cannot obscure the model barrier.+ send(202, 'WARM_HISTORY', 'terminal')+ send(202, 'BLOCK_STARTED', 'started')+ assert model.blocked.wait(20), diagnostic()+ send(202, 'NEVER_REPLAY', 'queued')+ send(101, 'SAFE_FIRST', 'queued')+ send(101, 'SAFE_SECOND', 'queued')+ send(303, 'REVOKED_FIRST', 'queued')+ send(303, 'REVOKED_SECOND', 'queued')+ before = rows()+ assert before['SAFE_FIRST']['session'] == before['SAFE_SECOND']['session']+ assert before['BLOCK_STARTED']['session'] == before['NEVER_REPLAY']['session']+ boots.append({'pid': proc.pid, 'epoch': desc['authority_epoch']})+ proc.kill()+ assert proc.wait(timeout=10) == -9+ model.release.set()+ env['TELEGRAM_ALLOWED_USERS'] = '101,202'+ for _ in range(2):+ with daemon(root, home, env, barrier=False) as (proc, desc):+ wait_for(lambda: rows()['SAFE_SECOND']['status'] == 'terminal', diagnostic)+ after = rows()+ assert after['SAFE_FIRST']['status'] == 'terminal'+ assert after['BLOCK_STARTED']['status'] == 'unknown'+ assert after['NEVER_REPLAY']['status'] == 'queued'+ assert after['REVOKED_FIRST'] == before['REVOKED_FIRST']+ assert after['REVOKED_SECOND'] == before['REVOKED_SECOND']+ for text in before:+ assert after[text]['id'] == before[text]['id']+ assert after[text]['session'] == before[text]['session']+ boots.append({'pid': proc.pid, 'epoch': desc['authority_epoch']})+ # Re-authorizing later proves refusal retained executable rows, not just tombstones.+ env['TELEGRAM_ALLOWED_USERS'] = '101,202,303'+ with daemon(root, home, env, barrier=False) as (proc, desc):+ wait_for(lambda: rows()['REVOKED_SECOND']['status'] == 'terminal', diagnostic)+ assert rows()['REVOKED_FIRST']['status'] == 'terminal'+ assert rows()['NEVER_REPLAY']['status'] == 'queued'+ boots.append({'pid': proc.pid, 'epoch': desc['authority_epoch']})+ texts = [next(m['content'] for m in reversed(r['messages']) if m['role'] == 'user') for r in model.requests]+ markers = ['WARM_HISTORY', 'BLOCK_STARTED', 'SAFE_FIRST', 'SAFE_SECOND', 'REVOKED_FIRST', 'REVOKED_SECOND']+ observed = [next((marker for marker in markers if marker in text), text) for text in texts]+ assert observed == markers, observed+ assert len(set(b['pid'] for b in boots)) == len(boots)+ assert all(b['epoch'] > a['epoch'] for a, b in zip(boots, boots[1:]))+ assert 'getUpdates' in bot.calls and bot.sent+ print(json.dumps({'boots': boots, 'model_inputs': observed, 'final_rows': rows()}))+ finally:+ model.release.set()+ for peer in (model, bot):+ peer.shutdown()+ peer.server_close()diff --cc tests/gateway/test_normal_runtime_boot.pyindex 60fff46473d,00000000000..818b9310190mode 100644,000000..100644--- a/tests/gateway/test_normal_runtime_boot.py+++ b/tests/gateway/test_normal_runtime_boot.py@@@ -1,222 -1,0 +1,222 @@@+"""The ordinary no-platform process must earn its bootstrap readiness."""+import asyncio+import json+import os+from pathlib import Path+import signal+import socket+import subprocess+import sys+import time++import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus+++def control(home, verb, params=None):+ """Bootstrap control channel: private named pipe on Windows, AF_UNIX elsewhere."""+ request = json.dumps({'protocol': 1, 'id': 1, 'verb': verb, 'params': params or {}}).encode() + b'\n'+ if os.name == 'nt':+ from gateway.runtime_bootstrap_windows import query_runtime_control+ raw = query_runtime_control(home, request, 2)+ else:+ pointer = home / 'gateway.sock.path'+ path = pointer.read_text(encoding='utf-8').strip() if pointer.exists() else str(home / 'gateway.sock')+ with socket.socket(socket.AF_UNIX) as peer:+ peer.settimeout(2)+ peer.connect(path)+ peer.sendall(request)+ with peer.makefile('rb') as stream:+ raw = stream.readline()+ reply = json.loads(raw.split(b'\n', 1)[0])+ assert reply['ok'], reply+ return reply['result']+++def model_peer():+ from http.server import ThreadingHTTPServer+ import threading+ from tests.gateway.fixtures.shared_authority_peer import ModelPeer+ server = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)+ server.requests, server.metadata_requests = [], []+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield server+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++async def handshake(home, descriptor):+ url = descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws'+ with pytest.raises(InvalidStatus):+ async with connect(url):+ pass+ binding = {'profile_id': str(home.resolve()), 'instance_id': descriptor['instance_id'],+ 'purpose': 'interactive'}+ grant = control(home, 'session-ticket', binding)+ protocols = ['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']]+ async with connect(url, subprotocols=protocols) as ws:+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 7, 'method': 'session.resume',+ 'params': {'session_id': 'not-registered'}}))+ while True:+ reply = json.loads(await asyncio.wait_for(ws.recv(), 10))+ if reply.get('id') == 7:+ break+ assert reply['error']['message'] == 'not_found', reply+ assert ws.subprotocol == 'hermes-gateway-v1'+ async def rpc(socket, method, expected_error=None, **params):+ await socket.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))+ async with asyncio.timeout(15):+ while True:+ result = json.loads(await socket.recv())+ if result.get('id') == method:+ if expected_error is not None:+ assert result.get('error', {}).get('message') == expected_error, result+ return result['error']+ assert 'result' in result, result+ return result['result']++ status = await rpc(ws, 'setup.status')+ assert status['provider_configured'] is True, status+ readiness = await rpc(ws, 'setup.runtime_check', provider='custom')+ assert readiness['ok'] is True and readiness['provider'] == 'custom', readiness+ for method in ('setup.status', 'setup.runtime_check'):+ await rpc(ws, method, expected_error='profile_mismatch', profile='foreign-profile')+ created = await rpc(ws, 'session.create', request_id='ordinary-launch', source='cli')+ sid = created['session_id']+ assert sid == created['stored_session_id']+ initial = await rpc(ws, 'session.resume', session_id=sid)+ admitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='ordinary-input', text='WS_SHARED')+ assert admitted['status'] == 'queued', admitted+ # A fresh control ticket and socket must see the same committed execution.+ fresh = control(home, 'session-ticket', binding)+ async with connect(url, subprotocols=['hermes-gateway-v1',+ 'hermes-gateway-ticket.' + fresh['ticket']]) as viewer:+ async with asyncio.timeout(25):+ while True:+ snapshot = await rpc(viewer, 'session.resume', session_id=sid)+ if 'LOCAL_ACK_WS_SHARED' in json.dumps(snapshot.get('messages', [])):+ break+ await asyncio.sleep(.05)+ assert snapshot['stored_session_id'] == sid+ # Transcript persistence precedes terminal publication; await the actual+ # replay receipt rather than assuming a persisted reply means settlement.+ async with asyncio.timeout(25):+ while True:+ replay = await rpc(viewer, 'session.events.since', session_id=sid,+ replay_epoch=initial['replay_epoch'],+ last_sequence=initial['last_sequence'])+ assert not replay['snapshot_required'], replay+ completed = [event for event in replay['events'] if event['type'] == 'message.complete']+ if completed:+ break+ await asyncio.sleep(.05)+ assert len(completed) == 1, replay+ assert 'LOCAL_ACK_WS_SHARED' in completed[0]['payload']['text'], replay+ snapshot = await rpc(viewer, 'session.resume', session_id=sid)+ assert completed[0]['seq'] <= snapshot['last_sequence']+ edit = {'session_id': sid, 'request_id': 'ordinary-rename',+ 'expected_revision': snapshot['revision'], 'operation': 'rename',+ 'payload': {'title': 'Shared metadata receipt'}}+ renamed = await rpc(viewer, 'session.mutate', **edit)+ assert renamed['title'] == edit['payload']['title'], renamed+ reconnect = control(home, 'session-ticket', binding)+ async with connect(url, subprotocols=['hermes-gateway-v1',+ 'hermes-gateway-ticket.' + reconnect['ticket']]) as viewer:+ assert await rpc(viewer, 'session.mutate', **edit) == renamed+ await rpc(viewer, 'session.mutate', expected_error='revision_conflict',+ **{**edit, 'request_id': 'stale-rename', 'payload': {'title': 'Stale overwrite'}})+ listing = await rpc(viewer, 'session.list')+ assert next(row for row in listing['sessions'] if row['session_id'] == sid)['title'] == renamed['title']+ print(json.dumps({'ordinary_created_session': sid, 'reply_persisted': True, 'reconnect_event_replay': True,+ 'mutation_retry_after_reconnect': True, 'stale_mutation_rejected': True}))+ with pytest.raises(InvalidStatus):+ async with connect(url, subprotocols=protocols):+ pass++- @pytest.mark.linux_only[email protected]("linux")+def test_normal_entrypoint_earns_authenticated_authority_readiness(tmp_path, model_peer):+ home = tmp_path / 'state'+ home.mkdir(mode=0o700)+ user = tmp_path / 'user'+ user.mkdir()+ model_url = f'http://127.0.0.1:{model_peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': model_url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1',+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=model_url)+ with (tmp_path / 'gateway.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ descriptor = {}+ try:+ deadline = time.monotonic() + 35+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.flush()+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ assert descriptor['authority_epoch'] > 0+ import sqlite3+ with sqlite3.connect(f"file:{home / 'state.db'}?mode=ro", uri=True) as db:+ assert db.execute('SELECT epoch, instance_id FROM runtime_epoch').fetchone() == (+ descriptor['authority_epoch'], descriptor['instance_id'])+ assert descriptor['served_profiles'] == [{'profile_id': str(home), 'home': str(home)}]+ assert 'session-authority-v1' in descriptor['capabilities']+ asyncio.run(handshake(home, descriptor))+ assert len(model_peer.requests) == 1, model_peer.requests+ process.send_signal(signal.SIGINT)+ assert process.wait(timeout=20) == 0+ assert not (home / 'gateway.pid').exists()+ assert not (home / 'gateway.sock').exists()+ print(json.dumps({k: descriptor[k] for k in ('instance_id', 'authority_epoch', 'state', 'capabilities')}))+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=15)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++async def test_api_bind_failure_unwinds_control_db_and_reservation(tmp_path, monkeypatch):+ from functools import partial+ from gateway import run_api+ from gateway.run import start_gateway+ from gateway.config import GatewayConfig+ from gateway.runtime_ownership import process_ownership+ from hermes_cli import web_server as web+ from hermes_constants import get_hermes_home++ home = get_hermes_home()+ with socket.socket() as blocker:+ blocker.bind(('127.0.0.1', 0))+ blocker.listen()+ monkeypatch.setattr(run_api, 'start_gateway_api', partial(+ run_api.start_gateway_api, port=blocker.getsockname()[1]))+ with pytest.raises(OSError):+ await start_gateway(GatewayConfig(), verbosity=None)+ assert getattr(web.app.state, 'gateway_runner', None) is None+ assert not (home / 'gateway.pid').exists()+ assert not (home / 'gateway.sock').exists()+ assert not process_ownership.owns(home)diff --cc tests/gateway/test_operator_cross_surface.pyindex b4821d1bba3,00000000000..8eb5b804174mode 100644,000000..100644--- a/tests/gateway/test_operator_cross_surface.py+++ b/tests/gateway/test_operator_cross_surface.py@@@ -1,31 -1,0 +1,31 @@@+"""Real native bootstrap and dashboard login share one canonical worker, not identities."""+import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++- @pytest.mark.linux_only[email protected]("linux")[email protected]('creator', ['native', 'dashboard'])+def test_operator_cross_surface_real_auth_fifo_and_attribution(tmp_path, creator):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ # Do not inherit credentials, plugins, provider configuration, or user state.+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1')+ result = subprocess.run(+ [sys.executable, str(root / 'tests/gateway/fixtures/operator_cross_surface_peer.py'), creator],+ cwd=root, env=env, capture_output=True, text=True, timeout=150)+ assert result.returncode == 0, result.stdout + result.stderr+ receipt = json.loads((home / 'operator-receipt.json').read_text())+ assert receipt['creator'] == creator+ assert receipt['model_requests'] == 2+ assert receipt['distinct_attribution'] is True+ assert receipt['disconnect_survived'] is True+ assert receipt['negative_boundaries'] is Truediff --cc tests/gateway/test_runtime_bootstrap.pyindex 5369b8295b4,00000000000..d02a4046713mode 100644,000000..100644--- a/tests/gateway/test_runtime_bootstrap.py+++ b/tests/gateway/test_runtime_bootstrap.py@@@ -1,125 -1,0 +1,125 @@@+import asyncio+from concurrent.futures import ThreadPoolExecutor+import json+import os++import pytest++- @pytest.mark.linux_only[email protected]("linux")+async def test_private_control_peer_mints_profile_bound_ticket(tmp_path):+ from gateway.control_socket import GatewayControlServer, resolve_client_socket_path+ home = tmp_path / 'home'+ home.mkdir(mode=0o700)+ server = GatewayControlServer(home)+ # The actual service must implement this closed verb; unknown-verb is the pre-feature RED.+ try:+ from gateway.runtime_bootstrap import TicketStore+ server.ticket_store = TicketStore('instance', frozenset({str(home.resolve())}))+ except ImportError:+ pass+ assert await server.start()+ async def request(params, **extra):+ reader, writer = await asyncio.open_unix_connection(str(resolve_client_socket_path(home)))+ writer.write(json.dumps({'protocol': 1, 'verb': 'session-ticket', 'params': params, **extra}).encode() + b'\n')+ await writer.drain()+ reply = json.loads(await asyncio.wait_for(reader.readline(), 5))+ writer.close()+ await writer.wait_closed()+ return reply+ params = {'profile_id': str(home.resolve()), 'instance_id': 'instance', 'purpose': 'interactive'}+ try:+ reply = await request(params)+ assert reply['ok'], reply+ ticket = reply['result']['ticket']+ grant = server.ticket_store.redeem(ticket, profile_id=params['profile_id'], purpose='interactive')+ assert grant['subject'] == f'uid:{os.getuid()}'+ assert grant['instance_id'] == 'instance'+ assert 'session:create' in grant['capabilities']+ for invalid in ({**params, 'instance_id': 'old'}, {**params, 'profile_id': '/wrong'}, {**params, 'subject': 'admin'}):+ assert not (await request(invalid))['ok']+ assert not (await request(params, origin='http://browser'))['ok']+ # Calling the dispatcher directly does not establish peer identity.+ assert not json.loads(server.handle_request_line(json.dumps({'verb': 'session-ticket', 'params': params}).encode()))['ok']+ finally:+ await server.stop()+++def test_ticket_atomic_single_use_profile_purpose_expiry_and_capacity(monkeypatch):+ from gateway.runtime_bootstrap import TicketStore+ clock = [0.0]+ monkeypatch.setattr('gateway.runtime_bootstrap.time.monotonic', lambda: clock[0])+ store = TicketStore('boot', frozenset({'a', 'b'}))+ ticket = store.mint(profile_id='a', subject='uid:1', purpose='interactive')+ for profile, purpose in [('b', 'interactive'), ('a', 'exposure')]:+ with pytest.raises(PermissionError):+ store.redeem(ticket, profile_id=profile, purpose=purpose)+ def consume(_):+ try:+ return store.redeem(ticket, profile_id='a', purpose='interactive')+ except PermissionError:+ return None+ with ThreadPoolExecutor(max_workers=8) as pool:+ grants = list(pool.map(consume, range(8)))+ assert sum(g is not None for g in grants) == 1+ expired = store.mint(profile_id='a', subject='uid:1', purpose='interactive')+ clock[0] = 30+ with pytest.raises(PermissionError):+ store.redeem(expired, profile_id='a', purpose='interactive')+ exposure = store.mint(profile_id='a', subject='uid:1', purpose='exposure')+ assert store.redeem(exposure, profile_id='a', purpose='exposure')['capabilities'] == frozenset({'transport:delegate'})+ for _ in range(store.MAX_ENTRIES):+ store.mint(profile_id='a', subject='uid:1', purpose='interactive')+ with pytest.raises(PermissionError):+ store.mint(profile_id='a', subject='uid:1', purpose='interactive')++- @pytest.mark.linux_only[email protected]("linux")+async def test_old_socket_cleanup_cannot_unlink_replacement(tmp_path):+ from gateway.control_socket import GatewayControlServer, resolve_client_socket_path+ home = tmp_path / 'private'+ home.mkdir(mode=0o700)+ old = GatewayControlServer(home)+ new = GatewayControlServer(home)+ assert await old.start()+ await old.stop()+ assert await new.start()+ try:+ old.cleanup_files()+ assert resolve_client_socket_path(home) is not None+ reader, writer = await asyncio.open_unix_connection(str(resolve_client_socket_path(home)))+ writer.write(b'{"verb":"identify"}\n')+ await writer.drain()+ assert json.loads(await reader.readline())['ok']+ writer.close()+ await writer.wait_closed()+ finally:+ await new.stop()++- @pytest.mark.windows_only[email protected]("windows")+def test_native_pipe_authenticated_peer_and_deadline(tmp_path):+ import time+ from gateway.runtime_bootstrap_windows import NativeControlServer, query_runtime_control+ def handler(raw, subject):+ assert subject.startswith('sid:S-1-')+ if raw == b'stall':+ time.sleep(1)+ return json.dumps({'subject': subject}).encode() + b'\n'+ server = NativeControlServer(tmp_path, handler)+ server.start()+ try:+ # The pipe must survive its first client: CPython's _winapi has no DisconnectNamedPipe,+ # so a server that reaches for it dies after one answer and every later query fails.+ for _ in range(3):+ assert json.loads(query_runtime_control(tmp_path, b'hello', 5))['subject'].startswith('sid:')+ assert server._thread.is_alive() and server._error is None, server._error+ started = time.monotonic()+ with pytest.raises(TimeoutError):+ query_runtime_control(tmp_path, b'stall', 0.1)+ assert time.monotonic() - started < 2+ finally:+ server.close()+ assert not server._thread.is_alive()diff --cc tests/gateway/test_runtime_ownership.pyindex a6580fc44eb,00000000000..ed12a208055mode 100644,000000..100644--- a/tests/gateway/test_runtime_ownership.py+++ b/tests/gateway/test_runtime_ownership.py@@@ -1,116 -1,0 +1,116 @@@+"""Real process exclusion before writable gateway construction."""+import os+from pathlib import Path+import subprocess+import sys++import pytest++- @pytest.mark.linux_only[email protected]("linux")+def test_losing_start_never_constructs_writable_runner(tmp_path):+ from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock+ assert acquire_gateway_runtime_lock()+ code = '''+import asyncio+from pathlib import Path+import os+import gateway.run as run+from gateway.config import GatewayConfig+class Witness:+ def __init__(self, config):+ Path(os.environ['WITNESS']).write_text('writable init reached')+ raise RuntimeError('initializer reached')+run.GatewayRunner = Witness+try:+ result = asyncio.run(run.start_gateway(GatewayConfig(), verbosity=None))+except RuntimeError:+ result = True+print('CLAIMED', result)+'''+ witness = tmp_path / 'witness'+ try:+ result = subprocess.run([sys.executable, '-c', code], env={**os.environ, 'WITNESS': str(witness)},+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert not witness.exists(), result.stdout + result.stderr+ assert 'CLAIMED False' in result.stdout+ finally:+ release_gateway_runtime_lock()++- @pytest.mark.linux_only[email protected]("linux")+async def test_reserved_home_is_eligible_for_same_user_bootstrap(tmp_path):+ import asyncio+ import json++ from gateway.control_socket import GatewayControlServer+ from gateway.runtime_bootstrap import TicketStore+ from gateway.runtime_ownership import ProfileOwnership+ from hermes_cli.gateway_runtime import discover_gateway_endpoint++ home = tmp_path / 'new-private-home'+ owner = ProfileOwnership()+ old_umask = os.umask(0o022)+ try:+ owner.reserve([home])+ finally:+ os.umask(old_umask)+ server = GatewayControlServer(home)+ server.ticket_store = TicketStore('fixture-owner', frozenset({str(home)}))+ try:+ assert await server.start()+ pointer = home / 'gateway.sock.path'+ socket_path = pointer.read_text().strip() if pointer.exists() else str(home / 'gateway.sock')+ reader, writer = await asyncio.open_unix_connection(socket_path)+ try:+ writer.write(json.dumps({'protocol': 1, 'verb': 'session-ticket', 'id': 1,+ 'params': {'profile_id': str(home), 'instance_id': 'fixture-owner',+ 'purpose': 'interactive'}}).encode() + b'\n')+ await writer.drain()+ reply = json.loads(await asyncio.wait_for(reader.readline(), 2))+ assert reply.get('ok') is True, reply.get('error')+ finally:+ writer.close()+ await writer.wait_closed()+ finally:+ await server.stop()+ owner.close()++ # Pre-existing readable homes are refused, not silently chmodded.+ existing = tmp_path / 'existing-readable-home'+ existing.mkdir(mode=0o755)+ existing.chmod(0o755)+ owner.reserve([existing])+ try:+ observed = await asyncio.to_thread(discover_gateway_endpoint, existing)+ assert (observed.state, observed.reason_code) == ('inaccessible', 'unsafe_control_permissions')+ assert existing.stat().st_mode & 0o777 == 0o755+ finally:+ owner.close()++- @pytest.mark.linux_only[email protected]("linux")+def test_profile_reservations_unwind_without_releasing_another_owner(tmp_path):+ from gateway import runtime_ownership+ homes = [tmp_path / 'a', tmp_path / 'b']+ for home in homes:+ home.mkdir()+ blocker = runtime_ownership.ProfileOwnership()+ blocker.reserve([homes[1]])+ contender = runtime_ownership.ProfileOwnership()+ with pytest.raises(runtime_ownership.OwnershipConflict):+ contender.reserve(reversed(homes))+ free = runtime_ownership.ProfileOwnership()+ free.reserve([homes[0]])+ contender.close()+ with pytest.raises(runtime_ownership.OwnershipConflict):+ contender.reserve([homes[1]])+ blocker.close()+ contender.reserve([homes[1]])+ blocker.close() # late cleanup must not affect replacement+ with pytest.raises(runtime_ownership.OwnershipConflict):+ blocker.reserve([homes[1]])+ free.close()+ contender.close()diff --cc tests/gateway/test_runtime_token_identity.pyindex 1f2fbc0aec5,00000000000..f07601d8bd6mode 100644,000000..100644--- a/tests/gateway/test_runtime_token_identity.py+++ b/tests/gateway/test_runtime_token_identity.py@@@ -1,181 -1,0 +1,181 @@@+"""Legacy token authentication must become an explicit authority principal."""+import asyncio+import json+import os+from pathlib import Path+import secrets+import signal+import socket+import subprocess+import sys+import tempfile+import time++import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus+++async def test_authenticated_token_can_create_without_identityless_permissions(tmp_path):+ from gateway.config import GatewayConfig+ from gateway.run import GatewayRunner+ from gateway.run_runtime import initialize_gateway_runtime, start_gateway_runtime_api, publish_gateway_runtime_ready+ from gateway.runtime_ownership import process_ownership+ from gateway.session_controls import AuthorityConnection+ from hermes_constants import get_hermes_home+ from hermes_cli import web_server as web++ # Session creation persists a restorable model policy, even without a turn.+ (get_hermes_home() / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'custom', 'default': 'local-wire-stub',+ 'base_url': 'http://127.0.0.1:1/v1'},+ 'platform_toolsets': {'cli': []},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ process_ownership.reserve([get_hermes_home()])+ runner = GatewayRunner(GatewayConfig())+ try:+ await initialize_gateway_runtime(runner)+ from gateway.control_socket import GatewayControlServer+ runner.session_control_server = GatewayControlServer()+ assert await runner.session_control_server.start()+ await start_gateway_runtime_api(runner)+ assert await runner.start()+ publish_gateway_runtime_ready(runner)+ url = runner.session_api.api_origin.replace('http:', 'ws:') + '/api/ws'+ with pytest.raises(InvalidStatus):+ async with connect(url + '?token=wrong'):+ pass+ async with connect(url + '?token=' + web._SESSION_TOKEN) as ws:+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'session.create',+ 'params': {'request_id': 'token-create', 'source': 'cli'}}))+ async with asyncio.timeout(10):+ while True:+ reply = json.loads(await ws.recv())+ if reply.get('id') == 1:+ break+ assert 'result' in reply, reply+ unbound = AuthorityConnection(runner.session_authority, object(), {})+ try:+ assert not unbound.actor.capabilities+ finally:+ await unbound.close()+ finally:+ await runner.stop()+ await runner.session_control_server.stop()+ process_ownership.close()++- @pytest.mark.linux_only[email protected]("linux")[email protected]('layout', ['normal', 'long', 'unicode', 'long-temp'])+def test_ordinary_daemon_keeps_control_auth_and_loop_witness(tmp_path, layout):+ from gateway.control_socket import identify_gateway, resolve_client_socket_path+ from gateway.shutdown_watchdog import get_loop_tick_socket_path+ from hermes_cli.gateway import probe_gateway_loop_liveness++ async def create(origin, token):+ url = origin.replace('http:', 'ws:') + '/api/ws'+ with pytest.raises(InvalidStatus):+ async with connect(url + '?token=wrong'):+ pass+ async with connect(url + '?token=' + token) as ws:+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'session.create',+ 'params': {'request_id': 'daemon-token', 'source': 'cli'}}))+ async with asyncio.timeout(15):+ while True:+ reply = json.loads(await ws.recv())+ if reply.get('id') == 1:+ assert 'result' in reply, reply+ return reply['result']['session_id']++ # A normal-path control, not a substitute for the deliberately long cases.+ with tempfile.TemporaryDirectory(prefix='hgw-') as short:+ if layout == 'normal':+ home = Path(short)+ elif layout == 'unicode':+ # The character count fits even though the encoded tick address does not.+ home = Path(short) / ('界' * 20)+ else:+ home = tmp_path / ('x' * 120)+ home.mkdir(mode=0o700, exist_ok=True)+ user = tmp_path / 'user'+ user.mkdir()+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'local-wire-stub',+ 'base_url': 'http://127.0.0.1:1/v1'},+ 'terminal': {'cwd': str(tmp_path)},+ 'platform_toolsets': {'cli': []},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ root = Path(__file__).resolve().parents[2]+ token = secrets.token_urlsafe(32)+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1', HERMES_DASHBOARD_SESSION_TOKEN=token)+ if layout == 'long-temp':+ temp = tmp_path / ('t' * 120)+ temp.mkdir()+ env['TMPDIR'] = str(temp)+ with (tmp_path / 'daemon.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ control_path = None+ try:+ descriptor = {}+ deadline = time.monotonic() + 35+ while process.poll() is None and time.monotonic() < deadline:+ descriptor = identify_gateway(home) or {}+ if descriptor.get('state') == 'ready':+ break+ time.sleep(.05)+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ assert descriptor['pid'] == process.pid+ control_path = resolve_client_socket_path(home)+ assert control_path is not None+ assert control_path.stat().st_mode & 0o077 == 0+ if control_path.parent != home:+ assert control_path.parent.stat().st_mode & 0o077 == 0+ sid = asyncio.run(create(descriptor['api_origin'], token))+ heartbeat = home / 'state' / 'gateway.heartbeat'+ while not heartbeat.exists() and time.monotonic() < deadline:+ time.sleep(.05)+ payload = json.loads(heartbeat.read_text())+ tick_path = get_loop_tick_socket_path(home, process.pid)+ receipt = {'layout': layout, 'home_bytes': len(os.fsencode(home)),+ 'tick_chars': len(str(tick_path)), 'tick_bytes': len(os.fsencode(tick_path)),+ 'control': str(control_path), 'created_session': sid,+ 'loop_tick_socket': payload['loop_tick_socket'],+ 'loop_tick_tcp_port': payload['loop_tick_tcp_port']}+ print(json.dumps(receipt))+ assert payload['loop_tick_socket'] is True, receipt+ port = payload['loop_tick_tcp_port']+ address = ('127.0.0.1', port) if port else str(get_loop_tick_socket_path(home, process.pid))+ with socket.socket(socket.AF_INET if port else socket.AF_UNIX) as peer:+ peer.settimeout(2)+ peer.connect(address)+ assert peer.recv(1) == b'1'+ # A fresh heartbeat alone must not hide a missing scheduling witness.+ assert probe_gateway_loop_liveness(process.pid, home=home, stale_after=0) == 'alive'+ process.send_signal(signal.SIGINT)+ assert process.wait(timeout=20) == 0+ assert not control_path.exists()+ assert not (home / 'gateway.sock.path').exists()+ if port:+ with socket.socket() as peer:+ peer.settimeout(2)+ assert peer.connect_ex(address) != 0+ else:+ assert not get_loop_tick_socket_path(home, process.pid).exists()+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=15)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+ if control_path is not None and control_path.parent != home:+ control_path.parent.rmdir()diff --cc tests/gateway/test_runtime_writer_drain.pyindex ce509b6698b,00000000000..0304edf6283mode 100644,000000..100644--- a/tests/gateway/test_runtime_writer_drain.py+++ b/tests/gateway/test_runtime_writer_drain.py@@@ -1,82 -1,0 +1,82 @@@+"""Real startup threads retain runtime exclusion after a drain deadline."""+import asyncio+import os+import subprocess+import sys+import threading+from types import SimpleNamespace++import pytest++- @pytest.mark.linux_only[email protected]("linux")[email protected]('partial_start', [False, True])+def test_live_runtime_writers_prevent_final_lock_release(tmp_path, monkeypatch, partial_start):+ import gateway.run as run+ from gateway.run_bootstrap import _start_gateway_start_cron_and_housekeeping+ from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock+ from cron import scheduler_provider++ home = tmp_path / 'runtime'+ home.mkdir()+ monkeypatch.setenv('HERMES_HOME', str(home))+ gate = threading.Event()+ started = threading.Event()+ threads = []++ class Provider:+ name = 'fixture'+ def start(self, stop, **kwargs):+ started.set()+ gate.wait(20)++ provider = Provider()+ monkeypatch.setattr(scheduler_provider, 'resolve_cron_scheduler', lambda: provider)+ monkeypatch.setattr(scheduler_provider, 'scheduler_for_profile_mode', lambda p, **kw: p)+ monkeypatch.setattr(run, '_start_gateway_housekeeping', lambda *a, **kw: gate.wait(20))+ original_start = threading.Thread.start++ def start_thread(thread):+ if thread.name == 'gateway-housekeeping' and partial_start:+ raise RuntimeError('owned thread-start failure')+ threads.append(thread)+ return original_start(thread)++ monkeypatch.setattr(threading.Thread, 'start', start_thread)+ runner = SimpleNamespace(config=SimpleNamespace(multiplex_profiles=False), adapters={})++ async def start():+ return _start_gateway_start_cron_and_housekeeping(runner)++ probe = '''+from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock+claimed = acquire_gateway_runtime_lock()+print('CLAIMED', claimed)+if claimed:+ release_gateway_runtime_lock()+'''++ def contender():+ result = subprocess.run([sys.executable, '-c', probe], env=os.environ.copy(),+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)+ assert result.returncode == 0, result.stderr+ return result.stdout.strip()++ assert acquire_gateway_runtime_lock()+ try:+ if partial_start:+ with pytest.raises(RuntimeError, match='owned thread-start failure'):+ asyncio.run(start())+ else:+ asyncio.run(start())+ assert started.wait(5)+ assert contender() == 'CLAIMED False'+ release_gateway_runtime_lock()+ assert contender() == 'CLAIMED False', 'final cleanup unlocked while a runtime writer survived'+ finally:+ gate.set()+ for thread in threads:+ thread.join(5)+ assert not thread.is_alive()+ release_gateway_runtime_lock()+ assert contender() == 'CLAIMED True'diff --cc tests/gateway/test_session_authority.pyindex 1e0b66f666a,00000000000..ee566562f33mode 100644,000000..100644--- a/tests/gateway/test_session_authority.py+++ b/tests/gateway/test_session_authority.py@@@ -1,70 -1,0 +1,70 @@@+"""Real messaging ingress and authenticated WS must share one warm agent."""++import json+import os+from pathlib import Path+import subprocess+import sys+import time++import pytest+++def test_messaging_then_authenticated_ws_reuses_live_agent(tmp_path):+ repo = Path(__file__).resolve().parents[2]+ home = tmp_path / "home"+ home.mkdir()+ state = tmp_path / "state"+ state.mkdir()+ # A fresh interpreter keeps import-time profile caches and background workers+ # away from both the user's state and pytest's process-global fixtures.+ env = {key: os.environ[key] for key in ("PATH", "SYSTEMROOT", "LANG", "TZ") if key in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state),+ PYTHONPATH=str(repo), PYTHONUNBUFFERED="1")+ result = subprocess.run(+ [sys.executable, str(Path(__file__).parent / "fixtures" / "shared_authority_peer.py")],+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100,+ )+ assert result.returncode == 0, result.stdout + "\n" + result.stderr+ receipt = json.loads((state / "receipt.json").read_text())+ print(json.dumps(receipt, indent=2))+ assert receipt["messaging_completed"], receipt+ assert receipt["unauthenticated_rejected"], receipt+ assert receipt["ws_completed"], receipt+ assert receipt["same_agent"], receipt++- @pytest.mark.linux_only[email protected]("linux")+def test_native_queue_survives_owner_kill_without_replaying_unknown(tmp_path):+ repo = Path(__file__).resolve().parents[2]+ home, state = tmp_path / 'home', tmp_path / 'state'+ home.mkdir()+ state.mkdir()+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state),+ PYTHONPATH=str(repo), PYTHONUNBUFFERED='1', AUTHORITY_PROBE_MODE='crash')+ command = [sys.executable, str(Path(__file__).parent / 'fixtures' / 'shared_authority_peer.py')]+ with (state / 'owner.log').open('w+') as log:+ child = subprocess.Popen(command, cwd=repo, env=env, stdin=subprocess.DEVNULL,+ stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 90+ while not (state / 'crash-ready.json').exists():+ if child.poll() is not None or time.monotonic() > deadline:+ log.seek(0)+ pytest.fail(log.read())+ time.sleep(0.05)+ child.kill()+ assert child.wait(timeout=10) < 0+ finally:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=10)+ env['AUTHORITY_PROBE_MODE'] = 'recover'+ for expected_calls in (1, 0):+ result = subprocess.run(command, cwd=repo, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=70)+ assert result.returncode == 0, result.stdout + '\n' + result.stderr+ receipt = json.loads((state / 'recovery-receipt.json').read_text())+ assert receipt['model_calls'] == expected_calls, receipt+ print(json.dumps(receipt, indent=2))diff --cc tests/gateway/test_session_busy_controls.pyindex 6b89ce462bc,00000000000..dd50d59dd65mode 100644,000000..100644--- a/tests/gateway/test_session_busy_controls.py+++ b/tests/gateway/test_session_busy_controls.py@@@ -1,185 -1,0 +1,185 @@@+"""Public owner controls never become a second admission or change the cached prefix."""+import asyncio+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+from pathlib import Path+import sqlite3+import threading++import pytest+from websockets.asyncio.client import connect++from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket+++class CorrectionModel(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ if messages:+ self.server.requests.append(body)+ text = next((m['content'] for m in reversed(messages) if m['role'] == 'user'), '')+ message = {'role': 'assistant', 'content': 'CONTROL_ACK'}+ finish = 'stop'+ if text in {'BLOCK_STEER', 'BLOCK_REDIRECT'}:+ self.server.blocked.set()+ self.server.release.wait(30)+ if text == 'BLOCK_STEER':+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'owned-tool', 'type': 'function', 'function': {+ 'name': 'terminal', 'arguments': json.dumps({'command': 'printf controls', 'timeout': 5})}}]}+ finish = 'tool_calls'+ payload = json.dumps({'id': 'controls', 'choices': [{'index': 0, 'message': message, 'finish_reason': finish}],+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}).encode()+ kind = 'application/json'+ if body.get('stream'):+ delta = dict(message)+ if 'tool_calls' in delta:+ delta['tool_calls'] = [dict(delta['tool_calls'][0], index=0)]+ payload = ('data: ' + json.dumps({'id': 'controls', 'choices': [{'index': 0, 'delta': delta,+ 'finish_reason': finish}]}) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ try:+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError):+ pass+++@contextmanager+def owner(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), CorrectionModel)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False}, 'display': {'busy_input_mode': 'steer'},+ 'model': {'provider': 'custom', 'default': 'controls-fixture', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1',+ HERMES_DASHBOARD_SESSION_TOKEN='other-controls-actor')+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ yield home, peer, desc+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+++def admissions(home):+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ return list(db.execute('SELECT request_id,status,seq FROM session_admissions ORDER BY seq'))+++async def settled(home):+ async with asyncio.timeout(40):+ while not admissions(home) or any(r[1] != 'terminal' for r in admissions(home)):+ await asyncio.sleep(.05)++- @pytest.mark.linux_only[email protected]("linux")+def test_busy_policy_is_authorized_session_scoped_and_not_inference(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ ids = []+ for name in ('a', 'b'):+ result = await rpc(ws, 'session.create', request_id=name, source='tui', toolsets=[])+ ids.append(result['result']['session_id'])+ config_before = (home / 'config.yaml').read_bytes()+ result = await rpc(ws, 'config.get', session_id=ids[0], key='busy')+ assert result.get('result', {}).get('value') == 'steer', result+ result = await rpc(ws, 'config.set', session_id=ids[0], key='busy', value='queue')+ assert result.get('result', {}).get('scope') == 'session', result+ async with websocket(home, desc) as viewer:+ assert (await rpc(viewer, 'config.get', session_id=ids[0], key='busy'))['result']['value'] == 'queue'+ assert (await rpc(ws, 'config.get', session_id=ids[1], key='busy'))['result']['value'] == 'steer'+ for method, params, reason in [+ ('config.get', {'session_id': ids[0], 'key': 'busy', 'profile': 'foreign'}, 'profile_mismatch'),+ ('config.set', {'key': 'busy', 'value': 'queue'}, 'invalid_params'),+ ('config.set', {'session_id': ids[0], 'key': 'model', 'value': 'other'}, 'invalid_params'),+ ]:+ result = await rpc(ws, method, **params)+ assert result.get('error', {}).get('message') == reason, result+ other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'+ async with connect(other_url) as other:+ for method in ('config.get', 'config.set'):+ params = {'value': 'queue'} if method == 'config.set' else {}+ result = await rpc(other, method, session_id=ids[0], key='busy', **params)+ # This configured dashboard token is another verified operator.+ assert result.get('result') == {+ 'key': 'busy', 'value': 'queue', 'scope': 'session'}, result+ assert (await rpc(ws, 'config.get', session_id=ids[0], key='busy'))['result']['value'] == 'queue'+ assert (await rpc(ws, 'config.get', session_id=ids[1], key='busy'))['result']['value'] == 'steer'+ assert (home / 'config.yaml').read_bytes() == config_before+ assert not admissions(home) and not peer.requests+ asyncio.run(probe())++- @pytest.mark.linux_only[email protected]("linux")+def test_corrections_are_generation_fenced_and_consumed_by_same_provider_loop(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='controls', source='tui', toolsets=['terminal'])+ sid = created['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM')+ await settled(home)+ for verb, status in [('steer', 'queued'), ('redirect', 'redirected')]:+ peer.blocked.clear()+ peer.release.clear()+ await rpc(ws, 'prompt.submit', session_id=sid, input_id=verb, text='BLOCK_' + verb.upper())+ assert await asyncio.to_thread(peer.blocked.wait, 25)+ snapshot = (await rpc(ws, 'session.resume', session_id=sid))['result']+ generation = snapshot['execution_generation']+ for extra, reason in [({'execution_generation': generation - 1}, 'stale_generation'),+ ({'profile': 'foreign'}, 'profile_mismatch')]:+ params = {'session_id': sid, 'text': 'DENIED_MARKER', 'execution_generation': generation, **extra}+ denied = await rpc(ws, 'session.' + verb, **params)+ assert denied.get('error', {}).get('message') == reason, denied+ other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'+ async with connect(other_url) as other:+ # Operator sharing does not bypass the execution-generation fence.+ denied = await rpc(other, 'session.' + verb, session_id=sid,+ execution_generation=generation - 1, text='DENIED_MARKER')+ assert denied.get('error', {}).get('message') == 'stale_generation', denied+ result = await rpc(other, 'session.' + verb, session_id=sid,+ execution_generation=generation, text='CORRECT_' + verb.upper())+ assert result.get('result', {}).get('status') == status, result+ assert result['result']['execution_generation'] == generation+ queue = await rpc(ws, 'prompt.submit', session_id=sid, input_id=verb + '-queue', text='FIFO_' + verb.upper())+ assert queue['result']['status'] == 'queued'+ peer.release.set()+ await settled(home)+ corrected = [r for r in peer.requests if 'CORRECT_' + verb.upper() in json.dumps(r['messages'])]+ assert corrected, peer.requests+ assert not any('DENIED_MARKER' in json.dumps(r) for r in peer.requests)+ stale = await rpc(ws, 'session.' + verb, session_id=sid,+ execution_generation=generation, text='TOO_LATE')+ assert stale.get('error', {}).get('message') == 'stale_generation', stale+ assert [r[0] for r in admissions(home)] == ['warm', 'steer', 'steer-queue', 'redirect', 'redirect-queue']+ prefixes = [[m for m in r['messages'] if m['role'] in {'system', 'developer'}] for r in peer.requests]+ assert prefixes and all(p == prefixes[0] for p in prefixes)+ tools = [r.get('tools') for r in peer.requests]+ assert all(t == tools[0] for t in tools)+ print(json.dumps({'ledger': admissions(home), 'model_requests': len(peer.requests),+ 'same_prefix': True, 'corrections_consumed': True}))+ asyncio.run(probe())diff --cc tests/gateway/test_session_commands.pyindex c47fd87479b,00000000000..99add7458b6mode 100644,000000..100644--- a/tests/gateway/test_session_commands.py+++ b/tests/gateway/test_session_commands.py@@@ -1,172 -1,0 +1,172 @@@+"""Local slash resolution is not another execution owner."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import signal+import sqlite3+import threading+from types import SimpleNamespace++import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus++from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket++- @pytest.mark.linux_only[email protected]("linux")+def test_ordinary_daemon_slash_skill_uses_durable_fifo(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'slash-fixture', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'quick_commands': {'probe-quick': {'type': 'alias', 'target': '/probe-skill'}},+ }))+ skill = home / 'skills' / 'probe-skill'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text(+ '---\nname: probe-skill\ndescription: Disposable slash fixture\n---\n'+ '# Probe\nSLASH_SKILL_BODY: follow this owned fixture instruction.\n')+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1',+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url,+ HERMES_DASHBOARD_SESSION_TOKEN='owned-slash-negative')+ receipts = []++ def rows():+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ return list(db.execute('SELECT request_id,status,seq FROM session_admissions ORDER BY seq'))++ async def probe(desc):+ with pytest.raises(InvalidStatus):+ async with connect(desc['api_origin'].replace('http:', 'ws:') + '/api/ws'):+ pass+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='slash', source='gui', toolsets=[])+ sid = created['result']['session_id']++ async def command(method='slash.exec', **params):+ result = await rpc(ws, method, session_id=sid, **params)+ receipts.append(result)+ return result++ help_reply = await command(command='help')+ assert help_reply.get('result', {}).get('output'), help_reply+ for read_command in ('commands', 'context', 'version', 'whoami'):+ read_reply = await command(command=read_command)+ assert read_reply.get('result', {}).get('output'), read_reply+ status = await command(command='status')+ assert sid in status['result']['output'], status+ for method, params in [('slash.exec', {'command': 'probe-quick TASK_ONE'}),+ ('command.dispatch', {'name': 'probe-skill', 'arg': 'TASK_TWO'})]:+ result = await command(method, **params)+ assert result.get('result', {}).get('type') == 'skill', result+ assert 'SLASH_SKILL_BODY' in result['result']['message'], result+ assert 'SLASH_SKILL_BODY' not in result['result']['display'], result+ assert not peer.requests and not rows(), 'resolution executed a turn'+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM_SLASH')+ async with asyncio.timeout(30):+ while not rows() or rows()[0][1] != 'terminal':+ await asyncio.sleep(.05)+ block = await rpc(ws, 'prompt.submit', session_id=sid, input_id='block', text='BLOCK_STARTED')+ assert block.get('result', {}).get('status') == 'queued', block+ assert await asyncio.to_thread(peer.blocked.wait, 25), ([m for r in peer.requests for m in r['messages'] if m['role'] == 'user'], rows())+ for index, marker in enumerate(('TASK_ONE', 'TASK_TWO')):+ directive = await command(command='probe-quick ' + marker)+ admitted = await rpc(ws, 'prompt.submit', session_id=sid,+ input_id=marker, text=directive['result']['message'])+ receipts.append(admitted)+ assert admitted['result']['status'] == 'queued', admitted+ retry = await rpc(ws, 'prompt.submit', session_id=sid,+ input_id=marker, text=directive['result']['message'])+ assert retry['result']['admission_id'] == admitted['result']['admission_id']+ assert [r[:2] for r in rows()] == [('warm', 'terminal'), ('block', 'started'), ('TASK_ONE', 'queued'), ('TASK_TWO', 'queued')]+ busy_title = await command(command='title forbidden-while-busy')+ assert 'mid-turn' in busy_title['result']['output'], busy_title+ for params, reason in [({'command': 'help', 'profile': 'foreign'}, 'profile_mismatch'),+ ({'command': 'help', 'source': 'telegram'}, 'invalid_params'),+ ({'command': 'restart'}, 'unsupported_command'),+ ({'command': 'approve'}, 'unsupported_command')]:+ denied = await command(**params)+ assert denied['error']['message'] == reason, denied+ # A second dashboard operator shares access but still obeys the busy fence.+ other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=owned-slash-negative'+ async with connect(other_url) as other:+ for method, payload in [('slash.exec', {'command': 'title stolen'}),+ ('command.dispatch', {'name': 'title', 'arg': 'stolen'})]:+ result = await rpc(other, method, session_id=sid, **payload)+ receipts.append(result)+ assert 'mid-turn' in result.get('result', {}).get('output', ''), result+ peer.release.set()+ async with asyncio.timeout(45):+ while any(row[1] != 'terminal' for row in rows()):+ await asyncio.sleep(.05)+ title = await command(command='title Owned slash title')+ assert 'Owned slash title' in title['result']['output'], title+ listing = await rpc(ws, 'session.list')+ assert next(r for r in listing['result']['sessions'] if r['id'] == sid)['title'] == 'Owned slash title'+ snapshot = await rpc(ws, 'session.resume', session_id=sid)+ assert 'TASK_TWO' in json.dumps(snapshot['result']['messages']), snapshot+ receipts.append({'session_id': sid, 'ledger': rows(), 'history': snapshot['result']['messages']})+ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ asyncio.run(probe(desc))+ texts = [next(m['content'] for m in reversed(r['messages']) if m['role'] == 'user') for r in peer.requests]+ assert len(texts) == 4 and texts[1] == 'BLOCK_STARTED', texts+ assert 'TASK_ONE' in texts[2] and 'TASK_TWO' in texts[3], texts+ systems = [[m for m in r['messages'] if m['role'] == 'system'] for r in peer.requests]+ assert systems[1] == systems[2] == systems[3], 'slash invalidated cached system prefix'+ proc.send_signal(signal.SIGINT)+ assert proc.wait(timeout=20) == 0+ print(json.dumps({'pid': proc.pid, 'exit': proc.returncode, 'descriptor': desc,+ 'wire_receipts': receipts, 'model_texts': texts,+ 'system_prefix_unchanged': True, 'unauthenticated_ws_rejected': True}))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+++async def test_command_authority_precedes_resolution_and_mutation(tmp_path, monkeypatch):+ from gateway.config import Platform+ from gateway.session import SessionSource+ from gateway.session_authority import SessionAuthority, LiveSession+ from gateway.session_controls import AuthorityConnection+ from agent import skill_commands++ runner = SimpleNamespace(_draining=False)+ authority = SessionAuthority(runner, profile_id=str(tmp_path), instance_id='owned', db=None, epoch=1)+ source = SessionSource(platform=Platform.LOCAL, chat_id='local-test', user_id='owner')+ authority.sessions['local-test'] = LiveSession(source, 'route')+ def forbidden(*args, **kwargs):+ pytest.fail('unauthorized command reached skill resolution')+ monkeypatch.setattr(skill_commands, 'get_skill_commands', forbidden)+ for identity, command, reason in [+ ({'user_id': 'owner', 'capabilities': ['session:read']}, 'title mutated', 'permission_denied'),+ ({'user_id': 'owner', 'capabilities': ['session:read']}, 'private-skill', 'permission_denied'),+ ({'user_id': 'other'}, 'help', 'permission_denied'),+ ({'user_id': 'owner', 'profile_id': 'foreign'}, 'help', 'profile_mismatch'),+ ({'user_id': 'owner', 'instance_id': 'stale'}, 'help', 'permission_denied'),+ ]:+ connection = AuthorityConnection(authority, object(), identity)+ for method, payload in [('slash.exec', {'command': command}),+ ('command.dispatch', {'name': command.split()[0], 'arg': 'mutated'})]:+ result = await connection.dispatch({'id': 1, 'method': method,+ 'params': {'session_id': 'local-test', **payload}})+ assert result.get('error', {}).get('message') == reason, result+ await connection.close()diff --cc tests/gateway/test_session_config_projection.pyindex 5e923e9b1bd,00000000000..72571d299c1mode 100644,000000..100644--- a/tests/gateway/test_session_config_projection.py+++ b/tests/gateway/test_session_config_projection.py@@@ -1,88 -1,0 +1,88 @@@+"""Native config/model reads cross the authenticated owner without executing."""+import asyncio+import json++import pytest+from websockets.asyncio.client import connect++from tests.gateway.test_session_busy_controls import owner, admissions+from tests.gateway.fixtures.local_recovery_probe import rpc, websocket++- @pytest.mark.linux_only[email protected]("linux")+def test_client_config_projection_keeps_session_policy_and_secrets_private(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ sid = (await rpc(ws, 'session.create', request_id='config', source='tui',+ toolsets=[], reasoning='low'))['result']['session_id']- import yaml++ import hermes_yaml as yaml+ config = yaml.safe_load((home / 'config.yaml').read_text())+ config.update(voice={'record_key': 'ctrl+r', 'submit_mode': 'draft', 'api_key': 'PRIVATE_VOICE'},+ paste_collapse_threshold=12)+ config['display'].update(tui_theme='light', bell_on_complete=True)+ config['approvals'] = {'mode': 'manual'}+ (home / 'config.yaml').write_text(yaml.safe_dump(config))+ before = (home / 'config.yaml').read_bytes()+ full = await rpc(ws, 'config.get', key='full', session_id=sid)+ assert full.get('result', {}).get('config', {}).get('voice', {}).get('record_key') == 'ctrl+r', full+ assert 'PRIVATE_VOICE' not in json.dumps(full)+ assert full['result']['config']['display']['bell_on_complete'] is True+ mtime = (await rpc(ws, 'config.get', key='mtime', session_id=sid))['result']+ assert mtime['mtime'] > 0 and mtime['mcp_rev']+ config['mcp_servers'] = {'later': {'command': 'not-started'}}+ (home / 'config.yaml').write_text(yaml.safe_dump(config))+ before = (home / 'config.yaml').read_bytes()+ assert (await rpc(ws, 'config.get', key='mtime', session_id=sid))['result']['mcp_rev'] == mtime['mcp_rev']+ assert (await rpc(ws, 'config.get', key='full'))['result']['config']['voice']['record_key'] == 'ctrl+r'+ assert (await rpc(ws, 'config.get', key='reasoning', session_id=sid))['result']['value'] == 'low'+ assert (await rpc(ws, 'config.get', key='project', session_id=sid, cwd=str(home)))['result']['cwd'] == str(home)+ assert (await rpc(ws, 'config.get', key='approvals.mode'))['result']['value'] == 'manual'+ assert (await rpc(ws, 'config.get', key='theme'))['result']['value'] == 'light'+ assert (await rpc(ws, 'config.set', key='busy', session_id=sid, value='queue'))['result']['value'] == 'queue'+ assert (await rpc(ws, 'config.get', key='busy', session_id=sid))['result']['value'] == 'queue'+ for method, params, reason in [+ ('config.get', {'key': 'full', 'profile': 'foreign'}, 'profile_mismatch'),+ ('config.get', {'key': 'full', 'session_id': sid, 'source': 'gui'}, 'invalid_params'),+ ('config.set', {'key': 'model', 'session_id': sid, 'value': 'other'}, 'invalid_params'),+ ]:+ assert (await rpc(ws, method, **params))['error']['message'] == reason+ other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'+ async with connect(other_url) as other:+ # Verified dashboard operators receive the same redacted projection.+ shared = await rpc(other, 'config.get', key='full', session_id=sid)+ current = await rpc(ws, 'config.get', key='full', session_id=sid)+ assert 'result' in shared, shared+ assert shared['result'] == current['result']+ assert 'PRIVATE_VOICE' not in json.dumps(shared)+ assert (await rpc(other, 'config.get', key='reasoning', session_id=sid))['result']['value'] == 'low'+ assert (home / 'config.yaml').read_bytes() == before+ assert not admissions(home) and not peer.requests+ asyncio.run(probe())++- @pytest.mark.linux_only[email protected]("linux")+def test_model_options_uses_frozen_selection_without_composer_global_writes(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ sid = (await rpc(ws, 'session.create', request_id='picker', source='tui',+ model='frozen-picker', toolsets=[]))['result']['session_id']+ before = (home / 'config.yaml').read_bytes()+ result = await rpc(ws, 'model.options', session_id=sid, include_unconfigured=True)+ assert result.get('result', {}).get('model') == 'frozen-picker', result+ assert result['result']['providers']+ assert all('slug' in row and isinstance(row['models'], list) for row in result['result']['providers'])+ assert 'loopback-only' not in json.dumps(result)+ assert (await rpc(ws, 'model.options', session_id=sid, profile='foreign'))['error']['message'] == 'profile_mismatch'+ assert (await rpc(ws, 'model.options', session_id=sid, refresh='yes'))['error']['message'] == 'invalid_params'+ other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'+ async with connect(other_url) as other:+ shared = await rpc(other, 'model.options', session_id=sid)+ current = await rpc(ws, 'model.options', session_id=sid)+ assert shared.get('result', {}).get('model') == 'frozen-picker', shared+ assert shared['result'] == current['result']+ assert 'loopback-only' not in json.dumps(shared)+ assert (home / 'config.yaml').read_bytes() == before+ assert not admissions(home) and not peer.requests+ asyncio.run(probe())diff --cc tests/gateway/test_session_mutation_branch.pyindex e50007bda0d,00000000000..40e2db17895mode 100644,000000..100644--- a/tests/gateway/test_session_mutation_branch.py+++ b/tests/gateway/test_session_mutation_branch.py@@@ -1,65 -1,0 +1,65 @@@+"""Branches are independent frozen local owners, never route aliases."""+import asyncio+import json+import sqlite3++import pytest+from websockets.asyncio.client import connect+from tests.gateway.test_native_http_auth import daemon, ticket+++async def branch_round(home, descriptor, previous=None):+ async with connect(descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws', subprotocols=[+ 'hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket(home, descriptor, 'interactive')]) as ws:+ async def rpc(method, **params):+ await ws.send(json.dumps({'id': 1, 'method': method, 'params': params}))+ while True:+ result = json.loads(await ws.recv())+ if result.get('id') == 1:+ return result+ if previous is None:+ created = await rpc('session.create', request_id='branch-owner', source='gui', toolsets=[])+ sid = created['result']['session_id']+ params = dict(session_id=sid, request_id='branch', expected_revision=0,+ expected_generation=0, operation='branch', payload={})+ else:+ params, receipt = previous+ response = await rpc('session.mutate', **params)+ assert 'result' in response, response+ if previous:+ assert response['result'] == receipt+ receipt = response['result']+ child = receipt['branched_session_id']+ assert child != params['session_id']+ if previous is None:+ # The branching viewer owns the child it just created: a submit on the+ # same connection is admitted without an explicit resume first (create parity).+ admitted = await rpc('prompt.submit', session_id=child, input_id='first-child-input', text='FIRST_CHILD_INPUT')+ assert admitted.get('result', {}).get('status') == 'queued', admitted+ for sid in (child, params['session_id']):+ resumed = await rpc('session.resume', session_id=sid)+ assert 'result' in resumed, resumed+ stale = await rpc('session.mutate', **(params | {'request_id': 'stale-branch'}))+ assert stale['error']['message'] == 'revision_conflict'+ changed = await rpc('session.mutate', **(params | {'payload': {'title': 'changed'}}))+ assert changed['error']['message'] == 'admission_conflict'+ return params, receipt++- @pytest.mark.linux_only[email protected]("linux")+def test_branch_route_and_frozen_policy_survive_owner_restart(tmp_path):+ with daemon(tmp_path) as (home, descriptor):+ previous = asyncio.run(branch_round(home, descriptor))+ sid = previous[0]['session_id']+ child = previous[1]['branched_session_id']+ with sqlite3.connect(home / 'state.db') as db:+ policies = [json.loads(db.execute('SELECT value FROM state_meta WHERE key=?',+ ('gateway.local_policy.v1:' + s,)).fetchone()[0]) for s in (sid, child)]+ assert policies[0]['policy'] == policies[1]['policy']+ assert policies[0]['principal_id'] == policies[1]['principal_id']+ assert policies[0]['route'] != policies[1]['route']+ assert db.execute('SELECT parent_session_id FROM sessions WHERE id=?', (child,)).fetchone()[0] == sid+ # An untitled branch is its own titled sidebar row (next name in the parent's lineage).+ assert db.execute('SELECT title FROM sessions WHERE id=?', (child,)).fetchone()[0]+ with daemon(tmp_path) as (home, descriptor):+ assert asyncio.run(branch_round(home, descriptor, previous)) == previousdiff --cc tests/gateway/test_session_mutation_cold.pyindex 41d1fdd77cf,00000000000..d79e0507cc1mode 100644,000000..100644--- a/tests/gateway/test_session_mutation_cold.py+++ b/tests/gateway/test_session_mutation_cold.py@@@ -1,29 -1,0 +1,29 @@@+"""Cold history authorization does not manufacture an execution route."""+import asyncio+import httpx+import pytest+from tests.gateway.test_native_http_auth import daemon, ticket, headers+from tests.gateway.test_session_mutation_retirement import create++- @pytest.mark.linux_only[email protected]("linux")+def test_cold_import_mutation_binds_owner_across_restart(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ # Native creation remains independently authorized while cold history binds.+ asyncio.run(create(home, descriptor))+ response = client.post('/api/sessions/import', headers=headers(ticket(home, descriptor)), json={+ 'request_id': 'import', 'expected_revision': 0, 'sessions': [+ {'id': 'cold', 'source': 'cli', 'messages': [{'role': 'user', 'content': 'history'}]}]})+ assert response.status_code == 200, response.text+ snapshot = client.get('/api/sessions/cold/mutation-snapshot', headers=headers(ticket(home, descriptor)))+ assert snapshot.status_code == 200, snapshot.text+ body = {'request_id': 'edit', 'expected_revision': snapshot.json()['runtime_revision'], 'title': 'Cold history'}+ edited = client.patch('/api/sessions/cold', headers=headers(ticket(home, descriptor)), json=body)+ assert edited.status_code == 200, edited.text+ stale = client.patch('/api/sessions/cold', headers=headers(ticket(home, descriptor)), json=body | {'request_id': 'competitor', 'title': 'stale'})+ assert stale.status_code == 409 and 'revision_conflict' in stale.text+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ assert client.patch('/api/sessions/cold', headers=headers(ticket(home, descriptor)), json=body).json() == edited.json()+ assert client.get('/api/sessions/cold/mutation-snapshot', headers=headers(ticket(home, descriptor))).status_code == 200+ denied = client.patch('/api/sessions/cold', headers={'Authorization': 'Bearer normal-http-owner'}, json=body | {'request_id': 'foreign'})+ assert denied.status_code == 403, denied.textdiff --cc tests/gateway/test_session_mutation_import_owner.pyindex 76a2099863c,00000000000..f111f69a4f2mode 100644,000000..100644--- a/tests/gateway/test_session_mutation_import_owner.py+++ b/tests/gateway/test_session_mutation_import_owner.py@@@ -1,19 -1,0 +1,19 @@@+"""The importer owns cold control before another authenticated actor can claim it."""+import httpx+import pytest+from tests.gateway.test_native_http_auth import daemon, ticket, headers++- @pytest.mark.linux_only[email protected]("linux")+def test_import_atomically_binds_each_new_history_to_its_importer(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ response = client.post('/api/sessions/import', headers=headers(ticket(home, descriptor)), json={+ 'request_id': 'owned-import', 'expected_revision': 0, 'sessions': [+ {'id': 'cli-import', 'source': 'cli'}, {'id': 'foreign-import', 'source': 'telegram'}]})+ assert response.status_code == 200, response.text+ for sid in ('cli-import', 'foreign-import'):+ body = {'request_id': 'edit', 'expected_revision': 1, 'title': sid}+ stolen = client.patch('/api/sessions/' + sid, headers={'Authorization': 'Bearer normal-http-owner'}, json=body)+ assert stolen.status_code == 403, stolen.text+ owned = client.patch('/api/sessions/' + sid, headers=headers(ticket(home, descriptor)), json=body)+ assert owned.status_code == 200, owned.textdiff --cc tests/gateway/test_session_mutation_lineage_delete.pyindex 5da34de2675,00000000000..356acbfcb99mode 100644,000000..100644--- a/tests/gateway/test_session_mutation_lineage_delete.py+++ b/tests/gateway/test_session_mutation_lineage_delete.py@@@ -1,27 -1,0 +1,27 @@@+"""Deleting a logical local owner retires its current physical transcript too."""+import asyncio+import json+import sqlite3+import httpx+import pytest+from tests.gateway.test_native_http_auth import daemon, ticket, headers+from tests.gateway.test_session_mutation_reset import reset_round++- @pytest.mark.linux_only[email protected]("linux")+def test_delete_after_reset_covers_physical_route_and_cache_generation(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ params, reset = asyncio.run(reset_round(home, descriptor))+ sid = params['session_id']+ target = reset['target_session_id']+ with sqlite3.connect(home / 'state.db') as db:+ route, source = db.execute('SELECT session_key,source FROM sessions WHERE id=?', (target,)).fetchone()+ before = db.execute('SELECT generation FROM conversation_generations WHERE source=? AND session_key=?', (source, route)).fetchone()[0]+ response = client.delete('/api/sessions/' + sid, params={'request_id': 'delete-reset',+ 'expected_revision': reset['revision'], 'expected_generation': reset['execution_generation']}, headers=headers(ticket(home, descriptor)))+ assert response.status_code == 200, response.text+ assert set(response.json()['deleted_ids']) == {sid, target}+ with sqlite3.connect(home / 'state.db') as db:+ assert db.execute('SELECT COUNT(*) FROM sessions WHERE id IN (?,?)', (sid, target)).fetchone()[0] == 0+ assert not any(json.loads(row[0])['session_id'] in {sid,target} for row in db.execute('SELECT entry_json FROM gateway_routing'))+ assert db.execute('SELECT generation FROM conversation_generations WHERE source=? AND session_key=?', (source, route)).fetchone()[0] > beforediff --cc tests/gateway/test_session_mutation_model.pyindex 90ad8c2fb19,00000000000..d2aa609d01dmode 100644,000000..100644--- a/tests/gateway/test_session_mutation_model.py+++ b/tests/gateway/test_session_mutation_model.py@@@ -1,105 -1,0 +1,105 @@@+"""Explicit model changes cross the real provider wire, not profile defaults."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++import pytest+from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket+++class CatalogModel(Model):+ def do_GET(self):+ payload = json.dumps({'data': [{'id': name} for name in ('original', 'switched')]}).encode()+ self.send_response(200)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++- @pytest.mark.linux_only[email protected]("linux")+def test_model_receipt_changes_next_wire_and_branch_keeps_independent_history(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), CatalogModel)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ cfg = {'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'original', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ (home / 'models_dev_cache.json').write_text(json.dumps({'custom': {'id': 'custom', 'models': {+ name: {'id': name, 'name': name, 'limit': {'context': 100000, 'output': 4000}}+ for name in ('original', 'switched')}}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')++ async def run(desc):+ async with websocket(home, desc) as ws:+ async def call(method, **params):+ response = await rpc(ws, method, **params)+ assert 'result' in response, response+ return response['result']+ async def turn(sid, text):+ await call('prompt.submit', session_id=sid, input_id=text, text=text)+ async with asyncio.timeout(30):+ while True:+ with sqlite3.connect(home / 'state.db') as db:+ status = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (text,)).fetchone()+ if status and status[0] == 'terminal':+ return await call('session.resume', session_id=sid)+ await asyncio.sleep(.03)+ sid = (await call('session.create', source='cli', request_id='owner', toolsets=[]))['session_id']+ before = await turn(sid, 'ORIGINAL_HISTORY')+ params = dict(session_id=sid, request_id='switch', operation='model', payload={'model': 'switched'},+ expected_revision=before['revision'], expected_generation=before['execution_generation'])+ from hermes_cli.gateway_chat_view import GatewayChatView+ from acp_adapter.gateway_server import GatewayACPAgent+ class Client:+ async def rpc(self, method, **kwargs):+ return await call(method, **kwargs)+ client = Client()+ view = GatewayChatView(client, before)+ await view.command('/model switched')+ result = await call('session.info', session_id=sid)+ assert result['model'] == 'switched'+ after = await turn(sid, 'AFTER_SWITCH')+ assert peer.requests[-1]['model'] == 'switched'+ assert peer.requests[0]['model'] == 'original'+ agent = GatewayACPAgent()+ agent._gateway = client+ agent._snapshots[sid] = after+ fork = await agent.fork_session(cwd=(await call('session.info', session_id=sid))['cwd'], session_id=sid)+ child = fork.session_id+ branched = await call('session.resume', session_id=child)+ assert branched['messages'] == after['messages']+ await turn(child, 'ONLY_BRANCH')+ parent = await call('session.resume', session_id=sid)+ assert 'ONLY_BRANCH' not in json.dumps(parent['messages'])+ assert peer.requests[-1]['model'] == 'switched'+ assert 'ORIGINAL_HISTORY' in json.dumps(peer.requests[-1]['messages'])+ return params, result+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ params, result = asyncio.run(run(desc))+ async def retry(desc):+ async with websocket(home, desc) as ws:+ info = await rpc(ws, 'session.info', session_id=params['session_id'])+ assert info['result']['model'] == 'switched'+ with daemon(root, home, env, barrier=False) as (_, desc):+ asyncio.run(retry(desc))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/gateway/test_session_mutation_reset.pyindex 824cf0e6565,00000000000..07522cbfb67mode 100644,000000..100644--- a/tests/gateway/test_session_mutation_reset.py+++ b/tests/gateway/test_session_mutation_reset.py@@@ -1,56 -1,0 +1,56 @@@+"""Reset commits the prepared physical target without changing logical ownership."""+import asyncio+import json+import sqlite3++import pytest+from websockets.asyncio.client import connect+from tests.gateway.test_native_http_auth import daemon, ticket+++async def reset_round(home, descriptor, previous=None):+ async with connect(descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws', subprotocols=[+ 'hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket(home, descriptor, 'interactive')]) as ws:+ async def rpc(method, **params):+ await ws.send(json.dumps({'id': 1, 'method': method, 'params': params}))+ while True:+ result = json.loads(await ws.recv())+ if result.get('id') == 1:+ return result+ if previous is None:+ created = await rpc('session.create', request_id='reset-owner', source='gui')+ sid = created['result']['session_id']+ params = dict(session_id=sid, request_id='reset', expected_revision=0,+ expected_generation=0, operation='reset', payload={})+ else:+ params, receipt = previous+ sid = params['session_id']+ response = await rpc('session.mutate', **params)+ assert 'result' in response, response+ if previous:+ assert response['result'] == receipt+ else:+ receipt = response['result']+ assert receipt['session_id'] == sid+ assert receipt['target_session_id'] != sid+ resumed = await rpc('session.resume', session_id=sid)+ assert 'result' in resumed, resumed+ stale = await rpc('session.mutate', **(params | {'request_id': 'stale-reset'}))+ assert stale['error']['message'] == 'revision_conflict'+ return params, receipt++- @pytest.mark.linux_only[email protected]("linux")+def test_reset_receipt_and_physical_target_survive_native_owner_restart(tmp_path):+ with daemon(tmp_path) as (home, descriptor):+ previous = asyncio.run(reset_round(home, descriptor))+ sid = previous[0]['session_id']+ target = previous[1]['target_session_id']+ with sqlite3.connect(home / 'state.db') as db:+ root = db.execute('SELECT runtime_revision,runtime_generation,end_reason FROM sessions WHERE id=?', (sid,)).fetchone()+ assert root == (previous[1]['revision'], previous[1]['execution_generation'], 'session_reset')+ assert db.execute('SELECT parent_session_id FROM sessions WHERE id=?', (target,)).fetchone()[0] == sid+ assert db.execute('SELECT COUNT(*) FROM messages WHERE session_id=?', (target,)).fetchone()[0] == 0+ with daemon(tmp_path) as (home, descriptor):+ assert asyncio.run(reset_round(home, descriptor, previous)) == previous+ print(json.dumps({'native_reset_restart': previous[1]}))diff --cc tests/gateway/test_session_mutation_retirement.pyindex 4199044ef6a,00000000000..82044f405e1mode 100644,000000..100644--- a/tests/gateway/test_session_mutation_retirement.py+++ b/tests/gateway/test_session_mutation_retirement.py@@@ -1,83 -1,0 +1,83 @@@+"""Native deletion retires routing and keeps only exact authorized retries."""+import asyncio+import json+import sqlite3++import httpx+import pytest+from websockets.asyncio.client import connect+from tests.gateway.test_native_http_auth import daemon, ticket, headers+++async def create(home, descriptor):+ async with connect(descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws',+ subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket(home, descriptor, 'interactive')]) as ws:+ await ws.send(json.dumps({'id': 1, 'method': 'session.create', 'params': {+ 'request_id': 'retirement', 'source': 'gui'}}))+ while True:+ response = json.loads(await ws.recv())+ if response.get('id') == 1:+ assert 'result' in response, response+ return response['result']['session_id']++- @pytest.mark.linux_only[email protected]("linux")+def test_native_delete_exact_retry_survives_owner_restart(tmp_path):+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ sid = asyncio.run(create(home, descriptor))+ path = '/api/sessions/' + sid+ snapshot = client.get(path + '/mutation-snapshot', headers=headers(ticket(home, descriptor))).json()+ params = dict(request_id='delete', expected_revision=snapshot['runtime_revision'],+ expected_generation=snapshot['runtime_generation'])+ deleted = client.delete(path, params=params, headers=headers(ticket(home, descriptor)))+ assert deleted.status_code == 200, deleted.text+ receipt = deleted.json()+ assert client.get(path, headers=headers(ticket(home, descriptor))).status_code == 404+ with sqlite3.connect(home / 'state.db') as db:+ assert not any(json.loads(row[0])['session_id'] == sid for row in db.execute('SELECT entry_json FROM gateway_routing'))+ assert client.delete(path, params=params, headers=headers(ticket(home, descriptor))).json() == receipt+ with daemon(tmp_path) as (home, descriptor), httpx.Client(base_url=descriptor['api_origin'], trust_env=False) as client:+ retry = client.delete(path, params=params, headers=headers(ticket(home, descriptor)))+ assert retry.status_code == 200 and retry.json() == receipt, retry.text+ changed = client.delete(path, params=params | {'expected_revision': 99}, headers=headers(ticket(home, descriptor)))+ assert changed.status_code == 409 and 'admission_conflict' in changed.text+ fresh = client.delete(path, params=params | {'request_id': 'different'}, headers=headers(ticket(home, descriptor)))+ assert fresh.status_code != 200+ foreign = client.delete(path, params=params, headers={'Authorization': 'Bearer normal-http-owner'})+ assert foreign.status_code != 200+ print(json.dumps({'native_delete_restart': receipt, 'changed_retry': changed.json(),+ 'fresh_request_status': fresh.status_code, 'foreign_status': foreign.status_code}))+++def test_route_retirement_rolls_back_with_receipt_and_rejects_stale_mirror(tmp_path):+ from gateway.config import GatewayConfig, Platform+ from gateway.session import SessionStore, SessionSource+ from hermes_state import SessionDB+ import hermes_state_runtime as rt+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ store._db = db+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='owned')+ entry = store.get_or_create_session(source)+ sid = entry.session_id+ if db.get_session(sid) is None:+ db.create_session(sid, source='telegram')+ serialized = json.dumps(entry.to_dict())+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ args = dict(epoch=epoch, principal_id='human', session_id=sid, request_id='delete',+ expected_revision=0, expected_generation=0, operation='delete', payload={})+ db._execute_write(lambda conn: conn.execute("CREATE TRIGGER reject_receipt BEFORE INSERT ON state_meta WHEN NEW.key LIKE 'gateway.mutation.v1.%' BEGIN SELECT RAISE(ABORT,'receipt unavailable'); END"))+ with pytest.raises(sqlite3.IntegrityError, match='receipt unavailable'):+ rt.mutate_runtime_session(db, **args)+ assert db.get_session(sid) is not None+ assert db.load_gateway_routing_entries(scope=store._routing_scope())+ db._execute_write(lambda conn: conn.execute('DROP TRIGGER reject_receipt'))+ rt.mutate_runtime_session(db, **args)+ assert not db.load_gateway_routing_entries(scope=store._routing_scope())+ db.save_gateway_routing_entry(entry.session_key, serialized, scope=store._routing_scope())+ db.replace_gateway_routing_entries({entry.session_key: serialized}, scope=store._routing_scope())+ assert not db.load_gateway_routing_entries(scope=store._routing_scope())+ # The pre-commit mirror remains on disk as in a crash before publication.+ restored = SessionStore(store.sessions_dir, GatewayConfig())+ restored._db = db+ assert restored.lookup_by_session_id(sid) is Nonediff --cc tests/gateway/test_shutdown_runtime_ownership.pyindex b7368098243,00000000000..fbe666605e2mode 100644,000000..100644--- a/tests/gateway/test_shutdown_runtime_ownership.py+++ b/tests/gateway/test_shutdown_runtime_ownership.py@@@ -1,58 -1,0 +1,58 @@@+"""Exit-state persistence is not the end of canonical writer lifetime."""+import asyncio+import os+import subprocess+import sys+from types import SimpleNamespace++import pytest++- @pytest.mark.linux_only[email protected]("linux")[email protected]('timed_out', [False, True])+def test_exit_state_keeps_runtime_reserved_until_final_cleanup(tmp_path, monkeypatch, timed_out):+ import gateway.run as run+ from gateway.run_shutdown import GatewayShutdownMixin+ from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock, write_pid_file, remove_pid_file++ home = tmp_path / 'runtime'+ home.mkdir()+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.setattr(run, '_hermes_home', home)+ states = []+ runner = SimpleNamespace(+ _restart_requested=False, _exit_reason=None, _restart_command_source=None,+ _restart_via_service=False, _restart_detached=False, _draining=True,+ _update_runtime_status=lambda *args: states.append(args),+ )+ ctx = SimpleNamespace(timed_out=timed_out, active_agents={}, elapsed=lambda: 0)+ probe = '''+from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock+claimed = acquire_gateway_runtime_lock()+print('CLAIMED', claimed)+if claimed:+ release_gateway_runtime_lock()+'''++ def contender():+ result = subprocess.run(+ [sys.executable, '-c', probe], cwd=os.getcwd(), env=os.environ.copy(),+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15,+ )+ assert result.returncode == 0, result.stderr+ return result.stdout.strip()++ assert acquire_gateway_runtime_lock()+ write_pid_file()+ try:+ assert contender() == 'CLAIMED False'+ # Async since main's launchd-budgeted status flush; ownership semantics are unchanged.+ asyncio.run(GatewayShutdownMixin._stop_persist_exit_state(runner, ctx))+ assert contender() == 'CLAIMED False', 'exit-state phase released ownership before writer drain'+ assert (home / 'gateway.pid').exists()+ assert (home / '.clean_shutdown').exists() is not timed_out+ assert states == [('stopped', None)]+ finally:+ remove_pid_file()+ release_gateway_runtime_lock()+ assert contender() == 'CLAIMED True'diff --cc tests/gateway/test_startup_model_context_warmup.pyindex 9ba2102ba41,9ba2102ba41..bba250e95da--- a/tests/gateway/test_startup_model_context_warmup.py+++ b/tests/gateway/test_startup_model_context_warmup.py@@@ -15,7 -15,7 +15,7 @@@ import gateway.run as gateway_rudef _quiet_tool_side(monkeypatch, tool_count):import model_tools-- monkeypatch.setattr(model_tools, "get_tool_definitions", lambda quiet_mode=False: ["t"] * tool_count)++ monkeypatch.setattr(model_tools, "get_tool_definitions", lambda quiet_mode=False, **_kw: ["t"] * tool_count)monkeypatch.setattr("hermes_cli.config.load_config_readonly", lambda: {"agent": {"environment_probe": False}})diff --cc tests/gateway/test_status.pyindex 5c688a3493b,e74c078901d..0feb7c29549--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@@ -1431,32 -1446,84 +1449,32 @@@ class TestLaunchdPlistRespawnGovernanceclass TestPermissionErrorOnLockFile:- @pytest.mark.linux_only- """Stale root-owned lock files from launchd Background sessions must not- crash the gateway on restart (issue #42685)."""-- def test_permission_error_on_lock_file_returns_false_and_removes(self, tmp_path, monkeypatch):- """When the lock file is not writable (root-owned), the function should- remove the stale file and report the lock as inactive."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = tmp_path / "gateway.lock"- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- if str(path) == str(lock_path):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)-- result = status.is_gateway_runtime_lock_active(lock_path)- assert result is False- assert not lock_path.exists(), "stale root-owned lock file should be removed"-- def test_permission_error_unlink_failure_still_returns_false(self, tmp_path, monkeypatch):- """Even if unlinking the stale lock file fails (e.g. directory not writable),- the function should still return False to allow startup."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = tmp_path / "gateway.lock"- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- if str(path) == str(lock_path):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- real_unlink = Path.unlink-- def deny_unlink(self, *args, **kwargs):- if str(self) == str(lock_path):- raise OSError(13, "Permission denied", str(self))- return real_unlink(self, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)- monkeypatch.setattr(Path, "unlink", deny_unlink)-- result = status.is_gateway_runtime_lock_active(lock_path)- assert result is False-- def test_acquire_gateway_runtime_lock_recovers_from_permission_error(self, tmp_path, monkeypatch):- """acquire_gateway_runtime_lock must survive a stale root-owned lock- file: unlink it and retry with a fresh file instead of crashing."""++ @pytest.mark.platforms("linux")+ def test_inaccessible_lock_is_not_deleted_or_treated_as_absence(self, tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = status._get_gateway_lock_path()- lock_path.parent.mkdir(parents=True, exist_ok=True)- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- # Simulate a root-owned file: opening fails while the ORIGINAL- # stale file is still on disk; after unlink, the fresh file the- # retry creates opens fine.- if (- str(path) == str(lock_path)- and lock_path.exists()- and lock_path.read_text(encoding="utf-8") == "stale"- ):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)-+ lock = tmp_path / "gateway.lock"+ lock.write_text("existing owner")+ inode = lock.stat().st_ino+ lock.chmod(0)try:- assert status.acquire_gateway_runtime_lock() is True+ assert status.is_gateway_runtime_lock_active(lock) is True+ assert status.acquire_gateway_runtime_lock() is False+ assert lock.stat().st_ino == inodefinally:- status.release_gateway_runtime_lock()+ lock.chmod(0o600)+ assert lock.read_text() == "existing owner"+ assert status.acquire_gateway_runtime_lock() is True+ status.release_gateway_runtime_lock()+ assert lock.stat().st_ino == inode+- @pytest.mark.linux_only++ @pytest.mark.platforms("linux")+ def test_runtime_lock_does_not_follow_symlink(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ target = tmp_path / "unrelated"+ target.write_text("unchanged")+ (tmp_path / "gateway.lock").symlink_to(target)+ assert status.acquire_gateway_runtime_lock() is False+ assert target.read_text() == "unchanged"class TestNormalizeUpdatedAt:diff --cc tests/gateway/test_terminal_commit_crash.pyindex 3079c87d3ab,00000000000..b2049167cf4mode 100644,000000..100644--- a/tests/gateway/test_terminal_commit_crash.py+++ b/tests/gateway/test_terminal_commit_crash.py@@@ -1,99 -1,0 +1,99 @@@+"""A committed result survives owner SIGKILL without pausing its follower."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import socket+import sqlite3+import threading++import aiohttp+import pytest+from tests.gateway.fixtures.local_recovery_probe import daemon, Model++- @pytest.mark.linux_only[email protected]("linux")+def test_terminal_commit_before_publication_survives_kill(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700); user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ with socket.socket() as sock:+ sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]+ base = f'http://127.0.0.1:{peer.server_port}/v1'+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},+ 'gateway': {'platforms': {'api_server': {'enabled': True, 'port': port, 'host': '127.0.0.1'}}, 'multiplex_profiles': False},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, API_SERVER_KEY='ordinary-daemon-owned-secret',+ API_SERVER_ENABLED='true', API_SERVER_PORT=str(port), PYTHONUNBUFFERED='1')+ url = f'http://127.0.0.1:{port}/v1'+ headers = {'Authorization': 'Bearer ordinary-daemon-owned-secret'}+ body = {'messages': [{'role': 'user', 'content': 'BLOCK_STARTED'}]}+ identity = {'X-Hermes-Session-Id': 'used', 'Idempotency-Key': 'once'}+ pids = []++ def snapshot():+ with sqlite3.connect(home / 'state.db') as db:+ rows = {rid.rsplit(':', 1)[-1]: status for rid, status in db.execute('SELECT request_id,status FROM session_admissions')}+ result = db.execute("SELECT value FROM state_meta WHERE key LIKE 'gateway.admission.result.v1.%' AND value LIKE '%RECOVERY_ACK_BLOCK_STARTED%'").fetchone()+ return rows, json.loads(result[0]) if result else None++ async def first(proc):+ async with aiohttp.ClientSession(headers=headers) as client:+ async with client.post(url + '/chat/completions', json={'messages': [{'role': 'user', 'content': 'WARM'}]},+ headers={'X-Hermes-Session-Id': 'used'}) as response:+ assert response.status == 200, await response.text()+ async def request():+ async with client.post(url + '/chat/completions', json=body, headers=identity) as response:+ return await response.json()+ pending = asyncio.create_task(request())+ try:+ assert await asyncio.to_thread(peer.blocked.wait, 20)+ async with client.post(url + '/runs', json={'input': 'FOLLOW_ON', 'session_id': 'used'},+ headers={'Idempotency-Key': 'follow'}) as response:+ follower = await response.json()+ assert response.status == 202, follower+ peer.release.set()+ async with asyncio.timeout(30):+ while snapshot()[1] is None:+ await asyncio.sleep(.02)+ rows, saved = snapshot()+ assert not pending.done(), 'HTTP result published before crash barrier'+ proc.kill(); await asyncio.to_thread(proc.wait, 10)+ assert rows[follower['run_id']] == 'queued'+ return saved, follower['run_id']+ finally:+ pending.cancel(); await asyncio.gather(pending, return_exceptions=True)++ async def restart(saved, follower):+ async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(total=15)) as client:+ async with client.post(url + '/chat/completions', json=body, headers=identity) as response:+ reply = await response.json()+ assert response.status == 200, reply+ assert reply['choices'][0]['message']['content'] == saved['result']['final_response']+ async with asyncio.timeout(25):+ while snapshot()[0][follower] != 'terminal':+ await asyncio.sleep(.03)+ assert snapshot()[0]['once'] == 'terminal'+ assert snapshot()[1] == saved++ try:+ with daemon(root, home, env, barrier=True, fixture='terminal_commit_daemon.py') as (proc, desc):+ pids.append(proc.pid)+ saved, follower = asyncio.run(first(proc))+ with daemon(root, home, env, barrier=False) as (proc, desc):+ pids.append(proc.pid)+ asyncio.run(restart(saved, follower))+ texts = [next(m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user') for r in peer.requests]+ assert sum('BLOCK_STARTED' in str(t) for t in texts) == 1, texts+ assert sum('FOLLOW_ON' in str(t) for t in texts) == 1, texts+ print(json.dumps({'pids': pids, 'inference_texts': texts, 'exact_result': saved, 'rows': snapshot()[0]}))+ finally:+ peer.release.set(); peer.shutdown(); peer.server_close()diff --cc tests/gateway/test_used_delete_restart.pyindex d24071faa5e,00000000000..95f5a515754mode 100644,000000..100644--- a/tests/gateway/test_used_delete_restart.py+++ b/tests/gateway/test_used_delete_restart.py@@@ -1,137 -1,0 +1,137 @@@+"""Real daemon delete/restart: history disappears, exact authorized retries survive."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import socket+import sqlite3+import threading++import aiohttp+import httpx+import pytest+from tests.gateway.fixtures.local_recovery_probe import daemon, Model, websocket, rpc+from tests.gateway.test_native_http_auth import ticket, headers as native_headers++- @pytest.mark.linux_only[email protected]("linux")+def test_used_api_and_native_delete_restart_exact_retry(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700); user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ with socket.socket() as sock:+ sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]+ base = f'http://127.0.0.1:{peer.server_port}/v1'+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},+ 'gateway': {'platforms': {'api_server': {'enabled': True, 'port': port, 'host': '127.0.0.1'}}, 'multiplex_profiles': False},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}+ (home / 'config.yaml').write_text(json.dumps(cfg), encoding='utf-8')+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, API_SERVER_KEY='ordinary-daemon-owned-secret',+ API_SERVER_ENABLED='true', API_SERVER_PORT=str(port), PYTHONUNBUFFERED='1',+ HERMES_DASHBOARD_SESSION_TOKEN='foreign-dashboard-owner')+ url = f'http://127.0.0.1:{port}/v1'+ headers = {'Authorization': 'Bearer ordinary-daemon-owned-secret'}+ body = {'messages': [{'role': 'user', 'content': 'API_USED_ONCE'}]}+ identity = {'X-Hermes-Session-Id': 'used-api', 'Idempotency-Key': 'once'}+ receipts = {}++ async def api_request():+ async with aiohttp.ClientSession(headers=headers) as client:+ async with client.post(url + '/chat/completions', json=body, headers=identity) as response:+ result = await response.json()+ assert response.status == 200, result+ return result['choices'][0]['message']['content'], result['usage']++ async def native_turn(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='native-used', source='gui', cwd=str(home), toolsets=[])+ sid = created['result']['session_id']+ submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='native-once', text='NATIVE_USED_ONCE')+ assert submitted['result']['status'] == 'queued', submitted+ async with asyncio.timeout(30):+ while True:+ with sqlite3.connect(home / 'state.db') as db:+ row = db.execute("SELECT status FROM session_admissions WHERE request_id='native-once'").fetchone()+ if row and row[0] == 'terminal':+ break+ await asyncio.sleep(.03)+ # Wait for the drain's publication, not only the earlier DB terminal commit.+ async with asyncio.timeout(20):+ while True:+ event = json.loads(await ws.recv())+ if event.get('params', {}).get('type') == 'message.complete':+ break+ return sid++ def delete(desc, sid):+ path = '/api/sessions/' + sid+ with httpx.Client(base_url=desc['api_origin'], trust_env=False) as client:+ snapshot = client.get(path + '/mutation-snapshot', headers=native_headers(ticket(home, desc)))+ assert snapshot.status_code == 200, snapshot.text+ snap = snapshot.json()+ params = dict(request_id='delete-' + sid, expected_revision=snap['runtime_revision'],+ expected_generation=snap['runtime_generation'])+ result = client.delete(path, params=params, headers=native_headers(ticket(home, desc)))+ assert result.status_code == 200, result.text+ assert client.get(path, headers=native_headers(ticket(home, desc))).status_code == 404+ receipts[sid] = (params, result.json())++ async def stale_native(desc, sid):+ async with websocket(home, desc) as ws:+ denied = await rpc(ws, 'prompt.submit', session_id=sid, input_id='stale-new', text='MUST_NOT_RUN')+ assert 'error' in denied, denied++ async def busy_delete_refused(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='native-busy', source='gui', cwd=str(home), toolsets=[])+ sid = created['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='busy-once', text='BLOCK_STARTED')+ assert await asyncio.to_thread(peer.blocked.wait, 20)+ with httpx.Client(base_url=desc['api_origin'], trust_env=False) as client:+ snap = client.get(f'/api/sessions/{sid}/mutation-snapshot', headers=native_headers(ticket(home, desc))).json()+ refused = client.delete('/api/sessions/' + sid, headers=native_headers(ticket(home, desc)),+ params=dict(request_id='delete-busy', expected_revision=snap['runtime_revision'],+ expected_generation=snap['runtime_generation']))+ assert refused.status_code == 409 and 'session_busy' in refused.text, refused.text+ peer.release.set()+ with sqlite3.connect(home / 'state.db') as db:+ assert db.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone()+ assert db.execute("SELECT 1 FROM session_admissions WHERE request_id='busy-once'").fetchone()++ try:+ with daemon(root, home, env, barrier=True) as (proc, desc):+ first = asyncio.run(api_request())+ native_sid = asyncio.run(native_turn(desc))+ asyncio.run(busy_delete_refused(desc))+ delete(desc, 'used-api'); delete(desc, native_sid)+ before = len(peer.requests)+ with daemon(root, home, env, barrier=False) as (proc, desc):+ with httpx.Client(base_url=desc['api_origin'], trust_env=False) as client:+ for sid, (params, receipt) in receipts.items():+ path = '/api/sessions/' + sid+ retry = client.delete(path, params=params, headers=native_headers(ticket(home, desc)))+ assert retry.status_code == 200 and retry.json() == receipt, retry.text+ changed = client.delete(path, params=params | {'expected_revision': 999}, headers=native_headers(ticket(home, desc)))+ assert changed.status_code == 409 and 'admission_conflict' in changed.text+ foreign = client.delete(path, params=params, headers={'Authorization': 'Bearer foreign-dashboard-owner'})+ assert foreign.status_code != 200, foreign.text+ assert asyncio.run(api_request()) == first+ asyncio.run(stale_native(desc, native_sid))+ with sqlite3.connect(home / 'state.db') as db:+ for sid in receipts:+ assert db.execute('SELECT 1 FROM sessions WHERE id=?', (sid,)).fetchone() is None+ assert db.execute('SELECT 1 FROM messages WHERE session_id=?', (sid,)).fetchone() is None+ assert db.execute('SELECT 1 FROM session_admissions WHERE target_session_id=?', (sid,)).fetchone() is None+ assert not db.execute('PRAGMA foreign_key_check').fetchall()+ assert len(peer.requests) == before+ print(json.dumps({'dispatch_hook_composed': True, 'restart_ordinary': True,+ 'deleted_ids': list(receipts), 'exact_api_reply': first, 'inference_count': before}))+ finally:+ peer.release.set(); peer.shutdown(); peer.server_close()diff --cc tests/gateway/test_worker_agent_execution.pyindex 2fc147dc951,00000000000..5532eddf6f9mode 100644,000000..100644--- a/tests/gateway/test_worker_agent_execution.py+++ b/tests/gateway/test_worker_agent_execution.py@@@ -1,108 -1,0 +1,108 @@@+"""Unmocked worker AIAgent / loopback inference / ordinary owner transport."""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+++class Model(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ if body.get('messages'):+ self.server.requests.append(body)+ message = {'role': 'assistant', 'content': 'RECOVERY_ACK_WORKER_INFERENCE'}+ usage = {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}+ frame = {'id': 'worker-reply', 'model': 'worker-model', 'usage': usage,+ 'choices': [{'index': 0, 'message': message, 'finish_reason': 'stop'}]}+ kind = 'application/json'+ if body.get('stream'):+ frame['choices'][0]['delta'] = frame['choices'][0].pop('message')+ payload = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ else:+ payload = json.dumps(frame).encode()+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++- @pytest.mark.linux_only[email protected]("linux")[email protected]('probe_constructors', [False, True])+def test_real_agent_worker_persists_context_usage_and_releases_lease(tmp_path, probe_constructors):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'worker-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ async def create(desc):+ async with websocket(home, desc) as ws:+ response = await rpc(ws, 'session.create', request_id='worker-session', source='cli',+ model='worker-model', toolsets=[])+ assert 'result' in response, response+ return response['result']['session_id']+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ sid = asyncio.run(create(desc))+ receipt = tmp_path / 'receipt.json'+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/agent_persistence_worker.py')],+ cwd=root, env=env, input=json.dumps({'home': str(home), 'url': url, 'session_id': sid,+ 'receipt': str(receipt), 'probe_constructors': probe_constructors}) + '\n',+ text=True, capture_output=True, timeout=60)+ assert result.returncode == 0, result.stdout + result.stderr+ proof = json.loads(receipt.read_text())+ assert not proof['failed'], proof+ assert 'RECOVERY_ACK_WORKER_INFERENCE' in proof['result'], proof+ if probe_constructors:+ assert proof['refusals']['child'] == 'worker_child_registration_required', proof['refusals']+ assert proof['refusals']['cron'] == 'worker_cron_registration_required', proof['refusals']+ assert proof['refusals']['ledger'] == 'worker_delegation_ledger_unavailable', proof['refusals']+ success, doc, final_response, error = proof['refusals']['script_result']+ assert success and error is None and 'SCRIPT_ONLY_RESULT' in doc+ assert final_response.strip() == 'SCRIPT_ONLY_RESULT'+ assert proof['opens'] == [] and proof['fds'] == [], json.dumps(proof['opens'], indent=2)+ assert proof['context']['system_prompt'], proof+ assert proof['context']['input_tokens'] == 10, proof+ assert proof['context']['output_tokens'] == 5, proof+ assert proof['finished']['status'] == 'terminal'+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ assert db.execute('SELECT COUNT(*) FROM session_turn_leases').fetchone()[0] == 0+ assert db.execute('SELECT input_tokens,output_tokens FROM sessions WHERE id=?', (sid,)).fetchone() == (10, 5)+ rows = db.execute('SELECT role,content FROM messages WHERE session_id=? ORDER BY id', (sid,)).fetchall()+ assert any(role == 'user' and 'WORKER_INFERENCE' in content for role, content in rows)+ assert any(role == 'assistant' and 'RECOVERY_ACK_WORKER_INFERENCE' in content for role, content in rows)+ assert len(peer.requests) == 1, peer.requests+ print(json.dumps({'result': proof['result'], 'opens': proof['opens'], 'fds': proof['fds'],+ 'input_tokens': proof['context']['input_tokens'],+ 'output_tokens': proof['context']['output_tokens'],+ 'prompt_persisted': bool(proof['context']['system_prompt']),+ 'finished': proof['finished'], 'refusals': proof['refusals'],+ 'rows': rows, 'inference_requests': len(peer.requests)}, default=str))+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/gateway/test_worker_compression_execution.pyindex 9a3bb519477,00000000000..a45c652f740mode 100644,000000..100644--- a/tests/gateway/test_worker_compression_execution.py+++ b/tests/gateway/test_worker_compression_execution.py@@@ -1,67 -1,0 +1,67 @@@+"""Real compression, real registered worker, real ordinary owner transport."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.gateway.test_worker_agent_execution import Model++- @pytest.mark.linux_only[email protected]("linux")+def test_ordinary_daemon_worker_compresses_without_canonical_sqlite_opens(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'worker-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False},+ 'compression': {'provider': 'custom', 'model': 'worker-model', 'base_url': url}},+ 'platform_toolsets': {'cli': []}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ async def create(desc, key):+ async with websocket(home, desc) as ws:+ response = await rpc(ws, 'session.create', request_id=key, source='cli', model='worker-model', toolsets=[])+ assert 'result' in response, response+ return response['result']['session_id']+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ sid = asyncio.run(create(desc, 'compressed'))+ foreign = asyncio.run(create(desc, 'foreign'))+ receipt = tmp_path / 'receipt.json'+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/compression_persistence_worker.py')],+ cwd=root, env=env, input=json.dumps(dict(home=str(home), url=url, session_id=sid,+ foreign=foreign, receipt=str(receipt))) + '\n', text=True, capture_output=True, timeout=120)+ assert result.returncode == 0, result.stdout + result.stderr+ proof = json.loads(receipt.read_text())+ assert proof['opens'] == proof['fds'] == []+ assert proof['compressed_count'] < proof['input_count']+ assert peer.requests, 'no actual summary inference'+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ assignment = db.execute('SELECT session_id,status FROM worker_executions').fetchone()+ assert assignment == (proof['after'], 'terminal')+ assert db.execute('SELECT COUNT(*) FROM messages WHERE session_id=? AND active=1', (proof['after'],)).fetchone()[0] == len(proof['history'])+ print(json.dumps(dict(before=proof['before'], after=proof['after'], opens=proof['opens'],+ fds=proof['fds'], negatives=proof['negatives'], requests=len(peer.requests),+ compressed_count=proof['compressed_count'], input_count=proof['input_count'],+ persisted_rows=len(proof['history']))))+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/gateway/test_worker_ledger_tool_execution.pyindex 7e5fb5625ba,00000000000..e6feaab37c5mode 100644,000000..100644--- a/tests/gateway/test_worker_ledger_tool_execution.py+++ b/tests/gateway/test_worker_ledger_tool_execution.py@@@ -1,98 -1,0 +1,98 @@@+"""Tool-enabled ordinary-daemon proof, distinct from unregistered ledger hooks."""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+++class Model(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ if messages:+ self.server.requests.append(body)+ tools = [message for message in messages if message.get('role') == 'tool']+ if tools:+ message = {'role': 'assistant', 'content': 'WORKER_TOOL_LEDGER_OK'}+ finish = 'stop'+ else:+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'inert-tool', 'index': 0, 'type': 'function', 'function': {'name': 'terminal',+ 'arguments': json.dumps({'command': 'printf WORKER_TOOL_LEDGER_OK'})}}]}+ finish = 'tool_calls'+ frame = {'id': 'tool-reply', 'model': 'worker-model',+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15},+ 'choices': [{'index': 0, 'message': message, 'finish_reason': finish}]}+ kind = 'application/json'+ if body.get('stream'):+ frame['choices'][0]['delta'] = frame['choices'][0].pop('message')+ payload = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ else:+ payload = json.dumps(frame).encode()+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++- @pytest.mark.linux_only[email protected]("linux")+def test_real_tool_enabled_worker_never_opens_canonical_database(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'worker-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}}))+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ async def create(desc):+ async with websocket(home, desc) as ws:+ response = await rpc(ws, 'session.create', request_id='worker-session', source='cli',+ model='worker-model', toolsets=['terminal'])+ assert 'result' in response, response+ return response['result']['session_id']+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ sid = asyncio.run(create(desc))+ receipt = tmp_path / 'receipt.json'+ worker = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/ledger_tool_worker.py')],+ cwd=root, env=env, input=json.dumps({'home': str(home), 'url': url, 'session_id': sid,+ 'receipt': str(receipt)}) + '\n',+ text=True, capture_output=True, timeout=90)+ assert worker.returncode == 0, worker.stdout + worker.stderr+ proof = json.loads(receipt.read_text())+ assert not proof['failed'] and proof['result'] == 'WORKER_TOOL_LEDGER_OK', proof+ assert proof['opens'] == [] and proof['fds'] == [], proof+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ tools = db.execute("SELECT content FROM messages WHERE session_id=? AND role='tool'", (sid,)).fetchall()+ assert len(tools) == 1 and 'WORKER_TOOL_LEDGER_OK' in tools[0][0], tools+ assert db.execute('SELECT COUNT(*) FROM session_turn_leases').fetchone()[0] == 0+ assert len(peer.requests) == 2+ assert any(tool['function']['name'] == 'terminal' for tool in peer.requests[0]['tools'])+ print(json.dumps(proof | {'inference_requests': len(peer.requests), 'tool_rows': tools}))+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/gateway/test_worker_lifecycle_execution.pyindex a6c5b0d0381,00000000000..d53edaaf2bdmode 100644,000000..100644--- a/tests/gateway/test_worker_lifecycle_execution.py+++ b/tests/gateway/test_worker_lifecycle_execution.py@@@ -1,116 -1,0 +1,116 @@@+"""Ordinary owner and worker exercise lifecycle parity without worker SQLite."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import threading+import time++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.gateway.test_worker_agent_execution import Model++- @pytest.mark.linux_only[email protected]("linux")+def test_worker_lifecycle_then_owner_successor_refuses_late_mutations(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'worker-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ async def create(desc):+ async with websocket(home, desc) as ws:+ ids = []+ for name in ('owned', 'foreign'):+ response = await rpc(ws, 'session.create', request_id=name, source='cli',+ model='worker-model', toolsets=[])+ assert 'result' in response, response+ ids.append(response['result']['session_id'])+ return ids++ def rows(sid):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ db.row_factory = sqlite3.Row+ return dict(db.execute('SELECT * FROM sessions WHERE id=?', (sid,)).fetchone())++ async def successor(desc, sid):+ async with websocket(home, desc) as ws:+ resumed = await rpc(ws, 'session.resume', session_id=sid)+ assert 'result' in resumed, resumed+ response = await rpc(ws, 'prompt.submit', session_id=sid, input_id='successor', text='SUCCESSOR')+ assert 'result' in response, response+ async with asyncio.timeout(30):+ while True:+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ status = db.execute('SELECT status FROM session_admissions WHERE request_id=?', ('successor',)).fetchone()+ if status and status[0] == 'terminal':+ return+ await asyncio.sleep(.05)+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ sid, foreign = asyncio.run(create(desc))+ ready, receipt = tmp_path / 'ready.json', tmp_path / 'receipt.json'+ with (tmp_path / 'worker.log').open('w+') as log:+ proc = subprocess.Popen([sys.executable, str(root / 'tests/gateway/fixtures/lifecycle_persistence_worker.py')],+ cwd=root, env=env, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, text=True)+ try:+ proc.stdin.write(json.dumps(dict(home=str(home), url=url, session_id=sid, foreign=foreign,+ ready=str(ready), receipt=str(receipt))) + '\n')+ proc.stdin.flush()+ deadline = time.monotonic() + 60+ while not ready.exists() and proc.poll() is None and time.monotonic() < deadline:+ time.sleep(.05)+ log.seek(0)+ assert ready.exists(), log.read()+ before = rows(sid)+ assert before['end_reason'] == 'agent_close' and before['title'] == 'worker-title'+ asyncio.run(successor(desc, sid))+ settled = rows(sid)+ assert settled['runtime_generation'] > before['runtime_generation']+ proc.stdin.write('successor-settled\n')+ proc.stdin.flush()+ proc.wait(timeout=30)+ log.seek(0)+ assert proc.returncode == 0, log.read()+ proof = json.loads(receipt.read_text())+ assert proof['opens'] == [] and proof['fds'] == [], proof+ assert set(proof['foreign'].values()) == {'permission_denied'}, proof+ assert len(proof['foreign']) == 3+ assert set(proof['late'].values()) == {'stale_generation'}, proof+ assert len(proof['late']) == 4+ assert proof['context']['input_tokens'] == 10 and proof['context']['output_tokens'] == 5+ assert proof['finished']['status'] == 'terminal'+ after = rows(sid)+ for key in ('title', 'end_reason', 'ended_at', 'billing_provider', 'runtime_generation'):+ assert after[key] == settled[key]+ assert rows(foreign)['title'] is None and rows(foreign)['ended_at'] is None+ assert len(peer.requests) == 2+ print(json.dumps(dict(worker=proof, before_generation=before['runtime_generation'],+ successor_generation=settled['runtime_generation'],+ inference_requests=len(peer.requests)), default=str))+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait(timeout=10)+ proc.stdin.close()+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/gateway/test_worker_persistence.pyindex 5abe377e6b4,00000000000..1bbcf8e16b8mode 100644,000000..100644--- a/tests/gateway/test_worker_persistence.py+++ b/tests/gateway/test_worker_persistence.py@@@ -1,82 -1,0 +1,82 @@@+"""Separate worker, ordinary daemon, production private control and authenticated WS."""+import asyncio+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket++- @pytest.mark.linux_only[email protected]("linux")+def test_worker_survives_owner_restart_without_repeating_tool(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'inert', 'base_url': 'http://127.0.0.1:9/v1'},+ 'auxiliary': {'title_generation': {'enabled': False}}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL='http://127.0.0.1:9/v1')+ async def create(desc):+ async with websocket(home, desc) as ws:+ response = await rpc(ws, 'session.create', request_id='worker-session', source='cli')+ assert 'result' in response, response+ return response['result']['session_id']+ with (tmp_path / 'worker.log').open('w+') as log:+ worker = subprocess.Popen([sys.executable, str(root / 'tests/gateway/fixtures/persistence_worker.py')],+ cwd=root, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, text=True)+ def command(op, **params):+ worker.stdin.write(json.dumps({'op': op, **params}) + '\n')+ worker.stdin.flush()+ import select+ assert select.select([worker.stdout], [], [], 30)[0], 'worker response timeout'+ raw = worker.stdout.readline()+ log.flush(); log.seek(0)+ assert raw, log.read()+ result = json.loads(raw)+ assert 'fatal' not in result, result+ return result+ try:+ with daemon(root, home, env, barrier=False) as (owner, desc):+ sid = asyncio.run(create(desc))+ first = command('start', home=str(home), session_id=sid)+ assert first['registered'], first+ assert first['rows'] == 3 and first['lost_ack_replayed']+ assert first['wrong_session'] == 'permission_denied'+ assert first['wrong_profile'] == 'profile_mismatch'+ assert first['wrong_generation'] == 'stale_generation'+ assert first['conflict'] == 'admission_conflict'+ assert first['outbox_full'] == 'outbox_full'+ assert first['writable_canonical_fds'] == []+ assert first['canonical_opens'] == []+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ assert db.execute('SELECT COUNT(*) FROM messages WHERE session_id=?', (sid,)).fetchone()[0] == 3+ assert db.execute('SELECT input_tokens FROM sessions WHERE id=?', (sid,)).fetchone()[0] == 11+ owner.kill(); owner.wait(timeout=10)+ outage = command('outage')+ assert outage['pending'] == 1 and outage['canonical_opens'] == []+ with daemon(root, home, env, barrier=False):+ second = command('adopt')+ assert second['stale'] == 'stale_epoch'+ assert second['epoch'] > first['epoch']+ assert second['writable_canonical_fds'] == []+ assert second['canonical_opens'] == []+ assert second['pid'] == first['pid'] == worker.pid+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ assert db.execute("SELECT COUNT(*) FROM messages WHERE content='tool-marker'").fetchone()[0] == 1+ assert db.execute('SELECT input_tokens FROM sessions WHERE id=?', (sid,)).fetchone()[0] == 11+ assert db.execute("SELECT input_tokens FROM session_model_usage WHERE task='compression'").fetchone()[0] == 5+ assert db.execute("SELECT status FROM worker_executions WHERE execution_id='owned-worker'").fetchone()[0] == 'terminal'+ assert (home / 'tool-marker').read_text() == 'once'+ print(json.dumps({'first': first, 'second': second}))+ finally:+ if worker.poll() is None:+ worker.kill()+ worker.wait(timeout=10)+ worker.stdin.close(); worker.stdout.close()diff --cc tests/gateway/test_worker_rotation_adoption.pyindex 77fe9497adb,00000000000..fb3f5914314mode 100644,000000..100644--- a/tests/gateway/test_worker_rotation_adoption.py+++ b/tests/gateway/test_worker_rotation_adoption.py@@@ -1,98 -1,0 +1,98 @@@+"""Real compression, real registered worker, real ordinary owner transport."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.gateway.test_worker_agent_execution import Model++- @pytest.mark.linux_only[email protected]("linux")+def test_rotated_agent_survives_owner_kill_and_explicit_adoption(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'worker-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False},+ 'compression': {'provider': 'custom', 'model': 'worker-model', 'base_url': url}},+ 'platform_toolsets': {'cli': []}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ async def create(desc, key):+ async with websocket(home, desc) as ws:+ response = await rpc(ws, 'session.create', request_id=key, source='cli', model='worker-model', toolsets=[])+ assert 'result' in response, response+ return response['result']['session_id']+ worker = None+ def wait_file(path):+ import time+ deadline = time.monotonic() + 40+ while not path.exists():+ assert worker.poll() is None, 'worker exited before publishing receipt'+ assert time.monotonic() < deadline, 'worker receipt deadline'+ time.sleep(0.05)+ try:+ with (tmp_path / 'worker.log').open('w+') as log:+ ready, outage, receipt = (tmp_path / name for name in ('ready.json', 'outage', 'receipt.json'))+ with daemon(root, home, env, barrier=False) as (owner, desc):+ sid = asyncio.run(create(desc, 'compressed'))+ worker = subprocess.Popen([sys.executable, str(root / 'tests/gateway/fixtures/rotation_persistence_worker.py')],+ cwd=root, env=env, stdin=subprocess.PIPE, stdout=log, stderr=log, text=True)+ def send(value):+ worker.stdin.write(value + '\n')+ worker.stdin.flush()+ send(json.dumps(dict(home=str(home), url=url, session_id=sid, restart=True,+ ready=str(ready), outage=str(outage), receipt=str(receipt))))+ wait_file(ready)+ first = json.loads(ready.read_text())+ assert first['session_id'] != sid+ assert len(peer.requests) == 1+ owner.kill()+ owner.wait(timeout=10)+ send('outage')+ wait_file(outage)+ with daemon(root, home, env, barrier=False):+ send('adopt')+ worker.wait(timeout=60)+ log.seek(0)+ assert worker.returncode == 0, log.read()+ proof = json.loads(receipt.read_text())+ assert proof['opens'] == proof['fds'] == [], proof['opens']+ assert proof['restart']['pid'] == worker.pid+ assert proof['restart']['after_epoch'] > first['epoch']+ assert len(peer.requests) == 2+ assert 'RECOVERY_ACK_WORKER_INFERENCE' in proof['result']+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ assert db.execute('SELECT COUNT(*) FROM session_turn_leases').fetchone()[0] == 0+ assert db.execute('SELECT session_id,status FROM worker_executions').fetchone() == (proof['after'], 'terminal')+ assert db.execute('SELECT input_tokens,output_tokens FROM sessions WHERE id=?', (proof['after'],)).fetchone() == (10, 5)+ assert db.execute('SELECT COUNT(*) FROM worker_receipts WHERE sequence=?',+ (proof['restart']['pending_sequence'],)).fetchone()[0] == 1+ print(json.dumps(dict(restart=proof['restart'], before=proof['before'], after=proof['after'],+ opens=proof['opens'], fds=proof['fds'], requests=len(peer.requests))))+ finally:+ if worker is not None:+ if worker.poll() is None:+ worker.kill()+ worker.wait(timeout=10)+ worker.stdin.close()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/gateway/test_worker_rotation_execution.pyindex dbf4fae7ea7,00000000000..6f27a10451amode 100644,000000..100644--- a/tests/gateway/test_worker_rotation_execution.py+++ b/tests/gateway/test_worker_rotation_execution.py@@@ -1,69 -1,0 +1,69 @@@+"""Real compression, real registered worker, real ordinary owner transport."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.gateway.test_worker_agent_execution import Model++- @pytest.mark.linux_only[email protected]("linux")+def test_full_agent_worker_rotation_continues_inference_without_canonical_opens(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'worker-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False},+ 'compression': {'provider': 'custom', 'model': 'worker-model', 'base_url': url}},+ 'platform_toolsets': {'cli': []}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ async def create(desc, key):+ async with websocket(home, desc) as ws:+ response = await rpc(ws, 'session.create', request_id=key, source='cli', model='worker-model', toolsets=[])+ assert 'result' in response, response+ return response['result']['session_id']+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ sid = asyncio.run(create(desc, 'compressed'))+ foreign = asyncio.run(create(desc, 'foreign'))+ receipt = tmp_path / 'receipt.json'+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/rotation_persistence_worker.py')],+ cwd=root, env=env, input=json.dumps(dict(home=str(home), url=url, session_id=sid,+ foreign=foreign, receipt=str(receipt))) + '\n', text=True, capture_output=True, timeout=120)+ assert result.returncode == 0, result.stdout + result.stderr+ proof = json.loads(receipt.read_text())+ assert proof['opens'] == proof['fds'] == [], json.dumps(proof['opens'], indent=2)+ assert proof['compressed_count'] < proof['input_count']+ assert len(peer.requests) == 2, 'summary and continuation must both run'+ assert 'RECOVERY_ACK_WORKER_INFERENCE' in proof['result']+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ assert db.execute('SELECT COUNT(*) FROM session_turn_leases').fetchone()[0] == 0+ assignment = db.execute('SELECT session_id,status FROM worker_executions').fetchone()+ assert assignment == (proof['after'], 'terminal')+ assert db.execute('SELECT COUNT(*) FROM messages WHERE session_id=? AND active=1', (proof['after'],)).fetchone()[0] == len(proof['history'])+ print(json.dumps(dict(before=proof['before'], after=proof['after'], opens=proof['opens'],+ fds=proof['fds'], negatives=proof['negatives'], requests=len(peer.requests),+ compressed_count=proof['compressed_count'], input_count=proof['input_count'],+ persisted_rows=len(proof['history']))))+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/hermes_cli/test_gateway_chat_native.pyindex 7543e47b3f9,00000000000..89704b893b2mode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_chat_native.py+++ b/tests/hermes_cli/test_gateway_chat_native.py@@@ -1,191 -1,0 +1,191 @@@+"""Native PTY clients against an ordinary daemon and loopback model only."""+import json+import os+from pathlib import Path+import shlex+import signal+import subprocess+import sys+import time+import uuid++import pytest++from tests.gateway.test_normal_runtime_boot import control, model_peer # noqa: F401++- @pytest.mark.linux_only[email protected]("linux")+def test_native_classic_fresh_resume_and_oneshot(tmp_path, model_peer, request):+ home = tmp_path / "state"+ home.mkdir(mode=0o700)+ user = tmp_path / "user"+ user.mkdir()+ cwd = tmp_path / "caller"+ cwd.mkdir()+ root = Path(__file__).resolve().parents[2]+ gateway_root = Path(request.config.getoption("--client-test-runtime-root", default=None) or root).resolve()+ model_url = f"http://127.0.0.1:{model_peer.server_port}/v1"+ (home / "config.yaml").write_text(json.dumps({+ "gateway": {"multiplex_profiles": False},+ "approvals": {"mode": "manual", "timeout": 60},+ "model": {"provider": "custom", "default": "local-wire-stub", "base_url": model_url},+ "auxiliary": {"title_generation": {"enabled": False}},+ }))+ env = {k: os.environ[k] for k in ("PATH", "LANG", "TZ") if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED="1",+ OPENAI_API_KEY="loopback-only", OPENAI_BASE_URL=model_url)+ # Instrument constructor calls without replacing runtime predicates or behavior.+ wrapper = tmp_path / "client.py"+ witness = tmp_path / "client-owner.json"+ wrapper.write_text('''import json, runpy, sys+from pathlib import Path+owners = []+def trace(frame, event, arg):+ if event == 'call' and frame.f_code.co_name == '__init__':+ obj = frame.f_locals.get('self')+ if type(obj).__name__ in {'AIAgent', 'SessionDB', 'GatewayRunner'}:+ owners.append(type(obj).__name__)+sys.setprofile(trace)+try:+ module = 'hermes_cli.main'+ if sys.argv[1:2] == ['--fixture-direct']:+ sys.argv.pop(1)+ module = 'cli'+ runpy.run_module(module, run_name='__main__')+finally:+ sys.setprofile(None)+ Path(sys.argv[0]).with_name('client-owner.json').write_text(json.dumps(owners))+''')+ # argv[0] is replaced by runpy, so the witness path is explicitly bound.+ wrapper.write_text(wrapper.read_text().replace("Path(sys.argv[0]).with_name('client-owner.json')", repr(str(witness)) + " and Path(" + repr(str(witness)) + ")"))+ tmux_name = "hermes-cli-test-" + uuid.uuid4().hex++ def tmux(*args):+ return subprocess.run(["tmux", "-L", tmux_name, *args], env=env,+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10)++ def screen():+ result = tmux("capture-pane", "-p", "-S", "-1000", "-t", "chat")+ return result.stdout++ def until(text, timeout=45):+ deadline = time.monotonic() + timeout+ output = ""+ while time.monotonic() < deadline:+ output = screen()+ if text in output:+ return output+ time.sleep(.1)+ raise AssertionError((text, output, log_path.read_text()))++ def launch(*args):+ command = shlex.join([sys.executable, str(wrapper), *args])+ result = tmux("new-session", "-d", "-s", "chat", "-x", "160", "-y", "45", "-c", str(cwd),+ command + '; rc=$?; printf "\\nCLI_RC=%s\\n" "$rc"; sleep 120')+ assert result.returncode == 0, result.stderr++ log_path = tmp_path / "gateway.log"+ with log_path.open("w") as log:+ daemon = subprocess.Popen([sys.executable, "-m", "gateway.run"], cwd=gateway_root,+ env={**env, "PYTHONPATH": str(gateway_root)},+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ descriptor = {}+ while daemon.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, "identify")+ if descriptor.get("state") == "ready":+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ assert descriptor.get("state") == "ready", log_path.read_text()+ launch("--cli", "chat")+ first = until("Welcome to Hermes Agent")+ sid = next(line.split("Session: ", 1)[1].strip() for line in first.splitlines() if "Session: " in line)+ tmux("send-keys", "-t", "chat", "WS_SHARED", "Enter")+ fresh = until("LOCAL_ACK_WS_SHARED")+ tmux("send-keys", "-t", "chat", "/quit", "Enter")+ detached = until("CLI_RC=0")+ assert json.loads(witness.read_text()) == [], witness.read_text()+ assert daemon.poll() is None+ tmux("kill-session", "-t", "chat")++ launch("--cli", "chat", "--resume", sid, "-q", "WS_SHARED resumed", "-Q")+ resumed = until("CLI_RC=0")+ assert "LOCAL_ACK_WS_SHARED" in resumed+ assert json.loads(witness.read_text()) == []+ tmux("kill-session", "-t", "chat")++ launch("-z", "WS_SHARED oneshot")+ oneshot = until("CLI_RC=0")+ assert "LOCAL_ACK_WS_SHARED" in oneshot+ assert json.loads(witness.read_text()) == []+ assert control(home, "identify")["instance_id"] == descriptor["instance_id"]+ assert len(model_peer.requests) == 3+ tmux("kill-session", "-t", "chat")+ launch("--fixture-direct", "-q", "WS_SHARED direct", "--oneshot", "--quiet")+ direct = until("CLI_RC=0")+ assert "LOCAL_ACK_WS_SHARED" in direct+ assert json.loads(witness.read_text()) == []+ tmux("kill-session", "-t", "chat")++ from tests.gateway.fixtures.authority_controls_peer import ModelPeer as ApprovalPeer+ target = tmp_path / "owned-removal"+ target.mkdir()+ (target / "owned.txt").write_text("disposable")+ model_peer.command = "rm -r -- " + shlex.quote(str(target))+ model_peer.RequestHandlerClass = ApprovalPeer+ launch("--cli", "chat", "-q", "Remove the owned fixture")+ approval = until("/approve ")+ approval_sid = next(line.split("Session: ", 1)[1].strip() for line in approval.splitlines() if "Session: " in line)+ prompt_id = next(line.split("/approve ", 1)[1].split()[0] for line in approval.splitlines() if "/approve " in line)+ assert target.exists()+ tmux("send-keys", "-t", "chat", f"/approve {prompt_id} forged", "Enter")+ until("invalid_params")+ assert target.exists(), "Invalid choice must not resolve the real approval"+ tmux("send-keys", "-t", "chat", "/quit", "Enter")+ until("CLI_RC=0")+ assert target.exists()+ tmux("kill-session", "-t", "chat")+ launch("--cli", "chat", "--resume", approval_sid)+ until("/approve ")+ tmux("send-keys", "-t", "chat", f"/approve {prompt_id} once", "Enter")+ approved = until("APPROVAL_FINISHED")+ assert not target.exists(), "Real terminal effect must follow native consent"+ tmux("send-keys", "-t", "chat", "/quit", "Enter")+ until("CLI_RC=0")+ assert json.loads(witness.read_text()) == []+ tmux("kill-session", "-t", "chat")+ cwd_supported = "cannot preserve caller cwd" not in first+ cwd_receipt = tmp_path / "cwd-proof.txt"+ model_peer.command = "pwd > " + shlex.quote(str(cwd_receipt))+ launch("--cli", "chat", "-q", "Record the caller directory", "-Q", "--in", str(cwd),+ "--model", "local-wire-stub", "--toolsets", "terminal")+ if cwd_supported:+ policy = until("CLI_RC=0")+ assert cwd_receipt.read_text().strip() == str(cwd)+ assert "APPROVAL_FINISHED" in policy+ else:+ policy = until("CLI_RC=1")+ assert "does not support --in" in policy+ assert not cwd_receipt.exists()+ assert json.loads(witness.read_text()) == []+ receipt = {"gateway_root": str(gateway_root), "caller_cwd_effect_verified": cwd_supported,+ "policy": policy, "direct_cli": direct,+ "approval_detach_reconnect": approval_sid, "approval": approved,+ "invalid_choice_no_effect": True, "real_terminal_effect": True,"session_id": sid, "daemon_pid": daemon.pid,+ "same_instance": descriptor["instance_id"], "client_agent_db_owners": [],+ "fresh": fresh, "detach": detached, "resume": resumed, "oneshot": oneshot}+ print("CLI_PTY_RECEIPT=" + json.dumps(receipt))+ finally:+ tmux("kill-server")+ if daemon.poll() is None:+ daemon.send_signal(signal.SIGINT)+ try:+ daemon.wait(timeout=20)+ except subprocess.TimeoutExpired:+ daemon.kill()+ daemon.wait(timeout=5)diff --cc tests/hermes_cli/test_gateway_chat_title_live.pyindex 2d6b8fd8d68,00000000000..cf1e0a97b53mode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_chat_title_live.py+++ b/tests/hermes_cli/test_gateway_chat_title_live.py@@@ -1,102 -1,0 +1,102 @@@+"""Title-keyed resume on the canonical CLI client against an ordinary daemon."""+import json+import os+from pathlib import Path+import signal+import subprocess+import sys+import time++import pytest++from tests.gateway.test_normal_runtime_boot import control, model_peer # noqa: F401++- @pytest.mark.linux_only[email protected]("linux")+def test_title_create_if_missing_then_resume_by_title_is_deterministic(tmp_path, model_peer):+ home = tmp_path / "state"+ home.mkdir(mode=0o700)+ user = tmp_path / "user"+ user.mkdir()+ root = Path(__file__).resolve().parents[2]+ model_url = f"http://127.0.0.1:{model_peer.server_port}/v1"+ (home / "config.yaml").write_text(json.dumps({+ "gateway": {"multiplex_profiles": False},+ "model": {"provider": "custom", "default": "local-wire-stub", "base_url": model_url},+ "auxiliary": {"title_generation": {"enabled": False}},+ }), encoding="utf-8")+ env = {k: os.environ[k] for k in ("PATH", "LANG", "TZ") if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ PYTHONUNBUFFERED="1", OPENAI_API_KEY="loopback-only", OPENAI_BASE_URL=model_url)+ witness = tmp_path / "client-owner.json"+ wrapper = tmp_path / "client.py"+ wrapper.write_text(encoding='utf-8', data=f'''import json, runpy, sys+owners = []+def trace(frame, event, arg):+ if event == 'call' and frame.f_code.co_name == '__init__':+ if type(frame.f_locals.get('self')).__name__ in {{'AIAgent', 'SessionDB', 'GatewayRunner'}}:+ owners.append(type(frame.f_locals.get('self')).__name__)+sys.setprofile(trace)+try:+ runpy.run_module('hermes_cli.main', run_name='__main__')+finally:+ sys.setprofile(None)+ open({str(witness)!r}, 'w', encoding='utf-8').write(json.dumps(owners))+''')++ def chat(*args):+ result = subprocess.run([sys.executable, str(wrapper), "--cli", "chat", *args, "-Q"], env=env,+ cwd=tmp_path, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=90)+ assert json.loads(witness.read_text(encoding="utf-8")) == [], witness.read_text(encoding="utf-8")+ sid = next((line.split("Session: ", 1)[1].strip() for line in result.stderr.splitlines()+ if "Session: " in line), None)+ return result, sid++ title = "wave36 titled thread"+ log_path = tmp_path / "gateway.log"+ with log_path.open("w") as log:+ daemon = subprocess.Popen([sys.executable, "-m", "gateway.run"], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ deadline = time.monotonic() + 40+ descriptor = {}+ while daemon.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, "identify")+ if descriptor.get("state") == "ready":+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ assert descriptor.get("state") == "ready", log_path.read_text(encoding="utf-8")++ missing, _ = chat("-c", title, "-q", "WS_SHARED absent")+ assert missing.returncode == 1 and f"No session found matching '{title}'" in missing.stderr, missing++ created, sid = chat("-c", title, "--create-if-missing", "-q", "WS_SHARED create")+ assert created.returncode == 0 and sid and "LOCAL_ACK_WS_SHARED" in created.stdout, created++ # The titled-thread turn shape: --in + --query-file+ # + --create-if-missing must resume the existing titled thread, never fork a second one.+ query_file = tmp_path / "dm.txt"+ query_file.write_text("WS_SHARED again", encoding="utf-8")+ again, again_sid = chat("--in", str(tmp_path), "-c", title, "--create-if-missing",+ "--query-file", str(query_file))+ assert again.returncode == 0 and again_sid == sid, again++ resumed, resumed_sid = chat("--resume", title, "-q", "WS_SHARED resumed")+ assert resumed.returncode == 0 and resumed_sid == sid, resumed+ # The whole thread accumulates on ONE session: the third turn sees both earlier turns.+ history = json.dumps(model_peer.requests[-1]["messages"])+ assert "WS_SHARED create" in history and "WS_SHARED again" in history+ assert len(model_peer.requests) == 3+ print("CLI_TITLE_RECEIPT=" + json.dumps({"session_id": sid, "daemon_pid": daemon.pid,+ "missing": missing.stderr, "resumed": resumed.stdout}))+ finally:+ if daemon.poll() is None:+ daemon.send_signal(signal.SIGINT)+ try:+ daemon.wait(timeout=20)+ except subprocess.TimeoutExpired:+ daemon.kill()+ daemon.wait(timeout=5)diff --cc tests/hermes_cli/test_gateway_runtime.pyindex 0b497abc24e,00000000000..740089e9ccamode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_runtime.py+++ b/tests/hermes_cli/test_gateway_runtime.py@@@ -1,123 -1,0 +1,123 @@@+"""Runtime discovery must distinguish absence from an unsafe/live owner."""++import asyncio+from contextlib import asynccontextmanager+from pathlib import Path++import pytest+++@asynccontextmanager+async def control_peer(home: Path, payload: dict):+ from gateway.control_socket import GatewayControlServer++ home.mkdir(mode=0o700)+ server = GatewayControlServer(home, verb_handlers={"identify": lambda: payload})+ assert await server.start()+ pointer = home / "gateway.sock.path"+ if pointer.exists():+ pointer.chmod(0o600)+ try:+ yield server+ finally:+ await server.stop()++- @pytest.mark.linux_only[email protected]("linux")+def test_live_discovery_does_not_treat_an_unusable_owner_as_absent(tmp_path):+ from hermes_cli.gateway_runtime import discover_gateway_endpoint++ async def probe():+ home = tmp_path / "profile"+ identity = str(home.resolve())+ payload = {+ "protocol": 1,+ "runtime_protocol": 1,+ "instance_id": "fixture-instance",+ "authority_epoch": 1,+ "hermes_home": identity,+ "state": "ready",+ "api_origin": "http://127.0.0.1:41817",+ "supervisor": "none",+ "served_profiles": [{"profile_id": identity, "home": identity}],+ "capabilities": ["session-authority-v1"],+ }+ absent = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)+ assert absent.state == "absent"+ async with control_peer(home, payload):+ ready = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)+ assert ready.state == "ready"+ assert ready.endpoint.profile_id == identity+ assert ready.endpoint.instance_id == "fixture-instance"+ assert ready.endpoint.api_origin == "http://127.0.0.1:41817"+ for key, value, expected in [+ ("runtime_protocol", 99, "incompatible"),+ ("runtime_protocol", True, "incompatible"),+ ("served_profiles", [], "inaccessible"),+ ("state", "draining", "draining"),+ ("api_origin", "http://secret:[email protected]:41817", "inaccessible"),+ ("api_origin", "http://example.com:41817", "inaccessible"),+ ("authority_epoch", True, "inaccessible"),+ ("capabilities", [], "incompatible"),+ ]:+ old = payload[key]+ payload[key] = value+ observed = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)+ assert observed.state == expected, (key, observed)+ assert "credential" not in repr(observed)+ payload[key] = old+ # A forged pointer is not permission to connect somewhere else or spawn.+ (home / "gateway.sock.path").write_text(str(tmp_path / "foreign.sock"))+ (home / "gateway.sock.path").chmod(0o666)+ refused = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)+ assert refused.state == "inaccessible"++ asyncio.run(probe())++- @pytest.mark.linux_only[email protected]("linux")+def test_fifo_control_pointer_is_rejected_without_a_writer(tmp_path):+ import os+ import subprocess+ import sys++ home = tmp_path / 'fifo-profile'+ home.mkdir(mode=0o700)+ os.mkfifo(home / 'gateway.sock.path', 0o600)+ code = (+ 'import sys; from pathlib import Path; '+ 'from hermes_cli.gateway_runtime import discover_gateway_endpoint; '+ 'r = discover_gateway_endpoint(Path(sys.argv[1]), timeout=0.1); '+ 'print(r.state, r.reason_code)'+ )+ try:+ result = subprocess.run(+ [sys.executable, '-c', code, str(home)],+ cwd=Path(__file__).resolve().parents[2], stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=3,+ )+ except subprocess.TimeoutExpired:+ pytest.fail('discovery blocked on a FIFO instead of rejecting its file type')+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == 'inaccessible unsafe_control_pointer'+++def test_start_decisions_do_not_turn_uncertainty_into_another_owner():+ from gateway.runtime_contract import RuntimeObservation, next_start_action++ cases = [+ (RuntimeObservation("ready"), "attach"),+ (RuntimeObservation("starting"), "wait-owner"),+ (RuntimeObservation("draining"), "wait-owner"),+ (RuntimeObservation("incompatible"), "reject-version"),+ (RuntimeObservation("inaccessible"), "reject-access"),+ (RuntimeObservation("conflict"), "reject-conflict"),+ (RuntimeObservation("absent"), "spawn-unmanaged"),+ (RuntimeObservation("absent", installed_service=True), "start-service"),+ (RuntimeObservation("absent", service_may_start=True), "wait-service"),+ (RuntimeObservation("ready", update_paused=True), "wait-update"),+ ]+ for observation, expected in cases:+ assert next_start_action(observation) == expected+ with pytest.raises(ValueError, match="unknown runtime state"):+ next_start_action(RuntimeObservation("invalid"))diff --cc tests/hermes_cli/test_gateway_runtime_discovery.pyindex 7ea5105c70b,00000000000..946abc538e5mode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_runtime_discovery.py+++ b/tests/hermes_cli/test_gateway_runtime_discovery.py@@@ -1,55 -1,0 +1,55 @@@+"""Private discovery must not assume another process shares its temp root."""+import json+import socket+import tempfile+import threading+from pathlib import Path++import pytest++from gateway.control_socket import _home_hash+from hermes_cli.gateway_runtime_discovery import DiscoveryError, query_identify++- @pytest.mark.linux_only[email protected]("linux")+def test_fallback_pointer_uses_owner_location_and_keeps_identity_checks(tmp_path):+ home = tmp_path / 'profile'+ home.mkdir(mode=0o700)+ # The owner has a distinct TMPDIR, as a service or native app commonly does.+ with tempfile.TemporaryDirectory(prefix='h-owner-') as root:+ directory = Path(root) / f'hermes-gw-{_home_hash(home)}'+ directory.mkdir(mode=0o700)+ target = directory / 'control.sock'+ pointer = home / 'gateway.sock.path'+ pointer.write_text(str(target), encoding='utf-8')+ pointer.chmod(0o600)+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server:+ server.bind(str(target))+ target.chmod(0o600)+ server.listen(1)+ server.settimeout(3)+ requests = []++ def respond():+ try:+ peer, _ = server.accept()+ with peer:+ requests.append(peer.recv(4096))+ peer.sendall(b'{"ok":true,"protocol":1,"id":1,"result":{"state":"ready"}}\n')+ except TimeoutError:+ return++ thread = threading.Thread(target=respond)+ thread.start()+ try:+ assert query_identify(home, timeout=2) == {'state': 'ready'}+ finally:+ thread.join(timeout=4)+ assert json.loads(requests[0])['verb'] == 'identify'+ pointer.write_text(str(directory.with_name('hermes-gw-wrong') / 'control.sock'), encoding='utf-8')+ with pytest.raises(DiscoveryError, match='invalid_control_pointer'):+ query_identify(home, timeout=2)+ pointer.write_text(str(target), encoding='utf-8')+ directory.chmod(0o755)+ with pytest.raises(DiscoveryError, match='unsafe_control_permissions'):+ query_identify(home, timeout=2)diff --cc tests/hermes_cli/test_gateway_runtime_ensure.pyindex 2857b2a300c,00000000000..85fb82b75e7mode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_runtime_ensure.py+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py@@@ -1,313 -1,0 +1,313 @@@+"""Real local-control and subprocess boundaries, never real service mutations."""+import asyncio+import json+import os+from pathlib import Path+import subprocess+import sys+import time++import pytest++- @pytest.mark.linux_only[email protected]("linux")+def test_ensure_waits_for_real_control_owner_without_claiming_pending_is_ready(tmp_path):+ from gateway.control_socket import GatewayControlServer+ from hermes_cli import gateway_runtime as runtime++ assert callable(getattr(runtime, "ensure_gateway_runtime", None))++ async def probe():+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ payload = {"runtime_protocol": 1, "state": "starting", "instance_id": "peer",+ "served_profiles": [{"profile_id": str(home), "home": str(home)}]}+ stalled = False+ def identify():+ if stalled:+ time.sleep(4) # longer than the caller's deadline: a stalled owner is 'starting', never ready+ return payload+ server = GatewayControlServer(home, verb_handlers={"identify": identify})+ assert await server.start()+ try:+ before = time.monotonic()+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=3.0)+ assert result.state == "starting" and result.reason_code == "deadline"+ assert time.monotonic() - before < 6+ payload["state"] = "draining"+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=3.0)+ assert result.state == "draining"+ payload["served_profiles"] = []+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=3.0)+ assert result.state == "inaccessible" and result.reason_code == "profile_mismatch"+ stalled = True+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=3.0)+ assert result.state == "starting" and result.reason_code == "deadline"+ assert not (home / "logs").exists()+ finally:+ await server.stop()+ asyncio.run(probe())++- @pytest.mark.linux_only[email protected]("linux")+def test_installed_service_start_is_nonmutating_and_failed_manager_never_spawns(tmp_path, monkeypatch):+ from hermes_cli import gateway as gw, gateway_runtime as runtime++ assert callable(getattr(runtime, "ensure_gateway_runtime", None))+ from hermes_cli.gateway_runtime_service import service_suffix+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ monkeypatch.setenv("HERMES_HOME", str(home))+ unit = tmp_path / ".config/systemd/user" / f"hermes-gateway-{service_suffix(home)}.service"+ unit.parent.mkdir(parents=True)+ unit.write_text("[Service]\nExecStart=/owned/inert/gateway\n", encoding="utf-8")+ original = unit.read_bytes()+ calls = tmp_path / "calls.jsonl"+ helper = tmp_path / "inert-supervisor"+ from hermes_cli.gateway_runtime_service_identity import SYSTEMD_IDENTITY_PROPERTIES+ identity = {key: "" for key in SYSTEMD_IDENTITY_PROPERTIES}+ identity.update(User=str(os.getuid()), DynamicUser="no",+ Environment=f'"HERMES_HOME={home}"',+ ExecStart=f'{{ path={sys.executable} ; argv[]={sys.executable} -m hermes_cli.main gateway run ; ignore_errors=no ; }}')+ effective = "\n".join(f"{key}={value}" for key, value in identity.items())+ helper.write_text('#!' + sys.executable + '\nimport json,sys,time\nfrom pathlib import Path\n'+ + f'p=Path({str(calls)!r})\n'+ + 'with p.open("a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'+ + 'if (p.parent/"stall").exists(): time.sleep(5)\n'+ + 'if (p.parent/"fail").exists(): print("private-supervisor-token"); sys.exit(3)\n'+ + 'if "show" in sys.argv and "system" in sys.argv and (p.parent/"single").exists():\n print("LoadState=not-found")\n'+ + 'elif "show-environment" in sys.argv: print("")\n'+ + 'elif "show" in sys.argv:\n print("LoadState=loaded\\nActiveState=inactive\\nSubState=dead\\nUnitFileState=enabled"); print(' + repr(effective) + ')\n'+ + 'elif "start" in sys.argv: sys.exit(0)\n'+ + 'else: sys.exit(91)\n', encoding="utf-8")+ helper.chmod(0o700)+ monkeypatch.setattr(gw, "_systemctl_cmd", lambda system=False: [str(helper), "system" if system else "user"])+ result = runtime.ensure_gateway_runtime(home, timeout=3.0)+ # Both scopes claiming this name is a conflict, never permission to choose one.+ assert result.state == "conflict"+ assert unit.read_bytes() == original+ assert not (home / "logs").exists()+ assert all(any(arg in {"show", "show-environment"} for arg in json.loads(line)) for line in calls.read_text().splitlines())+ (tmp_path / "single").touch()+ result = runtime.ensure_gateway_runtime(home, timeout=3.0)+ assert result.state == "starting" and result.reason_code == "deadline"+ assert sum("start" in json.loads(line) for line in calls.read_text().splitlines()) == 1+ assert unit.read_bytes() == original+ assert not (home / "logs").exists()+ (tmp_path / "fail").touch()+ result = runtime.ensure_gateway_runtime(home, timeout=3.0)+ assert result.state == "inaccessible" and result.reason_code == "service_manager_unavailable"+ assert "private-supervisor-token" not in repr(result)+ assert sum("start" in json.loads(line) for line in calls.read_text().splitlines()) == 1+ assert not (home / "logs").exists()+ (tmp_path / "stall").touch()+ before = time.monotonic()+ result = runtime.ensure_gateway_runtime(home, timeout=3.0)+ assert result.reason_code == "deadline"+ assert time.monotonic() - before < 6+ assert sum("start" in json.loads(line) for line in calls.read_text().splitlines()) == 1++- @pytest.mark.linux_only[email protected]("linux")+def test_public_ensure_json_deadline_and_invalid_invocation(tmp_path):+ from hermes_cli import gateway_runtime as runtime+ assert callable(getattr(runtime, "ensure_gateway_runtime", None))+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ (home / ".hermes-update-in-progress").write_text("private-token-not-for-stdout", encoding="utf-8")+ env = {**os.environ, "HERMES_HOME": str(home)}+ result = subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "ensure", "--json"],+ env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)+ assert result.returncode == 6, result.stderr+ value = json.loads(result.stdout)+ assert value["state"] == "draining" and value["reason_code"] == "update_paused"+ assert "private-token" not in result.stdout+ result = subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "ensure", "--json", "--timeout", "nan"],+ env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)+ assert result.returncode == 2+ assert json.loads(result.stdout)["reason_code"] == "invalid_invocation"+ result = subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "ensure", "--json", "--unknown", "private-value"],+ env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)+ assert result.returncode == 2+ assert json.loads(result.stdout)["reason_code"] == "invalid_invocation"+ assert "private-value" not in result.stdout++- @pytest.mark.linux_only[email protected]("linux")+def test_unmanaged_child_uses_explicit_home_and_survives_launcher_exit(tmp_path, monkeypatch):+ from hermes_cli import gateway_runtime_start as start+ assert callable(getattr(start, "spawn_unmanaged_gateway", None))+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ witness = home / "child.json"+ gate = home / "exit"+ launcher = tmp_path / "launcher.py"+ launcher.write_text(+ "import json,os,sys,time\nfrom pathlib import Path\n"+ "from hermes_cli.gateway_runtime_start import spawn_unmanaged_gateway\n"+ "import hermes_cli.gateway_runtime_start as start\n"+ f"home=Path({str(home)!r})\n"+ "real=start.subprocess.Popen\n"+ "def boundary(argv, **kw):\n"+ " assert argv[-3:] == ['gateway','run','--quiet']\n"+ " assert '--replace' not in argv and '--force' not in argv\n"+ " assert kw['env']['HERMES_HOME'] == str(home)\n"+ " code=\"import os,json,time; from pathlib import Path; h=Path(os.environ['HERMES_HOME']); (h/'child.json').write_text(json.dumps({'pid':os.getpid(),'sid':os.getsid(0),'home':str(h)}));\\nwhile not (h/'exit').exists(): time.sleep(.02)\"\n"+ " return real([sys.executable,'-c',code], **kw)\n"+ "start.subprocess.Popen=boundary\n"+ "child=spawn_unmanaged_gateway(home, deadline=time.monotonic()+5)\n"+ "print(child.pid, flush=True)\n", encoding="utf-8")+ env = {**os.environ, "PYTHONPATH": str(Path.cwd()), "HERMES_HOME": str(tmp_path / "wrong")}+ result = subprocess.run([sys.executable, str(launcher)], env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=10)+ try:+ assert result.returncode == 0, result.stderr+ deadline = time.monotonic() + 5+ while not witness.exists() and time.monotonic() < deadline:+ time.sleep(.02)+ value = json.loads(witness.read_text())+ assert value["pid"] == int(result.stdout) == value["sid"]+ assert value["home"] == str(home)+ finally:+ gate.touch()++- @pytest.mark.linux_only[email protected]("linux")[email protected]_gateway_lookalike # stub interpreter records env then exits; reaped below+def test_unmanaged_runtime_does_not_inherit_client_yolo(tmp_path, monkeypatch):+ from hermes_cli import gateway_runtime_start as start++ home = tmp_path / 'policy-home'+ home.mkdir(mode=0o700)+ witness = home / 'policy.json'+ executable = tmp_path / 'owned-interpreter'+ repo = Path(__file__).resolve().parents[2]+ executable.write_text(+ '#!' + sys.executable + '\nimport json, os, sys\nfrom pathlib import Path\n'+ + f'sys.path.insert(0, {str(repo)!r})\n'+ + 'from tools import approval\n'+ + f'Path({str(witness)!r}).write_text(json.dumps('+ + "{'yolo': approval._YOLO_MODE_FROZEN, 'sentinel': os.environ.get('RUNTIME_TEST_SENTINEL')}))\n",+ encoding='utf-8',+ )+ executable.chmod(0o700)+ monkeypatch.setattr(sys, 'executable', str(executable))+ monkeypatch.setenv('HERMES_YOLO_MODE', '1')+ monkeypatch.setenv('RUNTIME_TEST_SENTINEL', 'retained')+ child = start.spawn_unmanaged_gateway(home, deadline=time.monotonic() + 5)+ try:+ assert child.wait(timeout=10) == 0+ finally:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=5)+ assert json.loads(witness.read_text()) == {'yolo': False, 'sentinel': 'retained'}+ assert os.environ['HERMES_YOLO_MODE'] == '1'++- @pytest.mark.linux_only[email protected]("linux")+def test_reserved_profile_without_pid_or_control_is_never_absent(tmp_path):+ from gateway.runtime_ownership import ProfileOwnership+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ home = tmp_path / "reserved"+ home.mkdir(mode=0o700)+ owner = ProfileOwnership()+ owner.reserve([home])+ try:+ assert not (home / "gateway.pid").exists()+ assert discover_gateway_endpoint(home).state == "starting"+ (home / "gateway.lock").chmod(0)+ assert discover_gateway_endpoint(home).state == "inaccessible"+ finally:+ (home / "gateway.lock").chmod(0o600)+ owner.close()+ assert discover_gateway_endpoint(home).state == "absent"++- @pytest.mark.windows_only[email protected]("windows")+def test_native_windows_discovery_uses_same_user_pipe(tmp_path):+ from gateway.runtime_bootstrap_windows import NativeControlServer+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ home = tmp_path.resolve()+ def handle(raw, subject):+ assert subject.startswith("sid:")+ request = json.loads(raw)+ assert request["verb"] == "identify"+ return json.dumps({"protocol": 1, "id": 1, "ok": True, "result": {+ "runtime_protocol": 1, "state": "starting", "instance_id": "native-peer",+ "served_profiles": [{"home": str(home), "profile_id": str(home)}]+ }}).encode() + b"\n"+ server = NativeControlServer(home, handle)+ server.start()+ try:+ assert discover_gateway_endpoint(home, timeout=2).state == "starting"+ finally:+ server.close()++- @pytest.mark.windows_only[email protected]("windows")+def test_native_windows_spawn_never_retries_without_breakaway(tmp_path, monkeypatch):+ from hermes_cli import gateway_runtime_start as start+ from hermes_cli.gateway_runtime_service import RuntimeStartError+ from hermes_cli._subprocess_compat import windows_detach_flags+ calls = []+ def denied(argv, **kwargs):+ calls.append(kwargs)+ raise PermissionError("job forbids breakaway")+ monkeypatch.setattr(start.subprocess, "Popen", denied)+ with pytest.raises(RuntimeStartError, match="windows_breakaway_unavailable"):+ start.spawn_unmanaged_gateway(tmp_path, deadline=time.monotonic()+5)+ assert len(calls) == 1+ assert calls[0]["creationflags"] == windows_detach_flags()++- @pytest.mark.macos_only[email protected]("macos")+def test_native_launchd_ambiguous_domains_cannot_start(tmp_path, monkeypatch):+ from hermes_cli.gateway_runtime_service import discover_existing_gateway_service, RuntimeStartError+ peer = tmp_path / "inert_launchd.py"+ peer.write_text("print('state = not running')\n", encoding="utf-8")+ actual = subprocess.run+ calls = []+ def boundary(argv, **kwargs):+ assert argv[0] == "launchctl"+ calls.append(argv)+ return actual([sys.executable, str(peer), *argv[1:]], **kwargs)+ monkeypatch.setattr(subprocess, "run", boundary)+ with pytest.raises(RuntimeStartError, match="service_scope_conflict"):+ discover_existing_gateway_service(tmp_path.resolve(), deadline=time.monotonic()+5)+ assert len(calls) == 2 and all(argv[1] == "print" for argv in calls)++- @pytest.mark.linux_only[email protected]("linux")[email protected]_gateway_lookalike # stub interpreter records the resolved home then exits; reaped below+def test_unmanaged_root_home_child_ignores_sticky_active_profile(tmp_path, monkeypatch):+ """Explicit default selection survives the CLI child's own profile bootstrap (F15): with+ active_profile=other sticky, the spawned `gateway run` must still resolve the root home."""+ from hermes_cli import gateway_runtime_start as start+ root = tmp_path / ".hermes"+ (root / "profiles" / "other").mkdir(parents=True)+ (root / "active_profile").write_text("other", encoding="utf-8")+ witness = tmp_path / "resolved.json"+ real = start.subprocess.Popen++ def boundary(argv, **kwargs):+ assert argv[:3] == [sys.executable, "-m", "hermes_cli.main"]+ # Same argv and env as the real child; the module-import bootstrap is what resolves the profile.+ code = ("import json, os, sys\nsys.argv = ['hermes', *sys.argv[1:]]\nimport hermes_cli.main\n"+ f"open({str(witness)!r}, 'w').write(json.dumps({{'home': os.environ['HERMES_HOME'], 'argv': sys.argv}}))")+ return real([sys.executable, "-c", code, *argv[3:]], **kwargs)++ monkeypatch.setattr(start.subprocess, "Popen", boundary)+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("PYTHONPATH", str(Path(__file__).resolve().parents[2]))+ child = start.spawn_unmanaged_gateway(root, deadline=time.monotonic() + 5)+ try:+ assert child.wait(timeout=30) == 0+ finally:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=5)+ resolved = json.loads(witness.read_text())+ assert resolved["home"] == str(root), resolved+ assert resolved["argv"] == ["hermes", "gateway", "run", "--quiet"], resolveddiff --cc tests/hermes_cli/test_gateway_runtime_service.pyindex 7840dad3e1a,00000000000..61864c44374mode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_runtime_service.py+++ b/tests/hermes_cli/test_gateway_runtime_service.py@@@ -1,298 -1,0 +1,298 @@@+"""Installed identity proofs at inert native supervisor executable boundaries."""+import json+import os+from pathlib import Path+import subprocess+import sys+import time++import pytest++- @pytest.mark.linux_only[email protected]("linux")[email protected]("case,reason", [+ ("custom", "deadline"), ("named", "deadline"), ("alias", "deadline"),+ ("default", "deadline"),+ ("wrong_home", "profile_mismatch"), ("wrong_user", "service_account_mismatch"),+ ("missing_identity", "service_identity_unverified"),+ ("omitted_empty_exec_lists", "deadline"),+ ("env_file", "service_identity_unverified"), ("dynamic_user", "service_identity_unverified"),+ ("wrong_command", "service_identity_unverified"), ("command_profile", "profile_mismatch"),+ ("dropin_home", "profile_mismatch"), ("manager_home", "profile_mismatch"),+])+def test_ensure_checks_effective_service_binding_before_start(tmp_path, monkeypatch, case, reason):+ from hermes_cli import gateway_runtime as runtime+ from hermes_cli.gateway_runtime_service import service_suffix++ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ home = tmp_path / (".hermes" if case == "default" else "custom root")+ if case == "named":+ home = home / "profiles" / "worker"+ home.mkdir(mode=0o700, parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ suffix = service_suffix(home)+ unit = tmp_path / ".config/systemd/user" / f"hermes-gateway{'-' + suffix if suffix else ''}.service"+ unit.parent.mkdir(parents=True)+ unit.write_text(f'[Service]\nExecStart={sys.executable} -m hermes_cli.main gateway run\nEnvironment="HERMES_HOME={home}"\n', encoding="utf-8")+ original = unit.read_bytes()+ configured = home+ if case in {"wrong_home", "dropin_home"}:+ configured = tmp_path / "unrequested"+ if case == "wrong_home":+ unit.write_text(f'[Service]\nEnvironment="HERMES_HOME={configured}"\n', encoding="utf-8")+ original = unit.read_bytes()+ if case == "dropin_home":+ override = unit.parent / (unit.name + '.d') / 'override.conf'+ override.parent.mkdir()+ override.write_text(f'[Service]\nEnvironment="HERMES_HOME={configured}"\n', encoding="utf-8")+ if case == "alias":+ configured = tmp_path / "alias"+ configured.symlink_to(home, target_is_directory=True)+ command = f'{sys.executable} -m hermes_cli.main gateway run'+ if case == "named":+ command += " --profile worker"+ if case == "command_profile":+ command += " --profile stranger"+ if case == "wrong_command":+ command = '/bin/echo hermes_cli.main gateway run'+ props = dict(LoadState="loaded", ActiveState="inactive", SubState="dead", UnitFileState="enabled",+ User=str(os.getuid()), DynamicUser="no", Environment=f'"HERMES_HOME={configured}" "HERMES_SUPERVISED_CHILD=1"',+ EnvironmentFiles="", PassEnvironment="", UnsetEnvironment="", PAMName="",+ RootDirectory="", RootImage="", ExecStartPre="", ExecCondition="",+ ExecStart=f'{{ path={command.split()[0]} ; argv[]={command} ; ignore_errors=no ; }}',+ DropInPaths=str(unit.parent / (unit.name + '.d') / 'override.conf') if case == "dropin_home" else "")+ manager_env = ""+ if case == "wrong_user":+ props['User'] = str(os.getuid() + 1)+ if case == "missing_identity":+ props = {k: props[k] for k in ("LoadState", "ActiveState", "SubState", "UnitFileState")}+ if case == "omitted_empty_exec_lists":+ # systemd >= 25x prints nothing for empty exec-command lists and+ # EnvironmentFiles even under --all; absence there means empty, not unknown.+ for key in ("ExecStartPre", "ExecCondition", "EnvironmentFiles"):+ del props[key]+ if case == "env_file":+ env_file = tmp_path / "override.env"+ env_file.write_text(f'HERMES_HOME={tmp_path / "other"}\n', encoding="utf-8")+ props['EnvironmentFiles'] = f'{env_file} (ignore_errors=no)'+ if case == "dynamic_user":+ props['DynamicUser'] = 'yes'+ if case == "manager_home":+ props['Environment'] = 'HERMES_SUPERVISED_CHILD=1'+ manager_env = f'HERMES_HOME={tmp_path / "other"}\n'+ if case == "default":+ # An older default install may rely on the user manager's HOME.+ props['Environment'] = 'HERMES_SUPERVISED_CHILD=1'+ manager_env = f'HOME={tmp_path}\n'+ definition = tmp_path / "effective.json"+ definition.write_text(json.dumps({'props': props, 'system': False, 'env': manager_env}), encoding="utf-8")+ calls = tmp_path / 'calls.jsonl'+ executable = tmp_path / 'inert-supervisor'+ executable.write_text('#!' + sys.executable + '\nimport json,sys\nfrom pathlib import Path\n'+ + f'p=Path({str(tmp_path)!r})\nd=json.loads((p/"effective.json").read_text())\n'+ + 'with (p/"calls.jsonl").open("a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'+ + 'if "show-environment" in sys.argv: print(d["env"])\n'+ + 'elif "show" in sys.argv:\n'+ + ' if ("--user" not in sys.argv) == d["system"]: print("\\n".join(k+"="+v for k,v in d["props"].items()))\n'+ + ' else: print("LoadState=not-found")\n'+ + 'elif "start" not in sys.argv: sys.exit(91)\n', encoding='utf-8')+ executable.chmod(0o700)+ monkeypatch.setenv('PATH', str(tmp_path) + os.pathsep + os.environ['PATH'])+ from hermes_cli import gateway as gw+ monkeypatch.setattr(gw, "_systemctl_cmd", lambda system=False: [str(executable)] + ([] if system else ["--user"]))+ result = runtime.ensure_gateway_runtime(home, timeout=3.0)+ assert result.reason_code == reason+ commands = [json.loads(line) for line in calls.read_text().splitlines()]+ starts = [cmd for cmd in commands if 'start' in cmd]+ assert len(starts) == (1 if reason == 'deadline' else 0)+ assert all('--no-ask-password' in cmd for cmd in starts)+ assert unit.read_bytes() == original+ assert not (home / 'logs').exists()++[email protected]("configured,command,reason", [+ ("requested", "gateway", None), ("other", "gateway", "profile_mismatch"),+ ("requested", "echo", "service_identity_unverified"),+ (None, "gateway", "service_identity_unverified"),+ ("requested", "unsupervised", "service_identity_unverified"),+ ("requested", "wrong_account", "service_account_mismatch"),+])+def test_loaded_launchd_identity_is_independent_of_disk(configured, command, reason, tmp_path):+ from hermes_cli.gateway_runtime_service_identity import verify_launchd_loaded+ home = tmp_path / "requested"+ argv = [sys.executable, "-m", "hermes_cli.main", "gateway", "run"]+ if command == "echo":+ argv = ["/bin/echo", "hermes_cli.main", "gateway", "run"]+ environment = f"HERMES_HOME => {tmp_path / configured}" if configured else ""+ output = "gui/123/ai.hermes.gateway = {\n\tstate = not running\n\tprogram = " + argv[0] + "\n\targuments = {\n" + "\n".join("\t\t" + a for a in argv) + "\n\t}\n\tenvironment = {\n\t\t" + environment + "\n\t}\n}"+ if command != "unsupervised":+ output = output.replace("\n\tenvironment = {\n", "\n\tenvironment = {\n\t\tHERMES_SUPERVISED_CHILD => 1\n")+ if command == "wrong_account":+ output = output.replace("\n\tstate", "\n\tusername = other\n\tstate")+ if reason:+ with pytest.raises(ValueError, match=reason):+ verify_launchd_loaded(output, home, uid=123, username="owner")+ else:+ verify_launchd_loaded(output, home, uid=123, username="owner")++[email protected]("case,reason", [+ ("bound", None), ("utf16", None), ("wrong_home", "profile_mismatch"),+ ("wrong_user", "service_account_mismatch"), ("missing_user", "service_identity_unverified"),+ ("extra_action", "service_identity_unverified"), ("disabled", "service_disabled"),+ ("unknown_script", "service_identity_unverified"), ("malformed_xml", "service_identity_unverified"),+])+def test_task_xml_binds_actual_action_and_principal(case, reason, tmp_path):+ from hermes_cli.gateway_runtime_service_identity import verify_windows_task+ from hermes_cli.gateway_windows import _build_scheduled_task_xml+ home = tmp_path / 'requested'+ home.mkdir()+ script = home / 'gateway.vbs'+ configured = str(home if case != 'wrong_home' else tmp_path / 'other')+ # The current installed launcher grammar; no script is executed.+ script.write_text("\n".join([+ "' Hermes Agent Gateway", "Option Explicit", "Dim sh, env, existing_pp",+ 'Set sh = CreateObject("WScript.Shell")', 'Set env = sh.Environment("PROCESS")',+ f'env.Item("HERMES_HOME") = "{configured}"',+ 'env.Item("HERMES_SUPERVISED_CHILD") = "1"',+ 'env.Item("VIRTUAL_ENV") = "C:\\Hermes"',+ 'existing_pp = env.Item("PYTHONPATH")', 'If Len(existing_pp) > 0 Then',+ ' env.Item("PYTHONPATH") = "C:\\Hermes;" & existing_pp', 'Else',+ ' env.Item("PYTHONPATH") = "C:\\Hermes"', 'End If',+ f'sh.CurrentDirectory = "{home}"',+ f'sh.Run "{sys.executable} -m hermes_cli.main gateway run", 0, False',+ ]) + "\n", encoding='utf-8')+ user = 'DOMAIN\\owner'+ xml = _build_scheduled_task_xml('Hermes_Gateway', script, user)+ if case == 'wrong_user':+ xml = xml.replace(user, 'DOMAIN\\other')+ if case == 'missing_user':+ xml = xml.replace(f'<UserId>{user}</UserId>', '')+ if case == 'extra_action':+ xml = xml.replace('</Actions>', '<Exec><Command>other.exe</Command></Exec></Actions>')+ if case == 'disabled':+ xml = xml.replace('<Enabled>true</Enabled>', '<Enabled>false</Enabled>')+ if case == 'utf16':+ xml = xml.encode('utf-16')+ if case == 'malformed_xml':+ xml = '<Task>'+ if case == 'unknown_script':+ script.write_text('MsgBox "not a gateway"', encoding='utf-8')+ if reason:+ with pytest.raises(ValueError, match=reason):+ verify_windows_task(xml, home, user, 'S-1-5-21-123')+ else:+ verify_windows_task(xml, home, user, 'S-1-5-21-123')++- @pytest.mark.macos_only[email protected]("macos")[email protected]("case,reason", [("loaded_good_disk_wrong", None), ("loaded_wrong_disk_good", "profile_mismatch"), ("bootstrap", None)])+def test_native_launchd_checks_loaded_job_before_disk(case, reason, tmp_path, monkeypatch):+ import plistlib+ import pwd+ from types import SimpleNamespace+ from hermes_cli import gateway_runtime_service as service+ home = tmp_path / 'profile'+ home.mkdir(mode=0o700)+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.setattr(pwd, 'getpwuid', lambda uid: SimpleNamespace(pw_dir=str(tmp_path), pw_name="owner"))+ label = 'ai.hermes.gateway' + ('-' + service.service_suffix(home) if service.service_suffix(home) else '')+ plist = tmp_path / 'Library/LaunchAgents' / (label + '.plist')+ plist.parent.mkdir(parents=True)+ argv = [sys.executable, '-m', 'hermes_cli.main', 'gateway', 'run']+ disk_home = tmp_path / 'wrong' if case == 'loaded_good_disk_wrong' else home+ plist.write_bytes(plistlib.dumps(dict(Label=label, ProgramArguments=argv,+ EnvironmentVariables=dict(HERMES_HOME=str(disk_home), HERMES_SUPERVISED_CHILD='1'))))+ original = plist.read_bytes()+ loaded_home = tmp_path / 'wrong' if case == 'loaded_wrong_disk_good' else home+ output = 'gui/' + str(os.getuid()) + '/' + label + ' = {\n\tstate = not running\n\tprogram = ' + argv[0] + '\n\targuments = {\n' + '\n'.join('\t\t' + arg for arg in argv) + '\n\t}\n\tenvironment = {\n\t\tHERMES_HOME => ' + str(loaded_home) + '\n\t\tHERMES_SUPERVISED_CHILD => 1\n\t}\n}'+ peer = tmp_path / 'supervisor.py'+ peer.write_text('import sys\n' + f'output={output!r}\nbootstrap={case == "bootstrap"!r}\n' ++ 'if "print" in sys.argv:\n sys.exit(113) if bootstrap or any(a.startswith("user/") for a in sys.argv) else print(output)\n', encoding='utf-8')+ actual = subprocess.run+ calls = []+ def boundary(argv, **kw):+ assert argv[0] == 'launchctl'+ calls.append(argv)+ return actual([sys.executable, str(peer), *argv[1:]], **kw)+ monkeypatch.setattr(subprocess, 'run', boundary)+ if reason:+ with pytest.raises(service.RuntimeStartError, match=reason):+ service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)+ assert all(a[1] == 'print' for a in calls)+ else:+ found = service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)+ assert found is not None+ service.start_existing_gateway_service(found, deadline=time.monotonic()+5)+ assert calls[-1][1] == ('bootstrap' if case == 'bootstrap' else 'kickstart')+ assert plist.read_bytes() == original++- @pytest.mark.windows_only[email protected]("windows")[email protected]("wrong", [False, True])+def test_native_task_query_uses_installed_xml_and_vendor_launcher(wrong, tmp_path, monkeypatch):+ from hermes_cli import gateway_runtime_service as service+ from hermes_cli.gateway_windows import _build_gateway_vbs_script, _build_scheduled_task_xml+ home = tmp_path / 'profile'+ home.mkdir()+ monkeypatch.setenv('HERMES_HOME', str(home))+ script = home / 'gateway.vbs'+ # newline='' mirrors the installer's _atomic_write: the template is already CRLF and+ # Windows text mode would otherwise double it to \r\r\n, which is not the vendor template.+ script.write_text(_build_gateway_vbs_script(sys.executable, str(home), str(home), ''), encoding='utf-8', newline='')+ original = script.read_bytes()+ # whoami is read-only native account evidence; no task-manager mutation.+ identity = subprocess.run(['whoami.exe', '/USER', '/FO', 'CSV', '/NH'], stdin=subprocess.DEVNULL, capture_output=True, timeout=5)+ from hermes_cli.gateway_windows import _schtasks_encoding+ import csv+ account, sid = next(csv.reader(identity.stdout.decode(_schtasks_encoding()).splitlines()))+ suffix = service.service_suffix(home)+ name = 'Hermes_Gateway' + ('_' + suffix if suffix else '')+ xml = _build_scheduled_task_xml(name, script, 'S-1-5-18' if wrong else sid)+ peer = tmp_path / 'supervisor.py'+ row = f'"\\{name}","N/A","Ready"'+ peer.write_text('import sys\n' + f'xml={xml!r}\n' ++ 'if "/XML" in sys.argv: sys.stdout.buffer.write(xml.encode("utf-16"))\n'+ + f'elif "/Query" in sys.argv: print({row!r})\n', encoding='utf-8')+ actual = subprocess.run+ calls = []+ def boundary(argv, **kw):+ if argv[0] == 'whoami.exe':+ return actual(argv, **kw)+ assert argv[0] == 'schtasks.exe'+ calls.append(argv)+ return actual([sys.executable, str(peer), *argv[1:]], **kw)+ monkeypatch.setattr(subprocess, 'run', boundary)+ if wrong:+ with pytest.raises(service.RuntimeStartError, match='service_account_mismatch'):+ service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)+ assert not any('/Run' in a for a in calls)+ else:+ found = service.discover_existing_gateway_service(home, deadline=time.monotonic()+5)+ assert found is not None+ service.start_existing_gateway_service(found, deadline=time.monotonic()+5)+ assert sum('/Run' in a for a in calls) == 1+ assert script.read_bytes() == original++- @pytest.mark.linux_only[email protected]("linux")+def test_service_definition_reads_reject_fifo_without_waiting(tmp_path):+ from hermes_cli.gateway_runtime_service_identity import read_definition+ regular = tmp_path / 'regular'+ regular.write_bytes(b'installed definition')+ assert read_definition(regular) == regular.read_bytes()+ fifo = tmp_path / 'fifo'+ os.mkfifo(fifo, 0o600)+ with pytest.raises(ValueError, match='service_identity_unverified'):+ read_definition(fifo)++[email protected]("outer", ["python", "echo"])+def test_gateway_wrapper_requires_actual_python_entrypoint(outer, tmp_path):+ from hermes_cli.gateway_runtime_service_identity import verify_gateway_argv+ argv = [sys.executable if outer == 'python' else '/bin/echo', '-m', 'hermes_cli.stderr_timestamp', '--error-log', str(tmp_path / 'error.log'), '--', sys.executable, '-m', 'hermes_cli.main', 'gateway', 'run']+ if outer == 'echo':+ with pytest.raises(ValueError, match='service_identity_unverified'):+ verify_gateway_argv(argv, tmp_path)+ else:+ verify_gateway_argv(argv, tmp_path)diff --cc tests/hermes_cli/test_gateway_runtime_service_roots.pyindex f44e17fe09f,00000000000..d73ea667387mode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_runtime_service_roots.py+++ b/tests/hermes_cli/test_gateway_runtime_service_roots.py@@@ -1,38 -1,0 +1,38 @@@+"""Explicit requested-root naming and start-response encoding contracts."""+import subprocess+import sys+import time+from pathlib import Path++import pytest++[email protected]('named', [False, True])+def test_requested_service_name_does_not_borrow_callers_home(tmp_path, monkeypatch, named):+ from hermes_cli.gateway_runtime_service import service_suffix+ from hermes_cli.gateway import _profile_suffix+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)+ requested = tmp_path / 'custom'+ if named:+ requested = requested / 'profiles' / 'worker'+ requested.mkdir(parents=True)+ monkeypatch.setenv('HERMES_HOME', str(requested))+ installed = _profile_suffix()+ monkeypatch.setenv('HERMES_HOME', str(tmp_path / '.hermes'))+ assert service_suffix(requested) == installed++- @pytest.mark.linux_only[email protected]("linux")+def test_service_start_does_not_decode_irrelevant_supervisor_output():+ from hermes_cli.gateway_runtime_service import ExistingService, start_existing_gateway_service+ service = ExistingService('systemd', (sys.executable, '-c', 'import sys; sys.stdout.buffer.write(bytes([255]))'))+ start_existing_gateway_service(service, deadline=time.monotonic() + 5)+++def test_malformed_installed_plist_has_a_bounded_refusal():+ import plistlib+ from hermes_cli.gateway_runtime_service import _verify_binding, RuntimeStartError+ with pytest.raises(RuntimeStartError, match='service_identity_unverified'):+ _verify_binding(plistlib.loads, b'<?xml version="1.0"?><plist><dict>')+ definition = {'Label': 'ai.hermes.gateway'}+ assert _verify_binding(plistlib.loads, plistlib.dumps(definition)) == definitiondiff --cc tests/hermes_cli/test_gateway_service_choice.pyindex 485b8fa0719,00000000000..adf11ea781fmode 100644,000000..100644--- a/tests/hermes_cli/test_gateway_service_choice.py+++ b/tests/hermes_cli/test_gateway_service_choice.py@@@ -1,192 -1,0 +1,192 @@@+"""Service consent through real config/discovery/install; only OS peers are fake."""+import io+import json+import os+from pathlib import Path+import sys+import tempfile++import pytest++from hermes_cli import config as config_api+from hermes_cli import gateway+from hermes_cli import gateway_setup_service as setup_service+++def supervisor(tmp_path, monkeypatch):+ # The installer intentionally rejects /tmp profiles. A disposable RAM-backed+ # home exercises that real guard without disabling it or touching user state.+ with tempfile.TemporaryDirectory(prefix="hermes-choice-", dir="/dev/shm") as directory:+ home = Path(directory)+ profile = home / "profile"+ profile.mkdir()+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("HERMES_HOME", str(profile))+ runtime = home / "run"+ runtime.mkdir()+ (runtime / "bus").touch()+ monkeypatch.setenv("XDG_RUNTIME_DIR", str(runtime))+ monkeypatch.delenv("DBUS_SESSION_BUS_ADDRESS", raising=False)+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ calls = tmp_path / "calls.jsonl"+ state = tmp_path / "active"+ for name in ("systemctl", "loginctl", "sudo"):+ exe = bin_dir / name+ exe.write_text(+ f"#!{sys.executable}\n"+ "import json, os, pathlib, sys\n"+ f"calls = pathlib.Path({str(calls)!r})\n"+ "with calls.open('a') as stream: stream.write(json.dumps([pathlib.Path(sys.argv[0]).name, *sys.argv[1:]]) + '\\n')\n"+ f"active = pathlib.Path({str(state)!r})\n"+ "args = sys.argv[1:]\n"+ "if 'enable' in args and os.getenv('CHOICE_FAIL'): sys.exit(1)\n"+ "if 'start' in args: active.touch()\n"+ "if 'is-active' in args: print('active' if active.exists() else 'inactive')\n"+ "elif 'show-user' in args: print('yes')\n"+ "elif 'show' in args: print('LoadState=not-found')\n"+ "elif 'is-system-running' in args: print('running')\n",+ encoding="utf-8",+ )+ exe.chmod(0o700)+ monkeypatch.setenv("PATH", str(bin_dir) + os.pathsep + os.environ["PATH"])+ # Inject the owned executable at the OS command boundary, retaining the+ # live-system guard (which correctly blocks a command named systemctl).+ peer = bin_dir / "supervisor-peer"+ peer.write_bytes((bin_dir / "systemctl").read_bytes())+ peer.chmod(0o700)+ monkeypatch.setattr(gateway, "_systemctl_cmd", lambda system=False: [str(peer)])+ yield profile, calls+++def _operations(calls):+ return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []++- @pytest.mark.linux_only[email protected]("linux")[email protected]("choice", [None, "decline", "install"])[email protected]("installed", [False, True])+def test_import_and_ordinary_setup_never_authorize_install(supervisor, choice, installed):+ profile, calls = supervisor+ config_api.save_config({"gateway": {"service_install_choice": choice}})+ if installed:+ unit = gateway.get_systemd_unit_path()+ unit.parent.mkdir(parents=True)+ unit.write_text(gateway.generate_systemd_unit(), encoding="utf-8")+ before = (profile / "config.yaml").read_bytes()+ assert setup_service.ensure_gateway_service() is installed+ assert setup_service.ensure_gateway_service(interactive=True) is installed+ assert setup_service.ensure_gateway_service(context="import", install=True) is installed+ from hermes_cli.backup import _revive_gateway_after_import+ _revive_gateway_after_import(profile)+ assert gateway.get_systemd_unit_path().exists() is installed+ forbidden = {"enable", "enable-linger", "daemon-reload"}+ if not installed:+ forbidden.add("start")+ assert not any(set(op) & forbidden for op in _operations(calls))+ assert (profile / "config.yaml").read_bytes() == before++- @pytest.mark.linux_only[email protected]("linux")[email protected]("answer, fail", [(False, False), (True, False), (True, True)])+def test_explicit_setup_consent_is_durable_only_after_success(supervisor, monkeypatch, answer, fail):+ profile, calls = supervisor+ config_api.save_config({"gateway": {"service_install_choice": None}, "custom": "keep"})+ prompts = []+ monkeypatch.setattr(gateway, "prompt_yes_no", lambda *args: prompts.append(args) or answer)+ stream = io.StringIO()+ stream.isatty = lambda: True+ monkeypatch.setattr(sys, "stdin", stream)+ if fail:+ monkeypatch.setenv("CHOICE_FAIL", "1")+ config = config_api.load_config()+ result = setup_service.ensure_gateway_service(interactive=True, config=config)+ expected = None if fail else ("install" if answer else "decline")+ assert config_api.load_config()["gateway"]["service_install_choice"] == expected+ assert config["gateway"]["service_install_choice"] == expected+ assert config_api.load_config()["custom"] == "keep"+ assert result is (answer and not fail)+ assert len(prompts) == 1+ if not fail:+ setup_service.ensure_gateway_service(interactive=True)+ assert len(prompts) == 1+ if not answer:+ assert not gateway.get_systemd_unit_path().exists()+ assert not any(set(op) & {"enable", "enable-linger", "start", "daemon-reload"} for op in _operations(calls))++- @pytest.mark.linux_only[email protected]("linux")[email protected]("start_now", [False, True])[email protected]("consent", [False, True])+def test_wizard_service_choice_controls_installation(supervisor, monkeypatch, start_now, consent):+ profile, calls = supervisor+ config_api.save_config({"gateway": {"service_install_choice": None}})+ stream = io.StringIO()+ stream.isatty = lambda: True+ monkeypatch.setattr(sys, "stdin", stream)+ answers = iter([start_now, consent])+ monkeypatch.setattr(gateway, "prompt_yes_no", lambda *args: next(answers))+ monkeypatch.setattr(gateway, "prompt_choice", lambda *args, **kwargs: 0)+ spawned = []+ # Popen is the unmanaged process boundary; no real gateway is launched.+ original_popen = gateway.subprocess.Popen++ def popen(argv, *args, **kwargs):+ if "hermes_cli.main" in argv:+ spawned.append((argv, kwargs))+ return None+ return original_popen(argv, *args, **kwargs)++ monkeypatch.setattr(gateway.subprocess, "Popen", popen)+ setup_service._wizard_install_service("systemd")+ assert gateway.get_systemd_unit_path().exists() is consent+ assert bool(spawned) is (start_now and not consent)+ assert config_api.load_config()["gateway"]["service_install_choice"] == ("install" if consent else "decline")+ if spawned:+ assert "--replace" not in spawned[0][0]++- @pytest.mark.linux_only[email protected]("linux")[email protected]("fail", [False, True])+def test_explicit_install_records_only_completed_install(supervisor, monkeypatch, fail):+ from argparse import Namespace+ import subprocess++ config_api.save_config({"gateway": {"service_install_choice": "decline"}})+ if fail:+ monkeypatch.setenv("CHOICE_FAIL", "1")+ args = Namespace(start_now=False, start_on_login=True)+ if fail:+ with pytest.raises(subprocess.CalledProcessError):+ gateway._cmd_install(args)+ else:+ gateway._cmd_install(args)+ assert config_api.load_config()["gateway"]["service_install_choice"] == ("decline" if fail else "install")++- @pytest.mark.linux_only[email protected]("linux")+def test_wizard_start_does_not_spawn_over_reserved_owner(supervisor, monkeypatch):+ from gateway.runtime_ownership import ProfileOwnership+ profile, calls = supervisor+ profile.chmod(0o700)+ config_api.save_config({"gateway": {"service_install_choice": "decline"}})+ stream = io.StringIO()+ stream.isatty = lambda: True+ monkeypatch.setattr(sys, "stdin", stream)+ monkeypatch.setattr(gateway, "prompt_yes_no", lambda *args: True)+ spawned = []+ original = gateway.subprocess.Popen+ def boundary(argv, *args, **kwargs):+ if "hermes_cli.main" in argv:+ spawned.append(argv)+ return None+ return original(argv, *args, **kwargs)+ monkeypatch.setattr(gateway.subprocess, "Popen", boundary)+ owner = ProfileOwnership()+ owner.reserve([profile])+ try:+ setup_service._wizard_install_service("systemd")+ assert not spawned+ finally:+ owner.close()diff --cc tests/hermes_cli/test_kanban_gateway_restart_handoff.pyindex 7981b97a2e1,c02c4308fbd..1b2a7037755--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py@@@ -143,10 -140,10 +143,10 @@@ def test_standalone_dispatcher_keeps_di)assert kbd._default_spawn(task, str(workspace)) == 4243- assert captured_cmd[:3] == ["hermes", "-p", "coder"]+ assert captured_cmd == [sys.executable, "-m", "hermes_cli.kanban_worker_client"]- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")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:diff --cc tests/hermes_cli/test_profile_pm_portability.pyindex 00000000000,633cc0da115..1d01ea1f02emode 000000,100644..100644--- a/tests/hermes_cli/test_profile_pm_portability.py+++ b/tests/hermes_cli/test_profile_pm_portability.py@@@ -1,0 -1,186 +1,187 @@@+ """Portable transfers keep user files, not machine-specific PM state."""+ from argparse import Namespace+ from pathlib import Path+ import tarfile+ import zipfile++ import pytest+++ @pytest.fixture+ def transfer_home(tmp_path, monkeypatch):+ home = tmp_path / "source-home"+ home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))++ from hermes_cli import backup, gateway, profiles++ # Restoring data must not install host services or modify the test user's shell.- monkeypatch.setattr(gateway, "ensure_gateway_service", lambda **kwargs: False)++ from hermes_cli import gateway_setup_service++ monkeypatch.setattr(gateway_setup_service, "ensure_gateway_service", lambda *args, **kwargs: False)+ monkeypatch.setattr(gateway, "_is_service_running", lambda: False)+ monkeypatch.setattr(profiles, "check_alias_collision", lambda name: "test has no aliases")+ monkeypatch.setattr(backup, "_collect_memory_provider_external_paths", lambda: [])+ return home+++ def _write_files(root, files):+ for rel, content in files.items():+ target = root / rel+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(content, encoding="utf-8")+++ @pytest.mark.parametrize("route", ["backup", "default", "named", "distribution", "explicit"])+ def test_transfers_preserve_user_files_without_porting_pm_state(+ transfer_home, tmp_path, monkeypatch, route+ ):+ from hermes_cli.backup import run_backup, run_import+ from hermes_cli.profile_distribution import (+ DistributionManifest, install_distribution, write_manifest,+ )+ from hermes_cli.profiles import export_profile, get_profile_dir, import_profile++ portable = {+ "config.yaml": "model:\n model: portable\n",+ "SOUL.md": "Be kind.\n",+ "plugins/example/facts.json": '{"owner": "plugin"}\n',+ "skills/example/tools/helper.py": "print('portable tool')\n",+ "skills/example/cache/notes.txt": "user-authored data\n",+ }+ runtime = {+ "installs/install-id/facts.json": '{"environment": "C:/other-machine/generation"}\n',+ "installs/install-id/environments/generation/pyvenv.cfg": "home = other-machine\n",+ "tools/uv/bin/uv": "machine executable\n",+ "cache/partials/transfer.partial": "unfinished transfer\n",+ }+ source = get_profile_dir("porter") if route == "named" else transfer_home+ _write_files(source, portable | runtime)+ if route == "backup":+ portable |= {f"profiles/coder/{rel}": text for rel, text in list(portable.items())}+ runtime |= {f"profiles/coder/{rel}": text for rel, text in list(runtime.items())}+ _write_files(source, portable | runtime)+ archive = tmp_path / "portable.zip"+ run_backup(Namespace(output=str(archive)))+ with zipfile.ZipFile(archive) as reader:+ names = set(reader.namelist())+ elif route in {"default", "named"}:+ name = "porter" if route == "named" else "default"+ archive = export_profile(name, str(tmp_path / "portable.tar.gz"))+ with tarfile.open(archive) as reader:+ names = {member.name.removeprefix(f"{name}/") for member in reader if member.isfile()}+ else:+ owned = sorted({Path(rel).parts[0] for rel in portable | runtime}) if route == "explicit" else []+ write_manifest(source, DistributionManifest(name="portable", distribution_owned=owned))+ names = None++ if names is not None:+ assert set(portable) <= names+ assert not (set(runtime) & names)++ target_home = tmp_path / "target-home"+ target_home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(target_home))+ if route == "backup":+ run_import(Namespace(zipfile=str(archive), force=True))+ restored = target_home+ elif route in {"default", "named"}:+ restored = import_profile(str(archive), name="restored")+ else:+ restored = install_distribution(str(source), name="restored").target_dir++ for rel, content in portable.items():+ assert (restored / rel).read_text(encoding="utf-8") == content, (route, rel)+ for rel, content in runtime.items():+ assert not (restored / rel).exists(), (route, rel)+ assert (source / rel).read_text(encoding="utf-8") == content+++ @pytest.mark.parametrize("route", ["backup", "profile", "profile-denied", "distribution", "explicit"])+ def test_incoming_runtime_state_never_replaces_target_runtime(+ transfer_home, tmp_path, monkeypatch, route+ ):+ from hermes_cli.backup import run_import+ from hermes_cli.profile_distribution import (+ DistributionManifest, install_distribution, write_manifest,+ )+ from hermes_cli.profiles import get_profile_dir, import_profile++ incoming = {+ "config.yaml": "model:\n model: restored\n",+ "plugins/example/facts.json": '{"owner": "plugin"}\n',+ "skills/example/tools/helper.py": "print('user tool')\n",+ "skills/example/cache/notes.txt": "keep user files\n",+ }+ machine = {+ "installs/key/facts.json": "foreign generation\n",+ "tools/uv/bin/uv": "foreign executable\n",+ "cache": "foreign cache file\n",+ }+ if route == "backup":+ incoming |= {f"profiles/coder/{rel}": text for rel, text in list(incoming.items())}+ machine |= {f"profiles/coder/{rel}": text for rel, text in list(machine.items())}+ staged = tmp_path / "archive-source"+ _write_files(staged, incoming | machine)+ target = transfer_home if route == "backup" else get_profile_dir("restored")+ if not route.startswith("profile"):+ _write_files(target, dict.fromkeys(machine, "target-owned runtime\n"))++ if route == "backup":+ archive = tmp_path / "legacy.zip"+ with zipfile.ZipFile(archive, "w") as writer:+ for rel, content in (incoming | machine).items():+ writer.writestr(f".hermes/{rel}", content)+ run_import(Namespace(zipfile=str(archive), force=True))+ elif route.startswith("profile"):+ archive = tmp_path / "legacy.tar.gz"+ with tarfile.open(archive, "w:gz") as writer:+ writer.add(staged, arcname="legacy")+ if route == "profile-denied":+ from hermes_cli import profiles++ real_rmtree = profiles.shutil.rmtree++ def deny_runtime_removal(path, *args, **kwargs):+ if Path(path).name == "installs":+ if kwargs.get("ignore_errors"):+ return+ raise PermissionError("staged runtime is locked")+ return real_rmtree(path, *args, **kwargs)++ with monkeypatch.context() as scoped:+ scoped.setattr(profiles.shutil, "rmtree", deny_runtime_removal)+ with pytest.raises(PermissionError, match="staged runtime is locked"):+ import_profile(str(archive), name="restored")+ assert not target.exists()+ return+ target = import_profile(str(archive), name="restored")+ else:+ owned = sorted({Path(rel).parts[0] for rel in incoming | machine}) if route == "explicit" else []+ write_manifest(staged, DistributionManifest(name="legacy", distribution_owned=owned))+ target = install_distribution(str(staged), name="restored", force=True).target_dir++ for rel, content in incoming.items():+ assert (target / rel).read_text(encoding="utf-8") == content, (route, rel)+ for rel, content in machine.items():+ if route == "profile":+ assert not (target / rel).exists(), rel+ else:+ assert (target / rel).read_text(encoding="utf-8") == "target-owned runtime\n", (route, rel)+ assert (staged / rel).read_text(encoding="utf-8") == content++ if route == "explicit":+ # Windows-authored manifests use separators that must not bypass ownership.+ write_manifest(staged, DistributionManifest(+ name="legacy", distribution_owned=[rel.replace("/", "\\") for rel in incoming | machine],+ ))+ install_distribution(str(staged), name="restored", force=True)+ for rel in machine:+ assert (target / rel).read_text(encoding="utf-8") == "target-owned runtime\n", rel+ elif route == "backup":+ # An in-home traversal must not bypass the runtime-root classification.+ with zipfile.ZipFile(archive, "w") as writer:+ writer.writestr(".hermes/config.yaml", incoming["config.yaml"])+ writer.writestr(".hermes/skills/../installs/key/facts.json", "foreign generation\n")+ run_import(Namespace(zipfile=str(archive), force=True))+ assert (target / "installs/key/facts.json").read_text(encoding="utf-8") == "target-owned runtime\n"diff --cc tests/hermes_cli/test_profiles_sidebar_failed_load.pyindex 00000000000,74c18d7b419..5144b01e65bmode 000000,100644..100644--- a/tests/hermes_cli/test_profiles_sidebar_failed_load.py+++ b/tests/hermes_cli/test_profiles_sidebar_failed_load.py@@@ -1,0 -1,241 +1,179 @@@+ """A failed profile scan must not look like an empty session list.+-A lagged store is healed once. When that read still fails, or the one-shot-heal is already exhausted and the profile contributed no rows, the sidebar-slice is a failed load with a retry signal. ``sessions: []`` is reserved for++Browsing never repairs the owner's store: a read that fails (lagged schema, busy++store) makes that profile's sidebar slice a failed load with a retry signal. ``sessions: []`` is reserved for+ a successful read of zero rows. A structurally corrupt store keeps its own+ notice and is not offered Retry.+ """++ import sqlite3+ from pathlib import Path++ import pytest+++ @pytest.fixture(autouse=True)+ def _uncached_sidebar(monkeypatch):+ from hermes_cli.web_routers import profiles as profiles_routes++ monkeypatch.setattr(profiles_routes, "_SIDEBAR_CACHE_TTL_SECONDS", 0.0)+ profiles_routes._sidebar_profile_cache_clear()+ profiles_routes._profile_read_warned.clear()++[email protected](autouse=True)-def _fresh_heal_latch(monkeypatch):- from hermes_cli import web_server_sessions as sessions_mod-- monkeypatch.setattr(sessions_mod, "_session_db_heal_exhausted", set())- monkeypatch.setattr(sessions_mod, "_session_db_heal_warned", set())--+ @pytest.fixture+ def profiles_on_disk(tmp_path, monkeypatch, _isolate_hermes_home):+ from hermes_cli import profiles+ from hermes_constants import get_hermes_home++ default_home = get_hermes_home()+ profiles_root = default_home / "profiles"+ worker_home = profiles_root / "worker"+ for home in (default_home, worker_home):+ home.mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)+ return {"default": default_home, "worker": worker_home}+++ @pytest.fixture+ def client(monkeypatch, profiles_on_disk):+ try:+ from starlette.testclient import TestClient+ except ImportError:+ pytest.skip("fastapi/starlette not installed")++ import hermes_state+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app+ from hermes_constants import get_hermes_home++ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")+ http = TestClient(app)+ http.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ return http+++ def _seed_session(home, session_id, *, source="cli"):+ from hermes_state import SessionDB++ db = SessionDB(db_path=home / "state.db")+ try:+ db.create_session(session_id, source=source)+ db.append_message(session_id=session_id, role="user", content="hi")+ finally:+ db.close()+++ def _sidebar(client, profile):+ return client.get(+ "/api/profiles/sessions/sidebar",+ params={"recents_profile": profile},+ ).json()+++ def _assert_failed_load(slice_, profile):+ """A failed load is not an empty session list, and it asks for a retry."""+ assert "sessions" not in slice_+ assert slice_["failed"] is True+ assert slice_["retry"] is True+ assert [row["profile"] for row in slice_["errors"]] == [profile]+++ class TestSidebarFailedLoad:+ def test_read_error_is_a_failed_load_not_an_empty_list(+ self, client, profiles_on_disk, monkeypatch+ ):+ _seed_session(profiles_on_disk["worker"], "worker-chat")+ import hermes_state++ def boom(self, *args, **kwargs):+ raise sqlite3.OperationalError(+ "no such column: s.compression_ineffective_count"+ )++ monkeypatch.setattr(hermes_state.SessionDB, "list_sessions_rich", boom)++ payload = _sidebar(client, "worker")++ assert payload["storage"] == {}+ for key in ("recents", "cron", "messaging"):+ _assert_failed_load(payload[key], "worker")+ assert payload["errors"][0]["profile"] == "worker"+- def test_heal_exhausted_empty_read_is_a_failed_load(- self, client, profiles_on_disk, monkeypatch- ):- home = profiles_on_disk["worker"]- _seed_session(home, "worker-chat")- from hermes_cli import web_server_sessions as sessions_mod-- sessions_mod._session_db_heal_exhausted.add(str(home / "state.db"))- import hermes_state-- monkeypatch.setattr(- hermes_state.SessionDB,- "list_sessions_rich",- lambda self, *args, **kwargs: [],- )-- payload = _sidebar(client, "worker")-- for key in ("recents", "cron", "messaging"):- _assert_failed_load(payload[key], "worker")- assert "heal exhausted" in payload["errors"][0]["error"]-- def test_unfixable_schema_is_healed_once_then_a_failed_load(++ def test_stale_schema_is_a_failed_load_and_never_opens_a_writer(+ self, client, profiles_on_disk, monkeypatch+ ):+ home = profiles_on_disk["worker"]+ _seed_session(home, "worker-chat")+ from hermes_cli import web_server_sessions as sessions_mod++ monkeypatch.setattr(+ sessions_mod,+ "_session_db_read_probe_statements",+ lambda: ('SELECT "sessions"."not_a_real_column" FROM "sessions" LIMIT 0',),+ )+ import hermes_state++ writable_opens = []+ real_init = hermes_state.SessionDB.__init__++ def counting_init(self, *args, **kwargs):+ if not kwargs.get("read_only", False):+ writable_opens.append(1)+ return real_init(self, *args, **kwargs)++ monkeypatch.setattr(hermes_state.SessionDB, "__init__", counting_init)+ real_list = hermes_state.SessionDB.list_sessions_rich++ def list_then_miss(self, *args, **kwargs):+ if str(getattr(self, "_db_path", home / "state.db")):+ raise sqlite3.OperationalError("no such column: s.not_a_real_column")+ return real_list(self, *args, **kwargs)++ monkeypatch.setattr(hermes_state.SessionDB, "list_sessions_rich", list_then_miss)++ first = _sidebar(client, "worker")+ second = _sidebar(client, "worker")+- assert len(writable_opens) == 1- assert str(home / "state.db") in sessions_mod._session_db_heal_exhausted++ assert writable_opens == []+ for payload in (first, second):+ _assert_failed_load(payload["recents"], "worker")+- def test_heal_exhausted_with_rows_still_returns_them(self, client, profiles_on_disk):- home = profiles_on_disk["worker"]- _seed_session(home, "worker-chat")- from hermes_cli import web_server_sessions as sessions_mod-- sessions_mod._session_db_heal_exhausted.add(str(home / "state.db"))-- payload = _sidebar(client, "worker")-- assert payload["errors"] == []- assert payload["recents"].get("retry") is not True- assert [row["id"] for row in payload["recents"]["sessions"]] == ["worker-chat"]-- def test_successful_heal_still_returns_rows(self, client, profiles_on_disk):- home = profiles_on_disk["worker"]- _seed_session(home, "worker-chat")- legacy = sqlite3.connect(str(home / "state.db"))- try:- legacy.execute("DROP INDEX IF EXISTS idx_sessions_effective_activity")- legacy.execute("ALTER TABLE sessions DROP COLUMN last_activity_at")- legacy.commit()- finally:- legacy.close()-- payload = _sidebar(client, "worker")-- assert payload["errors"] == []- assert payload["recents"].get("retry") is not True- assert [row["id"] for row in payload["recents"]["sessions"]] == ["worker-chat"]-+ def test_healthy_empty_store_stays_an_empty_list(self, client, profiles_on_disk):+ from hermes_state import SessionDB++ SessionDB(db_path=profiles_on_disk["worker"] / "state.db").close()++ payload = _sidebar(client, "worker")++ assert payload["errors"] == []+ assert payload["recents"].get("retry") is not True+ assert payload["recents"]["sessions"] == []++ def test_mixed_scan_marks_only_the_failed_profile(+ self, client, profiles_on_disk, monkeypatch+ ):+ _seed_session(profiles_on_disk["default"], "default-chat")+ _seed_session(profiles_on_disk["worker"], "worker-chat")+ import hermes_state++ real_list = hermes_state.SessionDB.list_sessions_rich+ worker_db = (profiles_on_disk["worker"] / "state.db").resolve()++ def explode_worker(self, *args, **kwargs):+ if Path(self.db_path).resolve() == worker_db:+ raise sqlite3.OperationalError("database is locked")+ return real_list(self, *args, **kwargs)++ monkeypatch.setattr(hermes_state.SessionDB, "list_sessions_rich", explode_worker)++ payload = _sidebar(client, "all")++ assert [row["id"] for row in payload["recents"]["sessions"]] == ["default-chat"]+ failed = payload["recents"]["profiles_failed"]["worker"]+ assert failed["failed"] is True+ assert failed["retry"] is True+ assert "worker" not in {+ row["profile"] for row in payload["recents"]["sessions"]+ }diff --cc tests/hermes_cli/test_restore_own_holder_guard.pyindex d2e5a6ae749,7e7a5637eee..816bc809588--- a/tests/hermes_cli/test_restore_own_holder_guard.py+++ b/tests/hermes_cli/test_restore_own_holder_guard.py@@@ -14,7 -14,7 +14,8 @@@ import syimport pytest+from hermes_cli import backup as backup_mod+ from hermes_cli import backup_restore as backup_restore_modfrom hermes_cli import update_cmdfrom hermes_cli.sqlite_safe_read import connect_trackeddiff --cc tests/hermes_cli/test_restore_source_integrity.pyindex 00000000000,b25c23e5683..a3f30d4d086mode 000000,100644..100644--- a/tests/hermes_cli/test_restore_source_integrity.py+++ b/tests/hermes_cli/test_restore_source_integrity.py@@@ -1,0 -1,126 +1,127 @@@+ """Restore must read the literal source path and validate it before mutating a live database."""++ import json+ import sqlite3+ import zipfile+ from argparse import Namespace+ from contextlib import closing++ import pytest++ from hermes_cli import backup++ # Unescaped in a file: URI, '#' truncates the path and '%23' decodes to a different one.+ HOME_NAMES = ["x#y", "x%23y", "x y"]+++ def _database(path, count):+ with closing(sqlite3.connect(path)) as conn:+ conn.execute("CREATE TABLE sessions(id INTEGER PRIMARY KEY)")+ conn.execute("CREATE TABLE messages(id INTEGER PRIMARY KEY)")+ conn.executemany("INSERT INTO sessions VALUES (?)", [(n,) for n in range(count)])+ conn.executemany("INSERT INTO messages VALUES (?)", [(n,) for n in range(count)])+ conn.commit()+++ def _assert_no_decoy(tmp_path, home_name):+ assert {p.name for p in tmp_path.iterdir()} <= {home_name, "native", "backup.zip", "hermes_test"}+++ @pytest.fixture(params=HOME_NAMES)+ def home(tmp_path, monkeypatch, request):+ import hermes_cli.gateway as gateway++ home = tmp_path / request.param+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ # An existing default install keeps import from installing/starting a gateway.+ native = tmp_path / "native"+ native.mkdir()+ (native / "config.yaml").write_text("{}", encoding="utf-8")+ monkeypatch.setattr(backup, "_get_platform_default_hermes_home", lambda: native)- monkeypatch.setattr(gateway, "ensure_gateway_service", lambda **kwargs: False)++ from hermes_cli import gateway_setup_service++ monkeypatch.setattr(gateway_setup_service, "ensure_gateway_service", lambda *args, **kwargs: False)+ monkeypatch.setattr(gateway, "_is_service_running", lambda: False)+ return home+++ def _restore(entry, home, snapshot_id, source):+ if entry == "snapshot":+ return backup.restore_quick_snapshot(snapshot_id, hermes_home=home)+ archive = home.parent / "backup.zip"+ with zipfile.ZipFile(archive, "w") as zf:+ zf.write(source, "state.db")+ return backup.run_import(Namespace(zipfile=str(archive), force=True)) != 1+++ @pytest.mark.parametrize("entry", ["snapshot", "import"])+ def test_restore_uses_literal_paths_and_preserves_live_connection(+ tmp_path, capsys, home, entry+ ):+ from hermes_cli.sqlite_safe_read import connect_tracked++ target = home / "state.db"+ _database(target, 3)+ snapshot = home / "state-snapshots" / "saved"+ snapshot.mkdir(parents=True)+ source = snapshot / "state.db"+ _database(source, 1)+ (snapshot / "manifest.json").write_text(+ json.dumps({"files": {"state.db": source.stat().st_size}}), encoding="utf-8"+ )+ holder = connect_tracked(target)+ try:+ assert _restore(entry, home, "saved", source)+ if entry == "import":+ assert "3 session(s) / 3 message(s) -> 1 / 1" in capsys.readouterr().out+ assert holder.execute("SELECT id FROM messages").fetchall() == [(0,)]+ with closing(sqlite3.connect(target)) as reopened:+ assert reopened.execute("SELECT id FROM messages").fetchall() == [(0,)]+ finally:+ holder.close()+ _assert_no_decoy(tmp_path, home.name)+++ @pytest.mark.parametrize("entry", ["snapshot", "import"])+ @pytest.mark.parametrize("damage", ["header", "btree", "truncated"])+ def test_corrupt_source_cannot_replace_a_healthy_database(+ tmp_path, capsys, home, entry, damage+ ):+ live = home / "state.db"+ with closing(sqlite3.connect(live)) as db:+ db.execute("CREATE TABLE evidence(value TEXT)")+ db.execute("INSERT INTO evidence VALUES ('snapshot')")+ db.commit()+ snapshot_id = backup.create_quick_snapshot(hermes_home=home)+ assert snapshot_id+ source = home / "state-snapshots" / snapshot_id / "state.db"+ with closing(sqlite3.connect(live)) as db:+ db.execute("UPDATE evidence SET value='live'")+ db.commit()+ with closing(sqlite3.connect(source)) as db:+ page_size = db.execute("PRAGMA page_size").fetchone()[0]+ root_page = db.execute(+ "SELECT rootpage FROM sqlite_master WHERE name='evidence'"+ ).fetchone()[0]+ contents = bytearray(source.read_bytes())+ if damage == "header":+ contents[:16] = b"not a database!!"+ elif damage == "btree":+ contents[(root_page - 1) * page_size] = 0 # Invalid b-tree page type.+ else:+ del contents[page_size:]+ source.write_bytes(contents)+ assert not backup.verify_sqlite_integrity(source)["valid"]+ before = live.read_bytes()+ inode = live.stat().st_ino++ assert not _restore(entry, home, snapshot_id, source)+ if entry == "import":+ captured = capsys.readouterr()+ assert "failed its integrity check" in captured.out + captured.err++ assert live.read_bytes() == before+ assert live.stat().st_ino == inode+ with closing(sqlite3.connect(live)) as db:+ assert db.execute("SELECT value FROM evidence").fetchall() == [("live",)]+ _assert_no_decoy(tmp_path, home.name)diff --cc tests/hermes_cli/test_safe_mode.pyindex f79a0f25e7b,ec7d3e22421..d204adb0f6b--- a/tests/hermes_cli/test_safe_mode.py+++ b/tests/hermes_cli/test_safe_mode.py@@@ -22,235 -8,72 +22,235 @@@ import timimport pytest--_VARS = ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG", "HERMES_IGNORE_RULES")--[email protected](autouse=True)-def _clean_env(monkeypatch):- for var in _VARS:- monkeypatch.delenv(var, raising=False)- yield- for var in _VARS:- os.environ.pop(var, None)---def test_cmd_chat_safe_mode_sets_env_before_startup(monkeypatch):- import hermes_cli.main as main_mod- from hermes_cli._parser import build_top_level_parser-- parser, _subparsers, chat_parser = build_top_level_parser()- chat_parser.set_defaults(func=main_mod.cmd_chat)- args = parser.parse_args(["chat", "--safe-mode"])- captured: dict[str, object] = {}- fake_cli = types.ModuleType("cli")-- def fake_has_provider() -> bool:- assert os.environ["HERMES_SAFE_MODE"] == "1"- assert os.environ["HERMES_IGNORE_USER_CONFIG"] == "1"- assert os.environ["HERMES_IGNORE_RULES"] == "1"- return True-- def fake_main(**kwargs):- captured.update(kwargs)-- monkeypatch.setattr(main_mod, "_has_any_provider_configured", fake_has_provider)- monkeypatch.setattr(main_mod, "_pin_kanban_board_env", lambda: None)- monkeypatch.setattr(main_mod, "_sync_bundled_skills_for_startup", lambda: None)- setattr(fake_cli, "main", fake_main)- monkeypatch.setitem(sys.modules, "cli", fake_cli)-- main_mod.cmd_chat(args)-- assert captured["ignore_user_config"] is True- assert captured["ignore_rules"] is True-----def test_plugin_discovery_skipped(monkeypatch):- monkeypatch.setenv("HERMES_SAFE_MODE", "1")- from hermes_cli.plugins import PluginManager-- mgr = PluginManager()- called = []- monkeypatch.setattr(mgr, "_discover_and_load_inner", lambda: called.append(True))-- mgr.discover_and_load()-- assert called == []- assert mgr._discovered is True- assert mgr._plugins == {}----------+from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+++class Model(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ if body.get('messages'):+ self.server.requests.append({'auth': self.headers.get('Authorization'), 'path': self.path, 'body': body})+ message = {'role': 'assistant', 'content': 'SAFE_REPLY_OK'}+ choice = {'index': 0, 'message': message, 'finish_reason': 'stop'}+ frame = {'id': 'local', 'model': body.get('model'), 'choices': [choice],+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}+ kind = 'application/json'+ if body.get('stream'):+ choice['delta'] = choice.pop('message')+ payload = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ else:+ payload = json.dumps(frame).encode()+ try:+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError):+ pass+++def _pty_cli(argv, cwd, env, timeout=90):+ """Real PTY launch: stdin/stdout/stderr are a terminal, like a user's shell."""+ master, slave = pty.openpty()+ proc = subprocess.Popen(argv, cwd=cwd, env=env, stdin=slave, stdout=slave, stderr=slave, close_fds=True)+ os.close(slave)+ output, deadline = bytearray(), time.monotonic() + timeout+ with closing(os.fdopen(master, 'rb', buffering=0)) as reader:+ while time.monotonic() < deadline:+ ready, _, _ = select.select([reader], [], [], .2)+ if ready:+ try:+ chunk = reader.read(65536)+ except OSError:+ break+ if not chunk:+ break+ output.extend(chunk)+ elif proc.poll() is not None:+ break+ code = proc.wait(timeout=10)+ return code, output.decode('utf-8', 'replace')++- @pytest.mark.linux_only[email protected]("linux")+def test_canonical_safe_launch_is_frozen_policy_executed_in_isolated_worker(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user, work = tmp_path / 'state', tmp_path / 'user', tmp_path / 'work'+ home.mkdir(mode=0o700)+ user.mkdir()+ work.mkdir()+ events = home / 'events'+ events.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ # Sentinels: general plugin (import + pre_llm_call hook), shell hook, SOUL, project rules, skill.+ plugin = home / 'plugins' / 'sentinel'+ plugin.mkdir(parents=True)+ (plugin / 'plugin.yaml').write_text('name: sentinel\nversion: 1.0.0\nkind: standalone\n', encoding='utf-8')+ (plugin / '__init__.py').write_text(+ 'import os\nfrom pathlib import Path\n'+ f'EVENTS = Path({str(events)!r})\n'+ '(EVENTS / f"plugin-import-{os.getpid()}").touch()\n'+ 'def register(ctx):\n'+ ' ctx.register_hook("pre_llm_call", lambda **kw: (EVENTS / f"plugin-hook-{os.getpid()}").touch())\n',+ encoding='utf-8')+ shell_witness = tmp_path / 'shell_witness.py'+ shell_witness.write_text(f'import os; from pathlib import Path\nPath({str(events)!r}, "shell-" + str(os.getppid())).touch()\n', encoding='utf-8')+ (home / 'SOUL.md').write_text('SOUL_SENTINEL identity text', encoding='utf-8')+ (work / 'AGENTS.md').write_text('RULES_SENTINEL project rules', encoding='utf-8')+ skill = home / 'skills' / 'probe'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text('---\nname: probe\ndescription: SKILL_SENTINEL probe skill\n---\nSKILL_SENTINEL body\n', encoding='utf-8')+ config = {'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'owner-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'plugins': {'enabled': ['sentinel']}, 'hooks_auto_accept': True,+ 'hooks': {'pre_llm_call': [{'command': f'{sys.executable} {shell_witness}'}]},+ 'memory': {'memory_enabled': False, 'user_profile_enabled': False},+ 'platform_toolsets': {'cli': ['terminal']}}+ (home / 'config.yaml').write_text(json.dumps(config), encoding='utf-8')+ audit = tmp_path / 'opens.jsonl'+ site = tmp_path / 'audit-site'+ site.mkdir()+ (site / 'sitecustomize.py').write_text(+ "import json, os, sys\n"+ f"AUDIT = {str(audit)!r}\n"+ "def record(kind, **fields):\n"+ " with open(AUDIT, 'a', encoding='utf-8') as f:\n"+ " f.write(json.dumps({'kind': kind, 'pid': os.getpid(), **fields}) + '\\n')\n"+ "# sys.argv is not populated yet at site time; the kernel cmdline is.\n"+ "with open('/proc/self/cmdline', 'rb') as f:\n"+ " cmdline = f.read().split(b'\\0')\n"+ "record('start', ppid=os.getppid(), argv=[a.decode('utf-8', 'replace') for a in cmdline if a])\n"+ "import threading\n"+ "_busy = threading.local()\n"+ "def witness(event, args):\n"+ " if event != 'open' or AUDIT in str(args[0]) or getattr(_busy, 'on', False):\n"+ " return\n"+ " _busy.on = True\n"+ " try:\n"+ " path = str(args[0])\n"+ " fields = {}\n"+ " if '/plugins/' in path or path.endswith(('config.yaml', '.env', 'SOUL.md', 'AGENTS.md', 'SKILL.md')):\n"+ " frame, stack = sys._getframe(1), []\n"+ " while frame is not None and len(stack) < 14:\n"+ " stack.append(f'{frame.f_code.co_filename}:{frame.f_lineno}:{frame.f_code.co_name}')\n"+ " frame = frame.f_back\n"+ " fields['stack'] = stack\n"+ " record('open', path=path, mode=str(args[1]), **fields)\n"+ " finally:\n"+ " _busy.on = False\n"+ "sys.addaudithook(witness)\n", encoding='utf-8')+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), TERM='xterm',+ PYTHONPATH=os.pathsep.join([str(site), str(root)]), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ def query(sql, args=()):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return db.execute(sql, args).fetchall()++ def records():+ return [json.loads(line) for line in audit.read_text(encoding='utf-8').splitlines()]++ def worker_pids(owner_pid):+ return sorted({r['pid'] for r in records() if r['kind'] == 'start' and r['ppid'] == owner_pid+ and r['argv'][-2:] == ['-m', 'agent.managed_worker']})++ def system_text(request):+ return json.dumps([m for m in request['body']['messages'] if m['role'] in {'system', 'developer'}])++ async def ordinary_turn(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='ordinary', source='cli', cwd=str(work),+ model='owner-model', provider='custom', base_url=url, api_key='loopback-only')+ assert 'result' in created, created+ sid = created['result']['session_id']+ submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='ordinary-input', text='ORDINARY_PROBE')+ assert 'result' in submitted, submitted+ async with asyncio.timeout(60):+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('ordinary-input',)) != [('terminal',)]:+ await asyncio.sleep(.05)+ return sid++ def safe_cli(request_tag, *flags):+ code, output = _pty_cli([sys.executable, '-m', 'hermes_cli.main', 'chat', *flags, '--provider', 'custom',+ '--base-url', url, '--model', 'safe-fixture', '--api-key', 'fixture',+ '-Q', '-q', 'SAFE_PROBE_' + request_tag], cwd=work, env=env)+ assert code == 0, output+ assert 'SAFE_REPLY_OK' in output, output+ sid = re.search(r'Session: (\S+)', output).group(1)+ return sid, output++ try:+ with daemon(root, home, env, barrier=False) as (owner, desc):+ # Positive control: the ordinary in-process turn fires every sentinel in the owner.+ asyncio.run(ordinary_turn(desc))+ ordinary = [r for r in peer.requests if r['body']['model'] == 'owner-model']+ assert len(ordinary) == 1, [r['body']['model'] for r in peer.requests]+ assert 'SOUL_SENTINEL' in system_text(ordinary[0]) and 'RULES_SENTINEL' in system_text(ordinary[0])+ skill_in_ordinary = 'SKILL_SENTINEL' in system_text(ordinary[0])+ fired = sorted(p.name for p in events.iterdir())+ assert f'plugin-import-{owner.pid}' in fired and f'plugin-hook-{owner.pid}' in fired, fired+ assert f'shell-{owner.pid}' in fired, fired+ owner_opens = [r['path'] for r in records() if r['kind'] == 'open' and r['pid'] == owner.pid]+ assert any('/plugins/' in p for p in owner_opens) and any(p.endswith('config.yaml') for p in owner_opens)++ # Canonical safe launch through the real CLI on a real PTY.+ safe_sid, output = safe_cli('one', '--safe-mode')+ assert query('SELECT status FROM session_admissions WHERE target_session_id=?', (safe_sid,)) == [('terminal',)]+ assert query('SELECT status FROM worker_executions WHERE session_id=?', (safe_sid,)) == [('terminal',)]+ policy = json.loads(query('SELECT value FROM state_meta WHERE key=?', ('gateway.local_policy.v1:' + safe_sid,))[0][0])['policy']+ assert policy['safe_mode'] is True and policy['ignore_user_config'] is True+ workers = worker_pids(owner.pid)+ assert len(workers) == 1 and workers[0] != owner.pid, workers+ worker = workers[0]+ worker_records = [r for r in records() if r['kind'] == 'open' and r['pid'] == worker]+ assert worker_records, 'audit hook not live in the worker'+ leaked = [(r['path'], r.get('stack')) for r in worker_records+ if '/plugins/' in r['path'] or r['path'].endswith(('config.yaml', '.env', 'SOUL.md', 'AGENTS.md', 'SKILL.md'))]+ assert leaked == [], json.dumps(leaked, indent=1)+ assert not [name for name in os.listdir(events) if name.endswith(f'-{worker}')], sorted(os.listdir(events))+ def inferences(tag):+ # Title generation is a code default and also targets the explicit endpoint; the+ # probe turn itself must be inferred exactly once.+ return [r for r in peer.requests if r['body']['model'] == 'safe-fixture'+ and r['body']['messages'][-1].get('content') == 'SAFE_PROBE_' + tag+ and not str(r['body']['messages'][0].get('content', '')).startswith('You name chat sessions')]+ safe = inferences('one')+ assert len(safe) == 1 and safe[0]['auth'] == 'Bearer fixture' and safe[0]['path'] == '/v1/chat/completions', \+ [(r['path'], [str(m.get('content'))[:80] for m in r['body']['messages']]) for r in peer.requests]+ assert not any(s in system_text(safe[0]) for s in ('SOUL_SENTINEL', 'RULES_SENTINEL', 'SKILL_SENTINEL'))+ assert 'HERMES_SAFE_MODE' not in Path(f'/proc/{owner.pid}/environ').read_bytes().decode('utf-8', 'replace')++ # Malformed profile YAML: bypass launch still works and neither repairs nor rewrites it.+ (home / 'config.yaml').write_text('model: [unterminated\n', encoding='utf-8')+ before = (home / 'config.yaml').read_bytes()+ second_sid, _ = safe_cli('two', '--safe-mode')+ assert second_sid != safe_sid+ assert (home / 'config.yaml').read_bytes() == before+ second = inferences('two')+ assert len(second) == 1 and second[0]['body'].get('tools') == safe[0]['body'].get('tools')++ # Config-only keeps plugin discovery (the gate is safe_mode), yet reads no profile YAML.+ (home / 'config.yaml').write_text(json.dumps(config), encoding='utf-8')+ config_sid, _ = safe_cli('three', '--ignore-user-config')+ config_worker = [p for p in worker_pids(owner.pid) if p not in workers][-1]+ config_opens = [r['path'] for r in records() if r['kind'] == 'open' and r['pid'] == config_worker]+ assert any('/plugins/' in p for p in config_opens), 'config-only must still discover plugins'+ assert not [p for p in config_opens if p.endswith(('config.yaml', '.env'))]+ print(json.dumps({'owner_pid': owner.pid, 'safe_worker_pid': worker, 'config_only_worker_pid': config_worker,+ 'safe_session': safe_sid, 'skill_in_ordinary_prompt': skill_in_ordinary,+ 'sentinels_fired': fired, 'safe_worker_leaked_opens': leaked,+ 'model_requests': [r['body']['model'] for r in peer.requests]}))+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --cc tests/hermes_cli/test_update_restore_authority.pyindex e09ab572203,00000000000..2b5af4acf14mode 100644,000000..100644--- a/tests/hermes_cli/test_update_restore_authority.py+++ b/tests/hermes_cli/test_update_restore_authority.py@@@ -1,181 -1,0 +1,182 @@@+"""Maintenance must not replace the database behind a live authority."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket+++def test_restore_refuses_live_authority_without_changing_data(tmp_path):+ from hermes_cli.backup import create_quick_snapshot+ from hermes_cli.update_cmd_maint import _restore_state_db_from_snapshot++ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'fixture', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'platform_toolsets': {'cli': []},+ }))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ def rows():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return list(db.execute('SELECT request_id,status FROM session_admissions ORDER BY rowid'))++ async def exercise(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='create', source='tui', cwd=str(home), toolsets=[])+ session = created['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=session, input_id='warm', text='WARM')+ async with asyncio.timeout(30):+ while dict(rows()).get('warm') != 'terminal':+ await asyncio.sleep(.05)+ snapshot = create_quick_snapshot(hermes_home=home)+ assert snapshot, snapshot+ await rpc(ws, 'prompt.submit', session_id=session, input_id='started', text='BLOCK_STARTED')+ assert await asyncio.to_thread(peer.blocked.wait, 25)+ await rpc(ws, 'prompt.submit', session_id=session, input_id='queued', text='FOLLOWER')+ before = rows()+ assert dict(before) == {'warm': 'terminal', 'started': 'started', 'queued': 'queued'}+ import hashlib+ bundle = [Path(str(home / 'state.db') + suffix) for suffix in ('', '-wal', '-shm')]+ hashes = {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in bundle if p.exists()}+ restored = _restore_state_db_from_snapshot(home / 'state.db', home / 'state-snapshots' / snapshot / 'state.db')+ assert hashes == {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in bundle if p.exists()}+ after = rows()+ print(json.dumps({'live_restore': restored, 'before': before, 'after': after}), flush=True)+ assert not restored and after == before+ return snapshot++ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ snapshot = asyncio.run(exercise(desc))+ old_epoch = desc['authority_epoch']+ peer.release.set()+ assert _restore_state_db_from_snapshot(home / 'state.db', home / 'state-snapshots' / snapshot / 'state.db')+ assert rows() == [('warm', 'terminal')]+ with daemon(root, home, env, barrier=False) as (_, restarted):+ assert restarted['instance_id'] != desc['instance_id']+ assert restarted['authority_epoch'] > old_epoch+ assert rows() == [('warm', 'terminal')]+ later_epoch = restarted['authority_epoch']+ # Restoring the same older snapshot must not reuse a previous owner's epoch.+ assert _restore_state_db_from_snapshot(home / 'state.db', home / 'state-snapshots' / snapshot / 'state.db')+ with daemon(root, home, env, barrier=False) as (_, restored_again):+ assert restored_again['authority_epoch'] > later_epoch+ print(json.dumps({'offline_restore_restart_epochs': [old_epoch, later_epoch, restored_again['authority_epoch']],+ 'restart_instance_changed': restored_again['instance_id'] != restarted['instance_id']}), flush=True)+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+++def test_corrupt_epoch_refuses_profile_sweep_with_separate_recovery(tmp_path, monkeypatch, capsys):+ from hermes_cli import backup, update_cmd+ from hermes_cli.session_recovery import recover_session_database+ from hermes_state import SessionDB++ homes = [tmp_path / 'default', tmp_path / 'sibling']+ originals = {}+ snapshots = {}+ for home in homes:+ home.mkdir()+ with SessionDB(db_path=home / 'state.db') as db:+ db.create_session('retained', 'cli')+ db.append_message('retained', 'user', 'snapshot transcript')+ snapshot = backup.create_quick_snapshot(hermes_home=home)+ snapshots[home] = home / 'state-snapshots' / snapshot / 'state.db'+ (home / 'state.db').write_bytes(b'unreadable canonical runtime epoch')+ originals[home] = (home / 'state.db').read_bytes(), snapshots[home].read_bytes()+ monkeypatch.setattr(update_cmd, 'get_hermes_home', lambda: homes[0])+ monkeypatch.setattr(backup, '_sibling_profile_homes', lambda home: [('work', homes[1])])+ update_cmd._verify_and_restore_state_dbs_post_update()+ output = capsys.readouterr().out+ for home in homes:+ assert ((home / 'state.db').read_bytes(), snapshots[home].read_bytes()) == originals[home]+ assert 'Auto-restored' not in output+ assert 'separate' in output and 'hermes sessions recover' in output+ assert 'restored copy also failed integrity' not in output+ for home in homes:+ report = recover_session_database(snapshots[home], home / 'recovered.db')+ assert report['verified'] and report['source_unchanged']+ with closing(sqlite3.connect(home / 'recovered.db')) as db:+ assert db.execute('SELECT content FROM messages').fetchall() == [('snapshot transcript',)]+ assert (home / 'state.db').read_bytes() == originals[home][0]+++def test_update_restore_excludes_startup_until_publication(tmp_path, monkeypatch):+ import subprocess+ import sys+ from gateway.runtime_ownership import ProfileOwnership+ from hermes_cli import backup+ from hermes_cli.update_cmd_maint import _restore_state_db_from_snapshot++ home = tmp_path / 'state'+ home.mkdir()+ source, destination = tmp_path / 'snapshot.db', home / 'state.db'+ for path, value in ((source, 'snapshot'), (destination, 'current')):+ with closing(sqlite3.connect(path)) as db:+ db.execute('CREATE TABLE marker(value TEXT)')+ db.execute('INSERT INTO marker VALUES(?)', (value,))+ db.commit()+ before = destination.read_bytes(), source.read_bytes()+ owner = ProfileOwnership()+ owner.reserve([home])+ try:+ assert not (home / 'gateway.pid').exists()+ assert not _restore_state_db_from_snapshot(destination, source)+ assert (destination.read_bytes(), source.read_bytes()) == before+ finally:+ owner.close()++ # Pause only the actual database publication, with maintenance already held.+ arrived, release = threading.Event(), threading.Event()- publish = backup._restore_db_pages++ from hermes_cli import backup_restore++ publish = backup_restore._restore_db_pages+ def barrier(*args):+ arrived.set()+ assert release.wait(30)+ return publish(*args)- monkeypatch.setattr(backup, '_restore_db_pages', barrier)++ monkeypatch.setattr(backup_restore, '_restore_db_pages', barrier)+ results = []+ thread = threading.Thread(target=lambda: results.append(_restore_state_db_from_snapshot(destination, source)))+ thread.start()+ try:+ assert arrived.wait(20)+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(tmp_path / 'user'), HERMES_HOME=str(home), PYTHONPATH=str(root))+ contender = subprocess.run([sys.executable, '-c',+ "import logging, runpy; logging.basicConfig(level=logging.INFO); runpy.run_module('gateway.run', run_name='__main__')"],+ cwd=root, env=env, stdin=subprocess.DEVNULL, capture_output=True,+ text=True, encoding='utf-8', timeout=25)+ assert 'already owns profile' in contender.stdout + contender.stderr, contender+ assert (destination.read_bytes(), source.read_bytes()) == before+ finally:+ release.set()+ thread.join(timeout=30)+ assert not thread.is_alive() and results == [True]+ with closing(sqlite3.connect(destination)) as db:+ assert db.execute('SELECT value FROM marker').fetchall() == [('snapshot',)]+ assert source.read_bytes() == before[1]+ print(json.dumps({'startup_first_refused': True, 'maintenance_first_refused': True,+ 'snapshot_unchanged': True}), flush=True)diff --cc tests/hermes_cli/test_web_server.pyindex 53acadb4d3d,a82922a3575..7dca968bbf8--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@@ -487,12 -460,13 +487,14 @@@ class TestWebServerEndpointsassert response.status_code == 200payload = response.json()- assert payload["errors"] == []- assert [row["id"] for row in payload["recents"]["sessions"]] == [- "sidebar-stale"- ]+ assert payload["errors"]+ assert "schema" in payload["errors"][0]["error"]- assert payload["recents"]["sessions"] == []++ # A failed read is a retryable failed load, never an empty list.++ assert "sessions" not in payload["recents"]++ assert payload["recents"]["failed"] is Truedef test_startup_eager_reconcile_heals_stale_store(self):- """The lifespan's eager reconcile brings a stale store current.+ """The OWNER's startup open brings a stale store current; the dashboard only reads.#79531/#80037: after `hermes update` an old-schema state.db used tostay stale until the first NEW session forced a writable open —@@@ -4126,21 -4138,61 +4120,89 @@@ class TestDeleteSessionEndpointfinally:db.close()++ def test_delete_absent_session_is_idempotent(self, mutation_owner):+ from gateway.session_authority import LiveSession+ self._seed(['delete-retry'])+ mutation_owner.sessions['delete-retry'] = LiveSession(None, 'route')+ row = mutation_owner.db.get_session('delete-retry')+ params = dict(request_id='delete-once', expected_revision=row['runtime_revision'],+ expected_generation=row['runtime_generation'])+ first = self.auth_client.delete('/api/sessions/delete-retry', params=params)+ assert first.status_code == 200, first.text+ assert not self._exists('delete-retry')+ retry = self.auth_client.delete('/api/sessions/delete-retry', params=params)+ assert retry.status_code == 200, retry.text+ assert retry.json() == first.json()+++ def _canonical_delete(self, owner, sid, **query):++ from gateway.session_authority import LiveSession++ owner.sessions[sid] = LiveSession(None, 'route')++ row = owner.db.get_session(sid)++ params = dict(request_id=f'scrub-{sid}', expected_revision=row['runtime_revision'],++ expected_generation=row['runtime_generation'], **query)++ return self.auth_client.delete(f"/api/sessions/{sid}", params=params)++++ def test_delete_existing_session_scrubs_row_and_disk(self, mutation_owner):++ # The canonical delete retires rows; the endpoint must also remove the secret-bearing++ # session_<id>.json snapshots and request dumps the CLI delete path removes (#60207).++ from hermes_constants import get_hermes_home++++ self._seed(["disk-scrub"])+ sessions_dir = get_hermes_home() / "sessions"+ sessions_dir.mkdir(parents=True, exist_ok=True)+ for name, body in (+ ("session_disk-scrub.json", '{"messages": [{"content": "secret-token"}]}'),+ ("disk-scrub.jsonl", "{}\n"),+ ("request_dump_disk-scrub_001.json", "{}"),+ ):+ (sessions_dir / name).write_text(body, encoding="utf-8")+ # Another session's artifacts must survive.+ (sessions_dir / "session_disk-scrub-neighbour.json").write_text("{}", encoding="utf-8")+- resp = self.auth_client.delete("/api/sessions/disk-scrub")++ resp = self._canonical_delete(mutation_owner, "disk-scrub")+- assert resp.status_code == 200++ assert resp.status_code == 200, resp.text+ assert resp.json().get("ok") is True- db = SessionDB(db_path=db_path)- try:- assert db.get_session("disk-scrub") is None- finally:- db.close()++ assert not self._exists("disk-scrub")+ assert not (sessions_dir / "session_disk-scrub.json").exists()+ assert not (sessions_dir / "disk-scrub.jsonl").exists()+ assert not (sessions_dir / "request_dump_disk-scrub_001.json").exists()+ assert (sessions_dir / "session_disk-scrub-neighbour.json").exists()+- def test_delete_named_profile_session_scrubs_profile_disk(self):++ def test_delete_named_profile_session_scrubs_profile_disk(self, monkeypatch):++ from types import SimpleNamespace++ from gateway.session_authority import SessionAuthority+ from hermes_cli import profiles as profiles_mod++ from hermes_cli.web_server import app+ from hermes_state import SessionDB++ from hermes_state_runtime import begin_runtime_epoch++ profile_home = profiles_mod.get_profile_dir("worker")+ profile_home.mkdir(parents=True)+ (profile_home / "config.yaml").touch() # identity marker: bare dirs are not profiles+ sessions_dir = profile_home / "sessions"+ sessions_dir.mkdir(parents=True, exist_ok=True)- db_path = profile_home / "state.db"- db = SessionDB(db_path=db_path)++ db = SessionDB(db_path=profile_home / "state.db")++ # ?profile= is served by that home's own authority.++ owner = SessionAuthority(SimpleNamespace(_draining=False), profile_id=str(profile_home),++ instance_id='worker-owner', db=db, epoch=begin_runtime_epoch(db, instance_id='worker-owner'))++ monkeypatch.setattr(app.state, 'session_authority', owner, raising=False)+ try:+ db.create_session("profile-scrub", source="cli")- finally:- db.close()- (sessions_dir / "session_profile-scrub.json").write_text(- '{"messages": [{"content": "secret-token"}]}', encoding="utf-8"- )++ (sessions_dir / "session_profile-scrub.json").write_text(++ '{"messages": [{"content": "secret-token"}]}', encoding="utf-8"++ )+- resp = self.auth_client.delete("/api/sessions/profile-scrub?profile=worker")++ resp = self._canonical_delete(owner, "profile-scrub", profile="worker")+- assert resp.status_code == 200- assert resp.json().get("ok") is True- db = SessionDB(db_path=db_path)- try:++ assert resp.status_code == 200, resp.text++ assert resp.json().get("ok") is True+ assert db.get_session("profile-scrub") is None++ assert not (sessions_dir / "session_profile-scrub.json").exists()+ finally:+ db.close()- assert not (sessions_dir / "session_profile-scrub.json").exists()+class TestBulkDeleteSessionsEndpoint:"""Tests for ``POST /api/sessions/bulk-delete`` — backs thediff --cc tests/tools/test_bot_live_owner_delivery.pyindex e6d07779b9a,9bfbe2b38f2..5a772adc46a--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@@ -1,161 -1,239 +1,220 @@@-"""Durable mailbox invariants, using real disk and exec boundaries."""+"""Canonical delivery invariants: stable envelope IDs, authority-only admission,+immutable receipts. The mailbox is receipt storage, never an execution queue."""+ import jsonimport os-import subprocess-import sys+from pathlib import Pathimport pytest[email protected]("terminal_status", ["settled", "failed", "cancelled"])-def test_delivery_is_idempotent_fenced_and_permanent(tmp_path, terminal_status):- from tools import bot_live_delivery as mailbox+from tools import bot_live_delivery as mailbox+++class _FakeAuthority:+ """Stands in for the profile authority's ``bot_relay.deliver`` RPC."""++ def __init__(self):+ self.calls = []+ self.records = {}++ def __call__(self, home, params):+ self.calls.append((Path(home).resolve(), dict(params)))+ record = self.records.get(params["id"])+ if record is None:+ record = self.records[params["id"]] = dict(+ status="queued", delivery_id=params["id"], profile_home=str(Path(home).resolve()),+ session_id="local-bot", message=params["message"], admission_id="adm-" + params["id"][:6],+ reply="", **({"author": params["author"]} if "author" in params else {}))+ with mailbox._locked(home) as root:+ mailbox._write(root / f"{params['id']}.json", record)+ elif (record["message"] != params["message"]+ or record.get("author") != params.get("author")):+ raise ValueError("admission_conflict")+ return {k: record[k] for k in ("status", "delivery_id", "profile_home", "session_id", "reply")}- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")++def _owner(home):+ return dict(profile_home=str(Path(home).resolve()), session_id="local-bot",+ lease_id="authority-1", live_session_id="local-bot")+++def test_same_envelope_id_admits_once_and_conflicts_on_changed_payload(tmp_path, monkeypatch):+ authority = _FakeAuthority()+ monkeypatch.setattr(mailbox, "authority_delivery", authority)delivery_id = "a" * 32- queued = mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "hello", delivery_id=delivery_id)- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id=delivery_id)- assert queued["status"] == "queued"++ queued = mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "héllo 世界", delivery_id=delivery_id)+ assert queued["status"] == "queued" and queued["delivery_id"] == delivery_id++ # Receipts are written as plain UTF-8 and read back BOM-tolerantly (main 61dc26cd7d9).+ path = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{delivery_id}.json"+ raw = path.read_bytes()+ assert not raw.startswith(b"\xef\xbb\xbf")+ path.write_bytes(b"\xef\xbb\xbf" + raw)- assert mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id=delivery_id) == queued+ # Exact retry inspects the same admission; it never mints a second envelope.- assert mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "hello", delivery_id=delivery_id) == queued++ assert mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "héllo 世界", delivery_id=delivery_id) == queued+ assert [params["id"] for _home, params in authority.calls] == [delivery_id, delivery_id]+ assert len(authority.records) == 1with pytest.raises(ValueError):- mailbox.deliver_to_live_owner(tmp_path, owner, "different", delivery_id=delivery_id)- assert mailbox.claim_pending_delivery(tmp_path, dict(owner, lease_id="other")) is None- assert mailbox.claim_pending_delivery(tmp_path, dict(owner, live_session_id="other")) is None- script = (- "import json,sys; from tools.bot_live_delivery import claim_pending_delivery; "- "print(json.dumps(claim_pending_delivery(sys.argv[1],json.loads(sys.argv[2]))))"- )- children = [subprocess.Popen([sys.executable, "-c", script, str(tmp_path), json.dumps(owner)],- stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,- stderr=subprocess.PIPE, text=True) for _ in range(2)]- results = []- for child in children:- out, err = child.communicate(timeout=30)- assert child.returncode == 0, err- results.append(json.loads(out))- claims = [r for r in results if r is not None]- assert len(claims) == 1 and claims[0]["message"] == "héllo 世界"- assert mailbox.read_delivery_result(tmp_path, delivery_id)["status"] == "claimed"- assert mailbox.claim_pending_delivery(tmp_path, owner) is None- path.write_bytes(b"\xef\xbb\xbf" + path.read_bytes())- receipt = mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="réponse 世界")- assert not path.read_bytes().startswith(b"\xef\xbb\xbf")- path.write_bytes(b"\xef\xbb\xbf" + path.read_bytes())- assert mailbox.read_delivery_result(tmp_path, delivery_id) == receipt- assert mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="réponse 世界") == receipt- with pytest.raises(ValueError):- mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="rewrite")- assert mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id=delivery_id) == receipt- assert mailbox.claim_pending_delivery(tmp_path, owner) is None+ mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "different", delivery_id=delivery_id)+ # Reading the receipt resolves through the same admission, not a local guess.+ assert mailbox.read_delivery_result(tmp_path, delivery_id)["status"] == "queued"+ # The retired UI claim consumer never hands out work.+ assert mailbox.claim_pending_delivery(tmp_path, _owner(tmp_path)) is Noneif os.name != "nt":for path in (tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME).iterdir():assert path.stat().st_mode & 0o077 == 0++ @pytest.mark.parametrize("intent_state", ["new", "existing", "raced"])+ def test_live_dm_bom_readers_preserve_pinned_intent(tmp_path, monkeypatch, intent_state):- from pathlib import Path-- from hermes_cli.active_sessions import try_acquire_active_session++ """Main 61dc26cd7d9 on the canonical door: a BOM-prefixed DM payload and a BOM-prefixed pinned++ intent read back intact, a pinned intent is never replaced by a rewritten payload, and a++ damaged intent retains its evidence instead of retrying a transport."""++ import hermes_cli.gateway_runtime as runtime+ from hermes_state import SessionDB- from tools import bot_live_delivery as mailbox, bot_mode_dm++ from tools import bot_mode_dm++ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session(session_id="chat", source="cli")+ db.set_session_title("chat", "Bot Chat")- lease, refusal = try_acquire_active_session(- session_id="chat", surface="desktop", config={}, registry_home=tmp_path,- metadata=dict(live_session_id="live", bot_live_delivery_consumer=True))- assert refusal is None and lease is not None++ monkeypatch.setattr(runtime, "discover_gateway_endpoint", _ready("authority-1"))++ authority = _FakeAuthority()++ monkeypatch.setattr(mailbox, "authority_delivery", authority)+ try:+ owner = mailbox.find_canonical_live_owner(tmp_path)+ assert owner is not None+ payload = tmp_path / "message.txt"+ payload.write_bytes("héllo 世界".encode("utf-8-sig"))+ intent_path = Path(str(payload) + ".live.json")+ author = {"id": "bot:coder", "name": "Renée", "is_bot": True}+ intent = dict(owner=owner, message="pinned 世界", delivery_id="d" * 32, author=author)+ encoded = json.dumps(intent, ensure_ascii=False).encode("utf-8-sig")+ if intent_state == "existing":+ intent_path.write_bytes(encoded)+ elif intent_state == "raced":+ real_open = os.open++ def competing_intent(path, flags, *args, **kwargs):+ if Path(path) == intent_path:+ intent_path.write_bytes(encoded)+ return real_open(path, flags, *args, **kwargs)++ monkeypatch.setattr(os, "open", competing_intent)+ record = bot_mode_dm._admit_live_dm(tmp_path, str(payload), author)- assert record is not None- assert record["message"] == ("héllo 世界" if intent_state == "new" else "pinned 世界")- assert record["owner"] == owner and record["author"] == author++ assert record is not None and record["status"] == "queued"++ admitted = authority.records[record["delivery_id"]]++ assert admitted["message"] == ("héllo 世界" if intent_state == "new" else "pinned 世界")++ assert admitted["author"] == author+ if intent_state == "new":+ assert not intent_path.read_bytes().startswith(b"\xef\xbb\xbf")+ intent_path.write_bytes(b"\xef\xbb\xbf" + intent_path.read_bytes())+ payload.write_text("must not replace pinned payload", encoding="utf-8")+ assert bot_mode_dm._admit_live_dm(None, str(payload)) == record- claim = mailbox.claim_pending_delivery(tmp_path, owner)- assert claim is not None and claim["delivery_id"] == record["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner) is None++ assert len(authority.records) == 1+ intent_path.write_bytes(b"\xef\xbb\xbf{broken")+ assert bot_mode_dm._run_delivery([], str(payload), stdin_file=False, profile_home=tmp_path) == 1+ assert payload.exists() # Ambiguous admission must retain its evidence, not retry a transport.+ finally:- lease.release()+ db.close()+-def test_fifo_survives_clock_rollback(tmp_path, monkeypatch):- from tools import bot_live_delivery as mailbox+- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- for timestamp, message in ((100, "first"), (90, "second")):- monkeypatch.setattr(mailbox.time, "time_ns", lambda: timestamp)- mailbox.deliver_to_live_owner(tmp_path, owner, message)- assert mailbox.claim_pending_delivery(tmp_path, owner)["message"] == "first"- assert mailbox.claim_pending_delivery(tmp_path, owner)["message"] == "second"+def test_owner_from_another_home_or_malformed_id_is_refused_before_admission(tmp_path, monkeypatch):+ authority = _FakeAuthority()+ monkeypatch.setattr(mailbox, "authority_delivery", authority)+ foreign = dict(_owner(tmp_path), profile_home=str(tmp_path / "elsewhere"))+ with pytest.raises(ValueError, match="different profile home"):+ mailbox.deliver_to_live_owner(tmp_path, foreign, "hello", delivery_id="b" * 32)+ with pytest.raises(ValueError, match="delivery id"):+ mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "hello", delivery_id="../evil")+ assert authority.calls == []+++def test_receipt_read_forwards_the_immutable_author(tmp_path, monkeypatch):+ """F10: an authored admission is re-read with its stored author, so the authority sees the same payload."""+ authority = _FakeAuthority()+ monkeypatch.setattr(mailbox, "authority_delivery", authority)+ delivery_id = "d" * 32+ author = {"kind": "user", "id": "u-1", "display": "Ann"}+ queued = mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "hello", delivery_id=delivery_id, author=author)+ assert mailbox.read_delivery_result(tmp_path, delivery_id) == queued+ assert [params.get("author") for _home, params in authority.calls] == [author, author]++[email protected]("terminal_status", ["settled", "failed", "cancelled"])+def test_terminal_receipt_is_immutable(tmp_path, terminal_status):+ delivery_id = "c" * 32+ with mailbox._locked(tmp_path) as root:+ mailbox._write(root / f"{delivery_id}.json", dict(delivery_id=delivery_id, status="claimed",+ message="hello", created_at=1))+ receipt = mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="answer")+ assert mailbox.read_delivery_result(tmp_path, delivery_id) == receipt+ assert mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="answer") == receipt+ with pytest.raises(ValueError):+ mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="rewrite")+ with pytest.raises(ValueError):+ mailbox.complete_delivery(tmp_path, "d" * 32, status="not-terminal")+++def _ready(instance_id):+ from types import SimpleNamespace[email protected]("capable", [True, False])-def test_only_canonical_capable_owner_receives_across_compression(tmp_path, capable):+ return lambda home, timeout: SimpleNamespace(state="ready", endpoint=SimpleNamespace(instance_id=instance_id))+++def test_canonical_owner_is_the_authority_and_follows_compression(tmp_path, monkeypatch):from hermes_state import SessionDB- from hermes_cli.active_sessions import try_acquire_active_session, transfer_active_session- from tools import bot_live_delivery as mailbox+ import hermes_cli.gateway_runtime as runtime+ from types import SimpleNamespace++ monkeypatch.setattr(runtime, "discover_gateway_endpoint",+ lambda home, timeout: SimpleNamespace(state="absent", endpoint=None))+ with pytest.raises(ValueError, match="authority"):+ mailbox.find_canonical_live_owner(tmp_path)++ monkeypatch.setattr(runtime, "discover_gateway_endpoint", _ready("authority-1"))+ assert mailbox.find_canonical_live_owner(tmp_path) is None # no state.db yetdb = SessionDB(db_path=tmp_path / "state.db")- db.create_session(session_id="chat", source="cli")- db.set_session_title("chat", "Bot Chat")- meta = dict(live_session_id="live", bot_live_delivery_consumer=capable)- lease, refusal = try_acquire_active_session(session_id="chat", surface="desktop", config={},- registry_home=tmp_path, metadata=meta)- assert refusal is Nonetry:+ db.create_session(session_id="scratch", source="cli")+ db.set_session_title("scratch", "Scratch")+ # No Bot Chat yet is still a deliverable owner: the authority creates the chat on+ # first delivery (create-if-missing), so discovery reports an empty tip, not None.+ assert mailbox.find_canonical_live_owner(tmp_path)["session_id"] == ""+ db.create_session(session_id="chat", source="cli")+ db.set_session_title("chat", "Bot Chat")owner = mailbox.find_canonical_live_owner(tmp_path)- if not capable:- assert owner is None- return- assert owner["lease_id"] == lease.lease_id- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "before compression")+ assert owner["canonical"] is True and owner["lease_id"] == "authority-1"+ assert owner["session_id"] == owner["live_session_id"] == "chat"db.end_session("chat", "compression")db.create_session(session_id="tip", source="cli", parent_session_id="chat")- assert transfer_active_session(lease, session_id="tip", metadata=meta)- current = mailbox.find_canonical_live_owner(tmp_path)- assert current["session_id"] == "tip"- claim = mailbox.claim_pending_delivery(tmp_path, current)- assert claim["delivery_id"] == queued["delivery_id"]- assert claim["session_id"] == "chat"- assert mailbox.claim_pending_delivery(tmp_path, current) is None+ assert mailbox.find_canonical_live_owner(tmp_path)["session_id"] == "tip"finally:- lease.release()db.close()-def test_delivery_keeps_the_sender_and_refuses_a_different_one_under_the_same_id(tmp_path):++def test_delivery_keeps_the_sender_and_refuses_a_different_one_under_the_same_id(tmp_path, monkeypatch):from tools import bot_live_delivery as mailbox+ authority = _FakeAuthority()+ monkeypatch.setattr(mailbox, "authority_delivery", authority)owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat", lease_id="lease", live_session_id="live")author = {"id": "bot:coder", "name": "coder", "is_bot": True}- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author=author)- assert queued["author"] == author- assert mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author=author) == queued+ queued = mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author)+ assert authority.calls[-1][1]["author"] == author+ assert authority.records["b" * 32]["author"] == author+ assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author) == queuedwith pytest.raises(ValueError):- mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author={**author, "id": "bot:other"})- assert "author" not in mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)+ mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author={**author, "id": "bot:other"})+ mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)+ assert "author" not in authority.calls[-1][1][email protected]("posix")[email protected](getattr(os, "geteuid", lambda: 1)() == 0, reason='needs POSIX file permissions for an unreadable ticket')-def test_unreadable_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):- import logging+def test_non_dict_ticket_fails_exact_id_reads_closed(tmp_path):+ """Malformed is not absent: an exact-id receipt read raises instead of reporting "no record"."""from tools import bot_live_delivery as mailbox- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "readable", delivery_id="d" * 32)- root = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME- # A real admission that later turns unreadable: its sequence must survive the skip.- hidden = mailbox.deliver_to_live_owner(tmp_path, owner, "hidden", delivery_id="e" * 32)- (root / f"{'e' * 32}.json").chmod(0)- corrupt = root / f"{'1' * 32}.json"- corrupt.write_text("{not json", encoding="utf-8")- (root / f"{'2' * 32}.json").write_bytes(b"\xff\xfe\x00garbage") # invalid UTF-8, not just bad JSON- with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):- # Sender side: admission of a fresh id must survive the sequence sweep.- admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "second", delivery_id="f" * 32)- # Receiver side: every readable queued ticket must still be claimed, in order.- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]- for _ in range(10): # the idle poller rescans twice a second- assert mailbox.claim_pending_delivery(tmp_path, owner) is None- assert admitted["status"] == "queued"- assert admitted["sequence"] > hidden["sequence"] > queued["sequence"]- denied = [record for record in caplog.records- if record.message.startswith(f"bot_live_delivery: skipping unreadable ticket {'e' * 32}.json")- and "Permission denied" in record.message]- assert len(denied) == 1, "one persistent bad ticket must warn once per process, not per scan"-[email protected]("posix")[email protected](getattr(os, "geteuid", lambda: 1)() == 0, reason='needs POSIX file permissions for an unreadable ticket')-def test_unreadable_ticket_keeps_exact_id_reads_fail_closed(tmp_path):- from tools import bot_live_delivery as mailbox-- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- unreadable = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{'e' * 32}.json"- unreadable.parent.mkdir(parents=True, exist_ok=True)- unreadable.write_text('{"status": "queued"}', encoding="utf-8")- unreadable.chmod(0)- # Uninspectable is not absent: an exact-id retry must fail closed instead of- # minting a fresh receipt that overwrites the possibly-live one (#109820).- with pytest.raises(PermissionError):- mailbox.deliver_to_live_owner(tmp_path, owner, "same id", delivery_id="e" * 32)- with pytest.raises(PermissionError):- mailbox.read_delivery_result(tmp_path, "e" * 32)--def test_non_dict_ticket_is_skipped_by_scans_and_fails_exact_id_reads_closed(tmp_path, caplog):- import logging-- from tools import bot_live_delivery as mailbox-- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "readable", delivery_id="d" * 32)bad = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{'e' * 32}.json"+ bad.parent.mkdir(parents=True)bad.write_text('"oops"', encoding="utf-8") # parses, but is not a record- with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):- admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "second", delivery_id="f" * 32)- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner) is None- assert sum(r.message.startswith(f"bot_live_delivery: skipping unreadable ticket {'e' * 32}.json")- for r in caplog.records) == 1- # Malformed is not absent: exact-id reads fail closed rather than overwrite the receipt.- with pytest.raises(ValueError):- mailbox.deliver_to_live_owner(tmp_path, owner, "same id", delivery_id="e" * 32)with pytest.raises(ValueError):mailbox.read_delivery_result(tmp_path, "e" * 32)assert bad.read_text(encoding="utf-8") == '"oops"'diff --cc tests/tools/test_bot_mode_dm.pyindex 12054dc2c20,17707bec9d6..3b75daaf414--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@@ -728,9 -631,40 +728,44 @@@ def test_live_dm_runner_retry_never_reeassert dm_file.read_text(encoding="utf-8") == "hello"-# ── plaintext tempfile lifecycle ─────────────────────────────────────────────+# ── plaintext tempfile lifecycle (peer stdin transport) ─────────────────────[email protected]("stdin_file", [False, True])+ @pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])-def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file, encoding):++def test_peer_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, encoding):++ # Main 61dc26cd7d9 also ran the local query-file transport here; that lane has no local++ # child any more (a local delivery without a canonical owner is refused and retained,++ # see test_local_delivery_runner_surfaces_refusal_and_retains_payload), so only the peer++ # stdin transport keeps the file for the child.++ stdin_file = True+ dm_file = tmp_path / "message with spaces.txt"+ dm_file.write_bytes("secret λ $(not shell)".encode(encoding))+ observed = tmp_path / "observed.txt"+ child = tmp_path / "child.py"+ child.write_text(+ textwrap.dedent(+ """\+ import pathlib+ import sys++ source = sys.stdin if sys.argv[1] == "-" else open(sys.argv[1], encoding="utf-8-sig")+ with source:+ pathlib.Path(sys.argv[2]).write_text(source.read(), encoding="utf-8")+ """+ ),+ encoding="utf-8",+ )+ source_arg = "-" if stdin_file else str(dm_file)++ returncode = bot_mode_dm._run_delivery(+ [sys.executable, str(child), source_arg, str(observed)],+ str(dm_file),+ stdin_file=stdin_file,+ )++ assert returncode == 0+ assert observed.read_text(encoding="utf-8") == "secret λ $(not shell)"+ assert not dm_file.exists()@@@ -899,13 -874,9 +934,13 @@@ def test_real_peer_delivery_command_rouassert not dm_file.exists()- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_delivery_command_round_trip_through_windows_local_shell(tmp_path):- """Native runner paths must survive the Git Bash process boundary."""+ """Native runner paths must survive the Git Bash process boundary.++ Peer (stdin) transport, like the Linux sibling: a local query-file delivery without a+ canonical Bot Chat owner is refused with ``runtime_unavailable`` by design.+ """from tools.environments.local import _find_shelldm_file = tmp_path / "message with spaces.txt"diff --cc tests/tools/test_bot_turn_lock.pyindex e68a275d1d7,d27209df43a..df0bee65e39--- a/tests/tools/test_bot_turn_lock.py+++ b/tests/tools/test_bot_turn_lock.py@@@ -9,8 -9,13 +9,12 @@@ process, so threads exercise the true kfrom __future__ import annotations+ try:+ import fcntl # POSIX-only; on Windows the module is skipped wholesale+ except ImportError: # pragma: no cover - Windows+ fcntl = Noneimport jsonimport os-import subprocessimport sysimport threadingimport timediff --cc tests/tools/test_completed_process_results.pyindex 777751596f1,01d7bc81949..49f77f1afb6--- a/tests/tools/test_completed_process_results.py+++ b/tests/tools/test_completed_process_results.py@@@ -14,25 -15,32 +15,50 @@@ import timREPO_ROOT = Path(__file__).resolve().parents[2]+ def _new_background_notifications(messages, seen_counts):+ """Count new history occurrences, not positions shifted by request assembly."""+ counts = Counter(+ m["content"] for m in messages+ if m["role"] == "user"+ and isinstance(m.get("content"), str)+ and m["content"].startswith("[IMPORTANT: Background process ")+ )+ new = []+ for content, count in counts.items():+ new.extend([content] * max(0, count - seen_counts[content]))+ seen_counts[content] = max(seen_counts[content], count)+ return new+++ def test_background_notification_history_replay_is_not_new_delivery():+ notice = "[IMPORTANT: Background process proc_a exited (exit code 7).]"+ seen_counts = Counter()+ first = [{"role": "system", "content": "first"}, {"role": "user", "content": notice}]+ shifted = [{"role": "system", "content": "second"}, {"role": "user", "content": "query"}, *first[1:]]+ assert _new_background_notifications(first, seen_counts) == [notice]+ assert _new_background_notifications(shifted, seen_counts) == []+ assert _new_background_notifications([*shifted, first[1]], seen_counts) == [notice]++-def test_headless_terminal_result_survives_cli_exit(tmp_path):+def test_retained_result_lookup_does_not_initialize_session_store(tmp_path, monkeypatch):+ import hermes_state+ from gateway.session_context import scoped_current_session_id+ from tools import process_registry_results as receipts++ db_path = tmp_path / "state.db"+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", db_path)+ monkeypatch.setattr(receipts, "get_hermes_home", lambda: tmp_path)+ directory = tmp_path / "logs" / "process-results"+ directory.mkdir(parents=True)+ (directory / "proc_owned.json").write_text(json.dumps({+ "id": "proc_owned", "parent_session_id": "departed-owner",+ }), encoding="utf-8")+ with scoped_current_session_id("unrelated-reader"):+ assert receipts.load_completed_results() == {}+ assert not db_path.exists(), "Reading retained results initialized canonical storage"+++def test_headless_terminal_result_survives_cli_exit(tmp_path, request):"""Real CLI, tool dispatch, shell child and fresh reader; only the LLM is local."""home = tmp_path / "profile"home.mkdir()@@@ -157,12 -163,12 +193,13 @@@assert len(observed) == 1, (observed, producer.stdout, producer.stderr)process_id = observed[0]["session_id"]assert observed[0].get("notify_on_complete") is True, observed- # A terminal completion is an [IMPORTANT: Background process ...] event,- # not an [ASYNC DELEGATION ...] event. The same history entry can appear in- # several provider requests without being delivered a second time.+ # The owned notify_on_complete completion resumes as ONE follow-up turn on the owning- # daemon session, carrying the child's real output and exit code to the model.++ # daemon session, carrying the child's real output and exit code to the model. It is an++ # [IMPORTANT: Background process ...] event, not an [ASYNC DELEGATION ...] event, and the++ # same history entry can appear in several provider requests without being delivered twice.assert len(follow_ups) == 1, follow_ups- assert process_id in follow_ups[0]+ assert follow_ups[0].startswith(f"[IMPORTANT: Background process {process_id} exited (exit code 7).")assert "SYNTHETIC_REVIEW_COMPLETE" in follow_ups[0]- assert "exit code 7" in follow_ups[0]consumer = textwrap.dedent('''import json, sysdiff --cc tools/bot_mode_dm.pyindex 0e041050e18,2b595ac5269..5b0dd78434a--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@@ -436,8 -488,8 +436,8 @@@ def _admit_live_dm(profile_home: Pathassert profile_home is not Noneowner = find_canonical_live_owner(profile_home)if owner is None:- return None+ raise ValueError("canonical Bot Chat target is unavailable; no local fallback")- 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=_dm_delivery_id(dm_file),**({"author": author} if author else {}))try:@@@ -514,10 -570,13 +514,11 @@@ def _run_delivery(argv: list[str], dm_fenv = delivery_env(author, profile_home if not stdin_file else None)with _delivery_lock(argv, stdin_file=stdin_file):- if not stdin_file:- return _run_local_turn(argv, dm_file, env=env)# Keep the file open until the transport exits; cleanup occurs# after subprocess.run returns, not merely after stdin reaches EOF.- with open(dm_file, "r", encoding="utf-8") as stream:- return subprocess.run(argv, stdin=stream, check=False, env=env).returncode+ with open(dm_file, "r", encoding="utf-8-sig") as stream:+ # Passing the file descriptor as stdin bypasses the BOM-aware decoder.+ return subprocess.run(argv, input=stream.read().encode("utf-8"), check=False, env=env).returncodefinally:_unlink_dm_file(dm_file)diff --cc tools/bot_relay.pyindex 7491873a4b5,3f20af91d5f..8014c0d80d8--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@@ -345,7 -364,8 +346,7 @@@ def claim_pending_envelopes(root: Pathclaimed = base / CLAIMED_DIR / path.namewith contextlib.suppress(OSError, ValueError):os.replace(path, claimed) # atomic claim- envelope = json.loads(claimed.read_text(encoding="utf-8"))- os.utime(claimed, (now, now)) # the re-offer window counts from the claim, not the enqueue+ 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)@@@ -371,14 -392,13 +372,14 @@@ def _replay_unanswered(root: Path | strif (base / REPLIES_DIR / path.name).exists():continuewith contextlib.suppress(OSError, ValueError):- envelope = json.loads(path.read_text(encoding="utf-8"))- claimed_at = path.stat().st_mtime+ envelope = json.loads(path.read_text(encoding="utf-8-sig"))if not isinstance(envelope, dict):raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")+ if envelope.get("canonical_delivery_v1") is not True or envelope.get("id") in seen:+ continueenv_id = str(envelope.get("id") or "")label = f"@{envelope.get('target_handle') or '?'} on {envelope.get('target_connection') or '?'}"- created = float(envelope.get("created_at") or claimed_at)+ created = float(envelope.get("created_at") or path.stat().st_mtime)if now - created > REPLY_WAIT_SECONDS:write_reply(root, env_id, reason="delivery_timeout", error=(f"no reply from {label} within {REPLY_WAIT_SECONDS}s of sending — the Desktop picked "diff --cc tools/registry.pyindex 38241410ac1,57cffdc89aa..6a941d52a6e--- a/tools/registry.py+++ b/tools/registry.py@@@ -497,10 -470,7 +498,10 @@@ class ToolRegistrydef _merged_tools(self, scope: Optional[str] = None) -> Dict[str, ToolEntry]:"""Return global tools overlaid with one profile's plugin tools."""- entries = {**self._tools, **self._scoped_tools.get(scope or self.current_scope_key(), {})}- return {**self._tools, **self._scoped_tools.get(hermes_home_key(scope), {})}++ entries = {**self._tools, **self._scoped_tools.get(hermes_home_key(scope), {})}+ if scope is None:+ entries.update(self._scoped_tools.get(current_session_tool_scope(), {}))+ return entriesdef _toolset_entries(self, toolset: str, scope: Optional[str]) -> List[ToolEntry]:return self._grouped(self._merged_tools(scope).values()).get(toolset, [])diff --cc tui_gateway/agent_factory.pyindex a54ce901c29,00000000000..d7b628ba3famode 100644,000000..100644--- a/tui_gateway/agent_factory.py+++ b/tui_gateway/agent_factory.py@@@ -1,635 -1,0 +1,699 @@@+"""TUI agent_factory seam; functions bind to the server namespace at registration."""++from __future__ import annotations++from .method_ctx import bind_module++def _env_model_seed() -> str:+ """The launch-scoped model seed (``hermes --tui -m``, hosted provisioning); "" when unset."""+ return (os.environ.get("HERMES_MODEL", "") or os.environ.get("HERMES_INFERENCE_MODEL", "")).strip()+++def _resolve_model() -> str:+ if env := _env_model_seed():+ return env+ m = _load_cfg().get("model", "")+ if isinstance(m, dict):+ return str(m.get("default", "") or "").strip()+ if isinstance(m, str) and m:+ return m.strip()+ # No env seed / config preference: the cost-safe silent default (cache-only read), never an unpicked flagship.+ with contextlib.suppress(Exception):+ from hermes_cli.models import get_preferred_silent_default_model+ return get_preferred_silent_default_model()+ return "z-ai/glm-5.2"+++def _resolve_session_platform() -> str:+ """``HERMES_DESKTOP=1`` without ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then+ suggests TUI-only slash commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""+ desktop = is_truthy_value(os.environ.get("HERMES_DESKTOP"))+ return "desktop" if desktop and not is_truthy_value(os.environ.get("HERMES_DESKTOP_TERMINAL")) else "tui"+++def _resolve_session_source(explicit: str | None) -> str:+ """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is never+ rewritten; only empty/None falls back to the env-resolved platform."""+ return explicit or _resolve_session_platform()+++def _resolve_agent_platform(source: str | None) -> str:+ return _resolve_session_source(source)+++def _config_model_target() -> tuple[str, str]:+ """(model, provider) selected by config.yaml — and ONLY config: the HERMES_MODEL launch seed fed into+ the per-turn sync would be replayed as a /model switch and persisted globally, or pin the session so+ dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync."""+ cfg_model = _load_cfg().get("model")+ if isinstance(cfg_model, dict):+ provider = str(cfg_model.get("provider") or "").strip()+ return str(cfg_model.get("default", "") or "").strip(), "" if provider.lower() == "auto" else provider+ return (cfg_model.strip() if isinstance(cfg_model, str) else ""), ""+++def _resolve_startup_runtime() -> tuple[str, str | None]:+ model = _resolve_model()+ if explicit_provider := os.environ.get("HERMES_TUI_PROVIDER", "").strip():+ return model, explicit_provider+ if not (explicit_model := _env_model_seed()):+ return model, None+ with contextlib.suppress(Exception):+ from hermes_cli.model_switch import resolve_startup_model_route+ from hermes_cli.models import detect_static_provider_for_model+ full_cfg = _load_cfg()+ cfg = full_cfg.get("model") or {}+ current_provider = ((str(cfg.get("provider") or "").strip().lower() if isinstance(cfg, dict) else "")+ or os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip().lower() or "auto")+ # Same owner as HermesCLI/oneshot: ``custom:<name>:<model>`` selects that provider (#73943).+ if route := resolve_startup_model_route(+ explicit_model, current_provider=current_provider,+ user_providers=full_cfg.get("providers"), custom_providers=full_cfg.get("custom_providers")):+ return route.model, route.provider+ if detected := detect_static_provider_for_model(explicit_model, current_provider):+ provider, detected_model = detected+ return detected_model, provider+ return model, None+++# Bare billing buckets are not routable provider identities; restoring one as a session provider override+# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).+# (agent_init's fail-fast gate is a DIFFERENT set that also skips "openrouter" — there it means "default+# route, don't fail fast", not "unroutable".) ``openrouter`` is deliberately excluded here — it is a fully+# routable provider with its own API key and base_url. Sessions that used OpenRouter store+# ``billing_provider="openrouter"``; dropping it forces resume to the current global model (e.g. a custom+# endpoint), which is the wrong provider for the stored model. See #57588.+++def _is_routable_provider(provider: str) -> bool:+ with contextlib.suppress(Exception):+ from hermes_cli.runtime_provider import is_routable_provider+ return is_routable_provider(provider)+ return False+++def _overrides_have_routable_provider(overrides: dict) -> bool:+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""+ provider = str(overrides.get("provider_override") or "").strip()+ if not provider:+ provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()+ return bool(provider) and _is_routable_provider(provider)+++def _parse_model_config(raw, *, quiet: bool = False) -> dict:+ """A row's ``model_config`` (dict or JSON text) as a dict; ``{}`` when absent/invalid."""+ if isinstance(raw, dict):+ return raw+ if isinstance(raw, str) and raw.strip():+ try:+ parsed = json.loads(raw)+ return parsed if isinstance(parsed, dict) else {}+ except Exception:+ if not quiet:+ raise+ logger.debug("failed to parse stored session model_config", exc_info=True)+ return {}+++def _row_follows_profile(row: dict | None) -> bool:+ """Whether a stored row is a canonical Bot Chat whose runtime follows the member profile's config.+ Identity is the persisted ``follow_profile_config`` marker; the bare title compare stays ONLY here as+ the legacy fallback for rows written before the marker existed."""+ if not row:+ return False+ model_config = _parse_model_config(row.get("model_config"), quiet=True)+ return bool(model_config.get("follow_profile_config") or str(row.get("title") or "").strip() == "Bot Chat")+++def _stored_session_runtime_overrides(row: dict | None) -> dict:+ """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):+ resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode+ sessions normally rebuild from the member profile's CURRENT config (a stale provider pin left room bots+ "out of Nous credits" after a profile switch). A canonical Bot Chat may instead restore an explicit+ composer pick while the profile model it diverged from remains unchanged."""+ if not row:+ return {}+ model_config = _parse_model_config(row.get("model_config"), quiet=True)+ _row_title = str(row.get("title") or "").strip()+ room_plumbing = model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))+ composer_profile = model_config.get("composer_override_profile")+ composer_profile_matches = isinstance(composer_profile, dict) and (+ str(composer_profile.get("model") or "").strip(),+ str(composer_profile.get("provider") or "").strip(),+ ) == _config_model_target()+ if room_plumbing or (_row_follows_profile(row) and not composer_profile_matches):+ return {}+ overrides: dict = {}+ field = lambda k: str(model_config.get(k) or "").strip()+ model = str(row.get("model") or model_config.get("model") or "").strip()+ # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which+ # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.+ provider = field("provider")+ billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()+ if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:+ provider = billing_provider+ base_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")+ reasoning_config = model_config.get("reasoning_config")+ from hermes_cli.runtime_provider import is_foreign_provider_endpoint+ if is_foreign_provider_endpoint(provider, base_url):+ # The endpoint and its wire belong to the provider this chat left; resolve the stored one's own.+ base_url = api_mode = ""+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.+ if provider and not _is_routable_provider(provider):+ healed = None+ try:+ from hermes_cli.runtime_provider import canonical_custom_identity+ healed = canonical_custom_identity(base_url=base_url or None, model=model or None)+ except Exception:+ logger.debug("custom provider identity recovery failed", exc_info=True)+ if healed:+ logger.info("healed stale session provider %r to %r", provider, healed)+ provider = healed+ base_url = "" # the healed identity owns a registered endpoint; the snapshot URL must not override it+ else:+ provider = ""+ if model:+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.+ overrides["model_override"] = {+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}+ if provider:+ overrides["provider_override"] = provider+ if isinstance(reasoning_config, dict):+ overrides["reasoning_config_override"] = reasoning_config+ if service_tier: # None = "inherit the profile" at _make_agent; "" = real override "no priority tier"+ overrides["service_tier_override"] = "" if service_tier.lower() == "normal" else service_tier+ return overrides+++def _runtime_model_config(agent, existing: dict | None = None) -> dict:+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""+ config = dict(existing or {})+ attr = lambda k: str(getattr(agent, k, "") or "").strip()+ model, provider, base_url = attr("model"), attr("provider"), attr("base_url")+ if provider.lower() == "custom":+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.+ try:+ from hermes_cli.runtime_provider import canonical_custom_identity+ provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider+ except Exception:+ logger.debug("custom provider identity lookup failed", exc_info=True)+ reasoning_config = getattr(agent, "reasoning_config", None)+ live = {+ "model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),+ # An empty dict is still a real (present) reasoning config.+ "reasoning_config": reasoning_config if isinstance(reasoning_config, dict) else None,+ "service_tier": getattr(agent, "service_tier", None),+ }+ for key, value in live.items():+ if value or isinstance(value, dict):+ config[key] = value+ else:+ config.pop(key, None)+ return config+++def _persist_live_session_runtime(session: dict | None) -> None:+ """Persist active session runtime so future resumes restore the same footer."""+ live = _live_session_agent_db(session)+ if live is None:+ return+ agent, session_key, db = live+ try:+ row = db.get_session(session_key) or {}+ model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))+ if isinstance(composer_profile := session.get("composer_override_profile"), dict):+ model_config["composer_override_profile"] = composer_profile+ elif "composer_override_profile" in session:+ model_config.pop("composer_override_profile", None)+ if (tier_override := session.get("create_service_tier_override")) is not None:+ # agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.+ model_config["service_tier"] = tier_override or "normal"+ model = str(getattr(agent, "model", "") or "").strip()+ if hasattr(db, "update_session_meta"):+ db.update_session_meta(session_key, json.dumps(model_config), model or None)+ elif model and hasattr(db, "update_session_model"):+ db.update_session_model(session_key, model)+ except Exception:+ logger.debug("failed to persist live session runtime", exc_info=True)++def _load_approval_mode() -> str:+ """Effective ``approvals.mode`` via the gate's own ``_get_approval_mode`` (a raw re-read missed the+ managed overlay and ``${VAR}`` expansion)."""+ from tools.approval_context import _get_approval_mode+ mode = _get_approval_mode()+ return mode if mode in _APPROVAL_MODES else "manual"+++def _coerce_statusbar(raw) -> str:+ if raw is False:+ return "off"+ return s if isinstance(raw, str) and (s := raw.strip().lower()) in _STATUSBAR_MODES else "top"+++_MOUSE_TRACKING_ALIASES = {+ "0": "off", "1": "all", "all": "all", "any": "all", "button": "buttons", "buttons": "buttons",+ "click": "buttons", "false": "off", "full": "all", "no": "off", "off": "off", "on": "all",+ "scroll": "wheel", "true": "all", "wheel": "wheel", "yes": "all",+}+++def _display_mouse_tracking(display: dict) -> str:+ """display.mouse_tracking → ``off|wheel|buttons|all`` (bools: True → all, False → off); ``wheel`` (DEC+ 1000+1006) is the tmux-friendly subset without hover events. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""+ if not isinstance(display, dict):+ return "all"+ raw = display.get("mouse_tracking") if "mouse_tracking" in display else display.get("tui_mouse", True)+ if isinstance(raw, str):+ return _MOUSE_TRACKING_ALIASES.get(raw.strip().lower(), "all")+ return "off" if raw is False or raw == 0 else "all"+++def _load_reasoning_config(model: str = "") -> dict | None:+ """Via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config` (per-model override >+ global ``agent.reasoning_effort``; YAML False = disabled).++ Closes #21256.+ """+ from hermes_constants import resolve_reasoning_config+ return resolve_reasoning_config(_load_cfg(), model)+++_SERVICE_TIER_ALIASES = {"fast": "priority", "priority": "priority", "on": "priority", "auto": "auto", "cold": "cold"}+++def _load_service_tier() -> str | None:+ raw = str((_load_cfg().get("agent") or {}).get("service_tier", "") or "").strip().lower()+ return _SERVICE_TIER_ALIASES.get(raw)+++def _load_provider_routing() -> dict:+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""+ with contextlib.suppress(Exception):+ return _load_cfg().get("provider_routing", {}) or {}+ return {}+++def _load_show_reasoning() -> bool:+ # Fallback True — keep in sync with DEFAULT_CONFIG display.show_reasoning (no DEFAULT_CONFIG merge here).+ return bool(_display_cfg().get("show_reasoning", True))+++def _load_memory_notifications() -> str:+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the+ "💾 Self-improvement review" summary (gateway/CLI parity)."""+ raw = _display_cfg().get("memory_notifications")+ if isinstance(raw, bool):+ return "on" if raw else "off"+ return str(raw).lower() if raw else "on"+++_TOOL_PROGRESS_MODES = frozenset({"off", "new", "all", "verbose"})+++def _load_tool_progress_mode() -> str:+ env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()+ if env in _TOOL_PROGRESS_MODES:+ return env+ raw = _display_cfg().get("tool_progress", "all")+ if isinstance(raw, bool):+ return "all" if raw else "off"+ mode = str(raw or "all").strip().lower()+ return mode if mode in _TOOL_PROGRESS_MODES else "all"+++def _gui_surface_toolsets(platform: str) -> set[str]:+ """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""+ from toolsets import CLIENT_SURFACE_TOOLSETS+ return set(CLIENT_SURFACE_TOOLSETS) if platform == "desktop" else {"project"}+++def _with_session_toolsets(selection, platform: str | None) -> list[str]:+ """*selection* plus what the session carries whatever its config says (the client surface's+ toolsets when *platform* is given; the ones its PROFILE's role reserves, from the backend-written- profile.yaml under the session's home override), minus toolsets reserved for another role."""++ profile.yaml under the session's home override), minus toolsets reserved for another role.++++ The fold-in happens after ``_get_platform_tools`` already subtracted ``agent.disabled_toolsets``,++ so the same subtraction is applied to the fold-in itself — otherwise ``disabled_toolsets:++ [project]`` is a no-op on desktop/TUI, the only surfaces where the client toolsets exist++ (#54433). ``desktop_ui`` is kept regardless: it is the client's own control surface, not a++ model toolset."""+ from toolsets import profile_role_toolsets+ granted, denied = profile_role_toolsets()+ surface = _gui_surface_toolsets(platform) if platform is not None else set()+ kept = [name for name in selection if name not in denied]- return [*kept, *sorted((surface | granted) - set(kept))]++ fold_in = (surface | granted) - set(kept)++ disabled = set(_load_disabled_toolsets() or [])++ if disabled:++ fold_in -= disabled - {"desktop_ui"}++ return [*kept, *sorted(fold_in)]+++def _tui_notice(text: str) -> None:+ print(text, file=sys.stderr, flush=True)+++def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[str] | None | bool:+ """Resolve a HERMES_TUI_TOOLSETS pin: list, None for "all", False when nothing was valid."""+ built_in = [name for name in explicit if validate_toolset(name)]+ unresolved = [name for name in explicit if name not in built_in]+ if unresolved:+ try:+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ plugin_valid = [name for name in unresolved if validate_toolset(name)]+ except Exception:+ plugin_valid = []+ built_in.extend(plugin_valid)+ unresolved = [name for name in unresolved if name not in plugin_valid]+ if any(name in {"all", "*"} for name in built_in):+ if ignored := [name for name in explicit if name not in {"all", "*"}]:+ _tui_notice(f"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: {', '.join(ignored)}")+ return None+ if not unresolved:+ return built_in+ try: # (enabled, disabled) MCP server names from raw config; both empty on any failure+ from hermes_cli.config import read_raw_config+ from tools.mcp_tool_common import mcp_server_enabled+ raw_cfg = read_raw_config()+ mcp_servers = raw_cfg.get("mcp_servers") if isinstance(raw_cfg.get("mcp_servers"), dict) else {}+ mcp_names, mcp_disabled = set(), set()+ for name, server_cfg in mcp_servers.items():+ if isinstance(server_cfg, dict):+ on = mcp_server_enabled(server_cfg)+ (mcp_names if on else mcp_disabled).add(str(name))+ except Exception:+ mcp_names, mcp_disabled = set(), set()+ mcp_valid = [name for name in unresolved if name in mcp_names]+ disabled = [name for name in unresolved if name in mcp_disabled]+ unknown = [name for name in unresolved if name not in mcp_names and name not in mcp_disabled]+ if unknown:+ _tui_notice(f"[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: {', '.join(unknown)}")+ if disabled:+ _tui_notice("[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS "+ f"(set enabled: true in config.yaml to use): {', '.join(disabled)}")+ return (built_in + mcp_valid) or False+++def _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:+ """The agent's toolsets for this session (None = all): an explicit HERMES_TUI_TOOLSETS pin; else the+ coding posture (coding_context collapses to coding toolset + enabled MCP servers in a code workspace);+ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them."""+ session_platform = platform or _resolve_session_platform()+ explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]+ fallback_notice = None+ if not explicit:+ with contextlib.suppress(Exception):+ from agent.coding_context import coding_selection+ selection = coding_selection(platform=session_platform)+ if selection is not None:+ return sorted(_with_session_toolsets(selection, session_platform))+ try:+ from toolsets import validate_toolset+ except Exception:+ validate_toolset = None+ if explicit and validate_toolset is not None:+ resolved = _resolve_explicit_toolsets(explicit, validate_toolset)+ if resolved is not False:+ # An operator pin replaces the surface fold-in but never strips the profile's own role toolsets.+ return resolved if resolved is None else _with_session_toolsets(resolved, None)+ fallback_notice = "[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"+ try:+ from hermes_cli.config import load_config+ from hermes_cli.tools_config import _get_platform_tools+ cfg = load_config()+ # include_default_mcp_servers=True is the runtime variant (the agent must be able to call+ # default MCP servers); the config-editing variant would silently drop MCP tools from the TUI.+ # Passing ``False`` here is the config-editing variant — used when we need to persist a toolset list+ # without baking in implicit MCP defaults. Using the wrong variant at agent creation time makes MCP+ # tools silently missing from the TUI. See PR #3252 for the original design split.+ enabled = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)+ if fallback_notice is not None:+ _tui_notice(fallback_notice)+ return sorted(_with_session_toolsets(enabled, session_platform)) if enabled else None+ except Exception:+ if fallback_notice is not None:+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")+ return None++++def _load_disabled_toolsets() -> list[str] | None:++ """``agent.disabled_toolsets`` from config.yaml, or ``None``.++++ The classic CLI (``cli_init_mixin``) and the messaging gateway both forward this list to++ AIAgent, where ``get_tool_definitions`` strips the named toolsets even out of composite++ defaults like ``hermes-cli`` (#17309). The desktop/TUI gateway historically dropped it, so++ e.g. ``disabled_toolsets: [browser]`` silently had no effect on Desktop — the only consumer++ was ``_get_platform_tools``'s name-level subtraction, which can't reach inside a composite++ default toolset (#44499).++ """++ try:++ from agent.skill_utils import parse_config_string_list++++ from hermes_cli.config import load_config++++ agent_cfg = load_config().get("agent") or {}++ disabled = parse_config_string_list(agent_cfg.get("disabled_toolsets"))++ return [str(ts) for ts in disabled] or None++ except Exception:++ return None+++++def _session_tool_progress_mode(sid: str) -> str:+ return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")+++def _session_verbose(sid: str) -> bool:+ return _session_tool_progress_mode(sid) == "verbose"++++def _session_show_reasoning(sid: str) -> bool:++ """Session display flag. Missing means the config default, not hidden."""++ session = _sessions.get(sid) or {}++ if "show_reasoning" in session:++ return bool(session["show_reasoning"])++ return _load_show_reasoning()++++++def _process_tool_chrome_enabled(sid: str) -> bool:++ """Non-essential tool rows follow display.show_reasoning, not reasoning_effort."""++ return _session_show_reasoning(sid) and _tool_progress_enabled(sid)+++++def _tool_progress_enabled(sid: str) -> bool:+ return _session_tool_progress_mode(sid) != "off"++++_TOOL_LIFECYCLE_UI_TOOLS = frozenset({++ "clarify", "manage_connections", "setup_mcp",++ "image_generate", "manage_catalog", "delegate_task",++ # File edits are the turn's deliverable — the diff card the user reviews.++ "edit_file", "patch", "write_file",++})+++++def _tool_lifecycle_required_for_ui(name: str) -> bool:- """Interactive UI, not optional chrome: Desktop renders clarify / connection cards from the tool-call part."""- return name in ("clarify", "manage_connections", "setup_mcp")++ """Interactive UI / card surfaces, not optional chrome.++++ Desktop renders these from the tool-call part itself, so suppressing the++ lifecycle hides the turn's deliverable entirely (`isCardTool` /++ `isFileEditTool` in apps/desktop/src/lib/tool-render-class.ts must stay in++ sync with `_TOOL_LIFECYCLE_UI_TOOLS`): clarify / connection cards are++ consent surfaces, image_generate / manage_catalog / delegate_task draw the++ thing the user asked for, and file edits are the diff the user reviews.++ The start and complete guards both consult this set, so a card's++ `tool.complete` can never arrive without its `tool.start`.++ """++ return name in _TOOL_LIFECYCLE_UI_TOOLS++def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _RuntimeFallbackResolution:+ """Resolve the primary runtime or one complete provider/model fallback. Provider-only fallback entries+ are skipped so the unavailable primary model can never leak into a different runtime."""+ from hermes_cli.auth import AuthError+ from hermes_cli.runtime_provider import resolve_runtime_provider+ try:+ return _RuntimeFallbackResolution(resolve_runtime_provider(**(resolve_kwargs or {})), None, False)+ except AuthError as primary_exc:+ for entry in _load_fallback_model() or []:+ fb_provider = str(entry.get("provider") or "").strip() if isinstance(entry, dict) else ""+ fb_model = str(entry.get("model") or "").strip() if isinstance(entry, dict) else ""+ if not fb_provider or not fb_model:+ continue+ try:+ from hermes_cli.fallback_config import effective_runtime_provider, resolve_entry_api_key+ fb_kwargs: dict = {"requested": fb_provider, "target_model": fb_model,+ **({"explicit_base_url": entry["base_url"]} if entry.get("base_url") else {})}+ if fb_api_key := resolve_entry_api_key(entry):+ fb_kwargs["explicit_api_key"] = fb_api_key+ runtime = resolve_runtime_provider(**fb_kwargs)+ # Named custom entries resolve to the bare "custom" billing class; keep the configured+ # identity so the session/UI shows the provider name, matching the manual-switch path (#98739).+ runtime["provider"] = effective_runtime_provider(entry, runtime)+ from hermes_cli.auth import primary_failure_wording+ logging.getLogger(__name__).warning(+ "Primary %s (%s), falling back to %s model %s",+ primary_failure_wording(primary_exc)[0], primary_exc, fb_provider, fb_model)+ return _RuntimeFallbackResolution(runtime, fb_model, True)+ except Exception:+ continue+ raise+++def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[str, dict]:+ """(model, runtime) for a new agent; a per-session override (/model switch or a resumed row's persisted+ runtime) wins over global config/env. Older rows stored the resolved provider "custom" (no named entry+ matches) — recover the identity from the persisted base_url or the rebuild fails "No LLM provider+ configured". Persisted base_url/api_key/api_mode are honored only for the original runtime, never a fallback."""+ if isinstance(model_override, dict) and model_override.get("model"):+ model = str(model_override.get("model") or "")+ requested_provider = model_override.get("provider") or provider_override or None+ override_base_url = model_override.get("base_url")+ resolve_kwargs = {}+ if str(requested_provider or "").strip().lower() == "custom":+ from hermes_cli.runtime_provider import canonical_custom_identity+ if recovered := canonical_custom_identity(base_url=override_base_url or None, model=model or None):+ requested_provider = recovered+ if override_base_url:+ # Failing identity recovery, still hand base_url to the direct-alias branch so pool/env credentials resolve.+ resolve_kwargs["explicit_base_url"] = override_base_url+ resolve_kwargs.update(requested=requested_provider, target_model=model or None)+ overrides = {k: model_override.get(k) for k in ("base_url", "api_key", "api_mode")}+ else:+ model, requested_provider = _resolve_startup_runtime()+ if isinstance(model_override, str) and model_override:+ model = model_override+ if provider_override:+ requested_provider = provider_override+ resolve_kwargs = {"requested": requested_provider, "target_model": model or None}+ overrides = {}+ resolution = _resolve_runtime_with_fallback(resolve_kwargs)+ if resolution.used_fallback:+ if not resolution.selected_model:+ raise RuntimeError("Auth fallback resolved without a model")+ # Same pre-agent switch the messaging gateway surfaces (#74349); _make_agent pops it onto the+ # agent's one-shot notice so the TUI/Desktop user sees which provider actually answered.+ from hermes_cli.fallback_config import pre_agent_fallback_notice+ # requested_provider=None means resolve_runtime_provider read the persisted config provider;+ # ``model: <id>`` (string shorthand) names no provider.+ cfg_model = _load_cfg().get("model")+ primary_provider = requested_provider or (cfg_model.get("provider") if isinstance(cfg_model, dict) else None)+ resolution.runtime["_fallback_notice"] = pre_agent_fallback_notice(+ primary_provider, model, resolution.runtime.get("provider"), resolution.selected_model)+ return resolution.selected_model, resolution.runtime+ if resolution.runtime.get("source") == "local-runtime":+ # Live supervisor beat any persisted loopback URL for this identity.+ overrides.pop("base_url", None)+ resolution.runtime.update({k: v for k, v in overrides.items() if v})+ if any(overrides.values()):+ _rederive_per_model_route(model, resolution.runtime)+ return model, resolution.runtime+++def _rederive_per_model_route(model: str, runtime: dict) -> None:+ """A row's persisted api_mode/base_url were written for whichever model the session last ran. Providers+ that pick the wire per model (OpenCode Zen/Go, Copilot, Nous) must re-derive both from the target model,+ or a resumed opencode-go session keeps a MiniMax-era anthropic_messages route (and its /v1-stripped or+ other-family relay URL) for a chat_completions model like deepseek-v4-flash-vision-exp (#96066)."""+ from hermes_cli.model_switch import model_derived_api_mode+ from hermes_cli.models import normalize_opencode_base_url+ provider = str(runtime.get("requested_provider") or runtime.get("provider") or "")+ api_mode = model_derived_api_mode(provider, model)+ if api_mode is None:+ return+ runtime["api_mode"] = api_mode+ runtime["base_url"] = normalize_opencode_base_url(provider, api_mode, runtime.get("base_url"))+++def _startup_system_prompt(cfg: dict, task_id: str) -> str:+ """Config ephemeral system prompt + HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY requested+ skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""+ from hermes_cli.config import resolve_ephemeral_system_prompt_from_config+ system_prompt = resolve_ephemeral_system_prompt_from_config(cfg)+ startup_skills = _parse_tui_skills_env()+ if not startup_skills:+ return system_prompt+ from agent.skill_commands import build_preloaded_skills_prompt+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)+ if missing_skills:+ missing_display = ", ".join(missing_skills)+ if not loaded_skills:+ raise ValueError(f"Unknown skill(s): {missing_display}")+ logger.warning("Unknown skill(s) requested, skipping: %s. Continuing with: %s. "+ "List available skills with `hermes skills list`.", missing_display, ", ".join(loaded_skills))+ if skills_prompt:+ system_prompt = "\n\n".join(part for part in (system_prompt, skills_prompt) if part).strip()+ return system_prompt+++def _make_agent(+ sid: str, key: str, session_id: str | None = None, session_db=None,+ model_override: dict | str | None = None, provider_override: str | None = None,+ reasoning_config_override: dict | None = None, service_tier_override: str | None = None,+ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,+ cwd_override: str | None = None, auth_user_id: str | None = None):+ # AC-4 test seam: dead unless armed by the isolated certify harness.+ from tui_gateway.synthetic_turn import maybe_build_synthetic_agent+ synthetic = maybe_build_synthetic_agent(session_id or key, model_override)+ if synthetic is not None:+ return synthetic+ from run_agent import AIAgent+ # MCP discovery runs in a daemon thread (a dead server can't freeze the shell); the agent snapshots its tool+ # list once, so briefly wait for in-flight discovery. Dashboard /api/ws uses mcp_startup; TUI stdio uses entry.+ for _mod in ("hermes_cli.mcp_startup", "tui_gateway.entry"):+ with contextlib.suppress(Exception):+ importlib.import_module(_mod).wait_for_mcp_discovery()+ cfg = _load_cfg()+ # Load hooks alongside the same profile config used to construct this agent.+ from agent.shell_hooks import register_from_config+ register_from_config(cfg)+ system_prompt = _startup_system_prompt(cfg, session_id or key)+ model, runtime = _resolve_agent_model_runtime(model_override, provider_override)+ fallback_notice = runtime.pop("_fallback_notice", None)+ _pr = _load_provider_routing()+ platform = _resolve_agent_platform(platform_override)+ ignore_rules = is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))+ with _sessions_lock:+ session = _sessions.get(sid)+ agent = AIAgent(+ model=model, max_iterations=_cfg_max_turns(cfg, 500), provider=runtime.get("provider"),+ requested_provider=runtime.get("requested_provider"),+ base_url=runtime.get("base_url"), api_key=runtime.get("api_key"), api_mode=runtime.get("api_mode"),+ acp_command=runtime.get("command"), acp_args=runtime.get("args"),+ credential_pool=runtime.get("credential_pool"), quiet_mode=True,+ verbose_logging=False, # DEBUG agent logging; independent of tool_progress_mode+ reasoning_config=(+ reasoning_config_override if reasoning_config_override is not None else _load_reasoning_config(str(model or ""))),+ service_tier=service_tier_override if service_tier_override is not None else _load_service_tier(),+ enabled_toolsets=_load_enabled_toolsets(platform),++ disabled_toolsets=_load_disabled_toolsets(),+ # OpenRouter provider_routing prefs (gateway + CLI parity).+ providers_allowed=_pr.get("only"), providers_ignored=_pr.get("ignore"), providers_order=_pr.get("order"),+ provider_sort=_pr.get("sort"), provider_require_parameters=_pr.get("require_parameters", False),+ provider_data_collection=_pr.get("data_collection"), platform=platform, session_id=session_id or key,+ cwd=cwd_override,+ # The dashboard login identity reaches memory providers as the runtime user, like a gateway user id.+ # Builds that run before the record exists (branch, eager resume, compute host) pass it explicitly.+ user_id=auth_user_id if auth_user_id is not None else _session_auth_user_id(session),+ session_db=session_db if session_db is not None else _get_db(), ephemeral_system_prompt=system_prompt or None,+ checkpoints_enabled=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),+ pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),+ skip_context_files=ignore_rules, skip_memory=ignore_rules, fallback_model=_load_fallback_model(),- **_agent_cbs(sid))++ prefill_messages=_load_prefill_messages() or None, **_agent_cbs(sid))+ if context_cwd_is_launch_artifact is None:+ context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)+ agent._context_cwd_is_launch_artifact = bool(context_cwd_is_launch_artifact)+ if fallback_notice:+ # Emitted once on the first successful reply via _emit_pending_fallback_notice -> status_callback.+ agent._pending_fallback_notice = fallback_notice+ return agent+++def register(server):+ bind_module(globals(), server)diff --cc tui_gateway/command_discovery.pyindex b07751a462d,00000000000..631858f7c7cmode 100644,000000..100644--- a/tui_gateway/command_discovery.py+++ b/tui_gateway/command_discovery.py@@@ -1,276 -1,0 +1,276 @@@+"""Shared slash discovery data; no server import or session execution runtime.++Transport wrappers own authentication and profile binding before calling these+builders. Keep the legacy catalog and completion semantics identical here.+"""+import contextlib+from importlib import import_module+import logging++logger = logging.getLogger(__name__)++_TUI_HIDDEN: frozenset[str] = frozenset({"sethome", "set-home", "commands", "approve", "deny"})++_TUI_EXTRA: list[tuple[str, str, str]] = [+ ("/density", "Toggle compact display mode", "TUI"),+ ("/logs", "Show recent gateway log lines", "TUI"),+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]", "TUI"),+ ("/sessions", "Switch between live TUI sessions", "TUI"),+]++_SLASH_EXTRAS = [+ ("/density", "Toggle compact display mode"), ("/details", "Control agent detail visibility"),+ ("/logs", "Show recent gateway log lines"),+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]")]+++def _item(text: str, meta: str, display: str | None = None) -> dict:+ return {"text": text, "display": display if display is not None else text, "meta": meta}+++def _skill_usage_lookup():+ """``(usage, origin)`` callables for the skill catalog: activity count (use + view + patch) and+ "hub" / "bundled" / "local" (``/api/skills`` ``provenance``, "local" spelled "agent"). Failure → 0 / "local"."""+ try:+ from tools.skill_usage import (- _read_bundled_manifest_names, _read_hub_installed_names, activity_count, load_usage)- records, bundled, hub = load_usage(), _read_bundled_manifest_names(), _read_hub_installed_names()++ _read_bundled_names, _read_hub_installed_names, activity_count, load_usage)++ records, bundled, hub = load_usage(), _read_bundled_names(), _read_hub_installed_names()+ except Exception as e:+ logger.debug("skill usage lookup unavailable: %s", e)+ return (lambda _name: 0), (lambda _name: "local")++ def usage(name: str) -> int:+ with contextlib.suppress(Exception):+ return activity_count(records.get(name) or {})+ return 0++ def origin(name: str) -> str:+ return "hub" if name in hub else "bundled" if name in bundled else "local"+ return usage, origin+++_SLASH_COMPLETION_LIMIT = 30+++def _rank_slash_completions(items: list[dict], usage, origin_of, *, browsing: bool, score_of=None) -> list[dict]:+ """Registry commands keep their order; only skills reorder: fuzzy ``score_of`` first, then most-used, then+ A-Z. The limit is spent PER KIND (a flat cut on a large install offered no skill at all). ``browsing``+ (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING — nothing pruned, only reordered."""+ def name_of(item: dict) -> str:+ return str(item.get("text", "")).strip().lstrip("/").lower()+ commands = [item for item in items if item.get("kind") != "skill"]+ skills = [item for item in items if item.get("kind") == "skill"]+ if browsing:+ skills = [item for item in skills if origin_of(name_of(item)) != "bundled" or usage(name_of(item)) > 0]+ skills.sort(key=lambda item: (+ *(() if score_of is None else (score_of(item),)), -usage(name_of(item)), name_of(item)))+ return commands[:_SLASH_COMPLETION_LIMIT] + skills[:_SLASH_COMPLETION_LIMIT]+++_DETAILS_SECTIONS = ("thinking", "tools", "subagents", "activity")+_DETAILS_MODES = ("hidden", "collapsed", "expanded")+++def _details_root_meta(candidate: str) -> str:+ if candidate in _DETAILS_SECTIONS:+ return "section override"+ return "cycle global mode" if candidate == "cycle" else "global mode"+++def _details_completions(text: str) -> list[dict] | None:+ """Argument completions for ``/details [section] [mode]``; None when ``text`` is not that command."""+ if not text.lower().startswith("/details"):+ return None+ stripped = text.strip()+ if stripped and not "/details".startswith(stripped.lower().split()[0]):+ return None+ body = text[len("/details") :].removeprefix(" ")+ parts = body.split()+ trailing = text.endswith(" ")+ root_candidates = (*_DETAILS_MODES, "cycle", *_DETAILS_SECTIONS)+ if not body or (not parts and trailing):+ lead = "" if trailing else " "+ return [_item(f"{lead}{c}", _details_root_meta(c)) for c in root_candidates]+ if len(parts) == 1 and not trailing:+ prefix = parts[0].lower()+ return [_item(c, _details_root_meta(c)) for c in root_candidates if c.startswith(prefix) and c != prefix]+ section = parts[0].lower() if parts else ""+ if section not in _DETAILS_SECTIONS:+ return []++ def section_meta(candidate: str) -> str:+ return f"clear {section} override" if candidate == "reset" else f"set {section}"+ mode_candidates = (*_DETAILS_MODES, "reset")+ if len(parts) == 1: # trailing space after the section+ return [_item(c, section_meta(c)) for c in mode_candidates]+ if len(parts) == 2 and not trailing:+ prefix = parts[1].lower()+ return [_item(c, section_meta(c)) for c in mode_candidates if c.startswith(prefix) and c != prefix]+ return []+++class _Catalog:+ """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase+ key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""++ def __init__(self) -> None:+ self.pairs: list[list[str]] = []+ self.canon: dict[str, str] = {}+ self.commands: dict[str, dict[str, str | None]] = {}+ self.cat_map: dict[str, list[list[str]]] = {} # insertion order = category order++ def add(self, key: str, desc: str, cat: str) -> None:+ self.canon[key.lower()] = key+ self.pairs.append([key, desc])+ self.cat_map.setdefault(cat, []).append([key, desc])+++def _catalog_registry(cat: _Catalog, module_loader) -> None:+ commands = module_loader("hermes_cli.commands")+ for cmd in commands.COMMAND_REGISTRY:+ meta = commands.command_desktop_meta(cmd)+ cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})+ if cmd.name in _TUI_HIDDEN or cmd.gateway_only:+ continue+ cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)+ for a in cmd.aliases:+ cat.canon[f"/{a}".lower()] = f"/{cmd.name}"+ for name, desc, category in _TUI_EXTRA:+ # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).+ if name.lower() not in cat.canon:+ cat.add(name, desc, category)+++def _catalog_quick_commands(cat: _Catalog, load_cfg) -> None:+ qcmds = load_cfg().get("quick_commands", {}) or {}+ if not (isinstance(qcmds, dict) and qcmds):+ return+ cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed+ for qname, qc in sorted(qcmds.items()):+ if not isinstance(qc, dict):+ continue+ qtype = qc.get("type", "")+ default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}+ desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))+ cat.add(f"/{qname}", desc, "User commands")+++def _catalog_plugin_commands(cat: _Catalog, module_loader) -> None:+ plugin_cmds = module_loader("hermes_cli.plugins").get_plugin_commands() or {}+ if plugin_cmds:+ cat.cat_map.setdefault("Plugin commands", [])+ for pname, info in sorted(plugin_cmds.items()):+ key = f"/{pname}"+ if not isinstance(info, dict) or key.lower() in cat.canon:+ continue+ cat.add(key, str(info.get("description") or "Plugin command"), "Plugin commands")+ mode = info.get("argument_mode")+ if mode not in {"options", "text", "mixed"}:+ mode = "text" if str(info.get("args_hint") or "").strip() else None+ cat.commands[key] = {"argument_mode": mode, "desktop": None}+++def _catalog_skills(cat: _Catalog, skills: dict[str, dict], module_loader) -> str:+ """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them).+ Returns the one-line notice for skills whose name is a built-in command (no ``/<name>`` entry;+ ``agent.skill_commands`` guard), ``""`` when none."""+ usage, origin_of = _skill_usage_lookup()+ sc = module_loader("agent.skill_commands")+ for k, info in sorted(sc.scan_skill_commands().items()):+ cat.pairs.append([k, str(info.get("description", "Skill"))])+ name = str(info.get("name") or k.lstrip("/"))+ skills[k] = {"usage": usage(name), "origin": origin_of(name)}+ collision_note = getattr(sc, "skill_command_collision_note", None)+ if collision_note is None:+ return ""+ names = sorted(s["name"] for s in module_loader("tools.skills_tool")._find_all_skills())+ return "; ".join(filter(None, map(collision_note, names)))+++def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> dict:+ """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``+ (skills' message wins, then quick commands', then plugins'); only with no failure does it carry+ the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). ``scope``+ is a context manager binding the calling session's profile home and workspace around skill+ discovery so project-local skills register for the repo the session is actually in (#114359)."""+ if load_cfg is None:+ from hermes_cli.config import load_config_readonly+ load_cfg = load_config_readonly+ cat = _Catalog()+ _catalog_registry(cat, module_loader)+ warning = ""+ try:+ _catalog_quick_commands(cat, load_cfg)+ except Exception as e:+ warning = f"quick_commands discovery unavailable: {e}"+ try:+ _catalog_plugin_commands(cat, module_loader)+ except Exception as e:+ warning = warning or f"plugin command discovery unavailable: {e}"+ skills: dict[str, dict] = {}+ try:+ with scope if scope is not None else contextlib.nullcontext():+ collision_note = _catalog_skills(cat, skills, module_loader) # always runs: skills must list even when a loader failed+ warning = warning or collision_note+ except Exception as e:+ warning = f"skill discovery unavailable: {e}"+ return {+ "pairs": cat.pairs, "sub": {k: v[:] for k, v in module_loader("hermes_cli.commands").SUBCOMMANDS.items()},+ "canon": cat.canon,+ "commands": cat.commands,+ "categories": [{"name": c, "pairs": rows} for c, rows in cat.cat_map.items()],+ "skills": skills, "skill_count": len(skills), "warning": warning}+++def slash_completions(text: str = "", scope=None) -> dict:+ """``scope`` binds the calling session's profile and workspace around the skill/bundle lookups+ (home- and cwd-keyed) so the popup offers the project-local skills ``command.dispatch`` accepts+ for that session (#114359)."""+ if not text.startswith("/"):+ return {"items": []}+ from hermes_cli.commands_completion import SlashCommandCompleter+ from prompt_toolkit.document import Document+ from prompt_toolkit.formatted_text import to_plain_text+ from agent.skill_commands import get_skill_commands+ from agent.skill_bundles import get_skill_bundles+ with scope if scope is not None else contextlib.nullcontext():+ skill_commands, skill_bundles = dict(get_skill_commands()), dict(get_skill_bundles())+ completer = SlashCommandCompleter(+ skill_commands_provider=lambda: skill_commands, skill_bundles_provider=lambda: skill_bundles)+ # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):+ # skills/bundles are the only completions for an inline `/skill` typed mid-message.+ skill_names = {key.lstrip("/").lower() for key in (*skill_commands, *skill_bundles)}++ def to_items(doc: Document) -> list[dict]:+ # display/display_meta are FormattedText; the TUI contract is a plain string+ # (the raw list trips Ink's row layout into 1-char truncation).+ return [+ {+ "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,+ "meta": to_plain_text(c.display_meta) if c.display_meta else "",+ "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}+ for c in completer.get_completions(doc, None)]+ items = to_items(Document(text, len(text)))+ # Rank + bound while a `/token` is under the cursor (the one stage skills are+ # offered at); an argument stage (`/personality `) keeps its command's order.+ if text.rsplit(" ", 1)[-1].startswith("/"):+ score_of = None+ # Command-token stage: the completer only emits name-prefix matches, so merge in+ # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).+ if " " not in text and len(text) > 1:+ from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query+ items, score_of = fuzzy_rank_slash_items(+ items, to_items(Document("/", 1)), normalize_slash_search_query(text))+ usage, origin_of = _skill_usage_lookup()+ items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)+ else:+ items = items[:_SLASH_COMPLETION_LIMIT]+ text_lower = text.lower()+ for extra_text, extra_meta in _SLASH_EXTRAS:+ if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):+ items.append({**_item(extra_text, extra_meta), "kind": "command"})+ if (details_items := _details_completions(text)) is not None:+ return {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)}+ return {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1}++diff --cc tui_gateway/methods_config.pyindex 97ba584def8,3a631c18728..694fa34f3f1--- a/tui_gateway/methods_config.py+++ b/tui_gateway/methods_config.py@@@ -321,15 -435,35 +432,16 @@@ def _(rid, params: dict) -> dictrequested = str(params.get("provider") or "").strip() or Nonedef probe(profile, scoped):- if requested:- model, _startup_provider = _resolve_startup_runtime()- runtime = resolve_runtime_provider(requested=requested, target_model=model or None)- else:- model, runtime = _resolve_agent_model_runtime(None, None)- provider_configured = bool(_has_any_provider_configured(strict_profile_scope=bool(profile)))- provider = runtime.get("provider") or "provider"- source = str(runtime.get("source") or "")-- def fail(error, src):- return {"ok": False, "provider": provider, "model": model,- "source": src, "error": error, **scoped}- if (not provider_configured and provider == "bedrock"- and source in {"iam-role", "aws-sdk-default-chain"}):- return fail("No Hermes provider is configured.", source)- api_key = runtime.get("api_key")- api_key_text = "" if callable(api_key) else str(api_key or "").strip()- if not (callable(api_key) or api_key_text in {"aws-sdk", "no-key-required"}- or has_usable_secret(api_key_text) or bool(runtime.get("command"))):- return fail(f"No usable credentials found for {provider}.", runtime.get("source"))- from hermes_cli.anon_auth import route_is_welcome_host- # free_tier is keyed on the SELECTED route (the welcome host serves only nous/welcome), not- # on profile state: a paid Nous key beside a free-tier identity must not read as free.- return {"ok": True, "provider": runtime.get("provider"), "model": model,- "source": runtime.get("source"),- "free_tier": provider == "nous" and route_is_welcome_host(runtime.get("base_url")),+ def resolve():+ if requested:+ from hermes_cli.runtime_provider import resolve_runtime_provider+ model, _startup_provider = _resolve_startup_runtime()+ return model, resolve_runtime_provider(requested=requested, target_model=model or None)+ return _resolve_agent_model_runtime(None, None)+ return {**check_runtime_readiness(requested, strict_profile_scope=bool(profile), resolve=resolve),**scoped}- return _readiness_check(rid, params, probe)+ return _readiness_check(rid, params, probe, probe_key=f"runtime:{requested or ''}",+ wait_seconds=_READINESS_SHARE_WAIT_SECONDS)except Exception as e:return _ok(rid, {"ok": False, "error": str(e)})diff --cc tui_gateway/session_notifications.pyindex c26f376e853,43a43865ac1..6d44dc73159--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@@ -457,14 -456,15 +457,23 @@@ def _notif_poll_kanban_scoped(sid: str**({"display_metadata": {"notification_category": "diagnostic"}} if diagnostic else {}))+def _notif_defer_event(evt, claim, put=None):+ from tools.async_delegation import defer_completion_delivery+ from tools.process_registry import process_registry+ if claim:+ defer_completion_delivery(evt['delegation_id'], claim)+ (put or process_registry.completion_queue.put)(evt)+++ def _background_notifications_off(session: dict) -> bool:+ """Whether the owning profile set ``display.background_process_notifications: off``. Same+ gate the messaging gateway applies to its process-event injection; only ``off`` matters+ here (the other modes shape gateway chat receipts, not agent wakes)."""+ with _session_profile_runtime_scope(session):+ raw = (_load_cfg().get("display") or {}).get("background_process_notifications")+ return raw is False or str(raw or "").strip().lower() == "off"++def _notif_dispatch_event(sid: str, session: dict, evt: dict, text: str) -> None:"""Run the claimed (running=True) agent turn for one notification event."""from tools.async_delegation import claim_event_delivery, complete_event_delivery, release_event_deliverydiff --cc tui_gateway/transport.pyindex 5f7fa3dadbe,689f5614299..6719b48bce0--- a/tui_gateway/transport.py+++ b/tui_gateway/transport.py@@@ -145,8 -145,10 +145,11 @@@ class FanoutTransportOne slow socket must not stop the emitting turn or any healthy subscriber.Each peer has at most one daemon writer and a bounded backlog. On overflow- it loses its subscription (history/replay is the recovery path), not other- sessions sharing its socket. A write already in the OS cannot be revoked.- it loses its subscription and that peer's transport is closed so the client++ it loses its subscription; unless the writer supplies a resume notice for a++ still-healthy socket, that peer's transport is closed so the client+ notices, reconnects and replays history. Closing the socket also drops any+ other sessions multiplexed on it; the same reconnect + replay recovers them.+ Other sockets are unaffected. A write already in the OS cannot be revoked."""_MAX_PENDING_FRAMES = 256@@@ -241,11 -238,17 +244,22 @@@self._remove(peer)return+ def _signal_overflow_detach(self, transport: Transport) -> None:+ # Outside the fanout lock: abort()/close() may re-enter contains/detach, and+ # a WS close must not stall the emit turn or other subscribers. WSTransport+ # aborts (1011 socket close, off-loop safe); other transports just close.+ try:+ abort = getattr(transport, "abort", None)+ (abort or transport.close)()+ except Exception:+ logger.debug("fanout overflow close failed; membership already dropped", exc_info=True)+- def write(self, obj: dict) -> bool:+ def write(self, obj: dict, *, overflow: Callable[[Transport], Optional[dict]] | None = None) -> bool:+ """Fan *obj* out. A peer whose bounded backlog is full loses its subscription; *overflow*+ (called with its transport, under the membership lock) may return one final frame that+ replaces the dropped backlog, so a socket that is still healthy learns it must resume- rather than silently continuing with partial history."""++ rather than silently continuing with partial history. Without such a notice the peer's++ transport is closed so the client notices, reconnects and replays."""# Freeze the queued frame so a caller cannot mutate it after admission. Same serialization# guard as the single-peer transports: an unserializable frame reaches every peer as -32603.encoded = serialize_frame(obj, "fanout", logger)@@@ -258,16 -262,8 +273,18 @@@if (len(peer.pending) >= self._MAX_PENDING_FRAMESor peer.pending_bytes + size > self._MAX_PENDING_BYTES):logger.warning("fanout subscriber backlog full; detaching peer")- overflowed.append(peer.transport)self._remove(peer)+ notice = overflow(peer.transport) if overflow is not None else None- if notice is not None:++ if notice is None:++ overflowed.append(peer.transport)++ else:+ peer.pending.append((notice, 0))+ if peer not in self._peers:+ self._peers.append(peer)+ if not peer.writing:+ peer.writing = True+ threading.Thread(target=self._drain, args=(peer,),+ name="tui-fanout", daemon=True).start()continuepeer.pending.append((frame, size))peer.pending_bytes += sizediff --cc ui-tui/src/app/turnController.tsindex cca5ed86c92,e78475d141e..29791128b9a--- a/ui-tui/src/app/turnController.ts+++ b/ui-tui/src/app/turnController.ts@@@ -124,9 -122,37 +124,37 @@@ const finalTail = (finalText: string, sreturn tail}+ const interruptedText = (partial: string) => (partial ? `${partial}\n\n*[interrupted]*` : '*[interrupted]*')++ // What interruptTurn sealed into the transcript: `text` is the bubble it+ // appended (null when it only wrote a sys note), `partial` the reply text in it.+ export interface SealedInterrupt {+ partial: string+ text: null | string+ }++ // The bubble fix for an honoured interrupt: Ctrl+C seals the reply the moment+ // the key lands, but the agent keeps streaming until it notices the interrupt,+ // and it persists (and replays next turn) everything it streamed. The+ // interrupted message.complete carries that persisted partial; when it extends+ // what was sealed, the transcript takes it so the screen matches state.db.+ export const lateInterruptedReply = (+ sealed: null | SealedInterrupt,+ payload: MessageCompletePayload+ ): null | { from: null | string; to: string } => {+ const persisted = typeof payload.text === 'string' ? payload.text.trim() : ''+ const shown = sealed?.partial.trimEnd() ?? ''++ if (!sealed || payload.status !== 'interrupted' || persisted.length <= shown.length || !persisted.startsWith(shown)) {+ return null+ }++ return { from: sealed.text, to: interruptedText(persisted) }+ }+export interface InterruptDeps {appendMessage: (msg: Msg) => void- gw: { request: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T> }+ gw: { isCanonical?: boolean; request: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T> }sid: stringsys: (text: string) => void}diff --cc ui-tui/src/app/useMainApp.tsindex 0cd645d5d3e,a9003bafa0d..7f316dad398--- a/ui-tui/src/app/useMainApp.ts+++ b/ui-tui/src/app/useMainApp.ts@@@ -13,8 -13,7 +13,8 @@@ import { JSON_RPC_METHOD_NOT_FOUND, typimport { useStore } from '@nanostores/react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { sharedControlParams } from '../canonicalGateway.js'- import { DASHBOARD_TUI_MODE, STARTUP_RESUME_ID } from '../config/env.js'+ import { DASHBOARD_TUI_MODE, NATIVE_MODE, STARTUP_RESUME_ID } from '../config/env.js'import { WHEEL_SCROLL_STEP } from '../config/limits.js'import { RESIZE_COALESCE_MS } from '../config/timing.js'import { hasLeadGap, prevRenderedMsg } from '../domain/blockLayout.js'diff --cc ui-tui/src/gatewayClient.tsindex 3b8e7d497b0,3140430ed62..3c7912cdfd8--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@@ -1,8 -1,7 +1,7 @@@-import { type ChildProcess, spawn } from 'node:child_process'+import { execFile } from 'node:child_process'import { EventEmitter } from 'node:events'- import { existsSync } from 'node:fs'-import { delimiter, resolve } from 'node:path'-import { createInterface } from 'node:readline'+import { resolve } from 'node:path'+import { promisify } from 'node:util'import type { GatewayEvent } from '@hermes/shared/gateway-events'import {@@@ -113,19 -118,8 +111,19 @@@ const redactUrl = (raw: string): strin}}+export interface LocalGatewayGrant { url: string; protocols: string[]; profile_id: string; instance_id: string }++const bootstrapLocalGateway = async (start: boolean): Promise<LocalGatewayGrant> => {+ const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../')+- const { stdout } = await promisify(execFile)(resolvePython(root),++ const { stdout } = await promisify(execFile)(resolvePython(),+ [resolve(root, 'ui-tui/scripts/gateway_bootstrap.py'), ...(start ? ['--start'] : [])],+ { cwd: root, env: { ...process.env, PYTHONPATH: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })++ return JSON.parse(stdout) as LocalGatewayGrant+}+export class GatewayClient extends EventEmitter {- private proc: ChildProcess | null = nullprivate ws: WebSocket | null = nullprivate wsConnectPromise: Promise<void> | null = nullprivate sidecarWs: WebSocket | null = nulldiff --cc website/docs/user-guide/desktop.mdindex 2cca6e9838d,00caeff2b87..70c6b56c861--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@@ -418,7 -444,7 +446,7 @@@ When you start Hermes from the applicat## How it works- The packaged app ships the Electron shell and a native React chat surface. On first launch it can install the Hermes Agent runtime into `HERMES_HOME` (`~/.hermes`, or `%LOCALAPPDATA%\hermes` on Windows) — **the same layout a CLI install uses**, which is why the two are interchangeable. Backend resolution first honours `HERMES_DESKTOP_HERMES_ROOT`, then a completed managed install, then a probed `hermes` on `PATH` (unless `--ignore-existing` / `HERMES_DESKTOP_IGNORE_EXISTING=1` is set), and finally an explicit `HERMES_DESKTOP_HERMES` command override for packagers such as Nix. The React renderer talks to the profile's **gateway**: on first use of a local profile the app runs `hermes gateway ensure`, which attaches to that profile's running gateway or, when there is none, installs and starts a persistent per-profile gateway (a systemd/launchd service where one exists, otherwise a detached daemon) — the same process `hermes chat`, the TUI and messaging channels use. That gateway is not tied to the app's lifetime: it keeps running after you quit and has no idle shutdown; stop it with `hermes gateway stop` (or the gateway controls in Settings). The desktop app is **self-contained**: it needs no separate `hermes serve` process and never opens or requires the [web dashboard](./features/web-dashboard.md). Install, backend-resolution, and self-update logic live in the Electron main process.-The packaged app ships the Electron shell and a native React chat surface. On first launch it can install the Hermes Agent runtime into `HERMES_HOME` (`~/.hermes`, or `%LOCALAPPDATA%\hermes` on Windows) — **the same layout a CLI install uses**, which is why the two are interchangeable. Bundled apps use their included backend. Without a bundled backend, resolution honours `HERMES_DESKTOP_HERMES_ROOT`, then the development checkout, then an explicit `HERMES_DESKTOP_HERMES` command override for packagers such as Nix, and finally a usable managed install. The command override takes precedence over the managed install so a Nix desktop cannot silently launch an older mutable runtime. The React renderer talks to a headless backend the app launches for you — a `hermes serve` process that serves the `tui_gateway` JSON-RPC/WebSocket API — and reuses the agent runtime rather than embedding `hermes --tui`. The desktop app is **self-contained**: it runs its own `hermes serve` backend and never opens or requires the [web dashboard](./features/web-dashboard.md). (Runtimes older than the `serve` command fall back to a headless `dashboard --no-open` automatically, so an app update never outruns its backend.) Install, backend-resolution, and self-update logic live in the Electron main process.++The packaged app ships the Electron shell and a native React chat surface. On first launch it can install the Hermes Agent runtime into `HERMES_HOME` (`~/.hermes`, or `%LOCALAPPDATA%\hermes` on Windows) — **the same layout a CLI install uses**, which is why the two are interchangeable. Bundled apps use their included backend. Without a bundled backend, resolution honours `HERMES_DESKTOP_HERMES_ROOT`, then the development checkout, then an explicit `HERMES_DESKTOP_HERMES` command override for packagers such as Nix, and finally a usable managed install. The command override takes precedence over the managed install so a Nix desktop cannot silently launch an older mutable runtime. The React renderer talks to the profile's **gateway**: on first use of a local profile the app runs `hermes gateway ensure`, which attaches to that profile's running gateway or, when there is none, installs and starts a persistent per-profile gateway (a systemd/launchd service where one exists, otherwise a detached daemon) — the same process `hermes chat`, the TUI and messaging channels use. That gateway is not tied to the app's lifetime: it keeps running after you quit and has no idle shutdown; stop it with `hermes gateway stop` (or the gateway controls in Settings). The desktop app is **self-contained**: it needs no separate `hermes serve` process and never opens or requires the [web dashboard](./features/web-dashboard.md). Install, backend-resolution, and self-update logic live in the Electron main process.## Connecting to a remote backend